/
reactors.py
2325 lines (1933 loc) · 83.3 KB
/
reactors.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.
"""
Reactor objects represent the highest level in the hierarchy of structures that compose the system
to be modeled. Core objects represent collections of assemblies.
Core is a high-level object in the data model in ARMI. They contain assemblies which in turn contain
more refinement in representing the physical reactor. The reactor is the owner of many of the
plant-wide state variables such as keff, cycle, and node.
.. impl:: ARMI represents the Reactor heirarchically.
:id: IMPL_REACTOR_HIERARCHY_0
:links: REQ_REACTOR_HIERARCHY
The Reactor contains a Core, which contains a heirachical collection of Assemblies, which in turn
each contain a collection of Blocks.
"""
from typing import Optional
import collections
import copy
import itertools
import logging
import os
import tabulate
import time
import numpy
from armi import getPluginManagerOrFail, materials, nuclearDataIO, settings
from armi.nuclearDataIO import xsLibraries
from armi.reactor import assemblies
from armi.reactor import assemblyLists
from armi.reactor import composites
from armi.reactor import geometry
from armi.reactor import grids
from armi.reactor import parameters
from armi.reactor import reactorParameters
from armi.reactor import systemLayoutInput
from armi.reactor import zones
from armi.reactor.flags import Flags
from armi.settings.fwSettings.globalSettings import CONF_MATERIAL_NAMESPACE_ORDER
from armi.utils import createFormattedStrWithDelimiter, units
from armi.utils import directoryChangers
from armi.utils.iterables import Sequence
from armi.utils.mathematics import average1DWithinTolerance
from armi.reactor.converters.axialExpansionChanger import AxialExpansionChanger
# init logger
runLog = logging.getLogger(__name__)
class Reactor(composites.Composite):
"""
Top level of the composite structure, potentially representing all components in a reactor.
This class contains the core and any ex-core structures that are to be represented in the ARMI
model. Historically, the `Reactor` contained only the core. To support better representation of
ex-core structures, the old `Reactor` functionality was moved to the newer `Core` class, which
has a `Reactor` parent.
"""
pDefs = reactorParameters.defineReactorParameters()
def __init__(self, name, blueprints):
composites.Composite.__init__(self, "R-{}".format(name))
self.o = None
self.spatialGrid = None
self.spatialLocator = None
self.p.cycle = 0
self.p.flags |= Flags.REACTOR
self.core = None
self.blueprints = blueprints
def __getstate__(self):
r"""applies a settings and parent to the reactor and components."""
state = composites.Composite.__getstate__(self)
state["o"] = None
return state
def __setstate__(self, state):
composites.Composite.__setstate__(self, state)
def __deepcopy__(self, memo):
memo[id(self)] = newR = self.__class__.__new__(self.__class__)
newR.__setstate__(copy.deepcopy(self.__getstate__(), memo))
newR.name = self.name + "-copy"
return newR
def __repr__(self):
return "<{}: {} id:{}>".format(self.__class__.__name__, self.name, id(self))
def add(self, container):
composites.Composite.add(self, container)
cores = self.getChildrenWithFlags(Flags.CORE)
if cores:
if len(cores) != 1:
raise ValueError(
"Only 1 core may be specified at this time. Please adjust input. "
"Cores found: {}".format(cores)
)
self.core = cores[0]
def loadFromCs(cs):
"""
Load a Reactor based on the input settings.
"""
from armi.reactor import blueprints
bp = blueprints.loadFromCs(cs)
return factory(cs, bp)
def factory(cs, bp, geom: Optional[systemLayoutInput.SystemLayoutInput] = None):
"""Build a reactor from input settings, blueprints and geometry."""
from armi.reactor import blueprints
runLog.header("=========== Constructing Reactor and Verifying Inputs ===========")
# just before reactor construction, update the material "registry" with user settings,
# if it is set. Often it is set by the application.
if cs[CONF_MATERIAL_NAMESPACE_ORDER]:
materials.setMaterialNamespaceOrder(cs[CONF_MATERIAL_NAMESPACE_ORDER])
r = Reactor(cs.caseTitle, bp)
if cs["geomFile"]:
blueprints.migrate(bp, cs)
with directoryChangers.DirectoryChanger(cs.inputDirectory, dumpOnException=False):
# always construct the core first (for assembly serial number purposes)
if not bp.systemDesigns:
raise ValueError(
"The input must define a `core` system, but does not. Update inputs"
)
coreDesign = bp.systemDesigns["core"]
coreDesign.construct(cs, bp, r, geom=geom)
for structure in bp.systemDesigns:
if structure.name.lower() != "core":
structure.construct(cs, bp, r)
runLog.debug("Reactor: {}".format(r))
return r
class Core(composites.Composite):
"""
Reactor structure made up of assemblies. Could be a Core, spent fuel pool, reactor head, etc.
This has the bulk of the data management operations.
Attributes
----------
params : dict
Core-level parameters are scalar values that have time dependence. Examples are keff,
maxPercentBu, etc.
assemblies : list
List of assembly objects that are currently in the core
cs : CaseSettings object
Global settings for the case
"""
pDefs = reactorParameters.defineCoreParameters()
def __init__(self, name):
"""
Initialize the reactor object.
Parameters
----------
name : str
Name of the object. Flags will inherit from this.
"""
composites.Composite.__init__(self, name)
self.p.flags = Flags.fromStringIgnoreErrors(name)
self.assembliesByName = {}
self.circularRingList = {}
self.blocksByName = {} # lookup tables
self.numRings = 0
self.spatialGrid = None
self.xsIndex = {}
self.p.numMoves = 0
# build a spent fuel pool for this reactor
runLog.debug("Building spent fuel pools")
self.sfp = assemblyLists.SpentFuelPool("Spent Fuel Pool", self)
self._lib = None # placeholder for ISOTXS object
self.locParams = {} # location-based parameters
# overridden in case.py to include pre-reactor time.
self.timeOfStart = time.time()
self.zones = None
# initialize the list that holds all shuffles
self.moveList = {}
self.scalarVals = {}
self._nuclideCategories = {}
self.typeList = [] # list of block types to convert name - to -number.
# leftover default "settings" that are intended to eventually be elsewhere.
self._freshFeedType = "feed fuel"
self._trackAssems = False
self._circularRingMode = False
self._circularRingPitch = 1.0
self._automaticVariableMesh = False
self._minMeshSizeRatio = 0.15
self._inputHeightsConsideredHot = True
self._detailedAxialExpansion = False
def setOptionsFromCs(self, cs):
# these are really "user modifiable modeling constants"
self.p.jumpRing = cs["jumpRingNum"]
self._freshFeedType = cs["freshFeedType"]
self._trackAssems = cs["trackAssems"]
self._circularRingMode = cs["circularRingMode"]
self._circularRingPitch = cs["circularRingPitch"]
self._automaticVariableMesh = cs["automaticVariableMesh"]
self._minMeshSizeRatio = cs["minMeshSizeRatio"]
self._inputHeightsConsideredHot = cs["inputHeightsConsideredHot"]
self._detailedAxialExpansion = cs["detailedAxialExpansion"]
def __getstate__(self):
"""Applies a settings and parent to the core and components."""
state = composites.Composite.__getstate__(self)
return state
def __setstate__(self, state):
composites.Composite.__setstate__(self, state)
self.sfp.parent = self
self.regenAssemblyLists()
def __deepcopy__(self, memo):
memo[id(self)] = newC = self.__class__.__new__(self.__class__)
newC.__setstate__(copy.deepcopy(self.__getstate__(), memo))
newC.name = self.name + "-copy"
return newC
def __repr__(self):
return "<{}: {} id:{}>".format(self.__class__.__name__, self.name, id(self))
def __iter__(self):
"""
Override the base Composite __iter__ to produce stable sort order.
See Also
--------
getAssemblies()
"""
return iter(sorted(self._children))
@property
def r(self):
if isinstance(self.parent, Reactor):
return self.parent
return None
@property
def symmetry(self) -> geometry.SymmetryType:
if not self.spatialGrid:
raise ValueError("Cannot access symmetry before a spatialGrid is attached.")
return self.spatialGrid.symmetry
@symmetry.setter
def symmetry(self, val: str):
self.spatialGrid.symmetry = str(val)
self.clearCache()
@property
def geomType(self) -> geometry.GeomType:
if not self.spatialGrid:
raise ValueError("Cannot access geomType before a spatialGrid is attached.")
return self.spatialGrid.geomType
@property
def powerMultiplier(self):
"""
Symmetry factor for this model. 1 for full core, 3 for 1/3 core, etc.
Notes
-----
This should not be a state variable because it just reflects the current geometry.
It changes automatically if the symmetry changes (e.g. from a geometry conversion).
"""
return self.symmetry.symmetryFactor()
@property
def lib(self) -> Optional[xsLibraries.IsotxsLibrary]:
"""
Return the microscopic cross section library if one exists.
- If there is a library currently associated with the core,
it will be returned
- Otherwise, an ``ISOTXS`` file will be searched for in the working directory,
opened as ``ISOTXS`` object and returned.
- Finally, if no ``ISOTXS`` file exists in the working directory,
a None will be returned.
"""
isotxsFileName = nuclearDataIO.getExpectedISOTXSFileName()
if self._lib is None and os.path.exists(isotxsFileName):
runLog.info(f"Loading microscopic cross section library `{isotxsFileName}`")
self._lib = nuclearDataIO.isotxs.readBinary(isotxsFileName)
return self._lib
@lib.setter
def lib(self, value):
"""Set the microscopic cross section library."""
self._lib = value
@property
def isFullCore(self):
"""Return True if reactor is full core, otherwise False."""
# Avoid using `not core.isFullCore` to check if third core geometry
# use `core.symmetry.domain == geometry.DomainType.THIRD_CORE
return self.symmetry.domain == geometry.DomainType.FULL_CORE
@property
def refAssem(self):
"""
Return the "reference" assembly for this Core.
The reference assembly is defined as the center-most assembly with a FUEL flag,
if any are present, or the center-most of any assembly otherwise.
Warnings
========
The convenience of this property should be weighed against it's somewhat
arbitrary nature for any particular client. The center-most fueled assembly is
not particularly representative of the state of the core as a whole.
"""
key = lambda a: a.spatialLocator.getRingPos()
assems = self.getAssemblies(Flags.FUEL, sortKey=key)
if not assems:
assems = self.getAssemblies(sortKey=key)
return assems[0]
def summarizeReactorStats(self):
"""Writes a summary of the reactor to check the mass and volume of all of the blocks."""
totalMass = 0.0
fissileMass = 0.0
heavyMetalMass = 0.0
totalVolume = 0.0
numBlocks = len(self.getBlocks())
for block in self.getBlocks():
totalMass += block.getMass()
fissileMass += block.getFissileMass()
heavyMetalMass += block.getHMMass()
totalVolume += block.getVolume()
totalMass = totalMass * self.powerMultiplier / 1000.0
fissileMass = fissileMass * self.powerMultiplier / 1000.0
heavyMetalMass = heavyMetalMass * self.powerMultiplier / 1000.0
totalVolume = totalVolume * self.powerMultiplier
runLog.extra(
"Summary of {}\n".format(self)
+ tabulate.tabulate(
[
("Number of Blocks", numBlocks),
("Total Volume (cc)", totalVolume),
("Total Mass (kg)", totalMass),
("Fissile Mass (kg)", fissileMass),
("Heavy Metal Mass (kg)", heavyMetalMass),
],
tablefmt="armi",
)
)
def getScalarEvolution(self, key):
return self.scalarVals[key]
def locateAllAssemblies(self):
"""
Store the current location of all assemblies.
This is required for shuffle printouts, repeat shuffling, and
MCNP shuffling.
"""
for a in self.getAssemblies(includeAll=True):
a.lastLocationLabel = a.getLocation()
def removeAssembly(self, a1, discharge=True):
"""
Takes an assembly and puts it out of core.
Parameters
----------
a1 : assembly
The assembly to remove
discharge : bool, optional
Discharge the assembly, including adding it to the SFP. Default: True
Originally, this held onto all assemblies in the spend fuel pool. However, having
this sitting in memory becomes constraining for large simulations. It is more
memory-efficient to only save the assemblies that are required for detailed
history tracking. In fact, there's no need to save the assembly object at all,
just have the history interface save the relevant parameters.
Notes
-----
Please expect this method will delete your assembly (instead of moving it to a
Spent Fuel Pool) unless you set the ``trackAssems`` to True in your settings file.
See Also
--------
add : adds an assembly
"""
paramDefs = set(parameters.ALL_DEFINITIONS)
paramDefs.difference_update(set(parameters.forType(Core)))
paramDefs.difference_update(set(parameters.forType(Reactor)))
for paramDef in paramDefs:
if paramDef.assigned & parameters.SINCE_ANYTHING:
paramDef.assigned = parameters.SINCE_ANYTHING
if discharge:
runLog.debug("Removing {0} from {1}".format(a1, self))
else:
runLog.debug("Purging {0} from {1}".format(a1, self))
self.childrenByLocator.pop(a1.spatialLocator)
a1.p.dischargeTime = self.r.p.time
self.remove(a1)
if discharge and self._trackAssems:
self.sfp.add(a1)
else:
self._removeListFromAuxiliaries(a1)
def removeAssembliesInRing(self, ringNum, overrideCircularRingMode=False):
"""
Removes all of the assemblies in a given ring
Parameters
----------
ringNum : int
The ring to remove
overrideCircularRingMode : bool, optional
False ~ default: use circular/square/hex rings, just as the reactor defines them
True ~ If you know you don't want to use the circular ring mode, and instead want square or hex.
See Also
--------
getAssembliesInRing : definition of a ring
"""
for a in self.getAssembliesInRing(
ringNum, overrideCircularRingMode=overrideCircularRingMode
):
self.removeAssembly(a)
self.processLoading(settings.getMasterCs())
def _removeListFromAuxiliaries(self, assembly):
"""
Remove an assembly from all auxiliary reference tables and lists
Otherwise it will get added back into assembliesByName, etc.
History will fail if it tries to summarize an assembly that has been purged.
"""
del self.assembliesByName[assembly.getName()]
for b in assembly:
try:
del self.blocksByName[b.getName()]
except KeyError:
runLog.warning(
"Cannot delete block {0}. It is not in the Core.blocksByName structure"
"".format(b),
single=True,
label="cannot dereference: lost block",
)
def removeAllAssemblies(self, discharge=True):
"""
Clears the core.
Notes
-----
must clear auxiliary bookkeeping lists as well or else a regeneration step will
auto-add assemblies back in.
"""
assems = set(self)
for a in assems:
self.removeAssembly(a, discharge)
self.sfp.removeAll()
self.blocksByName = {}
self.assembliesByName = {}
def add(self, a, spatialLocator=None):
"""
Adds an assembly to the reactor.
An object must be added before it is placed in a particular cell
in the reactor's spatialGrid. When an object is added to a reactor
it get placed in a generic location at the center of the reactor unless
a spatialLocator is passed in as well.
Parameters
----------
a : ArmiObject
The object to add to the reactor
spatialLocator : SpatialLocator object, optional
The location in the reactor to add the new object to. Must be unoccupied.
See Also
--------
removeAssembly : removes an assembly
"""
# resetting .assigned forces database to be rewritten for shuffled core
paramDefs = set(parameters.ALL_DEFINITIONS)
paramDefs.difference_update(set(parameters.forType(Core)))
paramDefs.difference_update(set(parameters.forType(Reactor)))
for paramDef in paramDefs:
if paramDef.assigned & parameters.SINCE_ANYTHING:
paramDef.assigned = parameters.SINCE_ANYTHING
# could speed up output by passing format args as an arg and only process if verb good.
runLog.debug("Adding {0} to {1}".format(a, self))
composites.Composite.add(self, a)
aName = a.getName()
spatialLocator = spatialLocator or a.spatialLocator
if spatialLocator is not None and spatialLocator in self.childrenByLocator:
raise ValueError(
"Cannot add {} because location {} is already filled by {}."
"".format(
aName, a.spatialLocator, self.childrenByLocator[a.spatialLocator]
)
)
if spatialLocator is not None:
# transfer spatialLocator to Core one
spatialLocator = self.spatialGrid[tuple(spatialLocator.indices)]
if not self.spatialGrid.locatorInDomain(
spatialLocator, symmetryOverlap=True
):
raise LookupError(
"Location `{}` outside of the represented domain: `{}`".format(
spatialLocator, self.spatialGrid.symmetry.domain
)
)
a.moveTo(spatialLocator)
self.childrenByLocator[spatialLocator] = a
# build a lookup table for history tracking.
if aName in self.assembliesByName and self.assembliesByName[aName] != a:
# try to keep assem numbering correct
runLog.error(
"The assembly {1} in the reactor already has the name {0}.\nCannot add {2}. "
"Current assemNum is {3}"
"".format(
aName, self.assembliesByName[aName], a, assemblies.getAssemNum()
)
)
raise RuntimeError("Core already contains an assembly with the same name.")
self.assembliesByName[aName] = a
for b in a:
self.blocksByName[b.getName()] = b
if self.geomType == geometry.GeomType.HEX:
ring, _loc = self.spatialGrid.getRingPos(
a.spatialLocator.getCompleteIndices()
)
if ring > self.numRings:
self.numRings = ring
# track the highest assem Num so when we load from a DB the future assemNums remain constant
aNum = a.p.assemNum
if aNum > self.p.maxAssemNum:
self.p.maxAssemNum = aNum
if a.lastLocationLabel != a.DATABASE:
# time the assembly enters the core in days
a.p.chargeTime = self.r.p.time
# cycle that the assembly enters the core
a.p.chargeCycle = self.r.p.cycle
# convert to kg
a.p.chargeFis = a.getFissileMass() / 1000.0
a.p.chargeBu = a.getMaxParam("percentBu")
def genAssembliesAddedThisCycle(self):
"""
Yield the assemblies that have been added in the current cycle.
This uses the reactor's cycle parameter and the assemblies' chargeCycle
parameters.
"""
for a in self:
if a.p.chargeCycle == self.r.p.cycle:
yield a
def getNumRings(self, indexBased=False):
"""
Returns the number of rings in this reactor. Based on location so indexing will start at 1.
WARNING: If you loop through range(maxRing) then ring+1 is the one you want!!
Parameters
----------
indexBased : bool, optional
If true, will force location-index interpretation, even if "circular shuffling" is enabled.
When circular ring shuffling is activated, this changes interpretation.
Developers plan on making this another method for the secondary interpretation.
"""
if self.circularRingList and not indexBased:
return max(self.circularRingList)
else:
return self.getNumHexRings()
def getNumHexRings(self):
"""
Returns the number of hex rings in this reactor. Based on location so indexing will start at 1.
"""
maxRing = 0
for a in self.getAssemblies():
ring, _pos = self.spatialGrid.getRingPos(a.spatialLocator)
maxRing = max(maxRing, ring)
return maxRing
def getNumAssembliesWithAllRingsFilledOut(self, nRings):
"""
Returns nAssmWithBlanks (see description immediately below).
Parameters
----------
nRings : int
The number of hex assembly rings in this core, including
partially-complete (non-full) rings.
Returns
-------
nAssmWithBlanks: int
The number of assemblies that WOULD exist in this core if
all outer assembly hex rings were "filled out".
"""
if self.powerMultiplier == 1:
return 3 * nRings * (nRings - 1) + 1
else:
return nRings * (nRings - 1) + (nRings + 1) // 2
def getNumEnergyGroups(self):
"""
Return the number of energy groups used in the problem
See Also
--------
armi.nuclearDataIO.ISOTXS.read1D : reads the number of energy groups off the ISOTXS library.
"""
return self.lib.numGroups
def countBlocksWithFlags(self, blockTypeSpec, assemTypeSpec=None):
"""
Return the total number of blocks in an assembly in the reactor that
meets the specified type
Parameters
----------
blockTypeSpec : Flags or list of Flags
The types of blocks to be counted in a single assembly
assemTypeSpec : Flags or list of Flags
The types of assemblies that are to be examine for the blockTypes
of interest. None is every assembly
Returns
-------
maxBlocks : int
The maximum number of blocks of the specified types in a single
assembly in the entire core
"""
assems = self.getAssemblies(typeSpec=assemTypeSpec)
try:
return max(sum(b.hasFlags(blockTypeSpec) for b in a) for a in assems)
except ValueError:
# In case assems is empty
return 0
def countFuelAxialBlocks(self):
r"""
return the maximum number of fuel type blocks in any assembly in
the reactor
See Also
--------
getFirstFuelBlockAxialNode
"""
fuelblocks = (
a.getBlocks(Flags.FUEL) for a in self.getAssemblies(includeBolAssems=True)
)
try:
return max(len(fuel) for fuel in fuelblocks)
except ValueError: # thrown when iterator is empty
return 0
def getFirstFuelBlockAxialNode(self):
"""
Determine the offset of the fuel from the grid plate in the assembly
with the lowest fuel block.
This assembly will dictate at what block level the SASSYS reactivity
coefficients will start to be generated
"""
try:
return min(
i
for a in self.getAssemblies(includeBolAssems=True)
for (i, b) in enumerate(a)
if b.hasFlags(Flags.FUEL)
)
except ValueError:
"""ValueError is thrown if min is called on an empty sequence.
Since this is expected to be a rare case, try/except is more
efficient than an if/else condition that checks whether the
iterator is empty (the latter would require generating a list
or tuple, which further adds to the inefficiency). Hence Python's
mantra, "It's easier to ask forgiveness than permission." In fact
it's quicker to ask forgiveness than permission."""
return float("inf")
def getAssembliesInRing(
self,
ring,
typeSpec=None,
exactType=False,
exclusions=None,
overrideCircularRingMode=False,
):
"""
Returns the assemblies in a specified ring. Definitions of rings can change
with problem parameters.
This function acts as a switch between two separate functions that define what a
ring is based on a cs setting 'circularRingMode'
Parameters
----------
ring : int
The ring number
typeSpec : str, list
a string or list of assembly types of interest
exactType : bool
flag to match the assembly type exactly
exclusions : list of assemblies
list of assemblies that are not to be considered
overrideCircularRingMode : bool, optional
False ~ default: use circular/square/hex rings, just as the reactor defines them
True ~ If you know you don't want to use the circular ring mode, and instead want square or hex.
Returns
-------
aList : list of assemblies
A list of assemblies that match the criteria within the ring
"""
if self._circularRingMode and not overrideCircularRingMode:
getter = self.getAssembliesInCircularRing
else:
getter = self.getAssembliesInSquareOrHexRing
return getter(
ring=ring, typeSpec=typeSpec, exactType=exactType, exclusions=exclusions
)
def getMaxAssembliesInHexRing(self, ring, fullCore=False):
"""
Returns the maximum number of assemblies possible for a given Hexagonal ring.
ring - The ring of interest to calculate the maximum number of assemblies.
numEdgeAssems - The number of edge assemblies in the reactor model (1/3 core).
Notes
-----
Assumes that odd rings do not have an edge assembly in third core geometry.
These should be removed in: self._modifyGeometryAfterLoad during importGeom
"""
numAssemsUpToOuterRing = self.getNumAssembliesWithAllRingsFilledOut(ring)
numAssemsUpToInnerRing = self.getNumAssembliesWithAllRingsFilledOut(ring - 1)
maxAssemsInRing = numAssemsUpToOuterRing - numAssemsUpToInnerRing
# See note*
if not fullCore:
ringMod = ring % 2
if ringMod == 1:
maxAssemsInRing -= 1
return maxAssemsInRing
def getAssembliesInSquareOrHexRing(
self, ring, typeSpec=None, exactType=False, exclusions=None
):
"""
Returns the assemblies in a specified ring. Definitions of rings can change
with problem parameters
Parameters
----------
ring : int
The ring number
typeSpec : Flags or [Flags], optional
a Flags instance or list of Flags with assembly types of interest
exactType : bool
flag to match the assembly type exactly
exclusions : list of assemblies
list of assemblies that are not to be considered
Returns
-------
assems : list of assemblies
A list of assemblies that match the criteria within the ring
"""
assems = Sequence(self)
if exclusions:
exclusions = set(exclusions)
assems.drop(lambda a: a in exclusions)
# filter based on geomType
if (
self.geomType == geometry.GeomType.CARTESIAN
): # a ring in cartesian is basically a square.
assems.select(
lambda a: any(xy == ring for xy in abs(a.spatialLocator.indices[:2]))
)
else:
assems.select(lambda a: (a.spatialLocator.getRingPos()[0] == ring))
# filter based on typeSpec
if typeSpec:
assems.select(lambda a: a.hasFlags(typeSpec, exact=exactType))
return list(assems)
def getAssembliesInCircularRing(
self, ring, typeSpec=None, exactType=False, exclusions=None
):
"""
Gets an assemblies within a circular range of the center of the core. This
function allows for more circular styled assembly shuffling instead of the
current hex approach.
Parameters
----------
ring : int
The ring number
typeSpec : Flags or list of Flags
a Flags instance or list of Flags with assembly types of interest
exactType : bool
flag to match the assembly type exactly
exclusions : list of assemblies
list of assemblies that are not to be considered
Returns
-------
assems : list of assemblies
A list of assemblies that match the criteria within the ring
"""
if self.geomType == geometry.GeomType.CARTESIAN:
# a ring in cartesian is basically a square.
raise RuntimeError(
"A circular ring in cartesian coordinates has not been defined yet."
)
# determine if the circularRingList has been generated
# TODO: make circularRingList a property that is generated on request
if not self.circularRingList:
self.circularRingList = self.buildCircularRingDictionary(
self._circularRingPitch
)
assems = Sequence(self)
# Remove exclusions
if exclusions:
exclusions = set(exclusions)
assems.drop(lambda a: a in exclusions)
# get assemblies at locations
locSet = self.circularRingList[ring]
assems.select(lambda a: a.getLocation() in locSet)
if typeSpec:
assems.select(lambda a: a.hasFlags(typeSpec, exact=exactType))
return list(assems)
def buildCircularRingDictionary(self, ringPitch=1.0):
"""
Builds a dictionary of all circular rings in the core. This is required information for getAssembliesInCircularRing.
The purpose of this function is to allow for more circular core shuffling in the hex design.
Parameters
----------
ringPitch : float, optional
The relative pitch that should be used to define the spacing between each ring.
"""
runLog.extra(
"Building a circular ring dictionary with ring pitch {}".format(ringPitch)
)
referenceAssembly = self.childrenByLocator[self.spatialGrid[0, 0, 0]]
refLocation = referenceAssembly.spatialLocator
pitchFactor = ringPitch / self.spatialGrid.pitch
circularRingDict = collections.defaultdict(set)
for a in self:
dist = a.spatialLocator.distanceTo(refLocation)
# To reduce numerical sensitivity, round distance to 6 decimal places
# before truncating.
index = int(round(dist * pitchFactor, 6)) or 1 # 1 is the smallest ring.
circularRingDict[index].add(a.getLocation())
return circularRingDict
def _getAssembliesByName(self):
"""
If the assembly name-to-assembly object map is deleted or out of date, then this will
regenerate it.
"""
runLog.extra("Generating assemblies-by-name map.")
# NOTE: eliminated unnecessary repeated lookups in self for self.assembliesByName
self.assembliesByName = assymap = {}
# don't includeAll b/c detailed ones are not ready yet
for assem in self.getAssemblies(includeBolAssems=True, includeSFP=True):
aName = assem.getName()
if aName in assymap and assymap[aName] != assem:
# dangerous situation that can occur in restart runs where the global assemNum isn't updated.
# !=assem clause added because sometimes an assem is in one of the includeAll lists that is also in the
# core and that's ok.
runLog.error(
"Two (or more) assemblies in the reactor (and associated lists) have the name {0},\n"
"including {1} and {2}.".format(aName, assem, assymap[aName])
)
raise RuntimeError("Assembly name collision.")
assymap[aName] = assem
def getAssemblyByName(self, name):
"""
Find the assembly that has this name.
Parameters
----------
name : str
the assembly name e.g. 'A0001'
Returns
-------
assembly
See Also
--------
getAssembly : more general version of this method
"""
return self.assembliesByName[name]
def getAssemblies(
self,
typeSpec=None,
sortKey=None,
includeBolAssems=False,
includeSFP=False,
includeAll=False,
zones=None,
exact=False,
):
"""
Return a list of all the assemblies in the reactor.
Assemblies from the Core itself are sorted based on the Assemblies' comparison