/
geometryConverters.py
1501 lines (1297 loc) · 57.5 KB
/
geometryConverters.py
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
# Copyright 2019 TerraPower, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Change a reactor from one geometry to another.
Examples may include going from Hex to R-Z or from Third-core to full core. This module
contains **converters** (which create new reactor objects with different geometry), and
**changers** (which modify a given reactor in place) in this module.
Generally, mass is conserved in geometry conversions.
.. warning:: These are mostly designed for hex geometry.
"""
import collections
import copy
import math
import matplotlib
import matplotlib.pyplot as plt
import numpy
import operator
import os
from armi import materials
from armi import runLog
from armi.reactor import assemblies
from armi.reactor import blocks
from armi.reactor import components
from armi.reactor import reactors
from armi.reactor import parameters
from armi.reactor.parameters import Category
from armi.reactor.parameters import ParamLocation
from armi.reactor.parameters import NEVER
from armi.reactor.parameters import SINCE_LAST_GEOMETRY_TRANSFORMATION
from armi.reactor import geometry
from armi.reactor.converters import meshConverters
from armi.utils import plotting
from armi.utils import units
from armi.reactor import grids
from armi.reactor.flags import Flags
from armi.utils import hexagon
from armi.reactor.converters import blockConverters
BLOCK_AXIAL_MESH_SPACING = (
20 # Block axial mesh spacing set for nodal diffusion calculation (cm)
)
STR_SPACE = " "
class GeometryChanger:
"""Geometry changer class that updates the geometry (number of assems or blocks per assem) of a given reactor."""
def __init__(self, cs=None, quiet=False):
self._newAssembliesAdded = []
self._sourceReactor = None
self._cs = cs
self._assemblyModuleCounter = assemblies.getAssemNum()
if not quiet:
self._writeAssemblyModuleCounter()
def __repr__(self):
return "<{}>".format(self.__class__.__name__)
def getNewAssembliesAdded(self):
return self._newAssembliesAdded
def getAssemblyModuleCounter(self):
return self._assemblyModuleCounter
def _writeAssemblyModuleCounter(self):
runLog.debug(
"Assembly Module Counter is {}".format(self._assemblyModuleCounter)
)
def convert(self, r=None):
"""
Run the conversion.
Parameters
----------
r : Reactor object
The reactor to convert.
Returns
-------
convReactor : Reactor object
the converted reactor (converters only, not changers)
"""
raise NotImplementedError
class GeometryConverter(GeometryChanger):
"""
Base class for GeometryConverter which makes a new converted reactor.
Examples
--------
To convert a hex case to a R-Z case, do this:
>>> geomConv = armi.reactorConverters.HexToRZConverter(useMostCommonXsId=False, expandReactor=False)
>>> geomConv.convert(r)
>>> newR = geomConv.convReactor
>>> dif3d = dif3dInterface.Dif3dInterface('dif3dRZ', newR)
>>> dif3d.o = self.o
>>> dif3d.writeInput('rzGeom_actual.inp')
"""
def __init__(self, cs=None, quiet=False):
GeometryChanger.__init__(self, cs=cs, quiet=quiet)
self.convReactor = None
class FuelAssemNumModifier(GeometryChanger):
"""
Modify the number of fuel assemblies in the reactor.
Notes
-----
- The number of fuel assemblies should ALWAYS be set for the third-core regardless of the reactor geometry model.
- The modification is only valid for third-core and full-core geometry models.
"""
def __init__(self, cs):
GeometryChanger.__init__(self, cs)
self.numFuelAssems = None # in full core.
self.fuelType = "feed fuel"
self.overwriteList = [Flags.REFLECTOR, Flags.SHIELD]
self.ringsToAdd = []
self.modifyReactorPower = False
def convert(self, r=None):
"""
Set the number of fuel assemblies in the reactor.
Notes
-----
- While adding fuel, does not modify existing fuel/control positions, but does overwrite assemblies in the
overwriteList (e.g. reflectors, shields)
- Once specified amount of fuel is in place, removes all assemblies past the outer fuel boundary
- To re-add reflector/shield assemblies around the new core, use the ringsToAdd attribute
"""
self._sourceReactor = r
if r.core.powerMultiplier != 1 and r.core.powerMultiplier != 3:
raise ValueError(
"Invalid reactor geometry {} in {}. Reactor must be full or third core to modify the "
"number of assemblies.".format(r.core.powerMultiplier, self)
)
# Set the number of fueled and non-fueled positions within the core (Full core or third-core)
coreGeom = "full-core" if r.core.powerMultiplier == 1 else "third-core"
runLog.info(
"Modifying {} geometry to have {} fuel assemblies.".format(
coreGeom, self.numFuelAssems
)
)
nonFuelAssems = (
sum(not assem.hasFlags(Flags.FUEL) for assem in r.core)
* r.core.powerMultiplier
)
self.numFuelAssems *= r.core.powerMultiplier
totalCoreAssems = nonFuelAssems + self.numFuelAssems
# Adjust the total power of the reactor by keeping power per assembly constant
if self.modifyReactorPower:
r.core.p.power *= float(self.numFuelAssems) / (
len(r.core.getAssemblies(Flags.FUEL)) * r.core.powerMultiplier
)
# Get the sorted assembly locations in the core (Full core or third core)
assemOrderList = r.core.spatialGrid.generateSortedHexLocationList(
totalCoreAssems
)
if r.core.powerMultiplier == 3:
assemOrderList = [
loc for loc in assemOrderList if r.core.spatialGrid.isInFirstThird(loc)
]
# Add fuel assemblies to the core
addingFuelIsComplete = False
numFuelAssemsAdded = 0
for loc in assemOrderList:
assem = r.core.childrenByLocator.get(loc)
if numFuelAssemsAdded < self.numFuelAssems:
if assem is None:
raise KeyError("Cannot find expected fuel assem in {}".format(loc))
# Add new fuel assembly to the core
if assem.hasFlags(self.overwriteList):
fuelAssem = r.core.createAssemblyOfType(assemType=self.fuelType)
# Remove existing assembly in the core location before adding new assembly
if assem.hasFlags(self.overwriteList):
r.core.removeAssembly(assem, discharge=False)
r.core.add(fuelAssem, loc)
numFuelAssemsAdded += r.core.powerMultiplier
else:
# Keep the existing assembly in the core
if assem.hasFlags(Flags.FUEL):
# Count the assembly in the location if it is fuel
numFuelAssemsAdded += r.core.powerMultiplier
else:
pass
# Flag the completion of adding fuel assemblies (see note 1)
elif numFuelAssemsAdded == self.numFuelAssems:
addingFuelIsComplete = True
# Remove the remaining assemblies in the the assembly list once all the fuel has been added
if addingFuelIsComplete and assem is not None:
r.core.removeAssembly(assem, discharge=False)
# Remove all other assemblies from the core
for assem in r.core.getAssemblies():
if (
assem.spatialLocator not in assemOrderList
): # check if assembly is on the list
r.core.removeAssembly(
assem, discharge=False
) # get rid of the old assembly
# Add the remaining rings of assemblies to the core
for assemType in self.ringsToAdd:
self.addRing(assemType=assemType)
# Complete the reactor loading
r.core.processLoading(self._cs) # pylint: disable=protected-access
r.core.numRings = r.core.getNumRings()
r.core.regenAssemblyLists()
r.core.circularRingList = None # need to reset this (possibly other stuff too)
def addRing(self, assemType="big shield"):
r"""
Add a ring of fuel assemblies around the outside of an existing core
Works by first finding the assembly furthest from the center, then filling in
all assemblies that are within one pitch further with the specified assembly type
Parameters
----------
assemType : str
Assembly type that will be added to the outside of the core
"""
r = self._sourceReactor
# first look through the core and finds the one farthest from the center
maxDist = 0.0
for assem in r.core.getAssemblies():
dist = numpy.linalg.norm(
assem.spatialLocator.getGlobalCoordinates()
) # get distance from origin
dist = round(
dist, 6
) # round dist to 6 places to avoid differences due to floating point math
maxDist = max(maxDist, dist)
# add one hex pitch to the maximum distance to get the bounding distance for the new ring
hexPitch = r.core.spatialGrid.pitch
newRingDist = maxDist + hexPitch
maxArea = (
math.pi * (newRingDist + hexPitch) ** 2.0
) # area that is guaranteed to bound the new core
maxAssemsFull = maxArea / hexagon.area(
hexPitch
) # divide by hex area to get number of hexes in a full core
# generate ordered list of assembly locations
assemOrderList = r.core.spatialGrid.generateSortedHexLocationList(maxAssemsFull)
if r.core.powerMultiplier == 3:
assemOrderList = [
loc
for loc in assemOrderList
if self._sourceReactor.core.spatialGrid.isInFirstThird(loc)
]
elif r.core.powerMultiplier != 1:
raise RuntimeError("{} only works on full or 1/3 symmetry.".format(self))
# add new assemblies to core within one ring
for locator in assemOrderList:
assem = r.core.childrenByLocator.get(
locator
) # check on assemblies, moving radially outward
dist = numpy.linalg.norm(locator.getGlobalCoordinates())
dist = round(dist, 6)
if dist <= newRingDist: # check distance
if assem is None: # no assembly in that position, add assembly
newAssem = r.core.createAssemblyOfType(
assemType=assemType
) # create a fuel assembly
r.core.add(newAssem, locator) # put new assembly in reactor!
else: # all other types of assemblies (fuel, control, etc) leave as is
pass
else:
pass
class HexToRZThetaConverter(GeometryConverter):
"""
Convert hex-based cases to an equivalent R-Z-Theta full core geometry.
Parameters
----------
converterSettings: dict
Settings that specify how the mesh of the RZTheta reactor should be generated.
Controls the number of theta regions, how to group regions, etc.
uniformThetaMesh
bool flag that determines if the theta mesh should be uniform or not
thetaBins
Number of theta bins to create
radialConversionType
* ``Ring Compositions`` -- to convert by composition
axialConversionType
* ``Axial Coordinates`` -- use :py:class:`armi.reactor.converters.meshConverters._RZThetaReactorMeshConverterByAxialCoordinates`
* ``Axial Bins`` -- use :py:class:`armi.reactor.converters.meshConverters._RZThetaReactorMeshConverterByAxialBins`
expandReactor : bool
If True, the HEX-Z reactor will be expanded to full core geometry prior to converting to the RZT reactor.
Either way the converted RZTheta core will be full core.
strictHomogenization : bool
If True, the converter will restrict HEX-Z blocks with dissimilar XS types from being homogenized into an
RZT block.
"""
_GEOMETRY_TYPE = geometry.GeomType.RZT
_SYMMETRY_TYPE = geometry.SymmetryType(
domainType=geometry.DomainType.FULL_CORE,
boundaryType=geometry.BoundaryType.NO_SYMMETRY,
)
_BLOCK_MIXTURE_TYPE_MAP = {
"mixture control": ["control"],
"mixture fuel": ["fuel"],
"mixture radial shield": ["radial shield"],
"mixture axial shield": ["shield"],
"mixture structure": [
"grid plate",
"reflector",
"inlet nozzle",
"handling socket",
],
"mixture duct": ["duct"],
"mixture plenum": ["plenum"],
}
_BLOCK_MIXTURE_TYPE_EXCLUSIONS = ["control", "fuel", "radial shield"]
_MESH_BY_RING_COMP = "Ring Compositions"
_MESH_BY_AXIAL_COORDS = "Axial Coordinates"
_MESH_BY_AXIAL_BINS = "Axial Bins"
def __init__(
self, cs, converterSettings, expandReactor=False, strictHomogenization=False
):
GeometryConverter.__init__(self, cs)
self.converterSettings = converterSettings
self._o = None
self.meshConverter = None
self._expandSourceReactor = expandReactor
self._strictHomogenization = strictHomogenization
self._radialMeshConversionType = None
self._axialMeshConversionType = None
self._previousRadialZoneAssemTypes = None
self._currentRadialZoneType = None
self._assemsInRadialZone = collections.defaultdict(list)
self._newBlockNum = 0
self.blockMap = collections.defaultdict(list)
self.blockVolFracs = collections.defaultdict(dict)
def _generateConvertedReactorMesh(self):
"""
Convert the source reactor using the converterSettings
"""
runLog.info("Generating mesh coordinates for the reactor conversion")
self._radialMeshConversionType = self.converterSettings["radialConversionType"]
self._axialMeshConversionType = self.converterSettings["axialConversionType"]
converter = None
if self._radialMeshConversionType == self._MESH_BY_RING_COMP:
if self._axialMeshConversionType == self._MESH_BY_AXIAL_COORDS:
converter = meshConverters.RZThetaReactorMeshConverterByRingCompositionAxialCoordinates(
self.converterSettings
)
elif self._axialMeshConversionType == self._MESH_BY_AXIAL_BINS:
converter = meshConverters.RZThetaReactorMeshConverterByRingCompositionAxialBins(
self.converterSettings
)
if converter is None:
raise ValueError(
"No mesh converter exists for `radialConversionType` and `axialConversionType` settings "
"of {} and {}".format(
self._radialMeshConversionType, self._axialMeshConversionType
)
)
self.meshConverter = converter
return self.meshConverter.generateMesh(self._sourceReactor)
def convert(self, r):
"""
Run the conversion to 3 dimensional R-Z-Theta.
Attributes
----------
r : Reactor object
The reactor to convert.
Notes
-----
As a part of the RZT mesh converters it is possible to obtain a radial mesh that
has repeated ring numbers. For instance, if there are fuel assemblies and control
assemblies within the same radial hex ring then it's possible that a radial mesh
output from the byRingComposition mesh converter method will look something like:
self.meshConverter.radialMesh = [2, 3, 4, 4, 5, 5, 6, 6, 6, 7, 8, 8, 9, 10]
In this instance the hex ring will remain the same for multiple iterations over
radial direction when homogenizing the hex core into the RZT geometry. In this
case, the converter needs to keep track of the compositions within this ring so
that it can separate this repeated ring into multiple RZT rings. Each of the RZT
rings should have a single composition (fuel1, fuel2, control, etc.)
See Also
--------
armi.reactor.converters.meshConverters
"""
if r.core.geomType != geometry.GeomType.HEX:
raise ValueError(
"Cannot use {} to convert {} reactor".format(
self, str(r.core.geomType).upper()
)
)
self._sourceReactor = r
self._setupSourceReactorForConversion()
rztSpatialGrid = self._generateConvertedReactorMesh()
runLog.info(rztSpatialGrid)
self._setupConvertedReactor(rztSpatialGrid)
innerDiameter = 0.0
lowerRing = 1
radialMeshCm = [0.0]
for radialIndex, upperRing in enumerate(self.meshConverter.radialMesh):
lowerTheta = 0.0
# see notes
self._previousRadialZoneAssemTypes = (
self._previousRadialZoneAssemTypes if lowerRing == upperRing else []
)
if lowerRing == upperRing:
lowerRing = upperRing - 1
self._setNextAssemblyTypeInRadialZone(lowerRing, upperRing)
self._setAssemsInRadialZone(radialIndex, lowerRing, upperRing)
for thetaIndex, upperTheta in enumerate(self.meshConverter.thetaMesh):
zoneAssems = self._getAssemsInRadialThetaZone(
lowerRing, upperRing, lowerTheta, upperTheta
)
self._writeRadialThetaZoneHeader(
radialIndex,
lowerRing,
upperRing,
thetaIndex,
lowerTheta,
upperTheta,
)
outerDiameter = self._createRadialThetaZone(
innerDiameter,
thetaIndex,
radialIndex,
lowerTheta,
upperTheta,
zoneAssems,
)
lowerTheta = upperTheta
innerDiameter = outerDiameter
lowerRing = upperRing
radialMeshCm.append(outerDiameter / 2.0)
# replace temporary index-based ring indices with actual radial distances
self.convReactor.core.spatialGrid._bounds = (
self.convReactor.core.spatialGrid._bounds[0],
numpy.array(radialMeshCm),
self.convReactor.core.spatialGrid._bounds[2],
)
self.convReactor.core.updateAxialMesh()
self.convReactor.core.summarizeReactorStats()
def _setNextAssemblyTypeInRadialZone(self, lowerRing, upperRing):
"""
Change the currently-active assembly type to the next active one based on a specific order.
If this is called with the same (lowerRing, upperRing) twice, the next assembly type
will be applied. This is useful, for instance, in putting control zones amidst fuel.
"""
sortedAssemTypes = self._getSortedAssemblyTypesInRadialZone(
lowerRing, upperRing
)
for aType in sortedAssemTypes:
if aType not in self._previousRadialZoneAssemTypes:
self._previousRadialZoneAssemTypes.append(aType)
self._currentRadialZoneType = aType
break
def _getSortedAssemblyTypesInRadialZone(self, lowerRing, upperRing):
"""
Retrieve assembly types in a radial zone between (lowerRing, upperRing), sort from highest occurrence to lowest.
Notes
-----
- Assembly types are based on the assembly names and not the direct composition within each assembly. For
instance, if two assemblies are named `fuel 1` and `fuel 2` but they have the same composition at some reactor
state then they will still be separated as two different assembly types.
"""
aCountByTypes = collections.Counter()
for a in self._getAssembliesInCurrentRadialZone(lowerRing, upperRing):
aCountByTypes[a.getType().lower()] += 1
# sort on tuple (int, str) to force consistent ordering of result when counts are tied
sortedAssemTypes = sorted(
aCountByTypes, key=lambda aType: (aCountByTypes[aType], aType), reverse=True
)
return sortedAssemTypes
def _getAssembliesInCurrentRadialZone(self, lowerRing, upperRing):
ringAssems = []
for ring in range(lowerRing, upperRing):
ringAssems.extend(
self._sourceReactor.core.getAssembliesInSquareOrHexRing(ring)
)
return ringAssems
def _setupSourceReactorForConversion(self):
self._sourceReactor.core.summarizeReactorStats()
if self._expandSourceReactor:
self._expandSourceReactorGeometry()
self._o = self._sourceReactor.o
def _setupConvertedReactor(self, grid):
self.convReactor = reactors.Reactor(
"ConvertedReactor", self._sourceReactor.blueprints
)
core = reactors.Core("Core")
if self._cs is not None:
core.setOptionsFromCs(self._cs)
self.convReactor.add(core)
self.convReactor.core.spatialGrid = grid
grid.symmetry = self._SYMMETRY_TYPE
grid.geomType = self._GEOMETRY_TYPE
grid.armiObject = self.convReactor.core
self.convReactor.core.p.power = self._sourceReactor.core.p.power
self.convReactor.core.name += " - {0}".format(self._GEOMETRY_TYPE)
def _setAssemsInRadialZone(self, radialIndex, lowerRing, upperRing):
"""
Retrieve a list of assemblies in the reactor between (lowerRing, upperRing)
Notes
-----
self._assemsInRadialZone keeps track of the unique assemblies that are in each radial ring. This
ensures that no assemblies are duplicated when using self._getAssemsInRadialThetaZone()
"""
lowerTheta = 0.0
for _thetaIndex, upperTheta in enumerate(self.meshConverter.thetaMesh):
assemsInRadialThetaZone = self._getAssemsInRadialThetaZone(
lowerRing, upperRing, lowerTheta, upperTheta
)
newAssemsInRadialZone = set(assemsInRadialThetaZone)
oldAssemsInRadialZone = set(self._assemsInRadialZone[radialIndex])
self._assemsInRadialZone[radialIndex].extend(
sorted(list(newAssemsInRadialZone.union(oldAssemsInRadialZone)))
)
lowerTheta = upperTheta
if not self._assemsInRadialZone[radialIndex]:
raise ValueError(
"No assemblies in radial zone {} between rings {} and {}".format(
self._assemsInRadialZone[radialIndex], lowerRing, upperRing
)
)
@staticmethod
def _getAssembliesInSector(core, theta1, theta2):
"""
Locate assemblies in an angular sector.
Parameters
----------
theta1, theta2 : float
The angles (in degrees) in which assemblies shall be drawn.
Returns
-------
aList : list
List of assemblies in this sector
"""
aList = []
converter = EdgeAssemblyChanger(quiet=True)
converter.addEdgeAssemblies(core)
for a in core:
x, y, _ = a.spatialLocator.getLocalCoordinates()
theta = math.atan2(y, x)
if theta < 0.0:
theta = math.tau + theta
theta = math.degrees(theta)
phi = theta
if (
theta1 <= phi <= theta2
or abs(theta1 - phi) < 0.001
or abs(theta2 - phi) < 0.001
):
aList.append(a)
converter.removeEdgeAssemblies(core.r.core)
if not aList:
raise ValueError(
"There are no assemblies in {} between angles of {} and {}".format(
core, theta1, theta2
)
)
return aList
def _getAssemsInRadialThetaZone(self, lowerRing, upperRing, lowerTheta, upperTheta):
"""Retrieve list of assemblies in the reactor between (lowerRing, upperRing) and (lowerTheta, upperTheta)."""
thetaAssems = self._getAssembliesInSector(
self._sourceReactor.core, math.degrees(lowerTheta), math.degrees(upperTheta)
)
ringAssems = self._getAssembliesInCurrentRadialZone(lowerRing, upperRing)
if self._radialMeshConversionType == self._MESH_BY_RING_COMP:
ringAssems = self._selectAssemsBasedOnType(ringAssems)
ringAssems = set(ringAssems)
thetaAssems = set(thetaAssems)
assemsInRadialThetaZone = sorted(ringAssems.intersection(thetaAssems))
if not assemsInRadialThetaZone:
raise ValueError(
"No assemblies in radial-theta zone between rings {} and {} "
"and theta bounds of {} and {}".format(
lowerRing, upperRing, lowerTheta, upperTheta
)
)
return assemsInRadialThetaZone
def _selectAssemsBasedOnType(self, assems):
"""Retrieve a list of assemblies of a given type within a subset of an assembly list.
Parameters
----------
assems: list
Subset of assemblies in the reactor.
"""
selectedAssems = []
for a in assems:
if a.getType().lower() == self._currentRadialZoneType:
selectedAssems.append(a)
return selectedAssems
def _createRadialThetaZone(
self, innerDiameter, thetaIndex, radialIndex, lowerTheta, upperTheta, zoneAssems
):
"""
Add a new stack of circles to the TRZ reactor by homogenizing assems
Parameters
----------
innerDiameter : float
The current innerDiameter of the radial-theta zone
thetaIndex : float
The theta index of the radial-theta zone
radialIndex : float
The radial index of the radial-theta zone
lowerTheta : float
The lower theta bound for the radial-theta zone
upperTheta : float
The upper theta bound for the radial-theta zone
Returns
-------
outerDiameter : float
The outer diameter (in cm) of the radial zone just added
"""
newAssembly = assemblies.ThRZAssembly("mixtureAssem")
newAssembly.spatialLocator = self.convReactor.core.spatialGrid[
thetaIndex, radialIndex, 0
]
newAssembly.p.AziMesh = 2
newAssembly.spatialGrid = grids.axialUnitGrid(
len(self.meshConverter.axialMesh), armiObject=newAssembly
)
lowerAxialZ = 0.0
for axialIndex, upperAxialZ in enumerate(self.meshConverter.axialMesh):
# Setup the new block data
newBlockName = "B{:04d}{}".format(
int(newAssembly.getNum()), chr(axialIndex + 65)
)
newBlock = blocks.ThRZBlock(newBlockName)
# Compute the homogenized block data
(
newBlockAtoms,
newBlockType,
newBlockTemp,
newBlockVol,
) = self.createHomogenizedRZTBlock(
newBlock, lowerAxialZ, upperAxialZ, zoneAssems
)
# Compute radial zone outer diameter
axialSegmentHeight = upperAxialZ - lowerAxialZ
radialZoneVolume = self._calcRadialRingVolume(
lowerAxialZ, upperAxialZ, radialIndex
)
radialRingArea = (
radialZoneVolume
/ axialSegmentHeight
* self._sourceReactor.core.powerMultiplier
)
outerDiameter = blockConverters.getOuterDiamFromIDAndArea(
innerDiameter, radialRingArea
)
# Set new homogenized block parameters
material = materials.material.Material()
material.name = "mixture"
material.p.refDens = 1.0 # generic density. Will cancel out.
dims = {
"inner_radius": innerDiameter / 2.0,
"radius_differential": (outerDiameter - innerDiameter) / 2.0,
"inner_axial": lowerAxialZ,
"height": axialSegmentHeight,
"inner_theta": lowerTheta,
"azimuthal_differential": (upperTheta - lowerTheta),
"mult": 1.0,
"Tinput": newBlockTemp,
"Thot": newBlockTemp,
}
for nuc in self._sourceReactor.blueprints.allNuclidesInProblem:
material.setMassFrac(nuc, 0.0)
newComponent = components.DifferentialRadialSegment(
"mixture", material, **dims
)
newBlock.p.axMesh = int(axialSegmentHeight / BLOCK_AXIAL_MESH_SPACING) + 1
newBlock.p.zbottom = lowerAxialZ
newBlock.p.ztop = upperAxialZ
# Assign the new block cross section type and burn up group
newBlock.setType(newBlockType)
newXsType, newBuGroup = self._createBlendedXSID(newBlock)
newBlock.p.xsType = newXsType
newBlock.p.buGroup = newBuGroup
# Update the block dimensions and set the block densities
newComponent.updateDims() # ugh.
newBlock.p.height = axialSegmentHeight
newBlock.clearCache()
newBlock.add(newComponent)
for nuc, atoms in newBlockAtoms.items():
newBlock.setNumberDensity(nuc, atoms / newBlockVol)
self._writeRadialThetaZoneInfo(axialIndex + 1, axialSegmentHeight, newBlock)
self._checkVolumeConservation(newBlock)
newAssembly.add(newBlock)
lowerAxialZ = upperAxialZ
newAssembly.calculateZCoords() # builds mesh
self.convReactor.core.add(newAssembly)
return outerDiameter
def _calcRadialRingVolume(self, lowerZ, upperZ, radialIndex):
"""Compute the total volume of a list of assemblies within a ring between two axial heights."""
ringVolume = 0.0
for assem in self._assemsInRadialZone[radialIndex]:
for b, heightHere in assem.getBlocksBetweenElevations(lowerZ, upperZ):
ringVolume += b.getVolume() * heightHere / b.getHeight()
if not ringVolume:
raise ValueError("Ring volume of ring {} is 0.0".format(radialIndex + 1))
return ringVolume
def _checkVolumeConservation(self, newBlock):
"""Write the volume fractions of each hex block within the homogenized RZT block."""
newBlockVolumeFraction = 0.0
for hexBlock in self.blockMap[newBlock]:
newBlockVolumeFraction += self.blockVolFracs[newBlock][hexBlock]
if abs(newBlockVolumeFraction - 1.0) > 0.00001:
raise ValueError(
"The volume fraction of block {} is {} and not 1.0. An error occurred when converting the reactor"
" geometry.".format(newBlock, newBlockVolumeFraction)
)
def createHomogenizedRZTBlock(
self, homBlock, lowerAxialZ, upperAxialZ, radialThetaZoneAssems
):
"""
Create the homogenized RZT block by computing the average atoms in the zone.
Additional calculations are performed to determine the homogenized block type, the block average temperature,
and the volume fraction of each hex block that is in the new homogenized block.
"""
homBlockXsTypes = set()
numHexBlockByType = collections.Counter()
homBlockAtoms = collections.defaultdict(int)
homBlockVolume = 0.0
homBlockTemperature = 0.0
for assem in radialThetaZoneAssems:
blocksHere = assem.getBlocksBetweenElevations(lowerAxialZ, upperAxialZ)
for b, heightHere in blocksHere:
homBlockXsTypes.add(b.p.xsType)
numHexBlockByType[b.getType().lower()] += 1
blockVolumeHere = b.getVolume() * heightHere / b.getHeight()
if blockVolumeHere == 0.0:
raise ValueError(
"Geometry conversion failed. Block {} has zero volume".format(b)
)
homBlockVolume += blockVolumeHere
homBlockTemperature += b.getAverageTempInC() * blockVolumeHere
numDensities = b.getNumberDensities()
for nucName, nDen in numDensities.items():
homBlockAtoms[nucName] += nDen * blockVolumeHere
self.blockMap[homBlock].append(b)
self.blockVolFracs[homBlock][b] = blockVolumeHere
# Notify if blocks with different xs types are being homogenized. May be undesired behavior.
if len(homBlockXsTypes) > 1:
msg = "Blocks {} with dissimilar XS IDs are being homogenized in {} between axial heights {} " "cm and {} cm. ".format(
self.blockMap[homBlock],
self.convReactor.core,
lowerAxialZ,
upperAxialZ,
)
if self._strictHomogenization:
raise ValueError(
msg + "Modify mesh converter settings before proceeding."
)
else:
runLog.important(msg)
homBlockType = self._getHomogenizedBlockType(numHexBlockByType)
homBlockTemperature = homBlockTemperature / homBlockVolume
for b in self.blockMap[homBlock]:
self.blockVolFracs[homBlock][b] = (
self.blockVolFracs[homBlock][b] / homBlockVolume
)
return homBlockAtoms, homBlockType, homBlockTemperature, homBlockVolume
def _getHomogenizedBlockType(self, numHexBlockByType):
"""
Generate the homogenized block mixture type based on the frequency of hex block types that were merged
together.
Notes
-----
self._BLOCK_MIXTURE_TYPE_EXCLUSIONS:
The normal function of this method is to assign the mixture name based on the number of occurrences of the
block type. This list stops that and assigns the mixture based on the first occurrence.
(i.e. if the mixture has a set of blocks but it comes across one with the name of 'control' the process will
stop and the new mixture type will be set to 'mixture control'
self._BLOCK_MIXTURE_TYPE_MAP:
A dictionary that provides the name of blocks that are condensed together
"""
assignedMixtureBlockType = None
# Find the most common block type out of the types in the block mixture type exclusions list
excludedBlockTypesInBlock = set(
[
x
for x in self._BLOCK_MIXTURE_TYPE_EXCLUSIONS
for y in numHexBlockByType
if x in y
]
)
if excludedBlockTypesInBlock:
for blockType in self._BLOCK_MIXTURE_TYPE_EXCLUSIONS:
if blockType in excludedBlockTypesInBlock:
assignedMixtureBlockType = "mixture " + blockType
return assignedMixtureBlockType
# Assign block type by most common hex block type
mostCommonHexBlockType = sorted(numHexBlockByType.most_common(1))[0][
0
] # sort needed for tie break
for mixtureType in sorted(self._BLOCK_MIXTURE_TYPE_MAP):
validBlockTypesInMixture = self._BLOCK_MIXTURE_TYPE_MAP[mixtureType]
for validBlockType in validBlockTypesInMixture:
if validBlockType in mostCommonHexBlockType:
assignedMixtureBlockType = mixtureType
return assignedMixtureBlockType
assignedMixtureBlockType = "mixture structure"
runLog.debug(
f"The mixture type for this homogenized block {mostCommonHexBlockType} "
f"was not determined and is defaulting to {assignedMixtureBlockType}"
)
return assignedMixtureBlockType
def _createBlendedXSID(self, newBlock):
"""
Generate the blended XS id using the most common XS id in the hexIdList
"""
ids = [hexBlock.getMicroSuffix() for hexBlock in self.blockMap[newBlock]]
xsTypeList, buGroupList = zip(*ids)
xsType, _count = collections.Counter(xsTypeList).most_common(1)[0]
buGroup, _count = collections.Counter(buGroupList).most_common(1)[0]
return xsType, buGroup
def _writeRadialThetaZoneHeader(
self, radIdx, lowerRing, upperRing, thIdx, lowerTheta, upperTheta
):
radialAssemType = (
"({})".format(self._currentRadialZoneType)
if self._currentRadialZoneType is not None
else ""
)
runLog.info(
"Creating: Radial Zone {}, Theta Zone {} {}".format(
radIdx + 1, thIdx + 1, radialAssemType
)
)
runLog.extra(
"{} Hex Rings: [{}, {}), Theta Revolutions: [{:.2f}, {:.2f})".format(
9 * STR_SPACE,
lowerRing,
upperRing,
lowerTheta * units.RAD_TO_REV,
upperTheta * units.RAD_TO_REV,
)
)
runLog.debug(
"{} Axial Zone - Axial Height (cm) Block Number Block Type XS ID : Original Hex Block XS ID(s)".format(
9 * STR_SPACE
)
)
runLog.debug(
"{} ---------- - ----------------- ------------ ---------------------- ----- : ---------------------------".format(
9 * STR_SPACE
)
)
def _writeRadialThetaZoneInfo(self, axIdx, axialSegmentHeight, blockObj):
"""
Create a summary of the mapping between the converted reactor block ids to the hex reactor block ids
"""
self._newBlockNum += 1
hexBlockXsIds = []
for hexBlock in self.blockMap[blockObj]:
hexBlockXsIds.append(hexBlock.getMicroSuffix())
runLog.debug(
"{} {:<10} - {:<17.3f} {:<12} {:<22} {:<5} : {}".format(
9 * STR_SPACE,
axIdx,
axialSegmentHeight,
self._newBlockNum,
blockObj.getType(),
blockObj.getMicroSuffix(),
hexBlockXsIds,
)
)
def _expandSourceReactorGeometry(self):
"""
Expansion of the reactor geometry to build the R-Z-Theta core model
"""
runLog.info("Expanding source reactor core to a full core model")
reactorExpander = ThirdCoreHexToFullCoreChanger(self._cs)
reactorExpander.convert(self._sourceReactor)
self._sourceReactor.core.summarizeReactorStats()