-
Notifications
You must be signed in to change notification settings - Fork 92
/
Copy pathtest_reactors.py
1129 lines (955 loc) · 42.5 KB
/
test_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.
"""Testing for reactors.py."""
import copy
import logging
import os
import unittest
from numpy.testing import assert_allclose, assert_equal
from six.moves import cPickle
from armi import operators
from armi import runLog
from armi import settings
from armi import tests
from armi.materials import uZr
from armi.physics.neutronics.settings import CONF_XS_KERNEL
from armi.reactor import assemblies
from armi.reactor import blocks
from armi.reactor import geometry
from armi.reactor import grids
from armi.reactor import reactors
from armi.reactor.components import Hexagon, Rectangle
from armi.reactor.converters import geometryConverters
from armi.reactor.converters.axialExpansionChanger import AxialExpansionChanger
from armi.reactor.flags import Flags
from armi.settings.fwSettings.globalSettings import CONF_ASSEM_FLAGS_SKIP_AXIAL_EXP
from armi.settings.fwSettings.globalSettings import CONF_SORT_REACTOR
from armi.tests import ARMI_RUN_PATH, mockRunLogs, TEST_ROOT
from armi.utils import directoryChangers
TEST_REACTOR = None # pickled string of test reactor (for fast caching)
def buildOperatorOfEmptyHexBlocks(customSettings=None):
"""
Builds a operator w/ a reactor object with some hex assemblies and blocks, but all are empty.
Doesn't depend on inputs and loads quickly.
Parameters
----------
customSettings : dict
Dictionary of off-default settings to update
"""
settings.setMasterCs(None) # clear
cs = settings.Settings() # fetch new
settings.setMasterCs(cs) # reset
if customSettings is None:
customSettings = {}
customSettings["db"] = False # stop use of database
cs = cs.modified(newSettings=customSettings)
settings.setMasterCs(cs) # reset so everything matches the primary Cs
r = tests.getEmptyHexReactor()
r.core.setOptionsFromCs(cs)
o = operators.Operator(cs)
o.initializeInterfaces(r)
a = assemblies.HexAssembly("fuel")
a.spatialGrid = grids.axialUnitGrid(1)
b = blocks.HexBlock("TestBlock")
b.setType("fuel")
dims = {"Tinput": 600, "Thot": 600, "op": 16.0, "ip": 1, "mult": 1}
c = Hexagon("fuel", uZr.UZr(), **dims)
b.add(c)
a.add(b)
a.spatialLocator = r.core.spatialGrid[1, 0, 0]
o.r.core.add(a)
o.r.sort()
return o
def buildOperatorOfEmptyCartesianBlocks(customSettings=None):
"""
Builds a operator w/ a reactor object with some Cartesian assemblies and blocks, but all are empty.
Doesn't depend on inputs and loads quickly.
Parameters
----------
customSettings : dict
Off-default settings to update
"""
settings.setMasterCs(None) # clear
cs = settings.Settings() # fetch new
settings.setMasterCs(cs) # reset
if customSettings is None:
customSettings = {}
customSettings["db"] = False # stop use of database
cs = cs.modified(newSettings=customSettings)
settings.setMasterCs(cs) # reset
r = tests.getEmptyCartesianReactor()
r.core.setOptionsFromCs(cs)
o = operators.Operator(cs)
o.initializeInterfaces(r)
a = assemblies.CartesianAssembly("fuel")
a.spatialGrid = grids.axialUnitGrid(1)
b = blocks.CartesianBlock("TestBlock")
b.setType("fuel")
dims = {
"Tinput": 600,
"Thot": 600,
"widthOuter": 16.0,
"lengthOuter": 10.0,
"widthInner": 1,
"lengthInner": 1,
"mult": 1,
}
c = Rectangle("fuel", uZr.UZr(), **dims)
b.add(c)
a.add(b)
a.spatialLocator = r.core.spatialGrid[1, 0, 0]
o.r.core.add(a)
o.r.sort()
return o
"""
NOTE: If this reactor had 3 rings instead of 9, most unit tests that use it
go 4 times faster (based on testing). The problem is it would breat a LOT
of downstream tests that import this method. Probably still worth it though.
"""
def loadTestReactor(
inputFilePath=TEST_ROOT,
customSettings=None,
inputFileName="armiRun.yaml",
):
"""
Loads a test reactor. Can be used in other test modules.
Parameters
----------
inputFilePath : str, default=TEST_ROOT
Path to the directory of the input file.
customSettings : dict with str keys and values of any type, default=None
For each key in customSettings, the cs which is loaded from the
armiRun.yaml will be overwritten to the value given in customSettings
for that key.
inputFileName : str, default="armiRun.yaml"
Name of the input file to run.
Returns
-------
o : Operator
r : Reactor
"""
# TODO: it would be nice to have this be more stream-oriented. Juggling files is
# devilishly difficult.
global TEST_REACTOR
fName = os.path.join(inputFilePath, inputFileName)
customSettings = customSettings or {}
isPickeledReactor = fName == ARMI_RUN_PATH and customSettings == {}
assemblies.resetAssemNumCounter()
if isPickeledReactor and TEST_REACTOR:
# return test reactor only if no custom settings are needed.
o, r, assemNum = cPickle.loads(TEST_REACTOR)
assemblies.setAssemNumCounter(assemNum)
settings.setMasterCs(o.cs)
o.reattach(r, o.cs)
return o, r
cs = settings.Settings(fName=fName)
# Overwrite settings if desired
if customSettings:
cs = cs.modified(newSettings=customSettings)
if "verbosity" not in customSettings:
runLog.setVerbosity("error")
newSettings = {}
cs = cs.modified(newSettings=newSettings)
settings.setMasterCs(cs)
o = operators.factory(cs)
r = reactors.loadFromCs(cs)
o.initializeInterfaces(r)
# put some stuff in the SFP too.
for a in range(10):
a = o.r.blueprints.constructAssem(o.cs, name="feed fuel")
o.r.sfp.add(a)
o.r.core.regenAssemblyLists()
if isPickeledReactor:
# cache it for fast load for other future tests
# protocol=2 allows for classes with __slots__ but not __getstate__ to be pickled
TEST_REACTOR = cPickle.dumps((o, o.r, assemblies.getAssemNum()), protocol=2)
return o, o.r
def reduceTestReactorRings(r, cs, maxNumRings):
"""Helper method for the test reactor above.
The goal is to reduce the size of the reactor for tests that don't neeed
such a large reactor, and would run much faster with a smaller one.
"""
maxRings = r.core.getNumRings()
if maxNumRings > maxRings:
runLog.info("The test reactor has a maximum of {} rings.".format(maxRings))
return
elif maxNumRings <= 1:
raise ValueError("The test reactor must have multiple rings.")
# reducing the size of the test reactor, by removing the outer rings
for ring in range(maxRings, maxNumRings, -1):
r.core.removeAssembliesInRing(ring, cs)
class ReactorTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
# prepare the input files. This is important so the unit tests run from wherever
# they need to run from.
cls.directoryChanger = directoryChangers.DirectoryChanger(TEST_ROOT)
cls.directoryChanger.open()
@classmethod
def tearDownClass(cls):
cls.directoryChanger.close()
class HexReactorTests(ReactorTests):
def setUp(self):
self.o, self.r = loadTestReactor(
self.directoryChanger.destination, customSettings={"trackAssems": True}
)
def test_factorySortSetting(self):
# get a sorted Reactor (the default)
cs = settings.Settings(fName="armiRun.yaml")
r0 = reactors.loadFromCs(cs)
# get an unsorted Reactor (for whatever reason)
customSettings = {CONF_SORT_REACTOR: False}
cs = cs.modified(newSettings=customSettings)
r1 = reactors.loadFromCs(cs)
# the reactor / core should be the same size
self.assertEqual(len(r0), len(r1))
self.assertEqual(len(r0.core), len(r1.core))
# the reactor / core should be in a different order
a0 = [a.name for a in r0.core]
a1 = [a.name for a in r1.core]
self.assertNotEqual(a0, a1)
def test_sortChildren(self):
self.assertEqual(next(self.r.core.__iter__()), self.r.core[0])
self.assertEqual(self.r.core._children, sorted(self.r.core._children))
def test_sortAssemByRing(self):
"""Demonstrate ring/pos sorting."""
self.r.core.sortAssemsByRing()
self.assertEqual((1, 1), self.r.core[0].spatialLocator.getRingPos())
currentRing = -1
currentPos = -1
for a in self.r.core:
ring, pos = a.spatialLocator.getRingPos()
self.assertGreaterEqual(ring, currentRing)
if ring > currentRing:
ring = currentRing
currentPos = -1
self.assertGreater(pos, currentPos)
currentPos = pos
def test_getTotalParam(self):
# verify that the block params are being read.
val = self.r.core.getTotalBlockParam("power")
val2 = self.r.core.getTotalBlockParam("power", addSymmetricPositions=True)
self.assertEqual(val2 / self.r.core.powerMultiplier, val)
def test_geomType(self):
self.assertEqual(self.r.core.geomType, geometry.GeomType.HEX)
def test_growToFullCore(self):
nAssemThird = len(self.r.core)
self.assertEqual(self.r.core.powerMultiplier, 3.0)
self.assertFalse(self.r.core.isFullCore)
self.r.core.growToFullCore(self.o.cs)
aNums = []
for a in self.r.core.getChildren():
self.assertNotIn(a.getNum(), aNums)
aNums.append(a.getNum())
bNames = [b.getName() for b in self.r.core.getBlocks()]
for bName in bNames:
self.assertEqual(bNames.count(bName), 1)
self.assertEqual(self.r.core.powerMultiplier, 1.0)
self.assertTrue(self.r.core.isFullCore)
nAssemFull = len(self.r.core)
self.assertEqual(nAssemFull, (nAssemThird - 1) * 3 + 1)
def test_getBlocksByIndices(self):
indices = [(1, 1, 1), (3, 2, 2)]
actualBlocks = self.r.core.getBlocksByIndices(indices)
actualNames = [b.getName() for b in actualBlocks]
expectedNames = ["B0022-001", "B0043-002"]
self.assertListEqual(expectedNames, actualNames)
def test_getAllXsSuffixes(self):
actualSuffixes = self.r.core.getAllXsSuffixes()
expectedSuffixes = ["AA"]
self.assertListEqual(expectedSuffixes, actualSuffixes)
def test_countBlocksOfType(self):
numControlBlocks = self.r.core.countBlocksWithFlags([Flags.DUCT, Flags.CONTROL])
self.assertEqual(numControlBlocks, 3)
numControlBlocks = self.r.core.countBlocksWithFlags(
[Flags.DUCT, Flags.CONTROL, Flags.FUEL], Flags.CONTROL
)
self.assertEqual(numControlBlocks, 3)
def test_setB10VolOnCreation(self):
"""Test the setting of b.p.initialB10ComponentVol."""
for controlBlock in self.r.core.getBlocks(Flags.CONTROL):
controlComps = [c for c in controlBlock if c.getNumberDensity("B10") > 0]
self.assertEqual(len(controlComps), 1)
controlComp = controlComps[0]
startingVol = controlBlock.p.initialB10ComponentVol
self.assertGreater(startingVol, 0)
self.assertAlmostEqual(
controlComp.getArea(cold=True) * controlBlock.getHeight(), startingVol
)
# input temp is same as hot temp, so change input temp to test that behavior
controlComp.inputTemperatureInC = 30
# somewhat non-sensical since its hot, not cold but we just want to check the ratio
controlBlock.setB10VolParam(True)
self.assertGreater(startingVol, controlBlock.p.initialB10ComponentVol)
self.assertAlmostEqual(
startingVol / controlComp.getThermalExpansionFactor(),
controlBlock.p.initialB10ComponentVol,
)
def test_countFuelAxialBlocks(self):
"""Tests that the users definition of fuel blocks is preserved.
.. test:: Tests that the users definition of fuel blocks is preserved.
:id: TEST_REACTOR_2
:links: REQ_REACTOR
"""
numFuelBlocks = self.r.core.countFuelAxialBlocks()
self.assertEqual(numFuelBlocks, 3)
def test_getFirstFuelBlockAxialNode(self):
firstFuelBlock = self.r.core.getFirstFuelBlockAxialNode()
self.assertEqual(firstFuelBlock, 1)
def test_getMaxAssembliesInHexRing(self):
maxAssems = self.r.core.getMaxAssembliesInHexRing(3)
self.assertEqual(maxAssems, 4)
def test_getMaxNumPins(self):
numPins = self.r.core.getMaxNumPins()
self.assertEqual(169, numPins)
def test_addMoreNodes(self):
originalMesh = self.r.core.p.axialMesh
bigMesh = list(originalMesh)
bigMesh[2] = 30.0
smallMesh = originalMesh[0:2] + [40.0, 47.0] + originalMesh[2:]
newMesh1, originalMeshGood = self.r.core.addMoreNodes(originalMesh)
newMesh2, bigMeshGood = self.r.core.addMoreNodes(bigMesh)
newMesh3, smallMeshGood = self.r.core.addMoreNodes(smallMesh)
expectedMesh = [0.0, 25.0, 50.0, 75.0, 100.0, 118.75, 137.5, 156.25, 175.0]
expectedBigMesh = [
0.0,
25.0,
30.0,
36.75,
75.0,
100.0,
118.75,
137.5,
156.25,
175.0,
]
expectedSmallMesh = [
0.0,
25.0,
40.0,
47.0,
50.0,
53.75,
75.0,
100.0,
118.75,
137.5,
156.25,
175.0,
]
self.assertListEqual(expectedMesh, newMesh1)
self.assertListEqual(expectedBigMesh, newMesh2)
self.assertListEqual(expectedSmallMesh, newMesh3)
self.assertTrue(originalMeshGood)
self.assertFalse(bigMeshGood)
self.assertFalse(smallMeshGood)
def test_findAxialMeshIndexOf(self):
numMeshPoints = (
len(self.r.core.p.axialMesh) - 2
) # -1 for typical reason, -1 more because mesh includes 0
self.assertEqual(self.r.core.findAxialMeshIndexOf(0.0), 0)
self.assertEqual(self.r.core.findAxialMeshIndexOf(0.1), 0)
self.assertEqual(
self.r.core.findAxialMeshIndexOf(self.r.core[0].getHeight()), numMeshPoints
)
self.assertEqual(
self.r.core.findAxialMeshIndexOf(self.r.core[0].getHeight() - 0.1),
numMeshPoints,
)
self.assertEqual(
self.r.core.findAxialMeshIndexOf(self.r.core[0][0].getHeight() + 0.1), 1
)
def test_findAllAxialMeshPoints(self):
mesh = self.r.core.findAllAxialMeshPoints(applySubMesh=False)
self.assertEqual(mesh[0], 0)
self.assertAlmostEqual(mesh[-1], self.r.core[0].getHeight())
blockMesh = self.r.core.getFirstAssembly(Flags.FUEL).spatialGrid._bounds[2]
assert_allclose(blockMesh, mesh)
def test_findAllAxialMeshPoints_wSubmesh(self):
referenceMesh = [0.0, 25.0, 50.0, 75.0, 100.0, 118.75, 137.5, 156.25, 175.0]
mesh = self.r.core.findAllAxialMeshPoints(
assems=[self.r.core.getFirstAssembly(Flags.FUEL)], applySubMesh=True
)
self.assertListEqual(referenceMesh, mesh)
def test_findAllAziMeshPoints(self):
aziPoints = self.r.core.findAllAziMeshPoints()
expectedPoints = [
-50.7707392969,
-36.2648137835,
-21.7588882701,
-7.2529627567,
7.2529627567,
21.7588882701,
36.2648137835,
50.7707392969,
65.2766648103,
79.7825903236,
94.288515837,
108.7944413504,
123.3003668638,
]
assert_allclose(expectedPoints, aziPoints)
def test_findAllRadMeshPoints(self):
radPoints = self.r.core.findAllRadMeshPoints()
expectedPoints = [
-12.5625,
-4.1875,
4.1875,
12.5625,
20.9375,
29.3125,
37.6875,
46.0625,
54.4375,
62.8125,
71.1875,
79.5625,
87.9375,
96.3125,
104.6875,
113.0625,
121.4375,
129.8125,
138.1875,
146.5625,
]
assert_allclose(expectedPoints, radPoints)
def test_findNeighbors(self):
loc = self.r.core.spatialGrid.getLocatorFromRingAndPos(1, 1)
a = self.r.core.childrenByLocator[loc]
neighbs = self.r.core.findNeighbors(
a, duplicateAssembliesOnReflectiveBoundary=True
)
locs = [a.spatialLocator.getRingPos() for a in neighbs]
self.assertEqual(len(neighbs), 6)
self.assertIn((2, 1), locs)
self.assertIn((2, 2), locs)
self.assertEqual(locs.count((2, 1)), 3)
loc = self.r.core.spatialGrid.getLocatorFromRingAndPos(1, 1)
a = self.r.core.childrenByLocator[loc]
neighbs = self.r.core.findNeighbors(
a, duplicateAssembliesOnReflectiveBoundary=True
)
locs = [a.spatialLocator.getRingPos() for a in neighbs]
self.assertEqual(locs, [(2, 1), (2, 2)] * 3, 6)
loc = self.r.core.spatialGrid.getLocatorFromRingAndPos(2, 2)
a = self.r.core.childrenByLocator[loc]
neighbs = self.r.core.findNeighbors(
a, duplicateAssembliesOnReflectiveBoundary=True
)
locs = [a.spatialLocator.getRingPos() for a in neighbs]
self.assertEqual(len(neighbs), 6)
self.assertEqual(locs, [(3, 2), (3, 3), (3, 12), (2, 1), (1, 1), (2, 1)])
# try with edge assemblies
# With edges, the neighbor is the one that's actually next to it.
converter = geometryConverters.EdgeAssemblyChanger()
converter.addEdgeAssemblies(self.r.core)
loc = self.r.core.spatialGrid.getLocatorFromRingAndPos(2, 2)
a = self.r.core.childrenByLocator[loc]
neighbs = self.r.core.findNeighbors(
a, duplicateAssembliesOnReflectiveBoundary=True
)
locs = [a.spatialLocator.getRingPos() for a in neighbs]
self.assertEqual(len(neighbs), 6)
# in this case no locations that aren't actually in the core should be returned
self.assertEqual(locs, [(3, 2), (3, 3), (3, 4), (2, 1), (1, 1), (2, 1)])
converter.removeEdgeAssemblies(self.r.core)
# try with full core
self.r.core.growToFullCore(self.o.cs)
loc = self.r.core.spatialGrid.getLocatorFromRingAndPos(3, 4)
a = self.r.core.childrenByLocator[loc]
neighbs = self.r.core.findNeighbors(a)
self.assertEqual(len(neighbs), 6)
locs = [a.spatialLocator.getRingPos() for a in neighbs]
for loc in [(2, 2), (2, 3), (3, 3), (3, 5), (4, 5), (4, 6)]:
self.assertIn(loc, locs)
loc = self.r.core.spatialGrid.getLocatorFromRingAndPos(2, 2)
a = self.r.core.childrenByLocator[loc]
neighbs = self.r.core.findNeighbors(a)
locs = [a.spatialLocator.getRingPos() for a in neighbs]
for loc in [(1, 1), (2, 1), (2, 3), (3, 2), (3, 3), (3, 4)]:
self.assertIn(loc, locs)
# Try the duplicate option in full core as well
loc = self.r.core.spatialGrid.getLocatorFromRingAndPos(2, 2)
a = self.r.core.childrenByLocator[loc]
neighbs = self.r.core.findNeighbors(
a, duplicateAssembliesOnReflectiveBoundary=True
)
locs = [a.spatialLocator.getRingPos() for a in neighbs]
self.assertEqual(len(neighbs), 6)
self.assertEqual(locs, [(3, 2), (3, 3), (3, 4), (2, 3), (1, 1), (2, 1)])
def test_getAssembliesInCircularRing(self):
expectedAssemsInRing = [5, 6, 8, 10, 12, 16, 14, 2]
actualAssemsInRing = []
for ring in range(1, self.r.core.getNumRings()):
actualAssemsInRing.append(
len(self.r.core.getAssembliesInCircularRing(ring))
)
self.assertSequenceEqual(actualAssemsInRing, expectedAssemsInRing)
def test_getAssembliesInHexRing(self):
expectedAssemsInRing = [1, 2, 4, 6, 8, 10, 12, 14, 16]
actualAssemsInRing = []
for ring in range(1, self.r.core.getNumRings() + 1):
actualAssemsInRing.append(
len(self.r.core.getAssembliesInSquareOrHexRing(ring))
)
self.assertSequenceEqual(actualAssemsInRing, expectedAssemsInRing)
def test_genAssembliesAddedThisCycle(self):
allAssems = self.r.core.getAssemblies()
self.assertTrue(
all(
a1 is a2
for a1, a2 in zip(allAssems, self.r.core.genAssembliesAddedThisCycle())
)
)
a = self.r.core.getAssemblies()[0]
newA = copy.deepcopy(a)
newA.name = None
self.r.p.cycle = 1
self.assertEqual(len(list(self.r.core.genAssembliesAddedThisCycle())), 0)
self.r.core.removeAssembly(a)
self.r.core.add(newA)
self.assertEqual(next(self.r.core.genAssembliesAddedThisCycle()), newA)
def test_getAssemblyPitch(self):
self.assertEqual(self.r.core.getAssemblyPitch(), 16.75)
def test_getNumAssembliesWithAllRingsFilledOut(self):
nRings = self.r.core.getNumRings(indexBased=True)
nAssmWithBlanks = self.r.core.getNumAssembliesWithAllRingsFilledOut(nRings)
self.assertEqual(77, nAssmWithBlanks)
def test_getNumEnergyGroups(self):
# this Core doesn't have a loaded ISOTXS library, so this test is minimally useful
with self.assertRaises(AttributeError):
self.r.core.getNumEnergyGroups()
def test_getMinimumPercentFluxInFuel(self):
# there is no flux in the test reactor YET, so this test is minimally useful
with self.assertRaises(ZeroDivisionError):
_targetRing, _fluxFraction = self.r.core.getMinimumPercentFluxInFuel()
def test_getAssembly(self):
a1 = self.r.core.getAssemblyWithAssemNum(assemNum=10)
a2 = self.r.core.getAssembly(locationString="005-023")
a3 = self.r.core.getAssembly(assemblyName="A0010")
self.assertEqual(a1, a2)
self.assertEqual(a1, a3)
def test_restoreReactor(self):
aListLength = len(self.r.core.getAssemblies())
converter = self.r.core.growToFullCore(self.o.cs)
converter.restorePreviousGeometry(self.r)
self.assertEqual(aListLength, len(self.r.core.getAssemblies()))
def test_differentNuclideModels(self):
self.assertEqual(self.o.cs[CONF_XS_KERNEL], "MC2v3")
_o2, r2 = loadTestReactor(customSettings={CONF_XS_KERNEL: "MC2v2"})
self.assertNotEqual(
set(self.r.blueprints.elementsToExpand), set(r2.blueprints.elementsToExpand)
)
for b2, b3 in zip(r2.core.getBlocks(), self.r.core.getBlocks()):
for element in self.r.blueprints.elementsToExpand:
# nucspec allows elemental mass to be computed
mass2 = b2.getMass(element.symbol)
mass3 = b3.getMass(element.symbol)
assert_allclose(mass2, mass3)
constituentNucs = [nn.name for nn in element.nuclides if nn.a > 0]
nuclideLevelMass3 = b3.getMass(constituentNucs)
assert_allclose(mass3, nuclideLevelMass3)
def test_getDominantMaterial(self):
dominantDuct = self.r.core.getDominantMaterial(Flags.DUCT)
dominantFuel = self.r.core.getDominantMaterial(Flags.FUEL)
dominantCool = self.r.core.getDominantMaterial(Flags.COOLANT)
self.assertEqual(dominantDuct.getName(), "HT9")
self.assertEqual(dominantFuel.getName(), "UZr")
self.assertEqual(dominantCool.getName(), "Sodium")
self.assertEqual(list(dominantCool.getNuclides()), ["NA23"])
def test_getSymmetryFactor(self):
for b in self.r.core.getBlocks():
sym = b.getSymmetryFactor()
i, j, _ = b.spatialLocator.getCompleteIndices()
if i == 0 and j == 0:
self.assertEqual(sym, 3.0)
else:
self.assertEqual(sym, 1.0)
def test_getAssembliesOnSymmetryLine(self):
center = self.r.core.getAssembliesOnSymmetryLine(grids.BOUNDARY_CENTER)
self.assertEqual(len(center), 1)
upper = self.r.core.getAssembliesOnSymmetryLine(grids.BOUNDARY_120_DEGREES)
self.assertEqual(len(upper), 0)
lower = self.r.core.getAssembliesOnSymmetryLine(grids.BOUNDARY_0_DEGREES)
self.assertGreater(len(lower), 1)
def test_saveAllFlux(self):
# need a lightweight library to indicate number of groups.
class MockLib:
numGroups = 5
self.r.core.lib = MockLib()
for b in self.r.core.getBlocks():
b.p.mgFlux = range(5)
b.p.adjMgFlux = range(5)
self.r.core.saveAllFlux()
def test_getFluxVector(self):
class MockLib:
numGroups = 5
self.r.core.lib = MockLib()
for b in self.r.core.getBlocks():
b.p.mgFlux = range(5)
b.p.adjMgFlux = [i + 0.1 for i in range(5)]
b.p.extSrc = [i + 0.2 for i in range(5)]
mgFlux = self.r.core.getFluxVector(energyOrder=1)
adjFlux = self.r.core.getFluxVector(adjoint=True)
srcVec = self.r.core.getFluxVector(extSrc=True)
fluxVol = self.r.core.getFluxVector(volumeIntegrated=True)
expFlux = [i for i in range(5) for b in self.r.core.getBlocks()]
expAdjFlux = [i + 0.1 for b in self.r.core.getBlocks() for i in range(5)]
expSrcVec = [i + 0.2 for b in self.r.core.getBlocks() for i in range(5)]
expFluxVol = list(range(5)) * len(self.r.core.getBlocks())
assert_allclose(expFlux, mgFlux)
assert_allclose(expAdjFlux, adjFlux)
assert_allclose(expSrcVec, srcVec)
assert_allclose(expFluxVol, fluxVol)
def test_getFuelBottomHeight(self):
for a in self.r.core.getAssemblies(Flags.FUEL):
if a[0].hasFlags(Flags.FUEL):
a[0].setType("mud")
a[1].setType("fuel")
fuelBottomHeightRef = self.r.core.getFirstAssembly(Flags.FUEL)[0].getHeight()
fuelBottomHeightInCm = self.r.core.getFuelBottomHeight()
self.assertEqual(fuelBottomHeightInCm, fuelBottomHeightRef)
def test_getGridBounds(self):
(_minI, maxI), (_minJ, maxJ), (minK, maxK) = self.r.core.getBoundingIndices()
self.assertEqual((maxI, maxJ), (8, 8))
self.assertEqual((minK, maxK), (0, 0))
def test_locations(self):
loc = self.r.core.spatialGrid.getLocatorFromRingAndPos(3, 2)
a = self.r.core.childrenByLocator[loc]
assert_allclose(a.spatialLocator.indices, [1, 1, 0])
for bi, b in enumerate(a):
assert_allclose(b.spatialLocator.getCompleteIndices(), [1, 1, bi])
self.assertEqual(a.getLocation(), "003-002")
self.assertEqual(a[0].getLocation(), "003-002-000")
def test_getMass(self):
# If these are not in agreement check on block symmetry factor being applied to volumes
mass1 = self.r.core.getMass()
mass2 = sum([b.getMass() for b in self.r.core.getBlocks()])
assert_allclose(mass1, mass2)
def test_isPickleable(self):
loaded = cPickle.loads(cPickle.dumps(self.r))
# ensure we didn't break the current reactor
self.assertIs(self.r.core.spatialGrid.armiObject, self.r.core)
# make sure that the loaded reactor and grid are aligned
self.assertIs(loaded.core.spatialGrid.armiObject, loaded.core)
self.assertTrue(
all(
isinstance(key, grids.LocationBase)
for key in loaded.core.childrenByLocator.keys()
)
)
loc = loaded.core.spatialGrid[0, 0, 0]
loaded.core.sortAssemsByRing()
self.r.core.sortAssemsByRing()
self.assertIs(loc.grid, loaded.core.spatialGrid)
self.assertEqual(loaded.core.childrenByLocator[loc], loaded.core[0])
allIDs = set()
def checkAdd(comp):
self.assertNotIn(id(comp), allIDs)
self.assertNotIn(id(comp.p), allIDs)
allIDs.add(id(comp))
allIDs.add(id(comp.p))
# check a few locations to be equivalent
for a0, a1 in zip(self.r.core, loaded.core):
self.assertEqual(str(a0.getLocation()), str(a1.getLocation()))
self.assertIs(a0.spatialLocator.grid, self.r.core.spatialGrid)
self.assertIs(a1.spatialLocator.grid, loaded.core.spatialGrid)
checkAdd(a0)
checkAdd(a1)
for b0, b1 in zip(a0, a1):
self.assertIs(b0.spatialLocator.grid, a0.spatialGrid)
self.assertIs(b1.spatialLocator.grid, a1.spatialGrid)
self.assertEqual(str(b0.getLocation()), str(b1.getLocation()))
self.assertEqual(b0.getSymmetryFactor(), b1.getSymmetryFactor())
self.assertEqual(b0.getHMMoles(), b1.getHMMoles())
checkAdd(b0)
checkAdd(b1)
def test_removeAssembly(self):
a = self.r.core[-1] # last assembly
b = a[-1] # use the last block in case we ever figure out stationary blocks
aLoc = a.spatialLocator
self.assertIsNotNone(aLoc.grid)
bLoc = b.spatialLocator
self.r.core.removeAssembly(a)
self.assertNotEqual(aLoc, a.spatialLocator)
self.assertEqual(a.spatialLocator.grid, self.r.sfp.spatialGrid)
# confirm only attached to removed assem
self.assertIs(bLoc, b.spatialLocator) # block location does not change
self.assertIs(a, b.parent)
self.assertIs(a, b.spatialLocator.grid.armiObject)
def test_removeAssemblyNoSfp(self):
with mockRunLogs.BufferLog() as mock:
# we should start with a clean slate
self.assertEqual("", mock.getStdout())
runLog.LOG.startLog("test_removeAssemblyNoSfp")
runLog.LOG.setVerbosity(logging.INFO)
a = self.r.core[-1] # last assembly
aLoc = a.spatialLocator
self.assertIsNotNone(aLoc.grid)
core = self.r.core
del core.parent.sfp
core.removeAssembly(a)
self.assertIn("No Spent Fuel Pool", mock.getStdout())
def test_removeAssembliesInRing(self):
aLoc = [
self.r.core.spatialGrid.getLocatorFromRingAndPos(3, i + 1)
for i in range(12)
]
assems = {
i: self.r.core.childrenByLocator[loc]
for i, loc in enumerate(aLoc)
if loc in self.r.core.childrenByLocator
}
self.r.core.removeAssembliesInRing(3, self.o.cs)
for i, a in assems.items():
self.assertNotEqual(aLoc[i], a.spatialLocator)
self.assertEqual(a.spatialLocator.grid, self.r.sfp.spatialGrid)
def test_removeAssembliesInRingByCount(self):
self.assertEqual(self.r.core.getNumRings(), 9)
self.r.core.removeAssembliesInRing(9, self.o.cs)
self.assertEqual(self.r.core.getNumRings(), 8)
def test_removeAssembliesInRingHex(self):
"""
Since the test reactor is hex, we need to use the overrideCircularRingMode option
to remove assemblies from it.
"""
self.assertEqual(self.r.core.getNumRings(), 9)
for ringNum in range(6, 10):
self.r.core.removeAssembliesInRing(
ringNum, self.o.cs, overrideCircularRingMode=True
)
self.assertEqual(self.r.core.getNumRings(), 5)
def test_getNozzleTypes(self):
nozzleTypes = self.r.core.getNozzleTypes()
expectedTypes = ["Inner", "Outer", "lta", "Default"]
for nozzle in expectedTypes:
self.assertIn(nozzle, nozzleTypes)
def test_createAssemblyOfType(self):
"""Test creation of new assemblies."""
# basic creation
aOld = self.r.core.getFirstAssembly(Flags.FUEL)
aNew = self.r.core.createAssemblyOfType(aOld.getType(), cs=self.o.cs)
self.assertAlmostEqual(aOld.getMass(), aNew.getMass())
# test axial mesh alignment
aNewMesh = aNew.getAxialMesh()
for i, meshValue in enumerate(aNewMesh):
self.assertAlmostEqual(
meshValue, self.r.core.p.referenceBlockAxialMesh[i + 1]
) # use i+1 to skip 0.0
# creation with modified enrichment
aNew2 = self.r.core.createAssemblyOfType(aOld.getType(), 0.195, self.o.cs)
fuelBlock = aNew2.getFirstBlock(Flags.FUEL)
self.assertAlmostEqual(fuelBlock.getUraniumMassEnrich(), 0.195)
# creation with modified enrichment on an expanded BOL assem.
fuelComp = fuelBlock.getComponent(Flags.FUEL)
bol = self.r.blueprints.assemblies[aOld.getType()]
changer = AxialExpansionChanger()
changer.performPrescribedAxialExpansion(bol, [fuelComp], [0.05])
aNew3 = self.r.core.createAssemblyOfType(aOld.getType(), 0.195, self.o.cs)
self.assertAlmostEqual(
aNew3.getFirstBlock(Flags.FUEL).getUraniumMassEnrich(), 0.195
)
self.assertAlmostEqual(aNew3.getMass(), bol.getMass())
def test_createFreshFeed(self):
# basic creation
aOld = self.r.core.getFirstAssembly(Flags.FEED)
aNew = self.r.core.createFreshFeed(cs=self.o.cs)
self.assertAlmostEqual(aOld.getMass(), aNew.getMass())
def test_createAssemblyOfTypeExpandedCore(self):
"""Test creation of new assemblies in an expanded core."""
# change the mesh of inner blocks
mesh = self.r.core.p.referenceBlockAxialMesh[1:]
lastIndex = len(mesh) - 1
mesh = [val + 5 for val in mesh]
mesh[0] -= 5
mesh[lastIndex] -= 5
# expand the core
self.r.core.p.referenceBlockAxialMesh = [0] + mesh
for a in self.r.core:
a.setBlockMesh(mesh)
aType = self.r.core.getFirstAssembly(Flags.FUEL).getType()
# demonstrate we can still create assemblies
self.assertTrue(self.r.core.createAssemblyOfType(aType, cs=self.o.cs))
def test_getAvgTemp(self):
t0 = self.r.core.getAvgTemp([Flags.CLAD, Flags.WIRE, Flags.DUCT])
self.assertAlmostEqual(t0, 459.267, delta=0.01)
t1 = self.r.core.getAvgTemp([Flags.CLAD, Flags.FUEL])
self.assertAlmostEqual(t1, 545.043, delta=0.01)
t2 = self.r.core.getAvgTemp([Flags.CLAD, Flags.WIRE, Flags.DUCT, Flags.FUEL])
self.assertAlmostEqual(t2, 521.95269, delta=0.01)
def test_getScalarEvolution(self):
self.r.core.scalarVals["fake"] = 123
x = self.r.core.getScalarEvolution("fake")
self.assertEqual(x, 123)
def test_ifMissingSpatialGrid(self):
self.r.core.spatialGrid = None
with self.assertRaises(ValueError):
self.r.core.symmetry
with self.assertRaises(ValueError):
self.r.core.geomType
def test_removeAllAssemblies(self):
self.assertGreater(len(self.r.core.blocksByName), 100)
self.assertGreater(len(self.r.core.assembliesByName), 12)
self.r.core.removeAllAssemblies()
self.assertEqual(0, len(self.r.core.blocksByName))
self.assertEqual(0, len(self.r.core.assembliesByName))
def test_pinCoordsAllBlocks(self):
"""Make sure all blocks can get pin coords."""
for b in self.r.core.getBlocks():
coords = b.getPinCoordinates()
self.assertGreater(len(coords), -1)
def test_nonUniformAssems(self):
o, r = loadTestReactor(
customSettings={"nonUniformAssemFlags": ["primary control"]}
)
a = o.r.core.getFirstAssembly(Flags.FUEL)
self.assertTrue(all(b.p.topIndex != 0 for b in a[1:]))
a = o.r.core.getFirstAssembly(Flags.PRIMARY)
self.assertTrue(all(b.p.topIndex == 0 for b in a))
originalHeights = [b.p.height for b in a]
differntMesh = [val + 2 for val in r.core.p.referenceBlockAxialMesh]
# wont change because nonUnfiform assem doesn't conform to reference mesh
a.setBlockMesh(differntMesh)
heights = [b.p.height for b in a]
self.assertEqual(originalHeights, heights)
def test_applyThermalExpansion_CoreConstruct(self):
r"""Test that assemblies in core are correctly expanded.
Notes
-----
- all assertions skip the first block as it has no $\Delta T$ and does not expand
"""
originalAssems = self.r.core.getAssemblies()
# stash original axial mesh info
oldRefBlockAxialMesh = self.r.core.p.referenceBlockAxialMesh
oldAxialMesh = self.r.core.p.axialMesh
nonEqualParameters = ["heightBOL", "molesHmBOL", "massHmBOL"]
equalParameters = ["smearDensity", "nHMAtBOL", "enrichmentBOL"]
o, coldHeightR = loadTestReactor(
self.directoryChanger.destination,
customSettings={
"inputHeightsConsideredHot": False,
"assemFlagsToSkipAxialExpansion": ["feed fuel"],
},
)