-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathmake_particle.c
2560 lines (2467 loc) · 99 KB
/
make_particle.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* This module initializes the dipole set, either using predefined shapes or reading from a file;
* includes granule generator
*
* Copyright (C) ADDA contributors
* This file is part of ADDA.
*
* ADDA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* ADDA is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with ADDA. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include "const.h" // keep this first
// project headers
#include "cmplx.h"
#include "comm.h"
#include "debug.h"
#include "io.h"
#include "memory.h"
#include "param.h"
#include "timing.h"
#include "types.h"
#include "vars.h"
// 3rd party headers
#include "mt19937ar.h"
// system headers
#include <float.h> // for DBL_MAX
#include <limits.h>
#include <math.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <time.h> // for time and clock (used for random seed)
// SEMI-GLOBAL VARIABLES
// defined and initialized in param.c
extern const enum sh shape;
extern const double lambda;
extern double sizeX,dpl,a_eq;
extern const int jagged;
extern const char *shape_fname;
extern const char *shapename;
extern const bool volcor,save_geom;
extern const opt_index opt_sh;
#ifndef SPARSE
extern const int sh_Npars;
extern const double sh_pars[];
extern const char *save_geom_fname;
extern const double gr_vf;
extern double gr_d;
extern const int gr_mat;
extern enum shform sg_format;
extern const bool store_grans;
#endif
// defined and initialized in timing.c
extern TIME_TYPE Timing_Particle;
#ifndef SPARSE
extern TIME_TYPE Timing_Granul,Timing_GranulComm;
#endif
// used in interaction.c
double ZsumShift; // real distance between the lowest (in Z) dipoles and its image, must be positive
// used in param.c
bool volcor_used; // volume correction was actually employed
const char *sh_form_str1,*sh_form_str2; // strings for log file with shape parameters (first one should end with :)
size_t gr_N; // number of granules
double gr_vf_real; // actual granules volume fraction
size_t mat_count[MAX_NMAT+1]; // number of dipoles in each domain
// LOCAL VARIABLES
#define GEOM_FORMAT "%d %d %d" // format of the geom file
#define GEOM_FORMAT_EXT "%d %d %d %d" // extended format of the geom file
/* DDSCAT shape formats; several format are used, since first variable is unpredictable and last two are not actually
* used (only to produce warnings)
*/
static const char ddscat_format_read1[]="%*s %d %d %d %d %d %d";
static const char ddscat_format_read2[]="%*s %d %d %d %d";
#ifndef SPARSE
static const char ddscat_format_write[]="%zu %d %d %d %d %d %d\n";
#endif
// ratio of scatterer volume to sizeX^3; used for dpl correction and initialization by a_eq
static double volume_ratio;
static double Ndip; // total number of dipoles (in a circumscribing cube); has limited use in sparse mode
static double dpl_def; // default value of dpl
static int minX,minY,minZ; // minimum values of dipole positions in dipole file
static FILE * restrict dipfile; // handle of dipole file
static enum shform read_format; // format of dipole file, which is read
static double cX,cY,cZ; // center for DipoleCoord in units of dipoles (counted from 0)
static double drelX,drelY,drelZ; // ratios of dipole sizes to the maximal one (dsX/dsMax...)
static double yx_ratio,zx_ratio; // ratios of particle dimensions along different axes
#ifndef SPARSE
// shape parameters
static double coat_x,coat_y,coat_z,coat_r2;
static double shell_r2,core_r2; // for coated2
static double ad2,egnu,egeps; // for egg
static double chebeps,r0_2; // for Chebyshev
static int chebn; // for Chebyshev
static double hdratio,invsqY,invsqY2,invsqZ,invsqZ2,haspY,haspZ;
static double xcenter,zcenter; // coordinates of natural particle center (in units of Dx)
static double rc_2,ri_2; // squares of circumscribed and inscribed spheres (circles) in units of Dx
static double boundZ,zcenter1,zcenter2,ell_rsq1,ell_rsq2,ell_x1,ell_x2;
static double * restrict onion_r2; //for onion
static int nlayers; // for onion
static double rbcP,rbcQ,rbcR,rbcS; // for RBC
static double prang; // for prism
static double seE,seN,seT,seR,seToverR,seInvR; // for superellipsoid
// for axisymmetric; all coordinates defined here are relative
static double * restrict contSegRoMin,* restrict contSegRoMax,* restrict contRo,* restrict contZ;
static double contCurRo,contCurZ;
static int contNseg;
struct segment {
bool single; // whether segment consists of a single joint
int first; // index of the first point in the segment
int last; // index of the last point in the segment
double zmin; // minimum z-coordinate of the segment points
double zmax; // maximum z-coordinate of the segment points
double romid; // ro-coordinate of the point in the middle
struct segment *left; // pointer to left subsegment
struct segment *right; // pointer to right subsegment
double slope; // only for single; (z[i+1]-z[i])/(ro[i+1]-ro[i])
double add; // only for single; ro[i](1-slope);
};
struct segment * restrict contSeg;
/* TO ADD NEW SHAPE
* Add here all internal variables (aspect ratios, etc.), which you initialize in InitShape() and use in MakeParticle()
* afterwards. If you need local, intermediate variables, put them into the beginning of the corresponding function. Add
* descriptive comments, use 'static'.
*/
// temporary arrays before their real counterparts are allocated
static unsigned char * restrict material_tmp;
static unsigned short * restrict position_tmp;
#endif // !SPARSE
#ifndef SPARSE //much of the functionality here is disabled in sparse mode
// EXTERNAL FUNCTIONS
// chebyshev.c
void ChebyshevParams(double eps_in,int n_in,double *dx,double *dz,double *sz,double *vr);
//======================================================================================================================
static void SaveGeometry(void)
// saves dipole configuration to a file
{
char fname[MAX_FNAME];
FILE * restrict geom;
size_t i,j;
int mat;
/* TO ADD NEW FORMAT OF SHAPE FILE
* Add code to this function to save geometry in new format. It should consist of:
* 1) definition of default filename (by supplying an appropriate extension);
* 2) writing header to the beginning of the file;
* 3) writing a single line for each dipole (this is done in parallel).
* Each part is done in corresponding switch-case sequence
*/
TIME_TYPE tstart=GET_TIME();
// create save_geom_fname if not specified, by adding extension to the shapename
if (save_geom_fname[0]==0) {
const char *ext;
// choose extension
switch (sg_format) {
case SF_TEXT:
case SF_TEXT_EXT: ext="geom"; break;
case SF_DDSCAT6:
case SF_DDSCAT7: ext="dat"; break;
default: LogError(ONE_POS,"Unknown format for saved geometry file (%d)",(int)sg_format);
// no break
}
save_geom_fname=dyn_sprintf("%s.%s",shapename,ext);
}
// automatically change format if needed
if (sg_format==SF_TEXT && Nmat>1) sg_format=SF_TEXT_EXT;
// choose filename
#ifdef PARALLEL
SnprintfErr(ALL_POS,fname,MAX_FNAME,"%s/"F_GEOM_TMP,directory,ringid);
#else
SnprintfErr(ALL_POS,fname,MAX_FNAME,"%s/%s",directory,save_geom_fname);
#endif
geom=FOpenErr(fname,"w",ALL_POS);
// print head of file
#ifdef PARALLEL
if (ringid==0) { // this condition can be different from being root
#endif
switch (sg_format) {
case SF_TEXT:
case SF_TEXT_EXT:
fprintf(geom,"#generated by ADDA v."ADDA_VERSION"\n"
"#shape: '%s'\n"
"#box size: %dx%dx%d\n"
"#lattice spacings: %g %g %g\n",shapename,boxX,boxY,boxZ,rectScaleX,rectScaleY,rectScaleZ);
if (sg_format==SF_TEXT_EXT) fprintf(geom,"Nmat=%d\n",Nmat);
break;
case SF_DDSCAT6:
case SF_DDSCAT7:
fprintf(geom,"shape: '%s'; box size: %dx%dx%d; generated by ADDA v."ADDA_VERSION"\n"
"%zu = NAT\n"
"1 0 0 = A_1 vector\n"
"0 1 0 = A_2 vector\n"
"%g %g %g = lattice spacings (dx,dy,dz)/d\n",
shapename,boxX,boxY,boxZ,nvoid_Ndip,rectScaleX,rectScaleY,rectScaleZ);
if (sg_format==SF_DDSCAT7) fprintf(geom,"%g %g %g = coordinates (x0/dx,y0/dy,z0/dz) of the zero dipole "
"(IX=IY=IZ=0)\n",(1-boxX)/2.0,(1-boxY)/2.0,(1-boxZ)/2.0);
fprintf(geom,"JA IX IY IZ ICOMP(x,y,z)\n");
break;
}
#ifdef PARALLEL
} // end of if
#endif
// save geometry
for(i=0;i<local_nvoid_Ndip;i++) {
j=3*i;
switch (sg_format) {
case SF_TEXT:
fprintf(geom,GEOM_FORMAT"\n",position[j],position[j+1],position[j+2]);
break;
case SF_TEXT_EXT:
fprintf(geom,GEOM_FORMAT_EXT"\n",position[j],position[j+1],position[j+2],material[i]+1);
break;
case SF_DDSCAT6:
case SF_DDSCAT7:
mat=material[i]+1;
fprintf(geom,ddscat_format_write,i+local_nvoid_d0+1,position[j],position[j+1],position[j+2],mat,mat,
mat);
break;
}
}
FCloseErr(geom,fname,ALL_POS);
#ifdef PARALLEL
// wait for all processes to save their part of geometry
Synchronize();
// combine all files into one and clean
if (IFROOT) CatNFiles(directory,F_GEOM_TMP,save_geom_fname);
#endif
if (IFROOT) PRINTFB("Geometry saved to file\n");
Timing_FileIO+=GET_TIME()-tstart;
}
//======================================================================================================================
#define ALLOCATE_SEGMENTS(N) (struct segment *)voidVector((N)*sizeof(struct segment),ALL_POS,"contour segment");
void InitContourSegment(struct segment * restrict seg,const bool increasing)
/* recursively initialize a segment of a contour: allocates memory and calculates all elements. Some elements are
* calculated during the forward sweep (from long segments to short), others - during the backward sweep.
* Recursive function calls incurs certain overhead, however here it is not critical.
*/
{
int i;
struct segment * restrict s1,* restrict s2;
/* Remove constant parts in the beginning and end of segment, if present. After this procedure 'first' is guaranteed
* to be less than 'last' by definition of the segment
*/
while (contRo[seg->first]==contRo[seg->first+1]) {
(seg->first)++;
if (seg->first == seg->last) LogError(ONE_POS,"Bug in InitContour: One of the segments (ending at index %d) "
"has constant ro",seg->last);
}
while (contRo[seg->last-1]==contRo[seg->last]) (seg->last)--; // here above error checks are not needed
if (seg->first+1 == seg->last) { // segment with a single fragment
seg->single=true;
seg->zmin=MIN(contZ[seg->first],contZ[seg->last]);
seg->zmax=MAX(contZ[seg->first],contZ[seg->last]);
seg->slope=(contZ[seg->last]-contZ[seg->first])/(contRo[seg->last]-contRo[seg->first]);
seg->add=contZ[seg->first]-contRo[seg->first]*seg->slope;
}
else { // divide segment into two, and initialize each of them
seg->single=false;
i=(seg->first+seg->last)/2;
seg->romid=contRo[i];
// construct subsegments
s1=ALLOCATE_SEGMENTS(1);
s2=ALLOCATE_SEGMENTS(1);
s1->first=seg->first;
s1->last=s2->first=i;
s2->last=seg->last;
// initialize subsegments
InitContourSegment(s1,increasing);
InitContourSegment(s2,increasing);
// calculate zmax and zmin
seg->zmax=MAX(s1->zmax,s2->zmax);
seg->zmin=MIN(s1->zmin,s2->zmin);
// assign new segments to left and right based on 'increasing' - only weak monotonicity is assumed
if (increasing) {
seg->left=s1;
seg->right=s2;
}
else {
seg->left=s2;
seg->right=s1;
}
}
}
//======================================================================================================================
#define CHUNK_SIZE 128 // how many numbers are allocated at once for adjustable arrays
static void InitContour(const char *fname,double *ratio,double *shSize)
/* Reads a contour from the file, rotates it so that it starts from a local minimum in ro, then divides it into
* monotonic (over ro) segments. It produces data, which are later used to test each dipole for being inside the
* contour. Segments are either weakly increasing or weakly decreasing (i.e. can contain constant parts).
*/
{
size_t line; // current line number
int nr; // number of contour points read from the file
int size; // current size of the allocated memory for contour
int i,j,scanned;
double *bufRo,*bufZ; // temporary buffers
int *index;
double ro,z,romin,romax,zmin,zmax,mult,zmid;
FILE* file;
bool increasing;
char linebuf[BUF_LINE];
D("InitContour has started");
// Read contour from file
TIME_TYPE tstart=GET_TIME();
file=FOpenErr(fname,"r",ALL_POS);
line=SkipComments(file);
size=CHUNK_SIZE;
MALLOC_VECTOR(bufRo,double,size,ALL);
MALLOC_VECTOR(bufZ,double,size,ALL);
nr=0;
// this depends on variables been declared double
romin=zmin=DBL_MAX;
romax=zmax=-DBL_MAX;
// reading is performed in lines
while (FGetsError(file,fname,&line,linebuf,BUF_LINE,ONE_POS)!=NULL) {
// scan numbers in a line
scanned=sscanf(linebuf,"%lf %lf",&ro,&z);
// if sscanf returns EOF, that is a blank line -> just skip
if (scanned!=EOF) {
if (scanned!=2) // this in most cases indicates wrong format
LogError(ONE_POS,"Error occurred during scanning of line %zu in contour file %s",line,fname);
// check for consistency of input
if (ro<0) LogError(ONE_POS,"Negative ro-coordinate is found on line %zu in contour file %s",line,fname);
// update extreme values
if (z>zmax) zmax=z;
if (z<zmin) zmin=z;
if (ro>romax) romax=ro;
if (ro<romin) romin=ro;
// add allocated memory to buf, if needed
if (nr >= size) {
size+=CHUNK_SIZE;
REALLOC_VECTOR(bufRo,double,size,ALL);
REALLOC_VECTOR(bufZ,double,size,ALL);
}
bufRo[nr]=ro;
bufZ[nr]=z;
nr++;
}
}
FCloseErr(file,fname,ALL_POS);
Timing_FileIO+=GET_TIME()-tstart;
// Check number of points read
if (nr<3) LogError(ONE_POS,"Contour from file %s contains less than three points",fname);
// Determine initial point with local minimum ro[i-j]>ro[i-j+1]=...=ro[i]<ro[i+1]
i=0;
while (i<nr-1 && bufRo[i]>=bufRo[i+1]) i++;
if (i==0) { // first point is a minimum candidate
if (bufRo[0]>=bufRo[nr-1]) { // if required, search backwards; guaranteed to converge, since bufRo[1]>bufRo[0]
i=nr-1;
while (bufRo[i]>=bufRo[i-1]) i--;
}
}
// if the whole contour is non-decreasing, check for constancy
else if (i==nr-1 && bufRo[nr-1]==bufRo[0])
LogError(ONE_POS,"Contour from file %s has zero area. Hence the scatterer is void",fname);
/* Construct working contour so that its first point = last and is a local minimum. It is done by rotating buf and
* adding one extra point. Then free the buffer.
*/
MALLOC_VECTOR(contRo,double,nr+1,ALL);
memcpy(contRo,bufRo+i,(nr-i)*sizeof(double));
memcpy(contRo+nr-i,bufRo,i*sizeof(double));
contRo[nr]=contRo[0];
Free_general(bufRo);
// same for Z vectors
MALLOC_VECTOR(contZ,double,nr+1,ALL);
memcpy(contZ,bufZ+i,(nr-i)*sizeof(double));
memcpy(contZ+nr-i,bufZ,i*sizeof(double));
contZ[nr]=contZ[0];
Free_general(bufZ);
// scale coordinates to be relative to total diameter, and centered (by z) around 0
mult=1/(2*romax);
zmid=(zmax+zmin)/2;
*ratio=(zmax-zmin)*mult;
*shSize=2*romax;
ri_2=romin*romin*mult*mult;
for (i=0;i<=nr;i++) {
contRo[i]*=mult;
contZ[i]=(contZ[i]-zmid)*mult;
}
// divide the contour into the segments; actually only the index is constructed marking end points of the segments
MALLOC_VECTOR(index,int,nr+1,ALL); // this is enough, even if all segments are of one joint
index[0]=0;
i=j=1;
increasing=true;
while (i<nr) { // uses greedy algorithm for weak monotonicity
while (i<nr && (increasing ? (contRo[i]<=contRo[i+1]) : (contRo[i]>=contRo[i+1]))) i++;
index[j]=i;
j++;
increasing=!increasing;
}
contNseg=j-1;
if (IS_ODD(contNseg)) LogError(ONE_POS,"Bug in InitContour: Resulting number of monotonic (in values of ro) "
"segments (%d) is odd",contNseg);
/* Calculate maximum and minimum ro for segments; We implicitly use that first segment is increasing, second -
* decreasing, and so on.
*/
MALLOC_VECTOR(contSegRoMin,double,contNseg,ALL);
MALLOC_VECTOR(contSegRoMax,double,contNseg,ALL);
for (j=0;j<contNseg;j++) {
if (IS_EVEN(j)) {
contSegRoMin[j]=contRo[index[j]];
contSegRoMax[j]=contRo[index[j+1]];
}
else {
contSegRoMin[j]=contRo[index[j+1]];
contSegRoMax[j]=contRo[index[j]];
}
}
// Construct a tree of segments
contSeg=ALLOCATE_SEGMENTS(contNseg);
for (j=0;j<contNseg;j++) {
contSeg[j].first=index[j];
contSeg[j].last=index[j+1];
InitContourSegment(contSeg+j,IS_EVEN(j));
}
Free_general(index);
Free_general(contRo);
Free_general(contZ);
D("InitContour has finished");
D("Nseg=%d",contNseg);
D("minroSq="GFORM_DEBUG,ri_2);
}
#undef CHUNK_SIZE
#undef ALLOCATE_SEGMENTS
//======================================================================================================================
bool CheckContourSegment(struct segment * restrict seg)
/* Checks, whether point is under or above the segment, by traversing the tree of segments. It returns true, if
* intersecting z value is larger than given z, and false otherwise. Point is defined by local variables contCurRo and
* contCurZ.
*/
{
while (true) {
if (contCurZ < seg->zmin) return true;
else if (contCurZ > seg->zmax) return false;
else if (seg->single) return (contCurZ < seg->add + contCurRo*seg->slope);
else seg=(contCurRo<seg->romid ? seg->left : seg->right);
}
}
//======================================================================================================================
void FreeContourSegment(struct segment * restrict seg)
/* recursively frees memory allocated for contour segments;
* Recursive function calls incurs certain overhead, however here it is not critical.
*/
{
if (!(seg->single)) {
FreeContourSegment(seg->left);
FreeContourSegment(seg->right);
}
}
//======================================================================================================================
#define KEY_LENGTH 2 // length of key for initialization of random generator
#define MAX_ZERO_FITS 1E4 // maximum number of zero fits in a row (each - many granules)
#define MAX_FALSE_SKIP 10 // number of false skips in granule placement to complete the set
#define MAX_FALSE_SKIP_SMALL 10 // the same for small granules
#define MAX_GR_SET USHRT_MAX // maximum size of granule set
#define MIN_CELL_SIZE 4.0 // minimum cell size for small granules
#define CHECK_CELL(a) CheckCell(gr,vgran,tree_index,Di2,occup[a],&fits) // macro for simplicity
#define CHECK_CELL_TEST(a) (CHECK_CELL(a),fits) // ... combined with test for 'fits'
static inline int CheckCell(const double * restrict gr,const double * restrict vgran,
const unsigned short * restrict tree_index,const double Di2,const int start,bool * restrict fits)
// function that checks whether granule intersects anything in the cell
{
int index,last,index1;
double t1,t2,t3;
last=index=start;
while (index!=MAX_GR_SET && (*fits)) {
last=index;
index1=3*index;
t1=gr[0]-vgran[index1];
t2=gr[1]-vgran[index1+1];
t3=gr[2]-vgran[index1+2];
if ((t1*t1+t2*t2+t3*t3)<Di2) *fits=false;
index=tree_index[index];
}
return last;
}
//======================================================================================================================
static size_t PlaceGranules(void)
/* Randomly places granules inside the specified domain; Mersenne Twister is used for generating random numbers
*
* A simplest algorithm is used: to place randomly a sphere, and see if it overlaps with any dipoles (more exactly:
* centers of dipoles) of not correct domain; if not, accept it and fill all this dipoles with granules' domain.
* Optimized to perform in two steps: First it places of set of not-intersecting granules and do only a quick check
* against the "domain pattern" - coarse representation of the domain. On the second step granules of the whole set are
* thoroughly checked against the whole domain on each processor. When small granules are used, no domain pattern is
* used - makes it simpler. Intersection of two granules between the sets is checked only through dipoles, which is not
* exact, however it allows considering arbitrary complex domains, which is described only by a set of occupied dipoles.
*
* This algorithm is unsuitable for high volume fractions, it becomes very slow and for some volume fractions may fail
* at all (Metropolis algorithm should be more suitable, however it is hard to code for arbitrary domains). Moreover,
* statistical properties of the obtained granules distribution may be not perfect, however it seems good enough for our
* applications.
*
* Currently it is not working with jagged. That should be improved, by rewriting the jagged calculation throughout the
* program
*/
{
int i,j,k,zerofit,last;
size_t n,count,count_gr,false_count,ui;
size_t nd; // number of dipoles occupied by granules
int index,index1,index2; // indices for dipole grid
int dom_index,dom_index1,dom_index2; // indices for auxiliary grid
int gX,gY,gZ; // auxiliary grid dimensions
size_t gXY,gr_gN; // ... and their products
size_t avail; // number of available (free) domain cells
int gX2,gY2,gZ2,locgZ2;
int i0,i1,j0,j1,k0,k1;
bool fits;
int cur_Ngr,ig,max_Ngr; // number of granules in a current set, index, and maximum set size
double gdX,gdY,gdZ,gdXh,gdYh,gdZh; // auxiliary grid cell sizes and their halfs (h)
int locz0,locz1,locgZ,gr_locgN;
double R,R2,Di,Di2; // radius and diameter of granule, and their squares
double x0,x1,y0,y1,z0,z1; // where to put random number (inner box)
int id0,id1,jd0,jd1,kd0,kd1; // dipoles limit that fall inside inner box
int Nfit; // number of successfully placed granules in a current set
double overhead; // estimate of the overhead needed to have exactly needed N of granules
double tmp1,tmp2,t1,t2,t3;
// maximum shifts for checks of neighboring cells in auxiliary grid; for 'small' it is the shift in index
int sx,sy,sz;
unsigned long key[KEY_LENGTH]; // key to initialize random number generator
unsigned char * restrict dom; // information about the domain on a granule grid
unsigned short * restrict occup; // information about the occupied cells
int sm_gr; // whether granules are small (then simpler algorithm is used)
unsigned short * restrict tree_index; // index for traversing granules inside one cell (small)
double * restrict vgran; // coordinates of a set of granules
bool * restrict vfit; // results of granule fitting on the grid (boolean)
int * restrict ginX,* restrict ginY,* restrict ginZ; // indices to find dipoles inside auxiliary grid
int indX,indY,indZ; // indices for doubled auxiliary grid
int bit; // bit position in char of 'dom'
double gr[3]; // coordinates of a single granule
FILE * restrict file; // file for saving granule positions
char fname[MAX_FNAME]; // filename of file
double minval; // minimum size of auxiliary grid
// next line should never happen
if (rectDip) LogError(ONE_POS,"Incompatibility error in PlaceGranules");
/* redundant initialization to remove warnings; most of this is due to the fact that code for small and large
* granules is largely independent (although there are some common parts, which motivates against complete
* separation of them into two functions).
*/
zerofit=gX2=gY2=gZ2=locgZ2=id0=id1=jd0=jd1=kd0=kd1=indZ=locgZ=gr_locgN=sx=sy=sz=0;
gdXh=gdYh=gdZh=0;
ginX=ginY=ginZ=NULL;
dom=NULL;
tree_index=occup=NULL;
file=NULL;
// prepare granule file for saving if needed
if (store_grans && IFROOT) {
SnprintfErr(ONE_POS,fname,MAX_FNAME,"%s/"F_GRANS,directory);
file=FOpenErr(fname,"w",ONE_POS);
fprintf(file,"#generated by ADDA v."ADDA_VERSION"\n"
"#granule diameter = "GFORM"\n",gr_d);
}
// set variables; consider jagged
Di=gr_d/(gridspace*jagged);
if (Di<1) LogWarning(EC_WARN,ONE_POS,
"Granule diameter is smaller than dipole size. It is recommended to increase resolution");
R=Di/2;
R2=R*R;
Di2=4*R2;
// inner box
D("gr_N=%zu, Di="GFORMDEF,gr_N,Di);
x0=R-0.5;
x1=boxX-R-0.5;
y0=R-0.5;
y1=boxY-R-0.5;
z0=R-0.5;
z1=boxZ-R-0.5;
minval=MIN(x1-x0,MIN(y1-y0,z1-z0));
if (minval<=0) LogError(ONE_POS,"Granule size must be smaller than minimum particle dimension");
/* initialize auxiliary grid; grid size is chosen to be always <= D/sqrt(3). Thus we can be sure that each cell
* contain no more than 1 granule.
*/
CheckOverflow(MAX(boxX,MAX(boxY,boxZ))*10/Di,ONE_POS_FUNC);
tmp1=sqrt(3)/Di;
gX=(int)ceil((x1-x0)*tmp1);
gY=(int)ceil((y1-y0)*tmp1);
gZ=(int)ceil((z1-z0)*tmp1);
// this should occur only as a consequence of float inaccuracy in error check above
if (gX==0 || gY==0 || gZ==0) LogError(ONE_POS,"Granule size is too close to minimum particle dimension");
gdX=(x1-x0)/gX;
gdY=(y1-y0)/gY;
gdZ=(z1-z0)/gZ;
tmp1=MAX(2*Di,MIN_CELL_SIZE);
/* sets the discrimination for small or large granules; it should guarantee that no divisions by zero occur
* afterwards in the code for small granules
*/
sm_gr=minval>tmp1 && (gdX<2 || gdY<2 || gdZ<2);
if (sm_gr) {
if (IFROOT) PRINTFB("Using algorithm for small granules\n");
/* redefine auxiliary grid; now the grid size is chosen to be always >= 2*D. Thus we can be sure that granule
* can intersect with granule in either left or right (x=+-1) cell but not both (and analogously with other
* coordinates).
*/
tmp1=1/tmp1;
gX=(int)floor((x1-x0)*tmp1);
gdX=(x1-x0)/gX;
gY=(int)floor((y1-y0)*tmp1);
gdY=(y1-y0)/gY;
gZ=(int)floor((z1-z0)*tmp1);
gdZ=(z1-z0)/gZ;
}
else { // large granules
if (IFROOT) PRINTFB("Using algorithm for large granules\n");
gX2=2*gX;
gdXh=gdX/2;
gY2=2*gY;
gdYh=gdY/2;
gZ2=2*gZ;
gdZh=gdZ/2;
/* this sets maximum distance of neighboring cells to check; condition gdX<R can only occur if gX<=7, which is
* quite rare, so no optimization is performed. sx>3 can only occur if gX<=2 and then it doesn't make sense to
* take bigger sx. Absolutely analogous for y, z.
*/
if (gdX<R) sx=3;
else sx=2;
if (gdY<R) sy=3;
else sy=2;
if (gdZ<R) sz=3;
else sz=2;
}
gXY=MultOverflow(gX,gY,ONE_POS_FUNC);
gr_gN=MultOverflow(gXY,gZ,ONE_POS_FUNC);
// calculate maximum number of granules in a grid; crude estimate
tmp2=(ceil((x1-x0)/Di)+1)*(ceil((y1-y0)/Di)+1)*(ceil((z1-z0)/Di)+1);
max_Ngr=MIN(MAX_GR_SET,tmp2);
// local z grid + initialize communications
D("gr_gN=%zu, max_Ngr=%d",gr_gN,max_Ngr);
SetGranulComm(z0,z1,gdZ,gZ,gXY,max_Ngr,&locz0,&locz1,sm_gr);
if (!sm_gr) {
locgZ=locz1-locz0;
locgZ2=2*locgZ;
gr_locgN=gXY*locgZ;
}
if (IFROOT) {
// initialize random generator
key[0]=(unsigned long)time(NULL);
key[1]=(unsigned long)(clock());
init_by_array(key,KEY_LENGTH);
// allocate memory
MALLOC_VECTOR(occup,ushort,gr_gN,ONE);
if (sm_gr) MALLOC_VECTOR(tree_index,ushort,max_Ngr,ONE);
else MALLOC_VECTOR(dom,uchar,gr_gN,ALL);
}
else if (!sm_gr && locgZ!=0) MALLOC_VECTOR(dom,uchar,gr_locgN,ALL);
MALLOC_VECTOR(vgran,double,3*max_Ngr,ALL);
MALLOC_VECTOR(vfit,bool,max_Ngr,ALL);
if (!sm_gr && locgZ!=0) {
// build some more indices
MALLOC_VECTOR(ginX,int,gX2+1,ALL);
MALLOC_VECTOR(ginY,int,gY2+1,ALL);
MALLOC_VECTOR(ginZ,int,locgZ2+1,ALL);
for (i=0;i<=gX2;i++) ginX[i]=(int)ceil(x0+i*gdXh);
id0=ginX[0];
id1=ginX[gX2];
for (i=0;i<=gY2;i++) ginY[i]=(int)ceil(y0+i*gdYh);
jd0=ginY[0];
jd1=ginY[gY2];
for (i=0;i<=locgZ2;i++) ginZ[i]=(int)ceil(z0+(i+2*locz0)*gdZh);
kd0=MAX(ginZ[0],local_z0);
indZ=1;
if (kd0>=ginZ[1]) indZ++;
kd1=MIN(ginZ[locgZ2],local_z1_coer);
}
n=count=count_gr=false_count=0;
nd=0;
// crude estimate of the probability to place a small granule into domain
if (sm_gr) overhead=Ndip/mat_count[gr_mat];
else overhead=1;
// main cycle
D("Starting main iteration cycle");
while (n<gr_N) {
if (sm_gr) { // small granules
// just generate granules
if (IFROOT) {
cur_Ngr=MIN(ceil((gr_N-n)*overhead),max_Ngr);
// generate points and quick check
ig=false_count=0;
for (ui=0;ui<gr_gN;ui++) occup[ui]=MAX_GR_SET; // used as undefined
while (ig<cur_Ngr) {
count++;
false_count++;
fits=true;
// random position in a grid
gr[0]=genrand(0,gX);
gr[1]=genrand(0,gY);
gr[2]=genrand(0,gZ);
// coordinates in a grid
t1=floor(gr[0]);
t2=floor(gr[1]);
t3=floor(gr[2]);
indX=(int)t1;
indY=(int)t2;
indZ=(int)t3;
t1=gr[0]-t1; // t_i are distances to the edges
t2=gr[1]-t2;
t3=gr[2]-t3;
// convert to usual coordinates (in dipole grid)
gr[0]=gr[0]*gdX+x0;
gr[1]=gr[1]*gdY+y0;
gr[2]=gr[2]*gdZ+z0;
index=indZ*gXY+indY*gX+indX;
// 'last' is used only if fits, so when this test actually reaches last element
last=CHECK_CELL(index);
// weird construction (7-level nested 'ifs') but should be fast
if (fits) {
t1*=gdX; // transform shifts to usual coordinates; done only when needed
sx=0;
if (t1<Di) {
if (indX!=0) sx=-1;
}
else if ((t1=gdX-t1)<Di && indX!=gX-1) sx=1;
if (sx==0 || CHECK_CELL_TEST(index+sx)) { // test for x-neighbor
t2*=gdY;
sy=0;
if (t2<Di) {
if (indY!=0) sy=-gX;
}
else if ((t2=gdY-t2)<Di && indY!=gY-1) sy=gX;
if (sy==0 || CHECK_CELL_TEST(index+sy)) { // test for y-neighbor
t3*=gdZ;
sz=0;
if (t3<Di) {
if (indZ!=0) sz=-(int)gXY;
}
else if ((t3=gdZ-t3)<Di && indZ!=gZ-1) sz=gXY;
if (sz!=0) {
if (CHECK_CELL_TEST(index+sz)) { // test for z-neighbor
if (sy!=0) {
tmp1=Di2-t2*t2-t3*t3;
// test for yz- and xyz-neighbors
if (tmp1>0 && CHECK_CELL_TEST(index+sy+sz )&& sx!=0 && t1*t1<tmp1)
CHECK_CELL(index+sx+sy+sz);
}
else if (sx!= 0 && t1*t1+t3*t3<Di2) CHECK_CELL(index+sx+sz);
}
}
// test for xy-neighbor
else if (sx!=0 && sy!=0 && t1*t1+t2*t2<Di2) CHECK_CELL(index+sx+sy);
}
}
}
if (fits) {
memcpy(vgran+3*ig,gr,3*sizeof(double));
tree_index[ig]=MAX_GR_SET;
if (last==MAX_GR_SET) occup[index]=(unsigned short)ig;
else tree_index[last]=(unsigned short)ig;
ig++;
false_count=0;
}
if (false_count>MAX_FALSE_SKIP_SMALL) break;
}
// real number of placed granules for this set
cur_Ngr=ig;
}
}
else { // large granules
// generate domain pattern
if (locgZ!=0) {
for (i=0;i<gr_locgN;i++) dom[i]=0;
/* indices 'index' and 'dom_index' are build up gradually for optimization. Finally,
* index=(k-local_z0)*boxXY + j*boxX +i.
* TODO: ??? final formula for dom_index is unclear, moreover indZ seems to be not always initialized
*/
dom_index2=0;
index2=(kd0-local_z0)*boxXY;
bit=((indZ&1)^1)<<2;
for (k=kd0;k<kd1;k++,index2+=boxXY) {
index1=index2+jd0*boxX;
dom_index1=dom_index2;
indY=1;
bit&=~2;
for (j=jd0;j<jd1;j++,index1+=boxX) {
index=index1+id0;
dom_index=dom_index1;
indX=1;
bit&=~1;
for (i=id0;i<id1;i++,index++) {
if (material_tmp[index]!=gr_mat) dom[dom_index]|=(unsigned char)(1<<bit);
if (i+1==ginX[indX]) {
indX++;
bit^=1;
if (indX&1) dom_index++;
}
}
if (j+1==ginY[indY]) {
indY++;
bit^=2;
if (indY&1) dom_index1+=gX;
}
}
if (k+1==ginZ[indZ]) {
indZ++;
bit^=4;
if (indZ&1) dom_index2+=gXY;
}
}
}
D("Domain pattern generated");
// send/collect domain pattern
CollectDomainGranul(dom,gXY,locz0,locgZ,&Timing_GranulComm);
if (IFROOT) {
// analyze domain pattern
avail=0;
for (ui=0;ui<gr_gN;ui++) if (dom[ui]!=0xFF) avail++;
cur_Ngr=MIN(avail,(size_t)max_Ngr);
tmp1=(gr_N-n)*overhead;
if (cur_Ngr>tmp1) cur_Ngr=(int)ceil(tmp1);
// generate points and quick check
ig=false_count=0;
for (ui=0;ui<gr_gN;ui++) occup[ui]=MAX_GR_SET; // used as undefined
while (ig<cur_Ngr) {
count++;
// random position in a double grid
gr[0]=genrand(0,gX2);
gr[1]=genrand(0,gY2);
gr[2]=genrand(0,gZ2);
// coordinates in doubled grid
indX=(int)floor(gr[0]);
indY=(int)floor(gr[1]);
indZ=(int)floor(gr[2]);
bit=1<<((indX&1)+((indY&1)<<1)+((indZ&1)<<2)); // position bit inside one cell
// coordinates in usual grid
indX/=2;
indY/=2;
indZ/=2;
index=indZ*gXY+indY*gX+indX;
// two simple checks
if (!(dom[index]&bit) && occup[index]==MAX_GR_SET) {
// convert to usual coordinates (in dipole grid)
gr[0]=gr[0]*gdXh+x0;
gr[1]=gr[1]*gdYh+y0;
gr[2]=gr[2]*gdZh+z0;
fits=true;
false_count++;
if ((i0=indX-sx)<0) i0=0;
if ((i1=indX+sx+1)>gX) i1=gX;
if ((j0=indY-sy)<0) j0=0;
if ((j1=indY+sy+1)>gY) j1=gY;
if ((k0=indZ-sz)<0) k0=0;
if ((k1=indZ+sz+1)>gZ) k1=gZ;
dom_index2=k0*gXY;
for (k=k0;k<k1;k++,dom_index2+=gXY) {
dom_index1=dom_index2+j0*gX;
for (j=j0;j<j1;j++,dom_index1+=gX) {
dom_index=dom_index1+i0;
for (i=i0;i<i1;i++,dom_index++) if (occup[dom_index]!=MAX_GR_SET) {
index1=3*occup[dom_index];
t1=gr[0]-vgran[index1];
t2=gr[1]-vgran[index1+1];
t3=gr[2]-vgran[index1+2];
if ((t1*t1+t2*t2+t3*t3)<Di2) {
fits=false;
break;
}
}
if (!fits) break;
}
if (!fits) break;
}
if (fits) {
memcpy(vgran+3*ig,gr,3*sizeof(double));
occup[index]=(unsigned short)ig;
ig++;
false_count=0;
/* Here it is possible to correct the domain pattern because of the presence of a new
* granule. However it probably will be useful only for large volume fractions
*/
}
if (false_count>MAX_FALSE_SKIP) break;
}
}
// real number of placed granules for this set
cur_Ngr=ig;
}
} // end of large granules
D("Set of possible granules produced");
// cast to all processors
MyBcast(&cur_Ngr,int_type,1,&Timing_GranulComm);
MyBcast(vgran,double_type,3*cur_Ngr,&Timing_GranulComm);
count_gr+=cur_Ngr;
// final check if granules belong to the domain
for (ig=0;ig<cur_Ngr;ig++) {
memcpy(gr,vgran+3*ig,3*sizeof(double));
k0=MAX((int)ceil(gr[2]-R),local_z0);
k1=MIN((int)floor(gr[2]+R),local_z1_coer-1);
fits=true;
index2=(k0-local_z0)*boxXY;
for (k=k0;k<=k1;k++,index2+=boxXY) {
tmp1=R2-(gr[2]-k)*(gr[2]-k);
tmp2=sqrt(tmp1);
j0=(int)ceil(gr[1]-tmp2);
j1=(int)floor(gr[1]+tmp2);
index1=index2+j0*boxX;
for (j=j0;j<=j1;j++,index1+=boxX) {
tmp2=sqrt(tmp1-(gr[1]-j)*(gr[1]-j));
i0=(int)ceil(gr[0]-tmp2);
i1=(int)floor(gr[0]+tmp2);
index=index1+i0;
for (i=i0;i<=i1;i++,index++) {
if (material_tmp[index]!=gr_mat) {
fits=false;
break;
}
}
if (!fits) break;
}
if (!fits) break;
}
vfit[ig]=fits;
}
// collect fits
ExchangeFits(vfit,cur_Ngr,&Timing_GranulComm);
// fit dipole grid with successive granules
Nfit=n;
for (ig=0;ig<cur_Ngr && n<gr_N;ig++) {
if (vfit[ig]) { // a successful granule
n++;
// fill dipoles in the sphere with granule material
memcpy(gr,vgran+3*ig,3*sizeof(double));
k0=MAX((int)ceil(gr[2]-R),local_z0);
k1=MIN((int)floor(gr[2]+R),local_z1_coer-1);
index2=(k0-local_z0)*boxXY;
for (k=k0;k<=k1;k++,index2+=boxXY) {
tmp1=R2-(gr[2]-k)*(gr[2]-k);
tmp2=sqrt(tmp1);
j0=(int)ceil(gr[1]-tmp2);
j1=(int)floor(gr[1]+tmp2);
index1=index2+j0*boxX;
for (j=j0;j<=j1;j++,index1+=boxX) {
tmp2=sqrt(tmp1-(gr[1]-j)*(gr[1]-j));
i0=(int)ceil(gr[0]-tmp2);
i1=(int)floor(gr[0]+tmp2);
index=index1+i0;
for (i=i0;i<=i1;i++,index++) {
material_tmp[index]=(unsigned char)(Nmat-1);
nd++;
}
}
}
}
}
cur_Ngr=ig; // this is non-trivial only if n=gr_N occurred above
// save correct granule positions to file
if (store_grans && IFROOT) for (ig=0;ig<cur_Ngr;ig++) if (vfit[ig]) fprintf(file,GFORM3L"\n",
gridspace*(vgran[3*ig]-cX),gridspace*(vgran[3*ig+1]-cY),gridspace*(vgran[3*ig+2]-cZ));
Nfit=n-Nfit;
/* overhead is estimated based on the estimation of mean value - 1*standard deviation for the probability of
* fitting one granule. It is estimated from the Bernoulli statistics: k out of n successful hits.
* M(p)=(k+1)/(n+2); s^2(p)=(k+1)(n-k+1)/(n+3)(n+2)^2; M(p)-s(p)=[(k+1)/(n+2)]*[1-sqrt((n-k+1)/(k+1)(n+3))];
* overhead=1/latter.
*/
overhead=(cur_Ngr+2)/((1-sqrt((cur_Ngr-Nfit+1)/(double)((Nfit+1)*(cur_Ngr+3))))*(Nfit+1));
if (Nfit!=0) zerofit=0;
else {
zerofit++;
// check if taking too long
if (zerofit>MAX_ZERO_FITS) {
MyInnerProduct(&nd,sizet_type,1,&Timing_GranulComm);
LogError(ONE_POS,"The granule generator failed to reach required volume fraction ("GFORMDEF") of "
"granules. %zu granules were successfully placed up to a volume fraction of "GFORMDEF".",