def build_multi_presample_sequential_array(): from presamples import create_presamples_package tech_indices = [ (("test", "1"), ("test", "2"), 'technosphere'), (("test", "2"), ("test", "2"), 'production'), ] tech_samples = np.array(( [1, 2, 3], [100, 101, 102], )) bio_indices = [ (("bio", "a"), ("test", "2")), (("bio", "b"), ("test", "2")), (("bio", "b"), ("test", "1")), ] bio_samples = np.array(( [10, 11, 12], [1, 2, 3], [0, -1, -2], )) create_presamples_package(matrix_data=[ (tech_samples, tech_indices, 'technosphere'), (bio_samples, bio_indices, 'biosphere'), ], id_='seq', name='seq', dirpath=basedir, overwrite=True, seed='sequential')
def build_multi_presample_array_unseeded(): from presamples import create_presamples_package tech_indices = [ (("test", "1"), ("test", "2"), "technosphere"), (("test", "2"), ("test", "2"), "production"), ] tech_samples = np.array(( [1, 2, 3], [100, 101, 102], )) bio_indices = [ (("bio", "a"), ("test", "2")), (("bio", "b"), ("test", "2")), (("bio", "b"), ("test", "1")), ] bio_samples = np.array(( [10, 11, 12], [1, 2, 3], [0, -1, -2], )) create_presamples_package( matrix_data=[ (tech_samples, tech_indices, "technosphere"), (bio_samples, bio_indices, "biosphere"), ], id_="unseeded", name="unseeded", dirpath=basedir, overwrite=True, )
def create_presamples(self, name=None, id_=None, overwrite=False, dirpath=None, seed='sequential'): """Create a presamples package from generated samples Parameters ----------- name: str, optional A human-readable name for these samples. \id_: str, optional Unique id for this collection of presamples. Optional, generated automatically if not set. overwrite: bool, default=False If True, replace an existing presamples package with the same ``\id_`` if it exists. dirpath: str, optional An optional directory path where presamples can be created. If None, a subdirectory in the ``project`` folder. seed: {None, int, "sequential"}, optional, default="sequential" Seed used by indexer to return array columns in random order. Can be an integer, "sequential" or None. """ if not all([self.matrix_samples is not None, self.matrix_indices]): warnings.warn("No presamples created because there were no matrix data. " "Make sure to run `add_samples_for_all_acts` or " "`add_samples_for_act` for a set of acts first.") return id_, dirpath = create_presamples_package( matrix_data=split_inventory_presamples(self.matrix_samples, self.matrix_indices), name=name, id_=id_, overwrite=overwrite, dirpath=dirpath, seed=seed) print("Presamples with id_ {} written at {}".format(id_, dirpath)) return id_, dirpath
def parameters_package(): with tempfile.TemporaryDirectory() as d: dirpath = Path(d) # Matrix data mapping.add('ABCDEF') t1 = [('A', 'A', 0), ('A', 'B', 1), ('B', 'C', 3)] t2 = np.arange(12, dtype=np.int64).reshape((3, 4)) b1 = [('A', 'D'), ('A', 'E'), ('B', 'F')] b2 = np.arange(12, dtype=np.int64).reshape((3, 4)) c1 = 'DEF' c2 = np.arange(12, dtype=np.int64).reshape((3, 4)) inputs = [ (t2, t1, 'technosphere'), (b2, b1, 'biosphere'), (c2, c1, 'cf'), ] # Parameter data s1 = np.arange(16, dtype=np.int64).reshape((4, 4)) s2 = np.arange(12, dtype=np.int64).reshape((3, 4)) n1 = list('ABCD') n2 = list('EFG') id_, dirpath = create_presamples_package( matrix_data = inputs, parameter_data=[(s1, n1, 'winter'), (s2, n2, 'summer')], name='foo', id_='bar', dirpath=dirpath, seed=42 ) yield dirpath
def tempdir_package(): with tempfile.TemporaryDirectory() as d: _, dirpath = create_presamples_package([_package_data()], name='foo', id_='custom', dirpath=d) yield Path(dirpath)
def presamples_from_scenarios(self, name: str, scenarios: Iterable[Tuple[str, Iterable]]) -> (str, str): """ When given a iterable of multiple parameter scenarios, construct a presamples package with all of the recalculated exchange amounts. """ samples, indices = self.arrays_from_scenarios(scenarios) arrays = ps.split_inventory_presamples(samples, indices) ps_id, ps_path = ps.create_presamples_package( matrix_data=arrays, name=name, seed="sequential" ) return ps_id, ps_path
def build_single_presample_array(): from presamples import create_presamples_package tech_indices = [ (("test", "1"), ("test", "2"), 'technosphere'), (("test", "2"), ("test", "2"), 'production'), ] tech_samples = np.array(( [1], [1], )) bio_indices = [ (("bio", "a"), ("test", "2")), (("bio", "b"), ("test", "2")), (("bio", "b"), ("test", "1")), ] bio_samples = np.array(( [10], [1], [0], )) cf_indices = [("bio", "a")] cf_samples = np.array(([1], )) create_presamples_package( matrix_data=[ (tech_samples, tech_indices, 'technosphere'), (bio_samples, bio_indices, 'biosphere'), (cf_samples, cf_indices, 'cf'), ], id_='single-sample', name='single-sample', dirpath=basedir, overwrite=True, seed=54321, )
def presamples_from_scenarios( self, name: str, scenarios: Iterable[Tuple[str, Iterable]]) -> (str, str): """ When given a iterable of multiple parameter scenarios, construct a presamples package with all of the recalculated exchange amounts. """ sample_data, indice_data = zip(*(self.recalculate_scenario(values) for _, values in scenarios)) samples = np.concatenate(sample_data, axis=1) indices = next(iter(indice_data)) arrays = ps.split_inventory_presamples(samples, indices) ps_id, ps_path = ps.create_presamples_package(matrix_data=arrays, name=name, seed="sequential") return ps_id, ps_path
def test_existing_presamples_list(qtbot, bw2test): """ The presamples dropdown can recognize existing presample packages. """ cereal = np.array([49197200, 50778200, 50962400], dtype=np.int64) fertilizer = np.array([57.63016664, 58.92761065, 54.63277483], dtype=np.float64) land = np.array([17833000, 16161700, 15846800], dtype=np.int64) array_stack = np.stack([cereal, fertilizer, land], axis=0) names = ['cereal production [t]', 'fert consumption [kg/km2]', 'land [ha]'] _, pp_path = ps.create_presamples_package(parameter_data=[ (array_stack, names, "default") ], name="testificate") p_list = PresamplesList() qtbot.addWidget(p_list) packages = p_list.get_package_names() pkg_name = next(iter(packages)) p_list.sync(pkg_name) assert packages == ["testificate"] assert p_list.has_packages is True assert p_list.selection == "testificate"
params.stochastic(iterations=n_iter) params_sto = geothermal_conventional_model(params) # Create presamples matrix_data = [] for param in params_sto: if param[0][0] != "biosphere3": a = (param[2].reshape( (1, -1)), [(param[0], param[1], "technosphere")], "technosphere") else: a = (param[2].reshape( (1, -1)), [(param[0], param[1], "biosphere")], "biosphere") matrix_data.append(a) del a _, stochastic_filepath = ps.create_presamples_package( matrix_data, name='conventional geothermal model - stochastic') #MonteCarlo LCA single method mc_sto = bw.MonteCarloLCA({electricity_prod: 1}, ILCD[0], presamples=[stochastic_filepath]) mc_sto_results = np.array([next(mc_sto) for _ in range(n_iter)]) sb.distplot(mc_sto_results) #MonteCarlo LCA multi method # Initialize CF matrix, results dictionary CF_matr = {} mc_sto_results = {} #Initialize MCLCA object and do first iteration to create lci matrix mc_sto = bw.MonteCarloLCA({electricity_prod: 1},
def generate_base_presamples(project_name, database_name, result_dir, iterations, samples_batch, overwrite_ps=True, ps_base_name="base"): """Generate presamples for all elements of A and B matrices of given database The presamples are stored in a presamples resource in result_dir and added to a presamples campaign for easy reuse. It is recommended that presamples are generated in batches (e.g. of 1000 iterations each). This is implemented via the samples_batch argument. Parameters ----------- project_name : str Name of the brightway2 project where the database is imported database_name : str Name of the LCI database result_dir : str Path to directory where results are stored iterations : int Number of iterations to include in sample samples_batch : int, default=0 Integer id for sample batch. Used for campaigns names and for generating a seed for the RNG. The maximum value is 14. overwrite_ps : bool, default=True Overwrite presamples package if it exists ps_name_base : str, default="base" Base name for presamples resource. Returns ------- None """ projects.set_current(_check_project(project_name)) db = Database(_check_database(database_name)) result_dir = Path(_check_result_dir(result_dir)) if samples_batch > 14: raise ValueError("Cannot use samples_batch value greater than 14") sacrificial_LCA = LCA({act: act.get('production amount', 1) for act in db}) sacrificial_LCA.lci() seed = generate_seed_from_pi(samples_batch) print("Generating technosphere matrix samples") tech_samples, tech_indices = indices_and_samples_from_params( sacrificial_LCA.tech_params, iterations=iterations, seed=seed) print("Generating biosphere matrix samples") bio_samples, bio_indices = indices_and_samples_from_params( sacrificial_LCA.bio_params, iterations=iterations, seed=seed) print("Storing presamples") ps_dir = result_dir / "presamples" ps_dir.mkdir(exist_ok=True) ress_id = "{}_{}".format(ps_base_name, samples_batch) ps_id, ps_path = presamples.create_presamples_package( matrix_data=[(tech_samples, tech_indices, 'technosphere'), (bio_samples, bio_indices, 'biosphere')], name=ress_id, id_=ress_id, overwrite=overwrite_ps, dirpath=ps_dir, seed='sequential') ps_ress, _ = presamples.PresampleResource.get_or_create(name=ress_id, path=ps_path) campaign = _get_campaign(samples_batch) if not ps_ress in list(campaign.packages): campaign.add_presample_resource(ps_ress)
def package(): _, dirpath = create_presamples_package([_package_data()], name='foo', id_='custom') return Path(dirpath)