Exemplo n.º 1
0
 def test_writeInput(self):
     fName = os.path.join(TEST_ROOT, "armiRun.yaml")
     cs = settings.Settings(fName)
     baseCase = cases.Case(cs)
     with directoryChangers.TemporaryDirectoryChanger():
         case = baseCase.clone()
         case.writeInputs()
         self.assertTrue(os.path.exists(cs["shuffleLogic"]))
Exemplo n.º 2
0
    def test_temporary_cleans(self):
        """Make sure Temporary cleaner cleans up temporary files."""
        with directoryChangers.TemporaryDirectoryChanger() as dc:
            Path("file1.txt").touch()
            Path("file2.txt").touch()
            tempName = dc.destination

        self.assertFalse(os.path.exists(tempName))
Exemplo n.º 3
0
 def test_dumpReactorXdmf(self):
     # This does a lot, and is hard to verify. at least make sure it doesn't crash
     with directoryChangers.TemporaryDirectoryChanger(dumpOnException=False):
         db = Database3("testDatabase.h5", "w")
         with db:
             db.writeToDB(self.r)
         dumper = xdmf.XdmfDumper("testVtk", inputName="testDatabase.h5")
         with dumper:
             dumper.dumpState(self.r)
Exemplo n.º 4
0
    def setUp(self):
        self.td = directoryChangers.TemporaryDirectoryChanger()
        self.td.__enter__()
        self.o, self.r = test_reactors.loadTestReactor(TEST_ROOT)

        self.dbi = DatabaseInterface(self.r, self.o.cs)
        self.dbi.initDB(fName=self._testMethodName + ".h5")
        self.db: db.Database3 = self.dbi.database
        self.stateRetainer = self.r.retainState().__enter__()
Exemplo n.º 5
0
 def test_copyInterfaceInputs(self):
     testSetting = "shuffleLogic"
     cs = settings.Settings(ARMI_RUN_PATH)
     shuffleFile = cs[testSetting]
     with directoryChangers.TemporaryDirectoryChanger(
     ) as newDir:  # ensure we are not in IN_USE_TEST_ROOT
         newSettings = cases.case.copyInterfaceInputs(
             cs, destination=newDir.destination)
         newFilepath = os.path.join(newDir.destination, shuffleFile)
         self.assertEqual(newSettings[testSetting], str(newFilepath))
Exemplo n.º 6
0
 def setUp(self):
     self.td = directoryChangers.TemporaryDirectoryChanger()
     self.td.__enter__()
     self.init_mode = armi.CURRENT_MODE
     self.filepathXml = os.path.join(
         os.getcwd(), self._testMethodName + "test_setting_io.xml")
     self.filepathYaml = os.path.join(
         os.getcwd(), self._testMethodName + "test_setting_io.yaml")
     self.cs = settings.Settings()
     self.cs["nCycles"] = 55
Exemplo n.º 7
0
    def test_hashFiles(self):
        with directoryChangers.TemporaryDirectoryChanger() as dc:
            files = ["test_hashFiles1.txt", "test_hashFiles2.txt"]
            for fileName in files:
                with open(fileName, "w") as f:
                    f.write("hi")

            hashed = outputCache._hashFiles(files)

            self.assertEqual(hashed, "e9f5713dec55d727bb35392cec6190ce")
Exemplo n.º 8
0
    def test_summarizeDesign(self):
        """
        Ensure that the summarizeDesign method runs.

        Any assertions are bonus.
        """
        with directoryChangers.TemporaryDirectoryChanger():  # ensure we are not in IN_USE_TEST_ROOT
            cs = settings.Settings(ARMI_RUN_PATH)
            cs["verbosity"] = "important"
            case = cases.Case(cs)
            c2 = case.clone()
            c2.summarizeDesign(True, True)
            self.assertTrue(os.path.exists("Core Design Report.html"))
Exemplo n.º 9
0
 def test_plotMatrix(self):
     matrix = np.zeros([2, 2], dtype=float)
     matrix[0, 0] = 1
     matrix[0, 1] = 2
     matrix[1, 0] = 3
     matrix[1, 1] = 4
     xtick = ([0, 1], ["1", "2"])
     ytick = ([0, 1], ["1", "2"])
     fname = "test_plotMatrix_testfile"
     with directoryChangers.TemporaryDirectoryChanger():
         utils.plotMatrix(matrix, fname, show=True, title="plot")
         utils.plotMatrix(matrix, fname, minV=0, maxV=5, figsize=[3, 4])
         utils.plotMatrix(matrix, fname, xticks=xtick, yticks=ytick)
Exemplo n.º 10
0
    def test_deleteCache(self):
        with directoryChangers.TemporaryDirectoryChanger() as dc:
            outDir = "snapshotOutput_Cache"
            self.assertFalse(os.path.exists(outDir))

            os.mkdir(outDir)
            with open(os.path.join(outDir, "test_deleteCache2.txt"), "w") as f:
                f.write("hi there")

            self.assertTrue(os.path.exists(outDir))
            time.sleep(2)
            outputCache.deleteCache(outDir)
            self.assertFalse(os.path.exists(outDir))
Exemplo n.º 11
0
    def test_file_retrieval_missing_file(self):
        """Tests that the directory changer still returns a subset of files even if all do not exist."""
        def f(name):
            """Utility to avoid test clashes during cleanups"""
            return self._testMethodName + name

        with directoryChangers.TemporaryDirectoryChanger(
                filesToRetrieve=[f("file1.txt"),
                                 f("file2.txt")]):
            Path(f("file1.txt")).touch()

        self.assertTrue(os.path.exists(f("file1.txt")))
        self.assertFalse(os.path.exists(f("file2.txt")))
        os.remove(f("file1.txt"))
Exemplo n.º 12
0
    def setUp(self):
        self.dc = directoryChangers.TemporaryDirectoryChanger()
        self.dc.__enter__()

        # Create a little case suite on the fly. Whipping it up from defaults should be
        # more evergreen than committing settings files as a test resource
        cs = caseSettings.Settings()
        cs.writeToYamlFile("settings1.yaml")
        cs.writeToYamlFile("settings2.yaml")
        with open("notSettings.yaml", "w") as f:
            f.write("some: other\n" "yaml: file\n")
        os.mkdir("subdir")
        cs.writeToYamlFile("subdir/settings3.yaml")
        cs.writeToYamlFile("subdir/skipSettings.yaml")
Exemplo n.º 13
0
 def test_independentVariables(self):
     """Ensure that independentVariables added to a case move with it."""
     geom = systemLayoutInput.SystemLayoutInput()
     geom.readGeomFromStream(io.StringIO(GEOM_INPUT))
     bp = blueprints.Blueprints.load(BLUEPRINT_INPUT)
     cs = settings.Settings(ARMI_RUN_PATH)
     cs["verbosity"] = "important"
     baseCase = cases.Case(cs, bp=bp, geom=geom)
     with directoryChangers.TemporaryDirectoryChanger() as cwd:  # ensure we are not in IN_USE_TEST_ROOT
         vals = {"cladThickness": 1, "control strat": "good", "enrich": 0.9}
         case = baseCase.clone()
         case._independentVariables = vals  # pylint: disable=protected-access
         case.writeInputs()
         newCs = settings.Settings(fName=case.title + ".yaml")
         newCase = cases.Case(newCs)
         for name, val in vals.items():
             self.assertEqual(newCase.independentVariables[name], val)
Exemplo n.º 14
0
    def test_summarizeDesign(self):
        """
        Ensure that the summarizeDesign method runs.

        Any assertions are bonus.
        """
        with directoryChangers.TemporaryDirectoryChanger(
        ):  # ensure we are not in IN_USE_TEST_ROOT
            cs = settings.Settings(ARMI_RUN_PATH)
            cs = cs.modified(newSettings={"verbosity": "important"})
            case = cases.Case(cs)
            c2 = case.clone()
            c2.summarizeDesign(True, True)
            self.assertTrue(
                os.path.exists(
                    os.path.join("{}-reports".format(c2.cs.caseTitle),
                                 "index.html")))
Exemplo n.º 15
0
    def test_writeReports(self):
        with directoryChangers.TemporaryDirectoryChanger():
            reportTest = newReports.ReportContent("Test")
            table = newReports.Table("Example")
            table.addRow(["example", 1])
            table.addRow(["example", 2])

            reportTest["TableTest"]["Table Example"] = table

            reportTest.writeReports()
            # Want to check that two <tr> exists...
            times = 0
            with open("index.html") as f:
                for line in f:
                    if "<tr>" in line:
                        times = times + 1
            self.assertEqual(times, 2)
Exemplo n.º 16
0
    def test_ReportContents(self):
        with directoryChangers.TemporaryDirectoryChanger():
            reportTest = newReports.ReportContent("Test")

            getPluginManagerOrFail().hook.getReportContents(
                r=self.r,
                cs=self.o.cs,
                report=reportTest,
                stage=newReports.ReportStage.Begin,
                blueprint=self.r.blueprints,
            )

            self.assertTrue(
                isinstance(reportTest.sections, collections.OrderedDict))
            self.assertIn("Comprehensive Report", reportTest.sections)
            self.assertIn("Neutronics", reportTest.sections)
            self.assertTrue(
                isinstance(reportTest.tableOfContents(), htmltree.HtmlElement))
Exemplo n.º 17
0
    def test_BluePrintBlockModifier(self):
        """test BluePrintBlockModifier with build suite naming function argument"""

        case_nbr = 1

        builder = suiteBuilder.FullFactorialSuiteBuilder(self.baseCase)

        builder.addDegreeOfFreedom([
            inputModifiers.BluePrintBlockModifier(
                "fuel 1", "clad", "od", float("{:.2f}".format(22 / 7)))
        ])
        builder.addDegreeOfFreedom([
            inputModifiers.BluePrintBlockModifier("block 5", "clad", "od",
                                                  3.14159)
        ])

        def SuiteNaming(index, _case, _mods):
            uniquePart = "{:0>4}".format(index + case_nbr)
            return os.path.join(
                ".",
                "case-suite-testBPBM",
                uniquePart,
                self.baseCase.title + "-" + uniquePart,
            )

        with directoryChangers.TemporaryDirectoryChanger():
            suite = builder.buildSuite(namingFunc=SuiteNaming)
            suite.writeInputs()

            self.assertTrue(os.path.exists("case-suite-testBPBM"))

            yamlfile = open(
                f"case-suite-testBPBM/000{case_nbr}/armi-000{case_nbr}-blueprints.yaml",
                "r",
            )
            bp_dict = yaml.safe_load(yamlfile)
            yamlfile.close()

            self.assertEqual(bp_dict["blocks"]["fuel 1"]["clad"]["od"], 3.14)
            self.assertEqual(bp_dict["blocks"]["block 5"]["clad"]["od"],
                             3.14159)
Exemplo n.º 18
0
    def test_TimeSeries(self):
        """Test execution of TimeSeries object."""
        with directoryChangers.TemporaryDirectoryChanger():
            times = [0.1, 0.3, 0.5, 0.7, 0.9, 1.1, 1.3]
            data1 = [7, 4, 3, 2, 1, 5, 7]
            data2 = [1, 2, 3, 4, 5, 5, 7]
            # Labels are predetermined at creation...
            series = newReports.TimeSeries(
                "Example Plot",
                "ReactorName",
                ["data1", "data2"],
                "height (cm)",
                "plotexample.png",
                "This is the Caption",
            )

            for val in range(len(times)):
                series.add("data1", times[val], data1[val])
                series.add("data2", times[val], data2[val])

            series.plot()
            self.assertTrue(os.path.exists("ReactorName.plotexample.png"))
Exemplo n.º 19
0
    def test_example(self):
        builder = suiteBuilder.SeparateEffectsSuiteBuilder(self.baseCase)
        builder.addDegreeOfFreedom(
            inputModifiers.SettingsModifier("fpModel", v)
            for v in ("noFissionProducts", "infinitelyDilute", "MO99"))
        builder.addDegreeOfFreedom(
            inputModifiers.SettingsModifier("detailedAxialExpansion", v)
            for v in (True, ))
        builder.addDegreeOfFreedom(
            inputModifiers.SettingsModifier("buGroups", v) for v in (
                [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 100],
                [3, 5, 7, 9, 10, 20, 100],
                [3, 5, 10, 15, 20, 100],
            ))
        builder.addDegreeOfFreedom((inputModifiers.FullCoreModifier(), ))

        with directoryChangers.TemporaryDirectoryChanger():
            suite = builder.buildSuite()
            for c in suite:
                c.writeInputs()

            self.assertTrue(os.path.exists("case-suite"))
Exemplo n.º 20
0
    def test_standardRestart(self):
        self.td = directoryChangers.TemporaryDirectoryChanger()
        with self.td:
            # make DB to load from
            o = self._getOperatorThatChangesVariables(
                settings.Settings(os.path.join(TEST_ROOT, "armiRun.yaml"))
            )
            with o:
                o.operate()
                firstEndTime = o.r.p.time
                self.assertNotEqual(
                    firstEndTime, 0, "Time should have advanced by the end of the run."
                )

            # run standard restart case
            loadDB = "loadFrom.h5"
            os.rename("armiRun.h5", loadDB)
            cs = settings.Settings(os.path.join(TEST_ROOT, "armiRun.yaml"))
            newSettings = {}
            newSettings["loadStyle"] = "fromDB"
            newSettings["reloadDBName"] = loadDB
            newSettings["startCycle"] = 1
            newSettings["startNode"] = 1
            cs = cs.modified(newSettings=newSettings)
            o = self._getOperatorThatChangesVariables(cs)

            # the interact BOL has historically failed due to trying to write inputs
            # which are already in the DB from the _mergeStandardRunDB call
            with o:
                o.operate()
                self.assertEqual(
                    firstEndTime,
                    o.r.p.time,
                    "End time should have been the same for the restart run.\n"
                    "First end time: {},\nSecond End time: {}".format(
                        firstEndTime, o.r.p.time
                    ),
                )
Exemplo n.º 21
0
    def setUp(self):
        cs = settings.Settings(f"{CASE_TITLE}.yaml")
        cs["db"] = True
        cs["reloadDBName"] = pathlib.Path(f"{CASE_TITLE}.h5").absolute()
        cs["loadStyle"] = "fromDB"
        cs["detailAssemLocationsBOL"] = ["A1001"]
        cs["startNode"] = 1

        self.td = directoryChangers.TemporaryDirectoryChanger()
        self.td.__enter__()

        c = case.Case(cs)
        case2 = c.clone(title="armiRun")
        settings.setMasterCs(case2.cs)
        self.o = case2.initializeOperator()
        self.r = self.o.r

        self.o.getInterface("main").interactBOL()

        dbi = self.o.getInterface("database")
        # Get to the database state at the end of stack of time node 1.
        # The end of the interface stack is when history tracker tends to run.
        dbi.loadState(0, 1)
Exemplo n.º 22
0
    def setUpClass(cls):
        # Not using a directory changer since it isn't important that we go back in the
        # first place, and we don't want to get tangled with the directory change below.
        # We need to be in the TUTORIAL_DIR in the first place so that for `filesToMove`
        # to work right.
        os.chdir(TUTORIAL_DIR)

        # Make sure to do this work in a temporary directory to avoid race conditions
        # when running tests in parallel with xdist.
        cls.dirChanger = directoryChangers.TemporaryDirectoryChanger(
            filesToMove=TUTORIAL_FILES)
        cls.dirChanger.__enter__()
        runTutorialNotebook()

        reloadCs = settings.Settings(f"{CASE_TITLE}.yaml")
        reloadCs.caseTitle = "armiRun"
        reloadCs["db"] = True
        reloadCs["reloadDBName"] = pathlib.Path(f"{CASE_TITLE}.h5").absolute()
        reloadCs["runType"] = "Snapshots"
        reloadCs["loadStyle"] = "fromDB"
        reloadCs["detailAssemLocationsBOL"] = ["001-001"]
        o = armi.init(cs=reloadCs)
        cls.o = o
Exemplo n.º 23
0
    def setUpClass(cls):
        cls.td = directoryChangers.TemporaryDirectoryChanger()
        cls.td.__enter__()

        # The database writes the settings object to the DB rather
        # than the original input file. This allows settings to be
        # changed in memory like this and survive for testing.
        newSettings = {"verbosity": "extra"}
        newSettings["nCycles"] = 2
        newSettings["burnSteps"] = 3
        o, _r = test_reactors.loadTestReactor(customSettings=newSettings)

        settings.setMasterCs(o.cs)

        o.interfaces = [
            i for i in o.interfaces if isinstance(i, (DatabaseInterface))
        ]
        dbi = o.getInterface("database")
        dbi.enabled(True)
        dbi.initDB()  # Main Interface normally does this

        # update a few parameters
        def writeFlux(cycle, node):
            for bi, b in enumerate(o.r.core.getBlocks()):
                b.p.flux = 1e6 * bi + cycle * 100 + node
                b.p.mgFlux = numpy.repeat(b.p.flux / 33, 33)

        o.interfaces.insert(0, MockInterface(o.r, o.cs, writeFlux))
        with o:
            o.operate()

        cls.cs = o.cs
        cls.bp = o.r.blueprints
        cls.dbName = o.cs.caseTitle + ".h5"

        # needed for test_readWritten
        cls.r = o.r
Exemplo n.º 24
0
    def testConvert(self):
        converterSettings = {
            "radialConversionType": "Ring Compositions",
            "axialConversionType": "Axial Coordinates",
            "uniformThetaMesh": True,
            "thetaBins": 1,
            "axialMesh": [25, 50, 75, 100, 150, 175],
            "thetaMesh": [2 * math.pi],
        }

        expectedMassDict, expectedNuclideList = self._getExpectedData()
        geomConv = geometryConverters.HexToRZConverter(
            self.cs, converterSettings, expandReactor=self._expandReactor)
        geomConv.convert(self.r)
        newR = geomConv.convReactor

        self._checkBlockComponents(newR)
        self._checkNuclidesMatch(expectedNuclideList, newR)
        self._checkNuclideMasses(expectedMassDict, newR)
        self._checkBlockAtMeshPoint(geomConv)
        self._checkReactorMeshCoordinates(geomConv)
        figs = geomConv.plotConvertedReactor()
        with directoryChangers.TemporaryDirectoryChanger():
            geomConv.plotConvertedReactor("fname")
Exemplo n.º 25
0
 def setUp(self):
     self.dc = directoryChangers.TemporaryDirectoryChanger()
     self.dc.__enter__()
Exemplo n.º 26
0
 def setUp(self):
     self.td = directoryChangers.TemporaryDirectoryChanger()
     self.td.__enter__()
     cs = settings.Settings(os.path.join(TEST_ROOT, "armiRun.yaml"))
     self.o, cs = getSimpleDBOperator(cs)
     self.r = self.o.r