示例#1
0
    def generate_scenario_tree(self,
                               downsample_fraction=1.0,
                               include_scenarios=None,
                               bundles=None,
                               random_bundles=None,
                               random_seed=None):

        scenario_tree_instance = self._scenario_tree_instance
        if bundles is not None:
            if isinstance(bundles, string_types):
                bundles_file_path = None
                # we interpret the scenario bundle specification in one of
                # two ways. if the supplied name is a file, it is used
                # directly. otherwise, it is interpreted as the root of a
                # file with a .dat suffix to be found in the instance
                # directory.
                if os.path.exists(os.path.expanduser(bundles)):
                    bundles_file_path = \
                        os.path.expanduser(bundles)
                else:
                    bundles_file_path = \
                        os.path.join(self._scenario_tree_directory,
                                     bundles+".dat")

                if self._verbose:
                    if bundles_file_path is not None:
                        print("Scenario tree bundle specification filename="
                              +bundles_file_path)

                scenario_tree_instance = scenario_tree_instance.clone()
                scenario_tree_instance.Bundling._constructed = False
                scenario_tree_instance.Bundles._constructed = False
                scenario_tree_instance.BundleScenarios._constructed = False
                scenario_tree_instance.load(bundles_file_path)

        #
        # construct the scenario tree
        #
        scenario_tree = ScenarioTree(scenariotreeinstance=scenario_tree_instance,
                                     scenariobundlelist=include_scenarios)

        # compress/down-sample the scenario tree, if requested
        if (downsample_fraction is not None) and \
           (downsample_fraction < 1.0):
            scenario_tree.downsample(downsample_fraction,
                                     random_seed,
                                     self._verbose)

        #
        # create bundles from a dict, if requested
        #
        if bundles is not None:
            if not isinstance(bundles, string_types):
                if self._verbose:
                    print("Adding bundles to scenario tree from user-specified dict")
                if scenario_tree.contains_bundles():
                    if self._verbose:
                        print("Scenario tree already contains bundles. All existing "
                              "bundles will be removed.")
                    for bundle in list(scenario_tree.bundles):
                        scenario_tree.remove(bundle.name)
                for bundle_name in bundles:
                    scenario_tree.add_bundle(bundle_name, bundles[bundle_name])

        #
        # create random bundles, if requested
        #
        if (random_bundles is not None) and \
           (random_bundles > 0):
            if bundles is not None:
                raise ValueError("Cannot specify both random "
                                 "bundles and a bundles specification")

            num_scenarios = len(scenario_tree._scenarios)
            if random_bundles > num_scenarios:
                raise ValueError("Cannot create more random bundles "
                                 "than there are scenarios!")

            print("Creating "+str(random_bundles)+
                  " random bundles using seed="
                  +str(random_seed))

            scenario_tree.create_random_bundles(self._scenario_tree_instance,
                                                random_bundles,
                                                random_seed)

        scenario_tree._scenario_instance_factory = self

        return scenario_tree
示例#2
0
    def generate_scenario_tree(self,
                               downsample_fraction=1.0,
                               include_scenarios=None,
                               bundles=None,
                               random_bundles=None,
                               random_seed=None,
                               verbose=True):

        scenario_tree_model = self._scenario_tree_model
        if scenario_tree_model is not None:
            if has_networkx and \
               isinstance(scenario_tree_model, networkx.DiGraph):
                scenario_tree_model = \
                    ScenarioTreeModelFromNetworkX(scenario_tree_model)
            else:
                assert isinstance(scenario_tree_model, (_BlockData, Block)), \
                    str(scenario_tree_model)+" "+str(type(scenario_tree_model))

        if bundles is not None:
            if isinstance(bundles, six.string_types):
                if scenario_tree_model is None:
                    raise ValueError("A bundles file can not be used when the "
                                     "scenario tree input was not a Pyomo "
                                     "model or ScenarioStructure.dat file.")
                logger.debug("attempting to locate bundle file for input: %s" %
                             (bundles))
                # we interpret the scenario bundle specification in one of
                # two ways. if the supplied name is a file, it is used
                # directly. otherwise, it is interpreted as the root of a
                # file with a .dat suffix to be found in the instance
                # directory.
                orig_input = bundles
                if not bundles.endswith(".dat"):
                    bundles = bundles + ".dat"
                bundles = os.path.expanduser(bundles)
                if not os.path.exists(bundles):
                    if self.data_directory() is None:
                        raise ValueError(
                            "Could not locate bundle .dat file from input "
                            "'%s'. Path does not exist and there is no data "
                            "directory to search in." % (orig_input))
                    bundles = os.path.join(self.data_directory(), bundles)
                if not os.path.exists(bundles):
                    raise ValueError("Could not locate bundle .dat file "
                                     "from input '%s' as absolute path or "
                                     "relative to data directory: %s" %
                                     (orig_input, self.data_directory()))

                if verbose:
                    print("Scenario tree bundle specification filename=%s" %
                          (bundles))

                scenario_tree_model = scenario_tree_model.clone()
                scenario_tree_model.Bundling = True
                scenario_tree_model.Bundling._constructed = False
                scenario_tree_model.Bundling._data.clear()
                scenario_tree_model.Bundles.clear()
                scenario_tree_model.Bundles._constructed = False
                scenario_tree_model.Bundles._data.clear()
                scenario_tree_model.BundleScenarios.clear()
                scenario_tree_model.BundleScenarios._constructed = False
                scenario_tree_model.BundleScenarios._data.clear()
                scenario_tree_model.load(bundles)

        #
        # construct the scenario tree
        #
        if scenario_tree_model is not None:
            scenario_tree = ScenarioTree(
                scenariotreeinstance=scenario_tree_model,
                scenariobundlelist=include_scenarios)
        else:
            assert self._scenario_tree is not None
            if include_scenarios is None:
                scenario_tree = copy.deepcopy(self._scenario_tree)
            else:
                # note: any bundles will be lost
                if self._scenario_tree.contains_bundles():
                    raise ValueError("Can not compress a scenario tree that "
                                     "contains bundles")
                scenario_tree = self._scenario_tree.make_compressed(
                    include_scenarios, normalize=True)

        # compress/down-sample the scenario tree, if requested
        if (downsample_fraction is not None) and \
           (downsample_fraction < 1.0):
            scenario_tree.downsample(downsample_fraction, random_seed, verbose)

        #
        # create bundles from a dict, if requested
        #
        if bundles is not None:
            if not isinstance(bundles, six.string_types):
                if verbose:
                    print("Adding bundles to scenario tree from "
                          "user-specified dict")
                if scenario_tree.contains_bundles():
                    if verbose:
                        print("Scenario tree already contains bundles. "
                              "All existing bundles will be removed.")
                    for bundle in list(scenario_tree.bundles):
                        scenario_tree.remove_bundle(bundle.name)
                for bundle_name in bundles:
                    scenario_tree.add_bundle(bundle_name, bundles[bundle_name])

        #
        # create random bundles, if requested
        #
        if (random_bundles is not None) and \
           (random_bundles > 0):
            if bundles is not None:
                raise ValueError("Cannot specify both random "
                                 "bundles and a bundles specification")

            num_scenarios = len(scenario_tree._scenarios)
            if random_bundles > num_scenarios:
                raise ValueError("Cannot create more random bundles "
                                 "than there are scenarios!")

            if verbose:
                print("Creating " + str(random_bundles) +
                      " random bundles using seed=" + str(random_seed))

            scenario_tree.create_random_bundles(random_bundles, random_seed)

        scenario_tree._scenario_instance_factory = self

        return scenario_tree
示例#3
0
    def generate_scenario_tree(self,
                               downsample_fraction=1.0,
                               include_scenarios=None,
                               bundles=None,
                               random_bundles=None,
                               random_seed=None,
                               verbose=True):

        scenario_tree_model = self._scenario_tree_model
        if scenario_tree_model is not None:
            if has_networkx and \
               isinstance(scenario_tree_model, networkx.DiGraph):
                scenario_tree_model = \
                    ScenarioTreeModelFromNetworkX(scenario_tree_model)
            else:
                assert isinstance(scenario_tree_model, (_BlockData, Block)), \
                    str(scenario_tree_model)+" "+str(type(scenario_tree_model))

        if bundles is not None:
            if isinstance(bundles, six.string_types):
                if scenario_tree_model is None:
                    raise ValueError(
                        "A bundles file can not be used when the "
                        "scenario tree input was not a Pyomo "
                        "model or ScenarioStructure.dat file.")
                logger.debug("attempting to locate bundle file for input: %s"
                             % (bundles))
                # we interpret the scenario bundle specification in one of
                # two ways. if the supplied name is a file, it is used
                # directly. otherwise, it is interpreted as the root of a
                # file with a .dat suffix to be found in the instance
                # directory.
                orig_input = bundles
                if not bundles.endswith(".dat"):
                    bundles = bundles+".dat"
                bundles = os.path.expanduser(bundles)
                if not os.path.exists(bundles):
                    if self.data_directory() is None:
                        raise ValueError(
                            "Could not locate bundle .dat file from input "
                            "'%s'. Path does not exist and there is no data "
                            "directory to search in." % (orig_input))
                    bundles = os.path.join(self.data_directory(), bundles)
                if not os.path.exists(bundles):
                    raise ValueError("Could not locate bundle .dat file "
                                     "from input '%s' as absolute path or "
                                     "relative to data directory: %s"
                                     % (orig_input, self.data_directory()))

                if verbose:
                    print("Scenario tree bundle specification filename=%s"
                          % (bundles))

                scenario_tree_model = scenario_tree_model.clone()
                scenario_tree_model.Bundling = True
                scenario_tree_model.Bundling._constructed = False
                scenario_tree_model.Bundles.clear()
                scenario_tree_model.Bundles._constructed = False
                scenario_tree_model.BundleScenarios.clear()
                scenario_tree_model.BundleScenarios._constructed = False
                scenario_tree_model.load(bundles)

        #
        # construct the scenario tree
        #
        if scenario_tree_model is not None:
            scenario_tree = ScenarioTree(scenariotreeinstance=scenario_tree_model,
                                         scenariobundlelist=include_scenarios)
        else:
            assert self._scenario_tree is not None
            if include_scenarios is None:
                scenario_tree = copy.deepcopy(self._scenario_tree)
            else:
                # note: any bundles will be lost
                if self._scenario_tree.contains_bundles():
                    raise ValueError(
                        "Can not compress a scenario tree that "
                        "contains bundles")
                scenario_tree = self._scenario_tree.make_compressed(
                    include_scenarios,
                    normalize=True)

        # compress/down-sample the scenario tree, if requested
        if (downsample_fraction is not None) and \
           (downsample_fraction < 1.0):
            scenario_tree.downsample(downsample_fraction,
                                     random_seed,
                                     verbose)

        #
        # create bundles from a dict, if requested
        #
        if bundles is not None:
            if not isinstance(bundles, six.string_types):
                if verbose:
                    print("Adding bundles to scenario tree from "
                          "user-specified dict")
                if scenario_tree.contains_bundles():
                    if verbose:
                        print("Scenario tree already contains bundles. "
                              "All existing bundles will be removed.")
                    for bundle in list(scenario_tree.bundles):
                        scenario_tree.remove_bundle(bundle.name)
                for bundle_name in bundles:
                    scenario_tree.add_bundle(bundle_name,
                                             bundles[bundle_name])

        #
        # create random bundles, if requested
        #
        if (random_bundles is not None) and \
           (random_bundles > 0):
            if bundles is not None:
                raise ValueError("Cannot specify both random "
                                 "bundles and a bundles specification")

            num_scenarios = len(scenario_tree._scenarios)
            if random_bundles > num_scenarios:
                raise ValueError("Cannot create more random bundles "
                                 "than there are scenarios!")

            if verbose:
                print("Creating "+str(random_bundles)+
                      " random bundles using seed="
                      +str(random_seed))

            scenario_tree.create_random_bundles(random_bundles,
                                                random_seed)

        scenario_tree._scenario_instance_factory = self

        return scenario_tree