/
__init__.py
846 lines (693 loc) · 23.2 KB
/
__init__.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
# 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.
"""Generic ARMI utilities."""
# ruff: noqa: F405
import collections
import getpass
import hashlib
import math
import os
import pickle
import re
import shutil
import sys
import tempfile
import threading
import time
from armi import runLog
from armi.utils import iterables
from armi.utils.flags import Flag # noqa: unused-import
from armi.utils.mathematics import * # noqa: undefined-local-with-import-star
# Read in file 1 MB at a time to reduce memory burden of reading entire file at once
_HASH_BUFFER_SIZE = 1024 * 1024
def getFileSHA1Hash(filePath, digits=40):
"""
Generate a SHA-1 hash of the input file.
Parameters
----------
filePath : str
Path to file to obtain the SHA-1 hash
digits : int, optional
Number of digits to include in the hash (40 digit maximum for SHA-1)
"""
sha1 = hashlib.sha1()
with open(filePath, "rb") as f:
while True:
data = f.read(_HASH_BUFFER_SIZE)
if not data:
break
sha1.update(data)
return sha1.hexdigest()[:digits]
def copyWithoutBlocking(src, dest):
"""
Copy a file in a separate thread to avoid blocking while IO completes.
Useful for copying large files while ARMI moves along.
"""
files = "{} to {}".format(src, dest)
runLog.extra("Copying (without blocking) {}".format(files))
t = threading.Thread(target=shutil.copy, args=(src, dest))
t.start()
return t
def getPowerFractions(cs):
"""
Return the power fractions for each cycle.
Parameters
----------
cs : case settings object
Returns
-------
powerFractions : 2-list
A list with nCycles elements, where each element is itself a list of the
power fractions at each step of the cycle.
Notes
-----
This is stored outside of the Operator class so that it can be easily called
to resolve case settings objects in other contexts (i.e. in the preparation
of restart runs).
"""
if cs["cycles"] != []:
return [
expandRepeatedFloats(
(cycle["power fractions"])
if "power fractions" in cycle.keys()
else [1] * getBurnSteps(cs)[cycleIdx]
)
for (cycleIdx, cycle) in enumerate(cs["cycles"])
]
else:
valuePerCycle = (
expandRepeatedFloats(cs["powerFractions"])
if cs["powerFractions"] not in [None, []]
else [1.0] * cs["nCycles"]
)
return [
[value] * (cs["burnSteps"] if cs["burnSteps"] is not None else 0)
for value in valuePerCycle
]
def getCycleNames(cs):
"""
Return the names of each cycle. If a name is omitted, it is `None`.
Parameters
----------
cs : case settings object
Returns
-------
cycleNames : list
A list of the availability factors.
Notes
-----
This is stored outside of the Operator class so that it can be easily called
to resolve case settings objects in other contexts (i.e. in the preparation
of restart runs).
"""
if cs["cycles"] != []:
return [
(cycle["name"] if "name" in cycle.keys() else None)
for cycle in cs["cycles"]
]
else:
return [None] * cs["nCycles"]
def getAvailabilityFactors(cs):
"""
Return the availability factors for each cycle.
Parameters
----------
cs : case settings object
Returns
-------
availabilityFactors : list
A list of the availability factors.
Notes
-----
This is stored outside of the Operator class so that it can be easily called
to resolve case settings objects in other contexts (i.e. in the preparation
of restart runs).
"""
if cs["cycles"] != []:
availabilityFactors = []
for cycle in cs["cycles"]:
if "availability factor" in cycle.keys():
availabilityFactors.append(cycle["availability factor"])
else:
availabilityFactors.append(1)
return availabilityFactors
else:
return (
expandRepeatedFloats(cs["availabilityFactors"])
if cs["availabilityFactors"] not in [None, []]
else (
[cs["availabilityFactor"]] * cs["nCycles"]
if cs["availabilityFactor"] is not None
else [1]
)
)
def _getStepAndCycleLengths(cs):
r"""
Get both steps and lengths together to prevent chicken/egg problem.
Notes
-----
Using this method directly is more effecient than calling `getStepLengths`
and `getCycleLengths` separately, but it is probably more clear to the user
to call each of them separately.
"""
stepLengths = []
availabilityFactors = getAvailabilityFactors(cs)
if cs["cycles"] != []:
for cycleIdx, cycle in enumerate(cs["cycles"]):
cycleKeys = cycle.keys()
if "step days" in cycleKeys:
stepLengths.append(expandRepeatedFloats(cycle["step days"]))
elif "cumulative days" in cycleKeys:
cumulativeDays = cycle["cumulative days"]
stepLengths.append(getStepsFromValues(cumulativeDays))
elif "burn steps" in cycleKeys and "cycle length" in cycleKeys:
stepLengths.append(
[
cycle["cycle length"]
* availabilityFactors[cycleIdx]
/ cycle["burn steps"]
]
* cycle["burn steps"]
)
else:
raise ValueError(
f"No cycle time history is given in the detailed cycles history for cycle {cycleIdx}"
)
cycleLengths = [sum(cycleStepLengths) for cycleStepLengths in stepLengths]
cycleLengths = [
cycleLength / aFactor
for (cycleLength, aFactor) in zip(cycleLengths, availabilityFactors)
]
else:
cycleLengths = (
expandRepeatedFloats(cs["cycleLengths"])
if cs["cycleLengths"] not in [None, []]
else (
[cs["cycleLength"]] * cs["nCycles"]
if cs["cycleLength"] is not None
else [0]
)
)
cycleLengthsModifiedByAvailability = [
length * availability
for (length, availability) in zip(cycleLengths, availabilityFactors)
]
stepLengths = (
[
[length / cs["burnSteps"]] * cs["burnSteps"]
for length in cycleLengthsModifiedByAvailability
]
if cs["burnSteps"] not in [0, None]
else [[]]
)
return stepLengths, cycleLengths
def getStepLengths(cs):
"""
Return the length of each step in each cycle.
Parameters
----------
cs : case settings object
Returns
-------
stepLengths : 2-list
A list with elements for each cycle, where each element itself is a list
containing the step lengths in days.
Notes
-----
This is stored outside of the Operator class so that it can be easily called
to resolve case settings objects in other contexts (i.e. in the preparation
of restart runs).
"""
return _getStepAndCycleLengths(cs)[0]
def getCycleLengths(cs):
"""
Return the lengths of each cycle in days.
Parameters
----------
cs : case settings object
Returns
-------
cycleLengths : list
A list of the cycle lengths in days.
Notes
-----
This is stored outside of the Operator class so that it can be easily called
to resolve case settings objects in other contexts (i.e. in the preparation
of restart runs).
"""
return _getStepAndCycleLengths(cs)[1]
def getBurnSteps(cs):
"""
Return the number of burn steps for each cycle.
Parameters
----------
cs : case settings object
Returns
-------
burnSteps : list
A list of the number of burn steps.
Notes
-----
This is stored outside of the Operator class so that it can be easily called
to resolve case settings objects in other contexts (i.e. in the preparation
of restart runs).
"""
stepLengths = getStepLengths(cs)
return [len(steps) for steps in stepLengths]
def hasBurnup(cs):
"""Test if depletion is being modeled.
Parameters
----------
cs : case settings object
Returns
-------
bool
Are there any burnup steps?
"""
return sum(getBurnSteps(cs)) > 0
def getMaxBurnSteps(cs):
burnSteps = getBurnSteps(cs)
return max(burnSteps)
def getCumulativeNodeNum(cycle, node, cs):
"""
Return the cumulative node number associated with a cycle and time node.
Note that a cycle with n time steps has n+1 nodes, and for cycle m with n steps, nodes
(m, n+1) and (m+1, 0) are counted separately.
Parameters
----------
cycle : int
The cycle number
node : int
The intra-cycle time node (0 for BOC, etc.)
cs : Settings object
"""
nodesPerCycle = getNodesPerCycle(cs)
return sum(nodesPerCycle[:cycle]) + node
def getCycleNodeFromCumulativeStep(timeStepNum, cs):
"""
Return the (cycle, node) corresponding to a cumulative time step number.
"Node" refers to the node at the start of the time step.
Parameters
----------
timeStepNum : int
The cumulative number of time steps since the beginning
cs : case settings object
A case settings object to get the steps-per-cycle from
Notes
-----
Time steps are the spaces between time nodes, and are 1-indexed.
To get the (cycle, node) from a cumulative time node, see instead
getCycleNodeFromCumulativeNode.
"""
stepsPerCycle = getBurnSteps(cs)
if timeStepNum < 1:
raise ValueError("Cumulative time step cannot be less than 1.")
cSteps = 0 # cumulative steps
for i in range(len(stepsPerCycle)):
cSteps += stepsPerCycle[i]
if timeStepNum <= cSteps:
return (i, timeStepNum - (cSteps - stepsPerCycle[i]) - 1)
i = len(stepsPerCycle) - 1
return (i, timeStepNum - (cSteps - stepsPerCycle[i]) - 1)
def getCycleNodeFromCumulativeNode(timeNodeNum, cs):
"""
Return the (cycle, node) corresponding to a cumulative time node number.
Parameters
----------
timeNodeNum : int
The cumulative number of time nodes since the beginning
cs : case settings object
A case settings object to get the nodes-per-cycle from
Notes
-----
Time nodes are the start/end of time steps, and are 0-indexed. For a cycle
with n steps, there will be n+1 nodes (one at the start of the cycle and another
at the end, plus those separating the steps). For cycle m with n steps, nodes
(m, n+1) and (m+1, 0) are counted separately.
To get the (cycle, node) from a cumulative time step, see instead
getCycleNodeFromCumulativeStep.
"""
nodesPerCycle = getNodesPerCycle(cs)
if timeNodeNum < 0:
raise ValueError("Cumulative time node cannot be less than 0.")
cNodes = 0 # cumulative nodes
for i in range(len(nodesPerCycle)):
cNodes += nodesPerCycle[i]
if timeNodeNum < cNodes:
return (i, timeNodeNum - (cNodes - nodesPerCycle[i]))
i = len(nodesPerCycle) - 1
return (i, timeNodeNum - (cNodes - nodesPerCycle[i]))
def getNodesPerCycle(cs):
"""Return the number of nodes per cycle for the case settings object."""
return [s + 1 for s in getBurnSteps(cs)]
def getPreviousTimeNode(cycle, node, cs):
"""Return the (cycle, node) before the specified (cycle, node)."""
if (cycle, node) == (0, 0):
raise ValueError("There is no time step before (0, 0)")
if node != 0:
return (cycle, node - 1)
else:
nodesPerCycle = getNodesPerCycle(cs)
nodesInLastCycle = nodesPerCycle[cycle - 1]
indexOfLastNode = nodesInLastCycle - 1 # zero based indexing for nodes
return (cycle - 1, indexOfLastNode)
def tryPickleOnAllContents(obj, ignore=None, verbose=False):
r"""
Attempts to pickle all members of this object and identifies those who cannot be pickled.
Useful for debugging MPI-bcast errors
Not recursive yet. Would be nice to have it loop through nested objects (blocks in assems in reactors)
Parameters
----------
obj : object
Any object to be tested.
ignore : iterable
list of string variable names to ignore.
verbose : bool, optional
Print all objects whether they fail or not
"""
if ignore is None:
ignore = []
# pickle gives better error messages than cPickle
for name, ob in obj.__dict__.items():
if name not in ignore:
if verbose:
print("Checking {0}...".format(name))
try:
pickle.dumps(ob) # dump as a string
except: # noqa: bare-except
print(
"{0} in {1} cannot be pickled. It is: {2}. ".format(name, obj, ob)
)
def doTestPickleOnAllContents2(obj, ignore=None):
r"""
Attempts to find one unpickleable object in a nested object.
Returns
-------
pickleChain : list
list of names in a chain that are unpickleable. Just one example per object
e.g. ['r','assemblies','A101','lib] means the lib is unpicklable.
"""
if ignore is None:
ignore = []
unpickleable = []
if not hasattr(obj, "__dict__"):
print("done")
return unpickleable
for name, ob in obj.__dict__.items():
print(("checking ", name))
if name not in ignore:
try:
pickle.dumps(ob) # dump as a string
except: # noqa: bare-except
unpickleable.append(name)
print("Cant pickle {0}".format(name))
# recursive call.
unpickleable.extend(
doTestPickleOnAllContents2(ob, ignore=unpickleable + ignore)
)
return unpickleable
class MyPickler(pickle.Pickler):
r"""
This will find your pickle errors if all else fails.
Use with tryPickleOnAllContents3.
"""
def save(self, obj):
try:
pickle.Pickler.save(self, obj)
except Exception:
_excType, excValue, _excTraceback = sys.exc_info()
print("Object that failed: {}. Err: {}".format(obj, excValue))
raise
def tryPickleOnAllContents3(obj):
"""
Definitely find pickle errors.
Notes
-----
In this form, this just finds one pickle error and then crashes. If you want
to make it work like the other testPickle functions and handle errors, you could.
But usually you just have to find one unpickleable SOB.
"""
with tempfile.TemporaryFile() as output:
try:
MyPickler(output).dump(obj)
except (pickle.PicklingError, TypeError):
pass
def classesInHierarchy(obj, classCounts, visited=None):
"""Count the number of instances of each class contained in an objects heirarchy."""
if not isinstance(classCounts, collections.defaultdict):
raise TypeError(
"Need to pass in a default dict for classCounts (it's an out param)"
)
if visited is None:
classCounts[type(obj)] += 1
visited = set()
visited.add(id(obj))
try:
for c in obj.__dict__.values():
if id(c) not in visited:
classCounts[type(c)] += 1
visited.add(id(c))
classesInHierarchy(c, classCounts, visited=visited)
except AttributeError:
pass
def slantSplit(val, ratio, nodes, order="low first"):
"""
Returns a list of values whose sum is equal to the value specified.
The ratio between the highest and lowest value is equal to the specified ratio,
and the middle values trend linearly between them.
"""
val = float(val)
ratio = float(ratio)
nodes = int(nodes)
v0 = 2.0 * val / (nodes * (1.0 + ratio))
X = []
for i in range(nodes):
X.append(v0 + i * (v0 * ratio - v0) / (nodes - 1))
if order == "high first":
X.reverse()
return X
def prependToList(originalList, listToPrepend):
"""
Add a new list to the beginnning of an original list.
Parameters
----------
originalList : list
The list to prepend to.
listToPrepend : list
The list to add to the beginning of (prepend) the originalList.
Returns
-------
originalList : list
The original list with the listToPrepend at it's beginning.
"""
listToPrepend.reverse()
originalList.reverse()
originalList.extend(listToPrepend)
originalList.reverse()
listToPrepend.reverse()
return originalList
def capStrLen(s: str, length: int) -> str:
"""
Truncates a string to a certain length.
Adds '...' if it's too long.
Parameters
----------
s : str
The string to cap at length l.
length : int
The maximum length of the string s.
"""
if length <= 2:
raise Exception("l must be at least 3 in utils.capStrLen")
if len(s) <= length:
return s
return s[0 : length - 3] + "..."
def list2str(strings, width=None, preStrings=None, fmt=None):
"""
Turn a list of strings into one string, applying the specified format to each.
Parameters
----------
strings : list
The items to create centered strings in the line for.
Can be str, float, int, etc.
width : int, optional
The maximum width that the strings are allowed to take up.
Only strings are affected by this parameter, because it does
not make sense to truncate ints or floats.
preStrings : list of str, optional
Any strings that come before the centered strings.
fmt : str, optional
The format to apply to each string, such as
' >4d', '^12.4E'.
"""
if preStrings is None:
preStrings = []
if fmt is None:
fmt = ""
newStrings = []
for string in strings:
if isinstance(string, str) and width is not None:
string = capStrLen(str(string), width)
string = "{0:{fmt}}".format(string, fmt=fmt)
newStrings.append(string)
preStrings.extend(newStrings)
return "".join(preStrings)
def createFormattedStrWithDelimiter(
dataList, maxNumberOfValuesBeforeDelimiter=9, delimiter="\n"
):
r"""
Return a formatted string with delimiters from a list of data.
Parameters
----------
dataList : list
List of data that will be formatted into a string
maxNumberOfValuesBeforeDelimiter : int
maximum number of values to have before the delimiter is added
delimiter : str
A delimiter on the formatted string (default: "\n")
Notes
-----
As an example::
>>> createFormattedStrWithDelimiter(['hello', 'world', '1', '2', '3', '4'],
... maxNumberOfValuesBeforeDelimiter=3, delimiter = '\n')
"hello, world, 1, \n2, 3, \n4, 5\n"
"""
formattedString = ""
if not dataList:
return formattedString
if not maxNumberOfValuesBeforeDelimiter:
numRows = 1
else:
numRows = (
int(
math.ceil(
float(len(dataList)) / float(maxNumberOfValuesBeforeDelimiter)
)
)
or 1
)
# Create a list of string delimiters to use when joining the strings
commaList = ["," for d in dataList]
commaList[-1] = ""
dataList = [str(d) + commaList[i] for i, d in enumerate(dataList)]
for splitList in iterables.split(dataList, n=numRows, padWith=""):
formattedString += " ".join(splitList) + delimiter
return formattedString
def plotMatrix(
matrix,
fName,
minV=None,
maxV=None,
show=False,
title=None,
xlabel=None,
ylabel=None,
xticks=None,
yticks=None,
cmap=None,
figsize=None,
):
"""Plots a matrix."""
import matplotlib
import matplotlib.pyplot as plt
if figsize:
plt.figure(figsize=figsize)
else:
plt.figure()
if cmap is None:
cmap = plt.cm.jet
cmap.set_bad("w")
try:
matrix = matrix.todense()
except: # noqa: bare-except
pass
if minV:
norm = matplotlib.colors.Normalize(minV, maxV)
else:
norm = None
if title is None:
title = fName
# or bicubic or nearest#,vmin=0, vmax=300)
plt.imshow(matrix, cmap=cmap, norm=norm, interpolation="nearest")
plt.colorbar()
plt.title(title)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
if xticks:
plt.xticks(*xticks, rotation=90)
if yticks:
plt.yticks(*yticks)
plt.grid()
plt.savefig(fName)
if show:
plt.show()
plt.close()
def userName() -> str:
"""
Return a database-friendly username.
This will return the current user's username, removing any prefix like ``pre-``, if
present.
Notes
-----
ARMI uses the user name in a number of places, namely in the database names, which
cannot contain hyphens.
"""
return re.sub("^[a-zA-Z]-", "", getpass.getuser())
class MergeableDict(dict):
"""
Overrides python dictionary and implements a merge method.
Notes
-----
Allows multiple dictionaries to be combined in a single line
"""
def merge(self, *otherDictionaries) -> None:
for dictionary in otherDictionaries:
self.update(dictionary)
def safeCopy(src: str, dst: str) -> None:
"""This copy overwrites ``shutil.copy`` and checks that copy operation is truly completed before continuing."""
# Convert files to OS-independence
src = os.path.abspath(src)
dst = os.path.abspath(dst)
if os.path.isdir(dst):
dst = os.path.join(dst, os.path.basename(src))
srcSize = os.path.getsize(src)
if "win" in sys.platform:
cmd = f'copy "{src}" "{dst}"'
elif "linux" in sys.platform:
cmd = f'cp "{src}" "{dst}"'
else:
runLog.warning(
"Cannot perform ``safeCopy`` on files because ARMI only supports "
+ "Linux and Windows."
)
os.system(cmd)
waitTime = 0.01 # 10 ms
maxWaitTime = 1800 # 30 min
totalWaitTime = 0
while True:
dstSize = os.path.getsize(dst)
if srcSize == dstSize:
break
time.sleep(waitTime)
totalWaitTime += waitTime
if totalWaitTime > maxWaitTime:
runLog.warning(
f"File copy from {dst} to {src} has failed due to exceeding "
+ f"``maxWaitTime`` of {maxWaitTime/60} min."
)
break
runLog.extra("Copied {} -> {}".format(src, dst))
# Allow us to check the copy operation is complete before continuing
shutil_copy = shutil.copy
shutil.copy = safeCopy