-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharrt.C
1463 lines (1328 loc) · 41.7 KB
/
arrt.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
/*
* arrt (another random ray tracer)
* Gavin Ridley
* MIT 22.212 F2019
*
* NOTES: -> add quasi-monte carlo and compare convergence
* -> Add ability to plot lines across geometry plot
* -> Check time per integration
* -> Could use the exception system better
*/
#include<algorithm>
#include<array>
#include<cstdlib>
#include<experimental/filesystem>
#include<fstream>
#include<functional>
#include<iostream>
#include<iomanip>
#include<map>
#include<string>
#include<sstream>
#include<utility>
#include<vector>
#include<math.h>
#include<gd.h>
#define EPS 1e-6f
// Know npolar at compile time to speed stuff up in core MOC kernel
// This speedup is due to loop unrolling.
#define NPOLAR 3
using namespace std;
namespace fs = experimental::filesystem;
// Crappy RNG
constexpr float randmaxf = (float)RAND_MAX;
float randf() { return (float)rand() / randmaxf; }
// useful operators on 2D points
typedef pair<float, float> Pt2D;
template<class T>
pair<T, T> operator+(pair<T,T> x, pair<T,T> y)
{
pair<T, T> res;
res.first = x.first + y.first;
res.second = x.second + y.second;
return res;
}
template<class T>
pair<T, T> operator-(pair<T,T> x, pair<T,T> y)
{
pair<T, T> res;
res.first = x.first - y.first;
res.second = x.second - y.second;
return res;
}
template<class s, class T>
pair<T,T> operator*(s ss, pair<T,T> tt)
{
pair<T,T> res(tt);
res.first *= ss;
res.second *= ss;
return res;
}
// Magnitude squared of 2D vector
template<class T>
T sq(const pair<T,T>& in)
{
return in.first * in.first +
in.second * in.second;
}
// Swap items in a pair of the same type
template<class T>
void swappair(pair<T,T>& p)
{
T tmp = p.first;
p.first = p.second;
p.second = tmp;
}
// Some operations on vectors that are already defined
// on std::valarray, but I haven't played with that class
// yet and am on a time crunch. As a result, I'm going with
// what I know works.
template<class T>
void normalizeVector(vector<T>& vec)
{
// Calculate L1 norm of the vector
T norm = 0;
for (T x: vec) norm += abs(x);
for (T& x: vec) x /= norm;
}
template<class T>
vector<T> operator*(T fac, const vector<T>& vec)
{
vector<T> result(vec.size());
for (unsigned i=0; i<vec.size(); ++i)
result[i] = fac * vec[i];
return result;
}
template<class T>
vector<T> operator+(const vector<T>& vecl, const vector<T>& vecr)
{
vector<T> result(vecl.size());
for (unsigned i=0; i<vecl.size(); ++i)
result[i] = vecl[i] + vecr[i];
return result;
}
template<class T>
vector<T> operator*(const vector<T>& vecl, const vector<T>& vecr)
{
vector<T> result(vecl.size());
for (unsigned i=0; i<vecl.size(); ++i)
result[i] = vecl[i] * vecr[i];
return result;
}
template<class T>
void dumpVector(const vector<T>& vec, const string fname)
{
ofstream of(fname);
for (const T& x: vec) of << x << endl;
of.close();
}
// Printing of pairs of stuff
template<class T, class TT>
ostream& operator<<(ostream& os, pair<T,TT> x)
{
os << x.first << " " << x.second;
return os;
}
/* This defines a quasirandom number generator.
* This is code I copied from a past project, and I
* wanted to see if this improves convergence here.
*/
class HaltonSequence
{
int base, count;
vector<int> base_representation;
void incseq();
public:
HaltonSequence(int thisbase);
int calc_base_digits();
float get_xi();
void print_seq();
};
int HaltonSequence::calc_base_digits()
{
int n=1;
while ((float)INT8_MAX / pow(base,n) > 1.0) ++n;
return n;
}
HaltonSequence::HaltonSequence(int thisbase) :
base(thisbase),
count(1),
base_representation(calc_base_digits(), 0)
{
base_representation[base_representation.size()-1] = 1;
}
void HaltonSequence::incseq()
{
count += 1;
for (int i=base_representation.size()-1; i>=0; --i)
if (base_representation[i] != base-1)
{
base_representation[i]++;
break;
}
else
base_representation[i]=0;
}
float HaltonSequence::get_xi()
{
float res = 0.0;
int j =1;
for (int i=base_representation.size()-1; i>=0; --i)
res += (float)base_representation[i] / (float)pow(base,j++);
incseq();
return res;
}
// --- Definition of the only quadrature set anyone will ever need ---
template<unsigned npolar>
class TabuchiYamamoto
{
// default to a single sin theta quadrature
const unsigned npolar_;
const array<float, npolar> sinTheta;
const array<float, npolar> weights;
public:
inline unsigned nPolar(){ return npolar_; }
inline float getSinTheta(unsigned indx) { return sinTheta[indx]; }
inline float getWeight(unsigned indx) { return weights[indx]; }
explicit TabuchiYamamoto();
};
template<>
TabuchiYamamoto<1>::TabuchiYamamoto::TabuchiYamamoto() :
npolar_(1),
sinTheta({0.798184}),
weights({1.0})
{
}
template<>
TabuchiYamamoto<2>::TabuchiYamamoto::TabuchiYamamoto() :
npolar_(2),
sinTheta({0.363900,
0.899900}),
weights({0.212854,
0.787146})
{
}
template<>
TabuchiYamamoto<3>::TabuchiYamamoto::TabuchiYamamoto() :
npolar_(3),
sinTheta({0.166648,
0.537707,
0.932954}),
weights({0.046233,
0.283619,
0.670148})
{
}
// --- A ray in 2D space ---
class Ray2D
{
float x, y, phi, cosphi, sinphi;
// Restrict phi to [0,2pi)
void resetPhi();
public:
// two ways to construct
Ray2D(float thisx, float thisy, float thisphi);
Ray2D(Pt2D thisx, float thisphi);
// Advance to the next point
void advance(float newx, float newy);
void advance(Pt2D x);
// Reflects off a wall
void reflect_off_normal(float phi_normal);
float intersectXPlane(float xpos);
float intersectYPlane(float ypos);
// Set phi, updating cosphi and sinphi
void setPhi(float newphi);
// Get current 2D position
Pt2D getPosition();
// get unit direction
Pt2D getCosines();
// Check wheter the absolute value of the slope is relatively high,
// or relatively low. True if low.
bool hasLowSlopeValue();
// Since a ray has an infinite line associated with it,
// x and y should be calculable from each other. This
// is useful in finding cartesian grid intersections.
float y_from_x(float x);
float x_from_y(float y);
};
Ray2D::Ray2D(float thisx, float thisy, float thisphi) :
x(thisx),
y(thisy),
phi(thisphi),
cosphi(cos(phi)),
sinphi(sin(phi)) {}
Ray2D::Ray2D(Pt2D thisx, float thisphi) :
x(thisx.first),
y(thisx.second),
phi(thisphi),
cosphi(cos(phi)),
sinphi(sin(phi)) {}
void Ray2D::advance(float newx, float newy) { x = newx; y = newy; }
void Ray2D::advance(Pt2D newx) { x = newx.first; y = newx.second; }
void Ray2D::resetPhi()
{
constexpr float pi2 = 2.0 * M_PI;
if (phi >= pi2 or phi < 0.0)
{
float fractional_pos = phi / pi2;
int num_subtract = floor(fractional_pos);
phi -= num_subtract * pi2;
}
}
void Ray2D::reflect_off_normal(float phi_normal)
{
float newphi = -phi - M_PI + 2.0f * phi_normal;
setPhi(newphi);
}
void Ray2D::setPhi(float newphi)
{
phi = newphi;
resetPhi(); // Make sure in right interval
cosphi = cos(phi);
sinphi = sin(phi);
}
float Ray2D::intersectXPlane(float xpos) { return (xpos-x) / cosphi; }
float Ray2D::intersectYPlane(float ypos) { return (ypos-y) / sinphi; }
Pt2D Ray2D::getPosition() { return Pt2D(x,y); }
Pt2D Ray2D::getCosines() { return Pt2D(cosphi, sinphi); }
bool Ray2D::hasLowSlopeValue()
{
if ( phi <= M_PI / 4.0f
or
(phi >= 3.0 * M_PI / 4.0f and phi <= 5.0 * M_PI / 4.0f)
or
phi >= 7.0f * M_PI / 4.0f
) return true;
else return false;
}
float Ray2D::y_from_x(float thisx)
{
// Handle corner case
bool is_vertical = phi < M_PI/2.0 + EPS and phi > M_PI/2.0 - EPS;
is_vertical |= phi < M_PI*1.5f+EPS and phi > M_PI*1.5f - EPS;
if (is_vertical) return 0.0;
float m = tan(phi);
float b = y - m * x;
return m * thisx + b;
}
float Ray2D::x_from_y(float thisy)
{
// Handle corner case
bool is_horizontal = phi < EPS or phi > 2. * M_PI - EPS;
is_horizontal |= phi < M_PI*+EPS and phi > M_PI - EPS;
if (is_horizontal) return 0.0;
float m = 1.0f/tan(phi);
float b = x - m * y;
return m * thisy + b;
}
class Polygon
{
unsigned npoints;
unsigned pt_index;
vector<float> x;
vector<float> y;
public:
Polygon(unsigned np);
void add_point(float x, float y);
void add_point(Pt2D xy);
void checkFinished();
vector<Pt2D> getPoints();
void draw(gdImagePtr im, float square_size);
};
Polygon::Polygon(unsigned np) :
npoints(np),
pt_index(0),
x(np),
y(np)
{
}
void Polygon::add_point(float tx, float ty)
{
x[pt_index] = tx;
y[pt_index++] = ty;
}
void Polygon::add_point(pair<float,float> xy)
{
x[pt_index] = xy.first;
y[pt_index++] = xy.second;
}
void Polygon::checkFinished()
{
if (pt_index != npoints)
{
cerr << "Failed to fully construct polygon before use." << endl
<< pt_index + 1 << " points were added." << endl;
exit(1);
}
}
vector<pair<float,float>> Polygon::getPoints()
{
checkFinished();
vector<pair<float,float>> res(x.size());
int i = 0;
for (auto &p : res)
{
p.first = x[i];
p.second= y[i++];
}
return res;
}
void Polygon::draw(gdImagePtr im, float square_size)
{
checkFinished();
// Convert list of real coordinates to pixel coordinates
std::vector<unsigned> xp(x.size());
std::vector<unsigned> yp(x.size());
unsigned n_pix = gdImageSX(im);
float dx = square_size / n_pix;
for (unsigned i=0; i<x.size(); ++i)
{
int x0, y0;
x0 = (x[i] + square_size / 2.0) / dx;
y0 = (y[i] + square_size / 2.0) / dx;
// coodinates are from top left out
xp[i] = x0;
yp[i] = n_pix - y0;
}
int black = gdImageColorAllocate(im, 0, 0, 0);
unsigned i=0;
while (i<x.size()-1)
{
gdImageLine(im, xp[i], yp[i], xp[i+1], yp[i+1], black);
i++;
}
gdImageLine(im, xp[0], yp[0], xp[i], yp[i], black);
}
// Stores run settings
struct RunSettings
{
float ray_length, deadzone_length;
string xslibrary;
unsigned mesh_dimx;
unsigned ngroups;
unsigned raysperiteration;
unsigned ninactive;
unsigned nactive;
unsigned npolar;
public:
RunSettings(string inputfile);
};
RunSettings::RunSettings(string inputfile)
{
ifstream instream(inputfile);
string word;
while (instream >> word)
{
if (word == "deadlength")
instream >> deadzone_length;
else if (word == "raylength")
instream >> ray_length;
else if (word == "xslibrary")
instream >> xslibrary;
else if (word == "mesh_dimx")
instream >> mesh_dimx;
else if (word == "ngroups")
instream >> ngroups;
else if (word == "raysperiteration")
instream >> raysperiteration;
else if (word == "nactive")
instream >> nactive;
else if (word == "ninactive")
instream >> ninactive;
else if (word == "npolar")
instream >> npolar;
}
instream.close();
}
// Holds all of the macroscopic cross sections needed for a steady-state flux solution
struct Material
{
string name;
unsigned ngroups;
bool fissile;
vector<float> trans, abs, nuscat, chi, nufiss;
static const array<const string, 3> xs_types;
static const array<const string, 2> fiss_xs_types;
public:
Material(unsigned ngroups, bool fissile = false);
void setFissile();
};
const array<const string, 3> Material::xs_types = {"trans", "abs", "nuscat"} ;
const array<const string, 2> Material::fiss_xs_types = {"chi", "nufiss"};
Material::Material(unsigned thisngroups, bool thisfissile) :
ngroups(thisngroups),
fissile(thisfissile),
trans(ngroups),
abs(ngroups),
nuscat(ngroups*ngroups),
chi(fissile ? ngroups : 0),
nufiss(fissile ? ngroups : 0)
{
}
void Material::setFissile()
{
fissile = true;
chi.resize(ngroups);
nufiss.resize(ngroups);
}
// --- Implements the actual random ray algorithm ---
template<class G, class M, class Q>
class Solver2D
{
G geometry; // has to give next FSR ID given a ray
M materialSet; // has to return cross sections given an FSR ID
Q polarQuadrature;
RunSettings settings;
unsigned ngroups;
unsigned nfsr;
vector<float> fluxes;
vector<float> fiss_source;
vector<float> scat_source;
vector<float> cell_distance_traveled;
void calcSource();
void transportSweep();
/* These hold the cell ID numbers, and length traversed across
* each cell after a ray has been moved from a point to an edge */
unsigned max_fsr_crossings;
vector<int> fsr_crossing_ids;
vector<float> fsr_crossing_lengths;
public:
Solver2D(G geom, M materials, RunSettings setts);
float calcEigenvalue();
void printPeakingFactors();
/* run a ray starting from this given x0 and phi */
void run_ray(Pt2D x0, float phi, unsigned ray_id=0);
/* reference to geometry, for plotting and the like */
G& getGeom();
/* Set fission source at a single point */
void setSource(unsigned group, unsigned fsr_id, float value);
/* Calculate scattering source from current flux */
void scatter();
float fission(float k);
void zeroFlux();
// for dumping fields to files
void dumpFluxes(string fname);
void dumpScatter(string fname);
void dumpFission(string fname);
void normalizeFlux();
void normalizeByRelativeTraversalDistance();
void multiplyFlux(float x);
void addSourceToScalarFlux();
const vector<float>& getFlux() const;
};
template<class G, class M, class Q>
Solver2D<G, M, Q>::Solver2D(G geom, M materials, RunSettings setts) :
geometry(geom),
materialSet(materials),
settings(setts),
ngroups(setts.ngroups),
nfsr(setts.mesh_dimx * setts.mesh_dimx),
fluxes(setts.mesh_dimx * setts.mesh_dimx * ngroups, 1.0f),
fiss_source(fluxes.size(), 0.0f),
scat_source(fluxes.size(), 0.0f),
cell_distance_traveled(nfsr, 0.0f),
/* Calculate maximum possible number of FSRs that can be crossed as a ray
* goes from one boundary to the next. This list terminates with a -1 cell
* ID. */
max_fsr_crossings(2 * settings.mesh_dimx),
fsr_crossing_ids(max_fsr_crossings)
{
}
template <class G, class M, class Q>
const vector<float>& Solver2D<G, M, Q>::getFlux() const { return fluxes; }
template <class G, class M, class Q>
void Solver2D<G, M, Q>::normalizeFlux()
{
float sum_flux = 0.0;
// Loop over all fluxes
for (unsigned fsr=0; fsr<nfsr; ++fsr)
{
for (unsigned g=0; g<ngroups; ++g)
{
sum_flux += abs(fluxes[ngroups * fsr + g]);
}
}
if (sum_flux == 0.0f)
{
cerr << "Got zero flux when attempting to normalize flux." << endl;
exit(1);
}
transform(fluxes.begin(), fluxes.end(), fluxes.begin(),
bind(multiplies<float>(), placeholders::_1, 1.0f/sum_flux));
}
template <class G, class M, class Q>
void Solver2D<G, M, Q>::printPeakingFactors()
{
// The assumption here is that the nu value is
// pretty much constant throughout the problem
float cornerFission, edgeFission;
cornerFission = 0.0f;
edgeFission = 0.0f;
unsigned cellwide = geometry.mesh_dimx / 3;
// get corner pin fission rate
for (unsigned i=0; i<cellwide; ++i)
for (unsigned j=0; j<cellwide; ++j)
{
unsigned fsr = i*geometry.mesh_dimx + j;
string mat_name;
if (geometry.inside_fuel(fsr))
mat_name = "fuel";
else
mat_name = "mod";
const Material& mat = materialSet.getMaterial(mat_name);
if (not mat.fissile) continue;
const vector<float>& fiss = mat.nufiss;
for (unsigned g=0; g<ngroups; ++g)
cornerFission += fluxes[fsr*ngroups+g]*fiss[g];
}
// edge pin fission rate
for (unsigned i=0; i<cellwide; ++i)
for (unsigned j=cellwide; j<2*cellwide; ++j)
{
unsigned fsr = i*geometry.mesh_dimx + j;
string mat_name;
if (geometry.inside_fuel(fsr))
mat_name = "fuel";
else
mat_name = "mod";
const Material& mat = materialSet.getMaterial(mat_name);
if (not mat.fissile) continue;
const vector<float>& fiss = mat.nufiss;
for (unsigned g=0; g<ngroups; ++g)
edgeFission += fluxes[fsr*ngroups+g]*fiss[g];
}
// get peaking factors:
float avg = (cornerFission + edgeFission)/2.0f;
cout << "Corner pin peaking factor is " << cornerFission/avg << endl;
cout << "Edge pin peaking factor is " << edgeFission/avg << endl;
}
template <class G, class M, class Q>
void Solver2D<G, M, Q>::normalizeByRelativeTraversalDistance()
{
for (unsigned fsr=0; fsr<nfsr; ++fsr)
for (unsigned g=0; g<ngroups; ++g)
fluxes[fsr*ngroups + g] /= cell_distance_traveled[fsr];
fill(cell_distance_traveled.begin(), cell_distance_traveled.end(), 0.0f);
}
template <class G, class M, class Q>
void Solver2D<G, M, Q>::zeroFlux()
{
fill(fluxes.begin(), fluxes.end(), 0.0f);
}
template <class G, class M, class Q>
void Solver2D<G, M, Q>::addSourceToScalarFlux()
{
for (unsigned fsr=0; fsr<nfsr; ++fsr)
{
string mat_name;
if (geometry.inside_fuel(fsr))
mat_name = "fuel";
else
mat_name = "mod";
const Material& mat = materialSet.getMaterial(mat_name);
const vector<float>& sigmat = mat.trans;
for (unsigned g=0; g<ngroups; ++g)
{
unsigned indx = ngroups * fsr + g;
fluxes[indx] += (fiss_source[indx] + scat_source[indx]) / sigmat[g];
}
}
}
template <class G, class M, class Q>
void Solver2D<G, M, Q>::multiplyFlux(float x)
{
for (auto& f : fluxes) f *= x;
}
template <class G, class M, class Q>
void Solver2D<G, M, Q>::setSource(unsigned group, unsigned fsr_id, float value)
{
unsigned flux_id = ngroups * fsr_id + group;
fiss_source[flux_id] = value;
}
template <class G, class M, class Q>
void Solver2D<G, M, Q>::scatter()
{
for (unsigned fsr=0; fsr<nfsr; ++fsr)
{
string mat_name;
if (geometry.inside_fuel(fsr))
mat_name = "fuel";
else
mat_name = "mod";
const Material& mat = materialSet.getMaterial(mat_name);
const vector<float>& scatmat = mat.nuscat;
for (unsigned g=0; g<ngroups; ++g)
{
scat_source[ngroups * fsr + g] = 0.0f;
for (unsigned gprime=0; gprime<ngroups; ++gprime)
{
scat_source[ngroups * fsr + g] +=
scatmat[g*ngroups + gprime] * fluxes[ngroups * fsr + gprime];
}
}
}
}
template <class G, class M, class Q>
float Solver2D<G, M, Q>::fission(float k)
{
float fissionSource = 0.0;
for (unsigned fsr=0; fsr<nfsr; ++fsr)
{
string mat_name;
if (geometry.inside_fuel(fsr))
mat_name = "fuel";
else
{
mat_name = "mod";
continue;
}
const Material& mat = materialSet.getMaterial(mat_name);
const vector<float>& nusigf = mat.nufiss;
const vector<float>& chi = mat.chi;
// NOTE could be done more efficiently
for (unsigned g=0; g<ngroups; ++g)
{
fiss_source[ngroups * fsr + g] = 0.0f;
for (unsigned gprime=0; gprime<ngroups; ++gprime)
{
float this_fiss = chi[g] * fluxes[ngroups * fsr + gprime] * nusigf[gprime] / k;
fiss_source[ngroups * fsr + g] += this_fiss;
fissionSource += this_fiss;
}
}
}
return fissionSource;
}
template <class G, class M, class Q>
void Solver2D<G, M, Q>::run_ray(Pt2D x0, float phi, unsigned ray_id)
{
Ray2D ray(x0, phi);
float total_distance_remaining = settings.ray_length;
float dead_length_remaining = settings.deadzone_length;
float dist;
bool live = false;
unsigned npolar = polarQuadrature.nPolar();
constexpr float pi4 = 4.0f * M_PI;
float live_length = settings.ray_length - settings.deadzone_length;
// NOTE could give speed boost with std::array here
vector<float> track_fluxes(ngroups * npolar, 0.0);
// Loop over dead length (comments are in the live loop)
while (dead_length_remaining > 0.0)
{
dist = geometry.advance_to_boundary(ray, fsr_crossing_ids, fsr_crossing_lengths, ray_id);
for (unsigned s=0; s<fsr_crossing_ids.size(); ++s)
{
int fsr_id = fsr_crossing_ids[s];
float segment_length = fsr_crossing_lengths[s];
dead_length_remaining -= segment_length;
total_distance_remaining -= segment_length;
if (segment_length == 0.0f) continue;
string matname;
if (geometry.inside_fuel(fsr_id))
matname = "fuel";
else
matname = "mod";
const vector<float>& sigmat = materialSet.getMaterial(matname).trans;
for (unsigned g=0; g<ngroups; ++g) // groups
for (unsigned p=0; p<npolar; ++p) // polars
{
int scalar_flux_index = ngroups * fsr_id + g;
float tau = segment_length / polarQuadrature.getSinTheta(p) * sigmat[g];
float delta_psi = (track_fluxes[p+g*npolar] -
(fiss_source[scalar_flux_index] +
scat_source[scalar_flux_index])/(pi4*sigmat[g]))*
(1.0f - expf(-tau));
track_fluxes[p+g*npolar] -= delta_psi;
}
}
}
// Loop over live length
while (total_distance_remaining > 0.0)
{
dist = geometry.advance_to_boundary(ray, fsr_crossing_ids, fsr_crossing_lengths, ray_id);
for (unsigned s=0; s<fsr_crossing_ids.size(); ++s) // segments
{
int fsr_id = fsr_crossing_ids[s];
float segment_length = fsr_crossing_lengths[s];
total_distance_remaining -= segment_length;
if (segment_length == 0.0f) continue;
string matname;
if (geometry.inside_fuel(fsr_id))
matname = "fuel";
else
matname = "mod";
const vector<float>& sigmat = materialSet.getMaterial(matname).trans;
for (unsigned g=0; g<ngroups; ++g) // groups
for (unsigned p=0; p<npolar; ++p) // polars
{
int scalar_flux_index = ngroups * fsr_id + g;
float tau = segment_length / polarQuadrature.getSinTheta(p) * sigmat[g];
float delta_psi = (track_fluxes[p+g*npolar] -
(fiss_source[scalar_flux_index] +
scat_source[scalar_flux_index])/(pi4*sigmat[g]))*
(1.0f - expf(-tau));
fluxes[scalar_flux_index] += delta_psi / sigmat[g] * polarQuadrature.getWeight(p);
track_fluxes[p+g*npolar] -= delta_psi;
}
for (unsigned p=0; p<npolar; ++p)
cell_distance_traveled[fsr_id] += segment_length / polarQuadrature.getSinTheta(p)
* polarQuadrature.getWeight(p);
}
}
}
template <class G, class M, class Q>
G& Solver2D<G, M, Q>::getGeom() { return geometry; }
template <class G, class M, class Q>
void Solver2D<G, M, Q>::dumpFluxes(string fname)
{
ofstream f(fname, ofstream::out);
for (auto flx : fluxes) f << flx << endl;
f.close();
}
template <class G, class M, class Q>
void Solver2D<G, M, Q>::dumpScatter(string fname)
{
ofstream f(fname, ofstream::out);
for (auto flx : scat_source) f << flx << endl;
f.close();
}
template <class G, class M, class Q>
void Solver2D<G, M, Q>::dumpFission(string fname)
{
ofstream f(fname, ofstream::out);
for (auto flx : fiss_source) f << flx << endl;
f.close();
}
// Used for any scenario when only a finite amount of materials exist in
// a problem. This is anything without depletion, pretty much.
class FiniteMaterialSet
{
unsigned nmaterials;
vector<Material> materials;
map<string, unsigned> material_map;
void loadVector(vector<float>& to_vec, fs::path infile);
static unsigned getMaterialCount(string libname);
public:
const Material& getMaterial(string name);
FiniteMaterialSet(string xslib, unsigned ngroups);
};
void FiniteMaterialSet::loadVector(vector<float>& to_vec, fs::path infile)
{
// Checks correct number XS loaded
unsigned loadCount = 0;
ifstream instream(infile, ifstream::in);
if (not instream.good())
{
cerr << "cannot load " << infile << endl;
exit(1);
}
float value;
while (instream >> value)
{
to_vec[loadCount++] = value;
if (loadCount > to_vec.size())
{
cerr << "Tried to load too many XS from material " << infile << endl;
cerr << "too many groups or too few?" << endl;
exit(1);
}
}
if (loadCount != to_vec.size())
{
cerr << "too few xs values in " << infile << endl;
exit(1);
}
}
FiniteMaterialSet::FiniteMaterialSet(string xslib, unsigned ngroups) :
nmaterials(getMaterialCount(xslib)),
materials(nmaterials, Material(ngroups))
{
if (nmaterials == 0)
{
cout << "zero materials were found in xslib named: " << xslib << endl;
exit(1);
}
unsigned mat_indx = 0;
fs::path p(xslib);
for (const auto& entry : fs::directory_iterator(p))
{
// Load required XS
string materialname = entry.path().filename();
cout << "Processing material " << materialname << endl;
Material& mat = materials[mat_indx];
for (string xs_type : Material::xs_types)
{
loadVector(mat.trans, entry/"trans");
loadVector(mat.abs, entry/"abs");
loadVector(mat.nuscat, entry/"nuscat");
}
// Maybe load fissile XS
vector<bool> fissile_xs_present(Material::fiss_xs_types.size(), false);
unsigned fiss_i = 0;
for (string fiss_xs : Material::fiss_xs_types)
if (fs::exists(entry/fiss_xs)) fissile_xs_present[fiss_i++] = true;
bool no_fiss = none_of(fissile_xs_present.begin(), fissile_xs_present.end(),
[](bool x){ return x; });
bool all_fiss = any_of(fissile_xs_present.begin(), fissile_xs_present.end(),
[](bool x){ return x; });
if (not no_fiss ^ all_fiss) { cerr << "Some, but not all fiss. XS found. " << endl; exit(1); }
if (all_fiss)
{
mat.setFissile();
for (string fiss_xs : Material::fiss_xs_types)
{
loadVector(mat.chi, entry/"chi");
loadVector(mat.nufiss, entry/"nufiss");
}
}
pair<string, unsigned> mat_dict_entry(materialname, mat_indx++);
material_map.insert(mat_dict_entry);
}
}
const Material& FiniteMaterialSet::getMaterial(string name) { return materials[material_map[name]]; }
unsigned FiniteMaterialSet::getMaterialCount(string libname)
{
fs::path p(libname);
string filename;
unsigned nmaterials = 0;
// check all required cross sections present in each material
for (const auto& entry : fs::directory_iterator(p))
{
if (fs::is_directory(entry))
{
for (string xs_type : Material::xs_types)
if (not fs::exists(entry/xs_type))
{
cerr << "Required cross section " << xs_type <<
" not found in material " << entry << endl;
exit(1);
}
++nmaterials;
}
else
{
cerr << "Found non-directory file in xslib." << endl;
cerr << "That shouldn't be there. Name: " << entry << endl;
exit(1);
}
}
return nmaterials;
}
// --- A geometry class for the pedagogical fuel assembly in 22.212 ---
struct SquarePinGeom
{
unsigned mesh_dimx;
float mesh_dx;
array<unsigned, 6> index_endpoints;
// Prescribed fuel dimensions:
static constexpr float pitch = 1.2;
static constexpr float assembly_width = 3.0 * pitch;
static constexpr float assembly_radius = assembly_width / 2.0;
static constexpr float pin_width = pitch / 3.0;