Example #1
0
    def test_pluginSettings(self):
        pm = armi.getPluginManagerOrFail()
        pm.register(DummyPlugin1)
        # We have a setting; this should be fine
        cs = caseSettings.Settings()

        self.assertEqual(cs["extendableOption"], "DEFAULT")
        # We shouldn't have any settings from the other plugin, so this should be an
        # error.
        with self.assertRaises(vol.error.MultipleInvalid):
            newSettings = {"extendableOption": "PLUGIN"}
            cs = cs.modified(newSettings=newSettings)

        pm.register(DummyPlugin2)
        cs = caseSettings.Settings()
        self.assertEqual(cs["extendableOption"], "PLUGIN")
        # Now we should have the option from plugin 2; make sure that works
        cs = cs.modified(newSettings=newSettings)
        cs["extendableOption"] = "PLUGIN"
        self.assertIn("extendableOption", cs.keys())
        pm.unregister(DummyPlugin2)
        pm.unregister(DummyPlugin1)

        # Now try the same, but adding the plugins in a different order. This is to make
        # sure that it doesnt matter if the Setting or its Options come first
        pm.register(DummyPlugin2)
        pm.register(DummyPlugin1)
        cs = caseSettings.Settings()
        self.assertEqual(cs["extendableOption"], "PLUGIN")
Example #2
0
    def testLocationLabelMigration(self):
        """Make a setting with an old value and make sure it migrates to expected new value."""
        cs = caseSettings.Settings()
        cs["detailAssemLocationsBOL"] = ["B1012"]
        writer = SettingsWriter(cs)
        stream = io.StringIO()
        writer.writeYaml(stream)
        stream.seek(0)

        converter = ConvertAlphanumLocationSettingsToNum(stream=stream)
        newCs = caseSettings.Settings()
        reader = SettingsReader(newCs)
        reader.readFromStream(converter.apply())
        self.assertEqual(newCs["detailAssemLocationsBOL"][0], "011-012")
Example #3
0
    def test_neutronicsSettingsLoaded(self):
        """Check that various special neutronics-specifics settings are loaded"""
        cs = caseSettings.Settings()

        self.assertIn(CONF_INNERS_, cs)
        self.assertIn(CONF_OUTERS_, cs)
        self.assertIn(CONF_NEUTRONICS_KERNEL, cs)
Example #4
0
    def test_settingIsOkayToGrab(self):
        cs = caseSettings.Settings()
        newSettings = {"cycles": [{"cumulative days": [1]}]}
        cs = cs.modified(newSettings=newSettings)

        with self.assertRaises(ValueError):
            _ = cs["cycleLength"]
    def test_xsSettingsSetDefault(self):
        """Test the configuration options of the ``setDefaults`` method."""
        cs = caseSettings.Settings()
        cs["xsBlockRepresentation"] = "FluxWeightedAverage"
        cs[CONF_CROSS_SECTION].setDefaults(
            blockRepresentation=cs["xsBlockRepresentation"],
            validBlockTypes=None)
        self.assertEqual(cs[CONF_CROSS_SECTION]["AA"].validBlockTypes, None)

        cs[CONF_CROSS_SECTION].setDefaults(
            blockRepresentation=cs["xsBlockRepresentation"],
            validBlockTypes=True)
        self.assertEqual(cs[CONF_CROSS_SECTION]["AA"].validBlockTypes, None)

        cs[CONF_CROSS_SECTION].setDefaults(
            blockRepresentation=cs["xsBlockRepresentation"],
            validBlockTypes=False)
        self.assertEqual(cs[CONF_CROSS_SECTION]["AA"].validBlockTypes,
                         ["fuel"])

        cs[CONF_CROSS_SECTION].setDefaults(
            blockRepresentation=cs["xsBlockRepresentation"],
            validBlockTypes=["control", "fuel", "plenum"],
        )
        self.assertEqual(cs[CONF_CROSS_SECTION]["AA"].validBlockTypes,
                         ["control", "fuel", "plenum"])
Example #6
0
    def test_setModuleVerbosities(self):
        # init settings and use them to set module-level logging levels
        cs = caseSettings.Settings()
        newSettings = {
            "moduleVerbosity": {
                "test_setModuleVerbosities": "debug"
            }
        }
        cs = cs.modified(newSettings=newSettings)

        # set the logger once, and check it is was set
        cs.setModuleVerbosities()
        logger = logging.getLogger("test_setModuleVerbosities")
        self.assertEqual(logger.level, 10)

        # try to set the logger again, without forcing it
        newSettings = {
            "moduleVerbosity": {
                "test_setModuleVerbosities": "error"
            }
        }
        cs = cs.modified(newSettings=newSettings)
        cs.setModuleVerbosities()
        self.assertEqual(logger.level, 10)

        # try to set the logger again, with force=True
        cs.setModuleVerbosities(force=True)
        self.assertEqual(logger.level, 40)
Example #7
0
def bootstrapArmiTestEnv():
    """
    Perform ARMI config appropriate for running unit tests

    .. tip:: This can be imported and run from other ARMI applications
        for test support.
    """
    from armi.nucDirectory import nuclideBases

    cs = caseSettings.Settings()

    context.Mode.setMode(context.Mode.BATCH)
    settings.setMasterCs(cs)
    # Need to init burnChain.
    # see armi.cases.case.Case._initBurnChain
    with open(cs["burnChainFileName"]) as burnChainStream:
        nuclideBases.imposeBurnChain(burnChainStream)

    # turn on a non-interactive mpl backend to minimize errors related to
    # initializing Tcl in parallel tests
    matplotlib.use("agg")

    # set and create a test-specific FAST_PATH for parallel unit testing
    # Not all unit tests have operators, and operators are usually
    # responsible for making FAST_PATH, so we make it here.
    # It will be deleted by the atexit hook.
    context.activateLocalFastPath()
    if not os.path.exists(context.getFastPath()):
        os.makedirs(context.getFastPath())

    # some tests need to find the TEST_ROOT via an env variable when they're
    # filling in templates with ``$ARMITESTBASE`` in them or opening
    # input files use the variable in an `!include` tag. Thus
    # we provide it here.
    os.environ["ARMITESTBASE"] = TEST_ROOT
Example #8
0
    def test_settingsAreDiscovered(self):
        cs = caseSettings.Settings()
        nm = fuelCycle.CONF_CIRCULAR_RING_ORDER
        self.assertEqual(cs[nm], "angle")

        setting = cs.settings[nm]
        self.assertIn("distance", setting.options)
    def test_csBlockRepresentationFileLocation(self):
        """
        Test that default blockRepresentation is applied correctly to a
        XSModelingOption that has the ``fileLocation`` attribute defined.
        """
        cs = caseSettings.Settings()
        cs["xsBlockRepresentation"] = "FluxWeightedAverage"
        cs[CONF_CROSS_SECTION] = XSSettings()
        cs[CONF_CROSS_SECTION]["AA"] = XSModelingOptions("AA", fileLocation=[])

        # Check FluxWeightedAverage
        cs[CONF_CROSS_SECTION].setDefaults(
            cs["xsBlockRepresentation"],
            cs["disableBlockTypeExclusionInXsGeneration"])
        self.assertEqual(cs[CONF_CROSS_SECTION]["AA"].blockRepresentation,
                         "FluxWeightedAverage")

        # Check Average
        cs["xsBlockRepresentation"] = "Average"
        cs[CONF_CROSS_SECTION]["AA"] = XSModelingOptions("AA", fileLocation=[])
        cs[CONF_CROSS_SECTION].setDefaults(
            cs["xsBlockRepresentation"],
            cs["disableBlockTypeExclusionInXsGeneration"])
        self.assertEqual(cs[CONF_CROSS_SECTION]["AA"].blockRepresentation,
                         "Average")

        # Check Median
        cs["xsBlockRepresentation"] = "Average"
        cs[CONF_CROSS_SECTION]["AA"] = XSModelingOptions(
            "AA", fileLocation=[], blockRepresentation="Median")
        cs[CONF_CROSS_SECTION].setDefaults(
            cs["xsBlockRepresentation"],
            cs["disableBlockTypeExclusionInXsGeneration"])
        self.assertEqual(cs[CONF_CROSS_SECTION]["AA"].blockRepresentation,
                         "Median")
    def test_csBlockRepresentation(self):
        """
        Test that the XS block representation is applied globally,
        but only to XS modeling options where the blockRepresentation
        has not already been assigned.
        """
        cs = caseSettings.Settings()
        cs["xsBlockRepresentation"] = "FluxWeightedAverage"
        cs[CONF_CROSS_SECTION] = XSSettings()
        cs[CONF_CROSS_SECTION]["AA"] = XSModelingOptions("AA", geometry="0D")
        cs[CONF_CROSS_SECTION]["BA"] = XSModelingOptions(
            "BA", geometry="0D", blockRepresentation="Average")

        self.assertEqual(cs[CONF_CROSS_SECTION]["AA"].blockRepresentation,
                         None)
        self.assertEqual(cs[CONF_CROSS_SECTION]["BA"].blockRepresentation,
                         "Average")

        cs[CONF_CROSS_SECTION].setDefaults(
            cs["xsBlockRepresentation"],
            cs["disableBlockTypeExclusionInXsGeneration"])

        self.assertEqual(cs[CONF_CROSS_SECTION]["AA"].blockRepresentation,
                         "FluxWeightedAverage")
        self.assertEqual(cs[CONF_CROSS_SECTION]["BA"].blockRepresentation,
                         "Average")
Example #11
0
def pytest_sessionstart(session):
    import armi
    from armi import apps

    print("Initializing generic ARMI Framework application")
    armi.configure(apps.App())
    cs = caseSettings.Settings()
    settings.setMasterCs(cs)
Example #12
0
 def setUp(self):
     block = loadTestBlock()
     self.cs = caseSettings.Settings()
     self.cs[CONF_CROSS_SECTION].setDefaults(self.cs)
     self.cs["dragonDataPath"] = os.path.join("path", "to", "draglibendfb7r1SHEM361")
     options = dragonExecutor.DragonOptions("test")
     options.fromBlock(block)
     options.fromUserSettings(self.cs)
     self.writer = dragonWriter.DragonWriterHomogenized([block], options)
Example #13
0
    def test_getFailures(self):
        """Make sure the correct error is thrown when getting a nonexistent setting"""
        cs = caseSettings.Settings()

        with self.assertRaises(NonexistentSetting):
            cs.getSetting("missingFake")

        with self.assertRaises(NonexistentSetting):
            _ = cs["missingFake"]
Example #14
0
 def test_pluginValidatorsAreDiscovered(self):
     cs = caseSettings.Settings()
     cs["shuffleLogic"] = "nothere"
     inspector = settingsValidation.Inspector(cs)
     self.assertTrue(
         any([
             "Shuffling will not occur" in query.statement
             for query in inspector.queries
         ]))
Example #15
0
 def test_customSettingRoundTrip(self):
     """Check specialized settings can go back and forth."""
     cs = caseSettings.Settings()
     yaml = YAML()
     inp = yaml.load(io.StringIO(XS_EXAMPLE))
     cs[CONF_CROSS_SECTION] = inp
     cs[CONF_CROSS_SECTION] = cs[CONF_CROSS_SECTION]
     fname = "test_setting_obj_io_round.yaml"
     cs.writeToYamlFile(fname)
     os.remove(fname)
Example #16
0
 def test_customSettingObjectIO(self):
     """Check specialized settings can build objects as values and write."""
     cs = caseSettings.Settings()
     yaml = YAML()
     inp = yaml.load(io.StringIO(XS_EXAMPLE))
     cs[CONF_CROSS_SECTION] = inp
     self.assertEqual(cs[CONF_CROSS_SECTION]["AA"].geometry, "0D")
     fname = "test_setting_obj_io_.yaml"
     cs.writeToYamlFile(fname)
     os.remove(fname)
 def _setInitialXSSettings():
     cs = caseSettings.Settings()
     cs[CONF_CROSS_SECTION] = XSSettings()
     cs[CONF_CROSS_SECTION]["AA"] = XSModelingOptions("AA",
                                                      geometry="0D")
     cs[CONF_CROSS_SECTION]["BA"] = XSModelingOptions("BA",
                                                      geometry="0D")
     self.assertIn("AA", cs[CONF_CROSS_SECTION])
     self.assertIn("BA", cs[CONF_CROSS_SECTION])
     self.assertNotIn("CA", cs[CONF_CROSS_SECTION])
     self.assertNotIn("DA", cs[CONF_CROSS_SECTION])
     return cs
Example #18
0
    def setUp(self):
        self.o, self.r = test_reactors.loadTestReactor(TEST_ROOT)
        cs = caseSettings.Settings()

        self.dbi = database3.DatabaseInterface(self.r, cs)
        self.dbi.initDB(fName=self._testMethodName + ".h5")
        self.db: db.Database3 = self.dbi.database
        self.stateRetainer = self.r.retainState().__enter__()

        # used to test location-based history. see details below
        self.centralAssemSerialNums = []
        self.centralTopBlockSerialNums = []
Example #19
0
    def _applyToStream(self):
        cs = caseSettings.Settings()
        reader = settingsIO.SettingsReader(cs)
        reader.readFromStream(self.stream)
        self.stream.close()
        cs.path = self.path

        migrateCrossSectionsFromBlueprints(cs)
        writer = settingsIO.SettingsWriter(cs)
        newStream = io.StringIO()
        writer.writeYaml(newStream)
        newStream.seek(0)
        return newStream
Example #20
0
def pytest_sessionstart(session):
    import armi
    from armi import apps
    from armi.nucDirectory import nuclideBases

    print("Initializing generic ARMI Framework application")
    armi.configure(apps.App())
    cs = caseSettings.Settings()
    settings.setMasterCs(cs)
    # Need to init burnChain.
    # see armi.cases.case.Case._initBurnChain
    with open(cs["burnChainFileName"]) as burnChainStream:
        nuclideBases.imposeBurnChain(burnChainStream)
Example #21
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")
Example #22
0
    def _applyToStream(self):
        cs = caseSettings.Settings()
        reader = settingsIO.SettingsReader(cs)
        reader.readFromStream(self.stream)

        if reader.invalidSettings:
            runLog.info(
                "The following deprecated settings will be deleted:\n  * {}"
                "".format("\n  * ".join(list(reader.invalidSettings))))

        cs = _modify_settings(cs)
        writer = settingsIO.SettingsWriter(cs)
        newStream = io.StringIO()
        writer.writeYaml(newStream)
        newStream.seek(0)
        return newStream
Example #23
0
    def test_pluginValidatorsAreDiscovered(self):
        cs = caseSettings.Settings()
        cs = cs.modified(
            caseTitle="test_pluginValidatorsAreDiscovered",
            newSettings={
                "shuffleLogic": "nothere",
                "cycleLengths": [3, 4, 5, 6, 9],
                "powerFractions": [0.2, 0.2, 0.2, 0.2, 0.2],
            },
        )

        inspector = settingsValidation.Inspector(cs)
        self.assertTrue(
            any([
                "Shuffling will not occur" in query.statement
                for query in inspector.queries
            ]))
Example #24
0
def buildCase():
    """Build input components and a case."""
    bp = blueprints.Blueprints()
    bp.customIsotopics = isotopicOptions.CustomIsotopics()
    bp.nuclideFlags = isotopicOptions.genDefaultNucFlags()

    components = buildComponents()
    bp.blockDesigns = buildBlocks(components)
    bp.assemDesigns = buildAssemblies(bp.blockDesigns)
    bp.gridDesigns = buildGrids()
    bp.systemDesigns = buildSystems()

    cs = caseSettings.Settings()
    cs.path = None
    cs.caseTitle = "scripted-case"
    case = cases.Case(cs=cs, bp=bp)

    return case
    def _initSettings():
        """
        Provide hard-coded settings rather than user-provided ones.

        Notes
        -----
        We need to override this method to set our own settings object.

        These settings are modified because the base case is used for many other
        tests across the ARMI ecosystem. We start from them but modify as necessary
        to get the fixture run set up. By re-using this input file, we will
        benefit from getting automatically-updated test inputs as the ARMI
        framework progresses in the future.
        """
        cs = caseSettings.Settings(
            os.path.join(test_reactors.TEST_ROOT, "armiRun.yaml")
        )
        print("setting from _initSettings", cs[CONF_DIF3D_PATH])

        return cs
Example #26
0
def migrate_settings(settings_path):
    """Migrate a settings file to be compatible with the latest ARMI code base."""
    if not os.path.exists(settings_path):
        raise ValueError(
            "Case settings file {} does not exist".format(settings_path))

    runLog.info("Migrating case settings: {}".format(settings_path))
    shaHash = utils.getFileSHA1Hash(settings_path)
    runLog.info("\Settings: {}\n" "\tSHA-1: {}".format(settings_path, shaHash))
    cs = caseSettings.Settings()
    reader = cs.loadFromInputFile(settings_path, handleInvalids=False)
    if reader.invalidSettings:
        runLog.info(
            "The following deprecated settings will be deleted:\n  * {}"
            "".format("\n  * ".join(list(reader.invalidSettings))))

    _modify_settings(cs)
    newSettingsInput = cs.caseTitle + "_migrated.yaml"
    cs.writeToYamlFile(newSettingsInput)
    runLog.info("Successfully generated migrated settings file: {}".format(
        newSettingsInput))
Example #27
0
def migrateCrossSectionsFromBlueprints(settingsObj):
    settingsPath = settingsObj.path
    runLog.info(
        "Migrating cross section settings from blueprints file to settings file ({})..."
        .format(settingsPath))
    cs = caseSettings.Settings()
    cs.loadFromInputFile(settingsPath)

    fullBlueprintsPath = os.path.join(cs.inputDirectory, cs["loadingFile"])
    origXsInputLines = _convertBlueprints(fullBlueprintsPath)
    if not origXsInputLines:
        runLog.warning("No old input found in {}. Aborting migration.".format(
            fullBlueprintsPath))
        return cs
    newXsData = _migrateInputData(origXsInputLines)
    _writeNewSettingsFile(cs, newXsData)
    # cs now has a proper crossSection setting

    _finalize(fullBlueprintsPath, settingsPath)
    # update the existing cs with the new setting in memory so the GUI doesn't wipe it out!
    settingsObj[CONF_CROSS_SECTION] = cs.settings[CONF_CROSS_SECTION].dump()
    return cs
Example #28
0
    def test_modified(self):
        """prove that using the modified() method does not mutate the original object"""
        # init settings
        cs = caseSettings.Settings()

        # prove this setting doesn't exist
        with self.assertRaises(NonexistentSetting):
            cs.getSetting("extendableOption")

        # ensure that defaults in getSetting works
        val = cs.getSetting("extendableOption", 789)
        self.assertEqual(val, 789)

        # prove the new settings object has the new setting
        cs2 = cs.modified(newSettings={"extendableOption": "PLUGIN"})
        self.assertEqual(cs2["extendableOption"], "PLUGIN")

        # prove modified() didn't alter the original object
        with self.assertRaises(NonexistentSetting):
            cs.getSetting("extendableOption")

        # prove that successive applications of "modified" don't fail
        cs3 = cs2.modified(newSettings={"numberofGenericParams": 7})
        cs4 = cs3.modified(newSettings={"somethingElse": 123})
Example #29
0
 def setUp(self):
     self.cs = caseSettings.Settings()
Example #30
0
 def test_empty(self):
     cs = caseSettings.Settings()
     cs = cs.modified(newSettings={"buGroups": []})
     self.assertEqual(cs["buGroups"], [])