-
Notifications
You must be signed in to change notification settings - Fork 655
Expand file tree
/
Copy pathcmfd.py
More file actions
2991 lines (2529 loc) · 120 KB
/
Copy pathcmfd.py
File metadata and controls
2991 lines (2529 loc) · 120 KB
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 can be used to specify parameters used for coarse mesh finite
difference (CMFD) acceleration in OpenMC. CMFD was first proposed by [Smith]_
and is widely used in accelerating neutron transport problems.
References
----------
.. [Smith] K. Smith, "Nodal method storage reduction by non-linear
iteration", *Trans. Am. Nucl. Soc.*, **44**, 265 (1983).
"""
from collections.abc import Iterable, Mapping
from contextlib import contextmanager
from numbers import Real, Integral
import sys
import time
import warnings
import h5py
import numpy as np
from scipy import sparse
import openmc.lib
from .checkvalue import (check_type, check_length, check_value,
check_greater_than, check_less_than)
from .exceptions import OpenMCError
from ._sparse_compat import csr_array
# See if mpi4py module can be imported, define have_mpi global variable
try:
from mpi4py import MPI
have_mpi = True
except ImportError:
have_mpi = False
# Maximum/minimum neutron energies
_ENERGY_MAX_NEUTRON = np.inf
_ENERGY_MIN_NEUTRON = 0.
# Tolerance for detecting zero flux values
_TINY_BIT = 1.e-8
# For non-accelerated regions on coarse mesh overlay
_CMFD_NOACCEL = -1
# Constant to represent a zero flux "albedo"
_ZERO_FLUX = 999.0
# Map that returns index of current direction in numpy current matrix
_CURRENTS = {
'out_left': 0, 'in_left': 1, 'out_right': 2, 'in_right': 3,
'out_back': 4, 'in_back': 5, 'out_front': 6, 'in_front': 7,
'out_bottom': 8, 'in_bottom': 9, 'out_top': 10, 'in_top': 11
}
class CMFDMesh:
"""A structured Cartesian mesh used for CMFD acceleration.
Attributes
----------
lower_left : Iterable of float
The lower-left corner of a regular structured mesh. If only two
coordinates are given, it is assumed that the mesh is an x-y mesh.
upper_right : Iterable of float
The upper-right corner of a regular structured mesh. If only two
coordinates are given, it is assumed that the mesh is an x-y mesh.
dimension : Iterable of int
The number of mesh cells in each direction for a regular structured
mesh.
width : Iterable of float
The width of mesh cells in each direction for a regular structured
mesh
energy : Iterable of float
Energy bins in eV, listed in ascending order (e.g. [0.0, 0.625e-1,
20.0e6]) for CMFD tallies and acceleration. If no energy bins are
listed, OpenMC automatically assumes a one energy group calculation
over the entire energy range.
albedo : Iterable of float
Surface ratio of incoming to outgoing partial currents on global
boundary conditions. They are listed in the following order: -x +x -y
+y -z +z.
map : Iterable of int
An optional acceleration map can be specified to overlay on the coarse
mesh spatial grid. If this option is used, a ``0`` is used for a
non-accelerated region and a ``1`` is used for an accelerated region.
For a simple 4x4 coarse mesh with a 2x2 fuel lattice surrounded by
reflector, the map is:
::
[0, 0, 0, 0,
0, 1, 1, 0,
0, 1, 1, 0,
0, 0, 0, 0]
Therefore a 2x2 system of equations is solved rather than a 4x4. This
is extremely important to use in reflectors as neutrons will not
contribute to any tallies far away from fission source neutron regions.
A ``1`` must be used to identify any fission source region.
mesh_type : str
Type of structured mesh to use. Acceptable values are:
* "regular" - Use RegularMesh to define CMFD mesh
* "rectilinear" - Use RectilinearMesh to define CMFD
grid : Iterable of Iterable of float
Grid used to define RectilinearMesh. First dimension must have length
3 where grid[0], grid[1], and grid[2] correspond to the x-, y-, and
z-grids respectively
"""
def __init__(self):
self._lower_left = None
self._upper_right = None
self._dimension = None
self._width = None
self._energy = None
self._albedo = None
self._map = None
self._mesh_type = 'regular'
self._grid = None
def __repr__(self):
outstr = type(self).__name__ + '\n'
if self._mesh_type == 'regular':
outstr += (self._get_repr(self._lower_left, "Lower left") + "\n" +
self._get_repr(self._upper_right, "Upper right") + "\n" +
self._get_repr(self._dimension, "Dimension") + "\n" +
self._get_repr(self._width, "Width") + "\n" +
self._get_repr(self._albedo, "Albedo"))
elif self._mesh_type == 'rectilinear':
outstr += (self._get_repr(self._grid[0], "X-grid") + "\n" +
self._get_repr(self._grid[1], "Y-grid") + "\n" +
self._get_repr(self._grid[2], "Z-grid"))
return outstr
def _get_repr(self, list_var, label):
outstr = f"\t{label:<11} = "
if list(list_var):
outstr += ", ".join(str(i) for i in list_var)
return outstr
@property
def lower_left(self):
return self._lower_left
@property
def upper_right(self):
return self._upper_right
@property
def dimension(self):
return self._dimension
@property
def width(self):
return self._width
@property
def energy(self):
return self._energy
@property
def albedo(self):
return self._albedo
@property
def map(self):
return self._map
@property
def mesh_type(self):
return self._mesh_type
@property
def grid(self):
return self._grid
@lower_left.setter
def lower_left(self, lower_left):
check_type('CMFD mesh lower_left', lower_left, Iterable, Real)
check_length('CMFD mesh lower_left', lower_left, 2, 3)
self._lower_left = lower_left
self._display_mesh_warning('regular', 'CMFD mesh lower_left')
@upper_right.setter
def upper_right(self, upper_right):
check_type('CMFD mesh upper_right', upper_right, Iterable, Real)
check_length('CMFD mesh upper_right', upper_right, 2, 3)
self._upper_right = upper_right
self._display_mesh_warning('regular', 'CMFD mesh upper_right')
@dimension.setter
def dimension(self, dimension):
check_type('CMFD mesh dimension', dimension, Iterable, Integral)
check_length('CMFD mesh dimension', dimension, 2, 3)
for d in dimension:
check_greater_than('CMFD mesh dimension', d, 0)
self._dimension = dimension
@width.setter
def width(self, width):
check_type('CMFD mesh width', width, Iterable, Real)
check_length('CMFD mesh width', width, 2, 3)
for w in width:
check_greater_than('CMFD mesh width', w, 0)
self._width = width
self._display_mesh_warning('regular', 'CMFD mesh width')
@energy.setter
def energy(self, energy):
check_type('CMFD mesh energy', energy, Iterable, Real)
for e in energy:
check_greater_than('CMFD mesh energy', e, 0, True)
self._energy = energy
@albedo.setter
def albedo(self, albedo):
check_type('CMFD mesh albedo', albedo, Iterable, Real)
check_length('CMFD mesh albedo', albedo, 6)
for a in albedo:
check_greater_than('CMFD mesh albedo', a, 0, True)
check_less_than('CMFD mesh albedo', a, 1, True)
self._albedo = albedo
@map.setter
def map(self, mesh_map):
check_type('CMFD mesh map', mesh_map, Iterable, Integral)
for m in mesh_map:
check_value('CMFD mesh map', m, [0, 1])
self._map = mesh_map
@mesh_type.setter
def mesh_type(self, mesh_type):
check_value('CMFD mesh type', mesh_type, ['regular', 'rectilinear'])
self._mesh_type = mesh_type
@grid.setter
def grid(self, grid):
grid_length = 3
dims = ['x', 'y', 'z']
check_length('CMFD mesh grid', grid, grid_length)
for i in range(grid_length):
check_type(f'CMFD mesh {dims[i]}-grid', grid[i], Iterable,
Real)
check_greater_than(f'CMFD mesh {dims[i]}-grid length',
len(grid[i]), 1)
self._grid = [np.array(g) for g in grid]
self._display_mesh_warning('rectilinear', 'CMFD mesh grid')
def _display_mesh_warning(self, mesh_type, variable_label):
if self._mesh_type != mesh_type:
warn_msg = (f'Setting {variable_label} if mesh type is not set to '
f'{mesh_type} will have no effect')
warnings.warn(warn_msg, RuntimeWarning)
class CMFDRun:
r"""Class for running CMFD acceleration through the C API.
Attributes
----------
tally_begin : int
Batch number at which CMFD tallies should begin accumulating
solver_begin: int
Batch number at which CMFD solver should start executing
ref_d : list of floats
List of reference diffusion coefficients to fix CMFD parameters to
display : dict
Dictionary indicating which CMFD results to output. Note that CMFD
k-effective will always be outputted. Acceptable keys are:
* "balance" - Whether to output RMS [%] of the residual from the
neutron balance equation on CMFD tallies (bool)
* "dominance" - Whether to output the estimated dominance ratio from
the CMFD iterations (bool)
* "entropy" - Whether to output the *entropy* of the CMFD predicted
fission source (bool)
* "source" - Whether to output the RMS [%] between the OpenMC fission
source and CMFD fission source (bool)
downscatter : bool
Indicate whether an effective downscatter cross section should be used
when using 2-group CMFD.
feedback : bool
Indicate whether or not the CMFD diffusion result is used to adjust the weight
of fission source neutrons on the next OpenMC batch. Defaults to False.
cmfd_ktol : float
Tolerance on the eigenvalue when performing CMFD power iteration
mesh : openmc.cmfd.CMFDMesh
Structured mesh to be used for acceleration
norm : float
Normalization factor applied to the CMFD fission source distribution
power_monitor : bool
View convergence of power iteration during CMFD acceleration
run_adjoint : bool
Perform adjoint calculation on the last batch
w_shift : float
Optional Wielandt shift parameter for accelerating power iterations. By
default, it is very large so there is effectively no impact.
stol : float
Tolerance on the fission source when performing CMFD power iteration
reset : list of int
List of batch numbers at which CMFD tallies should be reset
write_matrices : bool
Write sparse matrices that are used during CMFD acceleration (loss,
production) and resultant normalized flux vector phi to file
spectral : float
Optional spectral radius that can be used to accelerate the convergence
of Gauss-Seidel iterations during CMFD power iteration.
gauss_seidel_tolerance : Iterable of float
Two parameters specifying the absolute inner tolerance and the relative
inner tolerance for Gauss-Seidel iterations when performing CMFD.
adjoint_type : {'physical', 'math'}
Stores type of adjoint calculation that should be performed.
``run_adjoint`` must be true for an adjoint calculation to be
performed. Options are:
* "physical" - Create adjoint matrices from physical parameters of
CMFD problem
* "math" - Create adjoint matrices mathematically as the transpose of
loss and production CMFD matrices
window_type : {'expanding', 'rolling', 'none'}
Specifies type of tally window scheme to use to accumulate CMFD
tallies. Options are:
* "expanding" - Have an expanding window that doubles in size
to give more weight to more recent tallies as more generations are
simulated
* "rolling" - Have a fixed window size that aggregates tallies from
the same number of previous generations tallied
* "none" - Don't use a windowing scheme so that all tallies from last
time they were reset are used for the CMFD algorithm.
window_size : int
Size of window to use for tally window scheme. Only relevant when
window_type is set to "rolling"
indices : numpy.ndarray
Stores spatial and group dimensions as [nx, ny, nz, ng]
cmfd_src : numpy.ndarray
CMFD source distribution calculated from solving CMFD equations
entropy : list of floats
"Shannon entropy" from CMFD fission source, stored for each generation
that CMFD is invoked
balance : list of floats
RMS of neutron balance equations, stored for each generation that CMFD
is invoked
src_cmp : list of floats
RMS deviation of OpenMC and CMFD normalized source, stored for each
generation that CMFD is invoked
dom : list of floats
Dominance ratio from solving CMFD matrix equations, stored for each
generation that CMFD is invoked
k_cmfd : list of floats
List of CMFD k-effectives, stored for each generation that CMFD is
invoked
time_cmfd : float
Time for entire CMFD calculation, in seconds
time_cmfdbuild : float
Time for building CMFD matrices, in seconds
time_cmfdsolve : float
Time for solving CMFD matrix equations, in seconds
use_all_threads : bool
Whether to use all threads allocated to OpenMC for CMFD solver
intracomm : mpi4py.MPI.Intracomm or None
MPI intercommunicator for running MPI commands
"""
def __init__(self):
"""Constructor for CMFDRun class. Default values for instance variables
set in this method.
"""
# Variables that users can modify
self._tally_begin = 1
self._solver_begin = 1
self._ref_d = np.array([])
self._display = {'balance': False, 'dominance': False,
'entropy': False, 'source': False}
self._downscatter = False
self._feedback = False
self._cmfd_ktol = 1.e-8
self._mesh = None
self._norm = 1.
self._power_monitor = False
self._run_adjoint = False
self._w_shift = 1.e6
self._stol = 1.e-8
self._reset = []
self._write_matrices = False
self._spectral = 0.0
self._gauss_seidel_tolerance = [1.e-10, 1.e-5]
self._adjoint_type = 'physical'
self._window_type = 'none'
self._window_size = 10
self._intracomm = None
self._use_all_threads = False
# External variables used during runtime but users cannot control
self._set_reference_params = False
self._indices = np.zeros(4, dtype=np.int32)
self._egrid = None
self._albedo = None
self._coremap = None
self._mesh_id = None
self._tally_ids = None
self._energy_filters = None
self._cmfd_on = False
self._mat_dim = _CMFD_NOACCEL
self._keff_bal = None
self._keff = None
self._adj_keff = None
self._phi = None
self._adj_phi = None
self._openmc_src_rate = None
self._flux_rate = None
self._total_rate = None
self._p1scatt_rate = None
self._scatt_rate = None
self._nfiss_rate = None
self._current_rate = None
self._flux = None
self._totalxs = None
self._p1scattxs = None
self._scattxs = None
self._nfissxs = None
self._diffcof = None
self._dtilde = None
self._dhat = None
self._hxyz = None
self._current = None
self._cmfd_src = None
self._openmc_src = None
self._entropy = []
self._balance = []
self._src_cmp = []
self._dom = []
self._k_cmfd = []
self._resnb = None
self._reset_every = None
self._time_cmfd = None
self._time_cmfdbuild = None
self._time_cmfdsolve = None
# All index-related variables, for numpy vectorization
self._first_x_accel = None
self._last_x_accel = None
self._first_y_accel = None
self._last_y_accel = None
self._first_z_accel = None
self._last_z_accel = None
self._notfirst_x_accel = None
self._notlast_x_accel = None
self._notfirst_y_accel = None
self._notlast_y_accel = None
self._notfirst_z_accel = None
self._notlast_z_accel = None
self._is_adj_ref_left = None
self._is_adj_ref_right = None
self._is_adj_ref_back = None
self._is_adj_ref_front = None
self._is_adj_ref_bottom = None
self._is_adj_ref_top = None
self._accel_idxs = None
self._accel_neig_left_idxs = None
self._accel_neig_right_idxs = None
self._accel_neig_back_idxs = None
self._accel_neig_front_idxs = None
self._accel_neig_bot_idxs = None
self._accel_neig_top_idxs = None
self._loss_row = None
self._loss_col = None
self._prod_row = None
self._prod_col = None
@property
def tally_begin(self):
return self._tally_begin
@property
def solver_begin(self):
return self._solver_begin
@property
def ref_d(self):
return self._ref_d
@property
def display(self):
return self._display
@property
def downscatter(self):
return self._downscatter
@property
def feedback(self):
return self._feedback
@property
def cmfd_ktol(self):
return self._cmfd_ktol
@property
def mesh(self):
return self._mesh
@property
def norm(self):
return self._norm
@property
def adjoint_type(self):
return self._adjoint_type
@property
def window_type(self):
return self._window_type
@property
def window_size(self):
return self._window_size
@property
def power_monitor(self):
return self._power_monitor
@property
def run_adjoint(self):
return self._run_adjoint
@property
def w_shift(self):
return self._w_shift
@property
def stol(self):
return self._stol
@property
def spectral(self):
return self._spectral
@property
def reset(self):
return self._reset
@property
def write_matrices(self):
return self._write_matrices
@property
def gauss_seidel_tolerance(self):
return self._gauss_seidel_tolerance
@property
def indices(self):
return self._indices
@property
def use_all_threads(self):
return self._use_all_threads
@property
def cmfd_src(self):
return self._cmfd_src
@property
def dom(self):
return self._dom
@property
def src_cmp(self):
return self._src_cmp
@property
def balance(self):
return self._balance
@property
def entropy(self):
return self._entropy
@property
def k_cmfd(self):
return self._k_cmfd
@tally_begin.setter
def tally_begin(self, begin):
check_type('CMFD tally begin batch', begin, Integral)
check_greater_than('CMFD tally begin batch', begin, 0)
self._tally_begin = begin
@solver_begin.setter
def solver_begin(self, begin):
check_type('CMFD feedback begin batch', begin, Integral)
check_greater_than('CMFD feedback begin batch', begin, 0)
self._solver_begin = begin
@ref_d.setter
def ref_d(self, diff_params):
check_type('Reference diffusion params', diff_params,
Iterable, Real)
self._ref_d = np.array(diff_params)
@display.setter
def display(self, display):
check_type('display', display, Mapping)
for key, value in display.items():
check_value('display key', key,
('balance', 'entropy', 'dominance', 'source'))
check_type(f"display['{key}']", value, bool)
self._display[key] = value
@downscatter.setter
def downscatter(self, downscatter):
check_type('CMFD downscatter', downscatter, bool)
self._downscatter = downscatter
@feedback.setter
def feedback(self, feedback):
check_type('CMFD feedback', feedback, bool)
self._feedback = feedback
@cmfd_ktol.setter
def cmfd_ktol(self, cmfd_ktol):
check_type('CMFD eigenvalue tolerance', cmfd_ktol, Real)
self._cmfd_ktol = cmfd_ktol
@mesh.setter
def mesh(self, cmfd_mesh):
check_type('CMFD mesh', cmfd_mesh, CMFDMesh)
if cmfd_mesh.mesh_type == 'regular':
# Check dimension defined
if cmfd_mesh.dimension is None:
raise ValueError('CMFD regular mesh requires spatial '
'dimensions to be specified')
# Check lower left defined
if cmfd_mesh.lower_left is None:
raise ValueError('CMFD regular mesh requires lower left '
'coordinates to be specified')
# Check that both upper right and width both not defined
if cmfd_mesh.upper_right is not None and cmfd_mesh.width is not None:
raise ValueError('Both upper right coordinates and width '
'cannot be specified for CMFD regular mesh')
# Check that at least one of width or upper right is defined
if cmfd_mesh.upper_right is None and cmfd_mesh.width is None:
raise ValueError('CMFD regular mesh requires either upper right '
'coordinates or width to be specified')
# Check width and lower length are same dimension and define
# upper_right
if cmfd_mesh.width is not None:
check_length('CMFD mesh width', cmfd_mesh.width,
len(cmfd_mesh.lower_left))
cmfd_mesh.upper_right = np.array(cmfd_mesh.lower_left) + \
np.array(cmfd_mesh.width) * np.array(cmfd_mesh.dimension)
# Check upper_right and lower length are same dimension and define
# width
elif cmfd_mesh.upper_right is not None:
check_length('CMFD mesh upper right', cmfd_mesh.upper_right,
len(cmfd_mesh.lower_left))
# Check upper right coordinates are greater than lower left
if np.any(np.array(cmfd_mesh.upper_right) <=
np.array(cmfd_mesh.lower_left)):
raise ValueError('CMFD regular mesh requires upper right '
'coordinates to be greater than lower '
'left coordinates')
cmfd_mesh.width = np.true_divide((np.array(cmfd_mesh.upper_right) -
np.array(cmfd_mesh.lower_left)),
np.array(cmfd_mesh.dimension))
elif cmfd_mesh.mesh_type == 'rectilinear':
# Check dimension defined
if cmfd_mesh.grid is None:
raise ValueError('CMFD rectilinear mesh requires spatial '
'grid to be specified')
cmfd_mesh.dimension = [len(cmfd_mesh.grid[i]) - 1 for i in range(3)]
self._mesh = cmfd_mesh
@norm.setter
def norm(self, norm):
check_type('CMFD norm', norm, Real)
self._norm = norm
@adjoint_type.setter
def adjoint_type(self, adjoint_type):
check_type('CMFD adjoint type', adjoint_type, str)
check_value('CMFD adjoint type', adjoint_type,
['math', 'physical'])
self._adjoint_type = adjoint_type
@window_type.setter
def window_type(self, window_type):
check_type('CMFD window type', window_type, str)
check_value('CMFD window type', window_type,
['none', 'rolling', 'expanding'])
self._window_type = window_type
@window_size.setter
def window_size(self, window_size):
check_type('CMFD window size', window_size, Integral)
check_greater_than('CMFD window size', window_size, 0)
if self._window_type != 'rolling':
warn_msg = 'Window size will have no effect on CMFD simulation ' \
'unless window type is set to "rolling".'
warnings.warn(warn_msg, RuntimeWarning)
self._window_size = window_size
@power_monitor.setter
def power_monitor(self, power_monitor):
check_type('CMFD power monitor', power_monitor, bool)
self._power_monitor = power_monitor
@run_adjoint.setter
def run_adjoint(self, run_adjoint):
check_type('CMFD run adjoint', run_adjoint, bool)
self._run_adjoint = run_adjoint
@w_shift.setter
def w_shift(self, w_shift):
check_type('CMFD Wielandt shift', w_shift, Real)
self._w_shift = w_shift
@stol.setter
def stol(self, stol):
check_type('CMFD fission source tolerance', stol, Real)
self._stol = stol
@spectral.setter
def spectral(self, spectral):
check_type('CMFD spectral radius', spectral, Real)
self._spectral = spectral
@reset.setter
def reset(self, reset):
check_type('tally reset batches', reset, Iterable, Integral)
self._reset = reset
@write_matrices.setter
def write_matrices(self, write_matrices):
check_type('CMFD write matrices', write_matrices, bool)
self._write_matrices = write_matrices
@gauss_seidel_tolerance.setter
def gauss_seidel_tolerance(self, gauss_seidel_tolerance):
check_type('CMFD Gauss-Seidel tolerance', gauss_seidel_tolerance,
Iterable, Real)
check_length('Gauss-Seidel tolerance', gauss_seidel_tolerance, 2)
self._gauss_seidel_tolerance = gauss_seidel_tolerance
@use_all_threads.setter
def use_all_threads(self, use_all_threads):
check_type('CMFD use all threads', use_all_threads, bool)
self._use_all_threads = use_all_threads
def run(self, **kwargs):
"""Run OpenMC with coarse mesh finite difference acceleration
This method is called by the user to run CMFD once instance variables of
CMFDRun class are set
Parameters
----------
**kwargs
All keyword arguments are passed to
:func:`openmc.lib.run_in_memory`.
"""
with self.run_in_memory(**kwargs):
for _ in self.iter_batches():
pass
@contextmanager
def run_in_memory(self, **kwargs):
""" Context manager for running CMFD functions with OpenMC shared
library functions.
This function can be used with a 'with' statement to ensure the
CMFDRun class is properly initialized/finalized. For example::
from openmc import cmfd
cmfd_run = cmfd.CMFDRun()
with cmfd_run.run_in_memory():
do_stuff_before_simulation_start()
for _ in cmfd_run.iter_batches():
do_stuff_between_batches()
Parameters
----------
**kwargs
All keyword arguments passed to :func:`openmc.lib.run_in_memory`.
"""
# Store intracomm for part of CMFD routine where MPI reduce and
# broadcast calls are made
if 'intracomm' in kwargs and kwargs['intracomm'] is not None:
self._intracomm = kwargs['intracomm']
elif have_mpi:
self._intracomm = MPI.COMM_WORLD
# Run and pass arguments to C API run_in_memory function
with openmc.lib.run_in_memory(**kwargs):
self.init()
yield
self.finalize()
def iter_batches(self):
""" Iterator over batches.
This function returns a generator-iterator that allows Python code to
be run between batches when running an OpenMC simulation with CMFD.
It should be used in conjunction with
:func`openmc.cmfd.CMFDRun.run_in_memory` to ensure proper
initialization/finalization of CMFDRun instance.
"""
status = 0
while status == 0:
status = self.next_batch()
yield
def init(self):
""" Initialize CMFDRun instance by setting up CMFD parameters and
calling :func:`openmc.lib.simulation_init`
"""
# Configure CMFD parameters
self._configure_cmfd()
# Create tally objects
self._create_cmfd_tally()
if openmc.lib.master():
# Compute and store array indices used to build cross section
# arrays
self._precompute_array_indices()
# Compute and store row and column indices used to build CMFD
# matrices
self._precompute_matrix_indices()
# Initialize all variables used for linear solver in C++
self._initialize_linsolver()
# Initialize simulation
openmc.lib.simulation_init()
# Set cmfd_run variable to True through C API
openmc.lib.settings.cmfd_run = True
def next_batch(self):
""" Run next batch for CMFDRun.
Returns
-------
int
Status after running a batch (0=normal, 1=reached maximum number of
batches, 2=tally triggers reached)
"""
# Initialize CMFD batch
self._cmfd_init_batch()
# Run next batch
status = openmc.lib.next_batch()
# Perform CMFD calculations
self._execute_cmfd()
# Write CMFD data to statepoint
if openmc.lib.is_statepoint_batch():
self.statepoint_write()
return status
def finalize(self):
""" Finalize simulation by calling
:func:`openmc.lib.simulation_finalize` and print out CMFD timing
information.
"""
# Finalize simulation
openmc.lib.simulation_finalize()
if openmc.lib.master():
# Print out CMFD timing statistics
self._write_cmfd_timing_stats()
def statepoint_write(self, filename=None):
"""Write all simulation parameters to statepoint
Parameters
----------
filename : str
Filename of statepoint
"""
if filename is None:
batch_str_len = len(str(openmc.lib.settings.get_batches()))
batch_str = str(openmc.lib.current_batch()).zfill(batch_str_len)
filename = f'statepoint.{batch_str}.h5'
# Call C API statepoint_write to save source distribution with CMFD
# feedback
openmc.lib.statepoint_write(filename=filename)
# Append CMFD data to statepoint file using h5py
self._write_cmfd_statepoint(filename)
def _write_cmfd_statepoint(self, filename):
"""Append all CNFD simulation parameters to existing statepoint
Parameters
----------
filename : str
Filename of statepoint
"""
if openmc.lib.master():
with h5py.File(filename, 'a') as f:
if 'cmfd' not in f:
if openmc.lib.settings.verbosity >= 5:
print(f' Writing CMFD data to {filename}...')
sys.stdout.flush()
cmfd_group = f.create_group("cmfd")
cmfd_group.attrs['cmfd_on'] = self._cmfd_on
cmfd_group.attrs['feedback'] = self._feedback
cmfd_group.attrs['solver_begin'] = self._solver_begin
cmfd_group.attrs['mesh_id'] = self._mesh_id
cmfd_group.attrs['tally_begin'] = self._tally_begin
cmfd_group.attrs['time_cmfd'] = self._time_cmfd
cmfd_group.attrs['time_cmfdbuild'] = self._time_cmfdbuild
cmfd_group.attrs['time_cmfdsolve'] = self._time_cmfdsolve
cmfd_group.attrs['window_size'] = self._window_size
cmfd_group.attrs['window_type'] = self._window_type
cmfd_group.create_dataset('k_cmfd', data=self._k_cmfd)
cmfd_group.create_dataset('dom', data=self._dom)
cmfd_group.create_dataset('src_cmp', data=self._src_cmp)
cmfd_group.create_dataset('balance', data=self._balance)
cmfd_group.create_dataset('entropy', data=self._entropy)
cmfd_group.create_dataset('reset', data=self._reset)
cmfd_group.create_dataset('albedo', data=self._albedo)
cmfd_group.create_dataset('coremap', data=self._coremap)
cmfd_group.create_dataset('egrid', data=self._egrid)
cmfd_group.create_dataset('indices', data=self._indices)
cmfd_group.create_dataset('tally_ids',
data=self._tally_ids)
cmfd_group.create_dataset('current_rate',
data=self._current_rate)
cmfd_group.create_dataset('flux_rate',
data=self._flux_rate)
cmfd_group.create_dataset('nfiss_rate',
data=self._nfiss_rate)
cmfd_group.create_dataset('openmc_src_rate',
data=self._openmc_src_rate)
cmfd_group.create_dataset('p1scatt_rate',
data=self._p1scatt_rate)
cmfd_group.create_dataset('scatt_rate',
data=self._scatt_rate)
cmfd_group.create_dataset('total_rate',
data=self._total_rate)
elif openmc.settings.verbosity >= 5:
print(' CMFD data not written to statepoint file as it '
'already exists in {}'.format(filename), flush=True)
def _initialize_linsolver(self):
# Determine number of rows in CMFD matrix
ng = self._indices[3]
n = self._mat_dim*ng
# Create temp loss matrix to pass row/col indices to C++ linear solver
loss_row = self._loss_row
loss_col = self._loss_col
temp_data = np.ones(len(loss_row))
temp_loss = csr_array((temp_data, (loss_row, loss_col)), shape=(n, n))
temp_loss.sort_indices()
# Pass coremap as 1-d array of 32-bit integers
coremap = np.swapaxes(self._coremap, 0, 2).flatten().astype(np.int32)
return openmc.lib._dll.openmc_initialize_linsolver(
temp_loss.indptr.astype(np.int32), len(temp_loss.indptr),
temp_loss.indices.astype(np.int32), len(temp_loss.indices), n,
self._spectral, coremap, self._use_all_threads
)
def _write_cmfd_output(self):
"""Write CMFD output to buffer at the end of each batch"""
# Display CMFD k-effective
outstr = '{:>11s}CMFD k: {:0.5f}'.format('', self._k_cmfd[-1])
# Display value of additional fields based on display dict