-
Notifications
You must be signed in to change notification settings - Fork 92
/
Copy pathcomposites.py
3279 lines (2724 loc) · 116 KB
/
composites.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.
"""
This module contains the basic composite pattern underlying the reactor package.
This follows the principles of the `Composite Design Pattern
<https://en.wikipedia.org/wiki/Composite_pattern>`_ to allow the construction of a part/whole
hierarchy representing a physical nuclear reactor. The composite objects act somewhat like lists:
they can be indexed, iterated over, appended, extended, inserted, etc. Each member of the hierarchy
knows its children and its parent, so full access to the hierarchy is available from everywhere.
This design was chosen because of the close analogy of the model to the physical nature of nuclear
reactors.
Warning
-------
Because each member of the hierarchy is linked to the entire tree, it is often unsafe to save
references to individual members; it can cause large and unexpected memory inefficiencies.
See Also
--------
:doc:`/developer/index`.
"""
import collections
import itertools
import operator
import timeit
from typing import Dict, Optional, Type, Tuple, List, Union
import numpy
import six
import tabulate
from armi import context
from armi import runLog
from armi import utils
from armi.nucDirectory import elements
from armi.nucDirectory import nucDir, nuclideBases
from armi.physics.neutronics.fissionProductModel import fissionProductModel
from armi.reactor import grids
from armi.reactor import parameters
from armi.reactor.flags import Flags, TypeSpec
from armi.reactor.parameters import resolveCollections
from armi.utils import densityTools
from armi.utils import units
from armi.utils.densityTools import calculateNumberDensity
class FlagSerializer(parameters.Serializer):
"""
Serializer implementation for Flags.
This operates by converting each set of Flags (too large to fit in a uint64) into a
sequence of enough uint8 elements to represent all flags. These constitute a
dimension of a 2-D numpy array containing all Flags for all objects provided to the
``pack()`` function.
"""
version = "1"
@staticmethod
def pack(data):
"""
Flags are represented as a 2-D numpy array of uint8 (single-byte, unsigned
integers), where each row contains the bytes representing a single Flags
instance. We also store the list of field names so that we can verify that the
reader and the writer can agree on the meaning of each bit.
Under the hood, this calls the private implementation providing the
:py:class:`armi.reactor.flags.Flags` class as the target output class.
"""
return FlagSerializer._packImpl(data, Flags)
@staticmethod
def _packImpl(data, flagCls: Type[utils.Flag]):
"""
Implement the pack operation given a target output Flag class.
This is kept separate from the public interface to permit testing of the
functionality without having to do unholy things to ARMI's actual set of
``reactor.flags.Flags``.
"""
npa = numpy.array(
[b for f in data for b in f.to_bytes()], dtype=numpy.uint8
).reshape((len(data), flagCls.width()))
return npa, {"flag_order": flagCls.sortedFields()}
@staticmethod
def _remapBits(inp: int, mapping: Dict[int, int]):
"""
Given an input bitfield, map each bit to the appropriate new bit position based
on the passed mapping.
Parameters
----------
inp : int
input bitfield
mapping : dict
dictionary mapping from old bit position -> new bit position
"""
f = 0
for bit in itertools.count():
if (1 << bit) > inp:
break
if (1 << bit) & inp:
f = f | (1 << mapping[bit])
return f
@classmethod
def unpack(cls, data, version, attrs):
"""
Reverse the pack operation.
This will allow for some degree of conversion from old flags to a new set of
flags, as long as all of the source flags still exist in the current set of
flags.
Under the hood, this calls the private implementation providing the
:py:class:`armi.reactor.flags.Flags` class as the target output class.
"""
return cls._unpackImpl(data, version, attrs, Flags)
@classmethod
def _unpackImpl(cls, data, version, attrs, flagCls: Type[utils.Flag]):
"""
Implement the unpack operation given a target output Flag class.
This is kept separate from the public interface to permit testing of the
functionality without having to do unholy things to ARMI's actual set of
``reactor.flags.Flags``.
If the set of flags for the currently-configured App match the input set of
flags, they are read in directly, which is good and cheap. However, if the set
of flags differ from the input and the current App, we will try to convert them
(as long as all of the input flags exist in the current App). Conversion is done
by forming a map from all input bit positions to the current-App bit positions
of the same meaning. E.g., if FUEL flag used to be the 3rd bit position, but now
it is the 6th bit position, the map will contain ``map[3] = 6``. Then for each
bitfield that is read in, each bit position is queried and if present, mapped to
the proper corresponding new bit position. The result of this mapping is used to
construct the Flags object.
"""
flagOrderPassed = attrs["flag_order"]
flagOrderNow = flagCls.sortedFields()
if version != cls.version:
raise ValueError(
"The FlagSerializer version used to pack the data ({}) does not match "
"the current version ({})! This database either needs to be migrated, "
"or on-the-fly inter-version conversion needs to be implemented.".format(
version, cls.version
)
)
flagSetIn = set(flagOrderPassed)
flagSetNow = set(flagOrderNow)
# Make sure that all of the old flags still exist
if not flagSetIn.issubset(flagSetNow):
missingFlags = flagSetIn - flagSetNow
raise ValueError(
"The set of flags in the database includes unknown flags. "
"Make sure you are using the correct ARMI app. Missing flags:\n"
"{}".format(missingFlags)
)
if all(i == j for i, j in zip(flagOrderPassed, flagOrderNow)):
out = [flagCls.from_bytes(row.tobytes()) for row in data]
else:
newFlags = {
i: flagOrderNow.index(oldFlag)
for (i, oldFlag) in enumerate(flagOrderPassed)
}
out = [
flagCls(
cls._remapBits(
int.from_bytes(row.tobytes(), byteorder="little"), newFlags
)
)
for row in data
]
return out
def _defineBaseParameters():
"""
Return parameter definitions that all ArmiObjects must have to function properly.
For now, this pretty much just includes ``flags``, since these are used throughout
the composite model to filter which objects are considered when traversing the
reactor model.
Note also that the base ParameterCollection class also has a ``serialNum``
parameter. These are defined in different locations, since serialNum is a guaranteed
feature of a ParameterCollection (for serialization to the database and history
tracking), while the ``flags`` parameter is more a feature of the composite model.
.. important::
Notice that the ``flags`` parameter is not written to the database. This is for
a couple of reasons:
* Flags are derived from an ArmiObject's name. Since the name is stored on
the DB, it is possible to recover the flags from that.
* Storing flags to the DB may be complicated, since it is easier to imagine a
number of flags that is greater than the width of natively-supported integer
types, requiring some extra tricks to store the flages in an HDF5 file.
* Allowing flags to be modified by plugins further complicates things, in that
it is important to ensure that the meaning of all bits in the flag value are
consistent between a database state and the current ARMI environment. This may
require encoding these meanings in to the database as some form of metadata.
"""
pDefs = parameters.ParameterDefinitionCollection()
pDefs.add(
parameters.Parameter(
"flags",
units=units.UNITLESS,
description="The type specification of this object",
location=parameters.ParamLocation.AVERAGE,
saveToDB=True,
default=Flags(0),
setter=parameters.NoDefault,
categories=set(),
serializer=FlagSerializer,
)
)
return pDefs
class CompositeModelType(resolveCollections.ResolveParametersMeta):
"""
Metaclass for tracking subclasses of ArmiObject subclasses.
It is often useful to have an easily-accessible collection of all classes that participate in
the ARMI composite reactor model. This metaclass maintains a collection of all defined
subclasses, called TYPES.
"""
TYPES: Dict[str, Type] = dict()
"""
Dictionary mapping class name to class object for all subclasses.
:meta hide-value:
"""
def __new__(cls, name, bases, attrs):
newType = resolveCollections.ResolveParametersMeta.__new__(
cls, name, bases, attrs
)
CompositeModelType.TYPES[name] = newType
return newType
class ArmiObject(metaclass=CompositeModelType):
"""
The abstract base class for all composites and leaves.
This:
* declares the interface for objects in the composition
* implements default behavior for the interface common to all classes
* Declares an interface for accessing and managing child objects
* Defines an interface for accessing parents.
Called "component" in gang of four, this is an ArmiObject here because the word component was
already taken in ARMI.
The :py:class:`armi.reactor.parameters.ResolveParametersMeta` metaclass is used to automatically
create ``ParameterCollection`` subclasses for storing parameters associated with any particular
subclass of ArmiObject. Defining a ``pDefs`` class attribute in the definition of a subclass of
ArmiObject will lead to the creation of a new subclass of
py:class:`armi.reactor.parameters.ParameterCollection`, which will contain the definitions from
that class's ``pDefs`` as well as the definitions for all of its parents. A new
``paramCollectionType`` class attribute will be added to the ArmiObject subclass to reflect
which type of parameter collection should be used.
Warning
-------
This class has far too many public methods. We are in the midst of a composite tree cleanup that
will likely break these out onto a number of separate functional classes grouping things like
composition, location, shape/dimensions, and various physics queries. Methods are being
collected here from the various specialized subclasses (Block, Assembly) in preparation for this
next step. As a result, the public API on this method should be considered unstable.
.. impl:: Parameters are accessible throughout the armi tree.
:id: I_ARMI_PARAM_PART
:implements: R_ARMI_PARAM_PART
An ARMI reactor model is composed of collections of ARMIObject objects. These
objects are combined in a hierarchical manner. Each level of the composite tree
is able to be assigned parameters which define it, such as temperature, flux,
or keff values. This class defines an attribute of type ``ParameterCollection``,
which contains all the functionality of an ARMI ``Parameter`` object. Because
the entire model is composed of ARMIObjects at the most basic level, each level
of the Composite tree contains this parameter attribute and can thus be queried.
Attributes
----------
name : str
Object name
parent : ArmiObject
The object's parent in a hierarchical tree
cached : dict
Some cached values for performance
p : ParameterCollection
The state variables
spatialGrid : grids.Grid
The spatial grid that this object contains
spatialLocator : grids.LocationBase
The location of this object in its parent grid, or global space
See Also
--------
armi.reactor.parameters
"""
paramCollectionType: Optional[Type[parameters.ParameterCollection]] = None
pDefs = _defineBaseParameters()
def __init__(self, name):
self.name = name
self.parent = None
self.cached = {}
self._backupCache = None
self.p = self.paramCollectionType()
# TODO: These are not serialized to the database, and will therefore
# lead to surprising behavior when using databases. We need to devise a
# way to either represent them in parameters, or otherwise reliably
# recover them.
self._lumpedFissionProducts = None
self.spatialGrid = None
self.spatialLocator = grids.CoordinateLocation(0.0, 0.0, 0.0, None)
def __lt__(self, other):
"""
Implement the less-than operator.
Implementing this on the ArmiObject allows most objects, under most
circumstances to be sorted. This is useful from the context of the Database
classes, so that they can produce a stable layout of the serialized composite
structure.
By default, this sorts using the spatial locator, in K, J, I order, which should
give a relatively intuitive order. For safety, it makes sure that the objects
being sorted live in the same grid, since it probably doesn't make
sense to sort things across containers or scopes. If this ends up being too
restrictive, it can probably be relaxed or overridden on specific classes.
"""
if self.spatialLocator is None or other.spatialLocator is None:
runLog.error("could not compare {} and {}".format(self, other))
raise ValueError(
"One or more of the compared objects have no spatialLocator"
)
if self.spatialLocator.grid is not other.spatialLocator.grid:
runLog.error("could not compare {} and {}".format(self, other))
raise ValueError(
"Composite grids must be the same to compare:\n"
"This grid: {}\n"
"Other grid: {}".format(self.spatialGrid, other.spatialGrid)
)
try:
t1 = tuple(reversed(self.spatialLocator.getCompleteIndices()))
t2 = tuple(reversed(other.spatialLocator.getCompleteIndices()))
return t1 < t2
except ValueError:
runLog.error(
"failed to compare {} and {}".format(
self.spatialLocator, other.spatialLocator
)
)
raise
def __getstate__(self):
"""
Python method for reducing data before pickling.
This removes links to parent objects, which allows one to, for example, pickle
an assembly without pickling the entire reactor. Likewise, one could
MPI_COMM.bcast an assembly without broadcasting the entire reactor.
Notes
-----
Special treatment of ``parent`` is not enough, since the spatialGrid also
contains a reference back to the armiObject. Consequently, the ``spatialGrid``
needs to be reassigned in ``__setstate__``.
"""
state = self.__dict__.copy()
state["parent"] = None
if "r" in state:
raise RuntimeError("An ArmiObject should never contain the entire Reactor.")
return state
def __setstate__(self, state):
"""
Sets the state of this ArmiObject.
Notes
-----
This ArmiObject may have lost a reference to its parent. If the parent was also
pickled (serialized), then the parent should update the ``.parent`` attribute
during its own ``__setstate__``. That means within the context of
``__setstate__`` one should not rely upon ``self.parent``.
"""
self.__dict__.update(state)
if self.spatialGrid is not None:
self.spatialGrid.armiObject = self
# Spatial locators also get disassociated with their grids when detached;
# make sure they get hooked back up
for c in self:
c.spatialLocator.associate(self.spatialGrid)
# now "reattach" children
for c in self:
c.parent = self
def __repr__(self):
return "<{}: {}>".format(self.__class__.__name__, self.name)
def __format__(self, spec):
return format(str(self), spec)
def __bool__(self):
"""
Flag that says this is non-zero in a boolean context.
Notes
-----
The default behavior for ``not [obj]`` that has a ``__len__`` defined is to see
if the length is zero. However, for these composites, we'd like Assemblies, etc.
to be considered non-zero even if they don't have any blocks. This is important
for parent resolution, etc. If one of these objects exists, it is non-zero,
regardless of its contents.
"""
return True
def __add__(self, other):
"""Return a list of all children in this and another object."""
return self.getChildren() + other.getChildren()
def duplicate(self):
"""
Make a clean copy of this object.
.. warning:: Be careful with inter-object dependencies. If one object contains a
reference to another object which contains links to the entire hierarchical
tree, memory can fill up rather rapidly. Weak references are designed to help
with this problem.
"""
raise NotImplementedError
def clearCache(self):
"""Clear the cache so all new values are recomputed."""
self.cached = {}
for child in self.getChildren():
child.clearCache()
def _getCached(self, name): # TODO: stop the "returns None" nonsense?
"""
Obtain a value from the cache.
Cached values can be used to temporarily store frequently read but
long-to-compute values. The practice is generally discouraged because it's
challenging to make sure to properly invalidate the cache when the state
changes.
"""
return self.cached.get(name, None)
def _setCache(self, name, val): # TODO: remove me
"""
Set a value in the cache.
See Also
--------
_getCached : returns a previously-cached value
"""
self.cached[name] = val
def copyParamsFrom(self, other):
"""
Overwrite this object's params with other object's.
Parameters
----------
other : ArmiObject
The object to copy params from
"""
self.p = other.p.__class__()
for p, val in other.p.items():
self.p[p] = val
def updateParamsFrom(self, new):
"""
Update this object's params with a new object's.
Parameters
----------
new : ArmiObject
The object to copy params from
"""
for paramName, val in new.p.items():
self.p[paramName] = val
def getChildren(self, deep=False, generationNum=1, includeMaterials=False):
"""Return the children of this object."""
raise NotImplementedError
def getChildrenWithFlags(self, typeSpec: TypeSpec, exactMatch=True):
"""Get all children that have given flags."""
raise NotImplementedError
def getComponents(self, typeSpec: TypeSpec = None, exact=False):
"""
Return all armi.reactor.component.Component within this Composite.
Parameters
----------
typeSpec : TypeSpec
Component flags. Will restrict Components to specific ones matching the
flags specified.
exact : bool, optional
Only match exact component labels (names). If True, 'coolant' will not match
'interCoolant'. This has no impact if compLabel is None.
Returns
-------
list of Component
items matching compLabel and exact criteria
"""
raise NotImplementedError()
def iterComponents(self, typeSpec: TypeSpec = None, exact=False):
"""Yield components one by one in a generator."""
raise NotImplementedError()
def doChildrenHaveFlags(self, typeSpec: TypeSpec, deep=False):
"""
Generator that yields True if the next child has given flags.
Parameters
----------
typeSpec : TypeSpec
Requested type of the child
"""
for c in self.getChildren(deep):
if c.hasFlags(typeSpec, exact=False):
yield True
else:
yield False
def containsAtLeastOneChildWithFlags(self, typeSpec: TypeSpec):
"""
Return True if any of the children are of a given type.
Parameters
----------
typeSpec : TypeSpec
Requested type of the children
See Also
--------
self.doChildrenHaveFlags
self.containsOnlyChildrenWithFlags
"""
return any(self.doChildrenHaveFlags(typeSpec))
def containsOnlyChildrenWithFlags(self, typeSpec: TypeSpec):
"""
Return True if all of the children are of a given type.
Parameters
----------
typeSpec : TypeSpec
Requested type of the children
See Also
--------
self.doChildrenHaveFlags
self.containsAtLeastOneChildWithFlags
"""
return all(self.doChildrenHaveFlags(typeSpec))
def copyParamsToChildren(self, paramNames):
"""
Copy param values in paramNames to all children.
Parameters
----------
paramNames : list
List of param names to copy to children
"""
for paramName in paramNames:
myVal = self.p[paramName]
for c in self.getChildren():
c.p[paramName] = myVal
@classmethod
def getParameterCollection(cls):
"""
Return a new instance of the specific ParameterCollection type associated with this object.
This has the same effect as ``obj.paramCollectionType()``. Getting a new
instance through a class method like this is useful in situations where the
``paramCollectionType`` is not a top-level object and therefore cannot be
trivially pickled. Since we know that by the time we want to make any instances
of/unpickle a given ``ArmiObject``, such a class attribute will have been
created and associated. So, we use this top-level method to dig
dynamically down to the underlying parameter collection type.
.. impl:: Composites (and all ARMI objects) have parameter collections.
:id: I_ARMI_CMP_PARAMS
:implements: R_ARMI_CMP_PARAMS
This class method allows a user to obtain the
``paramCollection`` object, which is the object containing the interface for
all parameters of an ARMI object.
See Also
--------
:py:meth:`armi.reactor.parameters.parameterCollections.ParameterCollection.__reduce__`
"""
return cls.paramCollectionType()
def getParamNames(self):
"""
Get a list of parameters keys that are available on this object.
Will not have any corner, edge, or timenode dependence.
"""
return sorted(k for k in self.p.keys() if not isinstance(k, tuple))
def nameContains(self, s):
"""
True if s is in this object's name (eg. nameContains('fuel')==True for 'testfuel'.
Notes
-----
Case insensitive (all gets converted to lower)
"""
name = self.name.lower()
if isinstance(s, list):
return any(n.lower() in name for n in s)
else:
return s.lower() in name
def getName(self):
"""Get composite name.
.. impl:: Composite name is accessible.
:id: I_ARMI_CMP_GET_NAME
:implements: R_ARMI_CMP_GET_NAME
This method returns the name of a Composite.
"""
return self.name
def setName(self, name):
self.name = name
def hasFlags(self, typeID: TypeSpec, exact=False):
"""
Determine if this object is of a certain type.
.. impl:: Composites have queryable flags.
:id: I_ARMI_CMP_FLAG0
:implements: R_ARMI_CMP_FLAG
This method queries the flags (i.e. the ``typeID``) of the Composite for a
given type, returning a boolean representing whether or not the candidate
flag is present in this ArmiObject. Candidate flags cannot be passed as a
``string`` type and must be of a type ``Flag``. If no flags exist in the
object then ``False`` is returned.
If a list of flags is provided, then all input flags will be
checked against the flags of the object. If exact is ``False``, then the
object must have at least one of candidates exactly. If it is ``True`` then
the object flags and candidates must match exactly.
Parameters
----------
typeID : TypeSpec
Flags to test the object against, to see if it contains them. If a list is
provided, each element is treated as a "candidate" set of flags. Return True
if any of candidates match. When exact is True, the object must match one of
the candidates exactly. If exact is False, the object must have at least the
flags contained in a candidate for that candidate to be a match; extra flags
on the object are permitted. None matches all objects if exact is False, or
no objects if exact is True.
exact : bool, optional
Require the type of the object to fully match the provided typeID(s)
Returns
-------
hasFlags : bool
True if this object is in the typeID list.
Notes
-----
Type comparisons use bitwise comparisons using valid flags.
If you have an 'inner control' assembly, then this will evaluate True for the
INNER | CONTROL flag combination. If you just want all FUEL, simply use FUEL
with no additional qualifiers. For more complex comparisons, use bitwise
operations.
Always returns true if typeID is none and exact is False, allowing for default
parameters to be passed in when the method does not care about the object type.
If the typeID is none and exact is True, this will always return False.
Examples
--------
If you have an object with the ``INNER``, ``DRIVER``, and ``FUEL`` flags, then
>>> obj.getType()
[some integer]
>>> obj.hasFlags(Flags.FUEL)
True
>>> obj.hasFlags(Flags.INNER | Flags.DRIVER | Flags.FUEL)
True
>>> obj.hasFlags(Flags.OUTER | Flags.DRIVER | Flags.FUEL)
False
>>> obj.hasFlags(Flags.INNER | Flags.FUEL)
True
>>> obj.hasFlags(Flags.INNER | Flags.FUEL, exact=True)
False
>>> obj.hasFlags([Flags.INNER | Flags.DRIVER | Flags.FUEL,
... Flags.OUTER | Flags.DRIVER | Flags.FUEL], exact=True)
False
"""
if not typeID:
return not exact
if isinstance(typeID, six.string_types):
raise TypeError(
"Must pass Flags, or an iterable of Flags; Strings are no longer "
"supported"
)
elif not isinstance(typeID, Flags):
# list behavior gives a spec1 OR spec2 OR ... behavior.
return any(self.hasFlags(typeIDi, exact=exact) for typeIDi in typeID)
if not self.p.flags:
# default still set, or null flag. Do down here so we get proper error
# handling of invalid typeSpecs
return False
if exact:
# all bits must be identical for exact match
return self.p.flags == typeID
# all bits that are 1s in the typeID must be present
return self.p.flags & typeID == typeID
def getType(self):
"""Return the object type."""
return self.p.type
def setType(self, typ, flags: Optional[Flags] = None):
"""
Set the object type.
.. impl:: Composites have modifiable flags.
:id: I_ARMI_CMP_FLAG1
:implements: R_ARMI_CMP_FLAG
This method allows for the setting of flags parameter of the Composite.
Parameters
----------
typ : str
The desired "type" for the object. Type describes the general class of the
object, and typically corresponds to the name of the blueprint that created
it.
flags : Flags, optional
The set of Flags to apply to the object. If these are omitted, then Flags
will be derived from the ``typ``.
Warning
-------
We are in the process of developing more robust definitions for things like
"name" and "type". "type" will generally refer to the name of the blueprint that
created a particular object. When present, a "name" will refer to a specific
instance of an object of a particular "type". Think unique names for each
assembly in a core, even if they are all created from the same blueprint and
therefore have the same "type". When this work is complete, it will be strongly
discouraged, or even disallowed to change the type of an object after it has
been created, and ``setType()`` may be removed entirely.
"""
self.p.flags = flags or Flags.fromStringIgnoreErrors(typ)
self.p.type = typ
def getVolume(self):
return sum(child.getVolume() for child in self)
def getArea(self, cold=False):
return sum(child.getArea(cold) for child in self)
def _updateVolume(self):
"""Recompute and store volume."""
children = self.getChildren()
# Derived shapes must come last so we temporarily change the order if we
# have one.
from armi.reactor.components import DerivedShape
for child in children[:]:
if isinstance(child, DerivedShape):
children.remove(child)
children.append(child)
for child in children:
child._updateVolume()
def getVolumeFractions(self):
"""
Return volume fractions of each child.
Sets volume or area of missing piece (like coolant) if it exists. Caching would
be nice here.
Returns
-------
fracs : list
list of (component, volFrac) tuples
See Also
--------
test_block.Block_TestCase.test_consistentAreaWithOverlappingComponents
Notes
-----
void areas can be negative in gaps between fuel/clad/liner(s), but these
negative areas are intended to account for overlapping positive areas to insure
the total area of components inside the clad is accurate. See
test_block.Block_TestCase.test_consistentAreaWithOverlappingComponents
"""
children = self.getChildren()
numerator = [c.getVolume() for c in children]
denom = sum(numerator)
if denom == 0.0:
numerator = [c.getArea() for c in children]
denom = sum(numerator)
fracs = [(ci, nu / denom) for ci, nu in zip(children, numerator)]
return fracs
def getVolumeFraction(self):
"""Return the volume fraction that this object takes up in its parent."""
if self.parent is not None:
for child, frac in self.parent.getVolumeFractions():
if child is self:
return frac
raise ValueError(
f"No parent is defined for {self}. Cannot compute its volume fraction."
)
def getMaxArea(self):
"""
The maximum area of this object if it were totally full.
See Also
--------
armi.reactor.blocks.HexBlock.getMaxArea
"""
raise NotImplementedError()
def getMass(self, nuclideNames=None):
"""
Determine the mass in grams of nuclide(s) and/or elements in this object.
.. impl:: Return mass of composite.
:id: I_ARMI_CMP_GET_MASS
:implements: R_ARMI_CMP_GET_MASS
This method allows for the querying of the mass of a Composite.
If the ``nuclideNames`` argument is included, it will filter for the mass
of those nuclide names and provide the sum of the mass of those nuclides.
Parameters
----------
nuclideNames : str, optional
The nuclide/element specifier to get the mass of in the object.
If omitted, total mass is returned.
Returns
-------
mass : float
The mass in grams.
"""
return sum([c.getMass(nuclideNames=nuclideNames) for c in self])
def getMassFrac(self, nucName):
"""
Get the mass fraction of a nuclide.
Notes
-----
If you need multiple mass fractions, use ``getMassFracs``.
"""
nuclideNames = self._getNuclidesFromSpecifier(nucName)
massFracs = self.getMassFracs()
return sum(massFracs.get(nucName, 0.0) for nucName in nuclideNames)
def getMicroSuffix(self):
raise NotImplementedError(
f"Cannot get the suffix on {type(self)} objects. Only certain subclasses"
" of composite such as Blocks or Components have the concept of micro suffixes."
)
def _getNuclidesFromSpecifier(self, nucSpec):
"""
Convert a nuclide specification to a list of valid nuclide/element keys.
nucSpec : nuclide specifier
Can be a string name of a nuclide or element, or a list of such strings.
This might get Zr isotopes when ZR is passed in if they exist, or it will get
elemental ZR if that exists. When expanding elements, all known nuclides are
returned, not just the natural ones.
"""
allNuclidesHere = self.getNuclides()
if nucSpec is None:
return allNuclidesHere
elif isinstance(nucSpec, (str)):
nuclideNames = [nucSpec]
elif isinstance(nucSpec, list):
nuclideNames = []
for ns in nucSpec:
nuclideNames.extend(self._getNuclidesFromSpecifier(ns))
else:
raise TypeError(
"nucSpec={0} is an invalid specifier. It is a {1}"
"".format(nucSpec, type(nucSpec))
)
# expand elementals if appropriate.
convertedNucNames = []
for nucName in nuclideNames:
if nucName in allNuclidesHere:
convertedNucNames.append(nucName)
continue
try:
# Need all nuclide bases, not just natural isotopics because, e.g. PU
# has no natural isotopics!
nucs = [
nb.name
for nb in elements.bySymbol[nucName].nuclides
if not isinstance(nb, nuclideBases.NaturalNuclideBase)
]
convertedNucNames.extend(nucs)
except KeyError:
convertedNucNames.append(nucName)
return sorted(set(convertedNucNames))
def getMassFracs(self):
"""
Get mass fractions of all nuclides in object.
Ni [1/cm3] * Ai [g/mole] ~ mass
"""
numDensities = self.getNumberDensities()
return densityTools.getMassFractions(numDensities)
def setMassFrac(self, nucName, val):