예제 #1
0
def random_project(wrapped, instance, args, kwargs):
    config.is_test = True
    projects._restore_orig_directory()
    string = random_string()
    while string in projects:
        string = random_string()
    projects.set_current(string)
    build_databases()
    result = wrapped(*args, **kwargs)
    projects.set_current("default", writable=False)
    projects.delete_project(name=string, delete_dir=True)
    return result
예제 #2
0
 def create_functions(self, data=None):
     """Take method data that defines functions in strings, and turn them into actual Python code. Returns a dictionary with flows as keys and functions as values."""
     if data is None:
         data = self.load()
     prefix = "created_function_{}_".format(random_string())
     functions = {}
     for key, value in data.items():
         if isinstance(value, str):
             # Backwards compatibility
             if '%s' in value:
                 warnings.simplefilter(
                     'always', DeprecationWarning
                 )  #otherwise not warning and fail to pass test
                 warnings.warn(
                     "Functions can now be normal Python code; please change def %s() to def some_name().",
                     DeprecationWarning)
                 value = value % "created_function"
             functions[key] = FunctionWrapper(value)
     return functions
예제 #3
0
def tree_worker(base_project, activities, cutoff, list_methods, iterations,
                output_fp, worker_id):
    """Function that generates Monte Carlo results for network and tree
    representations of product systems."""

    # Create new project for this worker. Will be deleted later.
    projects.set_current(base_project)
    new_project_name = "temp project {}".format(random_string())
    projects.copy_project(new_project_name)

    ecoinvent = Database('ecoinvent')

    # Generate matrices with characterization factors. This is much faster than
    # using "switch_method" during Monte Carlo.
    characterization_matrices = get_characterization_matrices(
        activities[0], list_methods)

    for i, act_key in enumerate(activities):
        act = get_activity(act_key)

        # Create dict with tree specifications (in terms of cut-off)
        model_types = ['network', 'deterministic', 'tree-{}'.format(cutoff)]

        # Generate results collector
        results = {method: {} for method in list_methods}
        for method in list_methods:
            for model_type in model_types:
                if model_type != 'deterministic':
                    results[method][model_type] = np.zeros(iterations)

        # Generate metadata collector
        tree_metadata = {}

        # Deterministic
        lca = LCA({act: 1})
        lca.lci()
        for method, cfs in characterization_matrices.items():
            results[method]['deterministic'] = (cfs * lca.inventory).sum()

        # Tree LCAs
        tree = Tree({act: 1})
        tree.traverse(list_methods,
                      'temp-{}'.format(act['code']),
                      cutoff=cutoff,
                      store_leaves_as_scores=False)

        # Store some information on tree
        tree_metadata = {}
        tree_metadata['number of branches'] = len(tree.list_branches)
        tree_metadata['number of leaves'] = len(tree.list_leafs)
        tree_metadata['branch_contribution'] = {}

        for method in tree.methods:
            tree_metadata['branch_contribution'][method] = 0
            for node in tree.listTreeNodeDatasets:
                if (node['node type'] == 'branch'
                        or node['node type'] == 'root'):
                    tree_metadata['branch_contribution'][method] += (
                        node['gate-to-gate contribution'][method] /
                        tree.scores[method])

        tree.write_tree()

        # Do Monte Carlo
        MC = MonteCarloLCA({tree.root: 1})
        next(MC)

        tree_demand = MC.demand_array.copy()
        tree_guess = MC.guess.copy()

        MC.build_demand_array({act: 1})
        MC.guess = None
        network_demand = MC.demand_array.copy()
        network_guess = MC.solve_linear_system()

        for iteration in range(iterations):
            # Get scores for tree
            MC.demand_array = tree_demand
            MC.guess = tree_guess
            s = next(MC)
            lci = MC.biosphere_matrix * s
            for method, cfs in characterization_matrices.items():
                results[method]['tree-{}'.format(cutoff)][iteration] = (
                    cfs * lci).sum()

            # Use same technosphere matrix iteration to get scores for network
            MC.demand_array = network_demand
            MC.guess = network_guess
            s = MC.solve_linear_system()
            lci = MC.biosphere_matrix * s
            for method, cfs in characterization_matrices.items():
                results[method]['network'][iteration] = (cfs * lci).sum()

        #Dump results to disk
        with open(os.path.join(output_fp, "{}.pickle".format(act['code'])),
                  "wb") as f:
            pickle.dump(results, f, protocol=pickle.HIGHEST_PROTOCOL)
        with open(
                os.path.join(output_fp,
                             "_metadata_{}.pickle".format(act['code'])),
                "wb") as f:
            pickle.dump(tree_metadata, f, protocol=pickle.HIGHEST_PROTOCOL)

    projects.delete_project(new_project_name, True)
예제 #4
0
 def test_random_string(self):
     s = random_string(10)
     self.assertEqual(len(s), 10)
     self.assertTrue(isinstance(s, str))