|
| 1 | +''' Net Present Value with Renewable Power and co2 emissions ''' |
| 2 | + |
| 3 | +import pandas as pd |
| 4 | +import numpy as np |
| 5 | +import os |
| 6 | +import yaml |
| 7 | + |
| 8 | +from pathlib import Path |
| 9 | +from pqdm.processes import pqdm |
| 10 | + |
| 11 | +__all__ = ['ren_npv_co2'] |
| 12 | + |
| 13 | +HERE = Path().cwd() # fallback for ipynb's |
| 14 | +HERE = HERE.resolve() |
| 15 | + |
| 16 | +def ren_npv_co2(pred_data, keys_opt, report, save_emissions=False): |
| 17 | + ''' |
| 18 | + Net Present Value with Renewable Power and co2 emissions (with eCalc) |
| 19 | +
|
| 20 | + Parameters |
| 21 | + ---------- |
| 22 | + pred_data : array_like |
| 23 | + Ensemble of predicted data. |
| 24 | +
|
| 25 | + keys_opt : list |
| 26 | + Keys with economic data. |
| 27 | +
|
| 28 | + report : list |
| 29 | + Report dates. |
| 30 | +
|
| 31 | + Returns |
| 32 | + ------- |
| 33 | + objective_values : array_like |
| 34 | + Objective function values (NPV) for all ensemble members. |
| 35 | + ''' |
| 36 | + |
| 37 | + # some globals, for pqdm |
| 38 | + global const |
| 39 | + global kwargs |
| 40 | + global report_dates |
| 41 | + global sim_data |
| 42 | + |
| 43 | + # define a data getter |
| 44 | + get_data = lambda i, key: pred_data[i+1][key].squeeze() - pred_data[i][key].squeeze() |
| 45 | + |
| 46 | + # ensemble size (ne), number of report-dates (nt) |
| 47 | + nt = len(pred_data) |
| 48 | + try: |
| 49 | + ne = len(get_data(1,'fopt')) |
| 50 | + except: |
| 51 | + ne = 1 |
| 52 | + |
| 53 | + np.save('co2_emissions', np.zeros((ne, nt-1))) |
| 54 | + |
| 55 | + # Economic and other constatns |
| 56 | + const = dict(keys_opt['npv_const']) |
| 57 | + kwargs = dict(keys_opt['npv_kwargs']) |
| 58 | + report_dates = report[1] |
| 59 | + |
| 60 | + # Load energy arrays. These arrays contain the excess windpower used for gas compression, |
| 61 | + # and the energy from gas which is used in the water intection. |
| 62 | + power_arrays = np.load(kwargs['power']+'.npz') |
| 63 | + |
| 64 | + sim_data = {'fopt': np.zeros((ne, nt-1)), |
| 65 | + 'fgpt': np.zeros((ne, nt-1)), |
| 66 | + 'fwpt': np.zeros((ne, nt-1)), |
| 67 | + 'fwit': np.zeros((ne, nt-1)), |
| 68 | + 'thp' : np.zeros((ne, nt-1)), |
| 69 | + 'days': np.zeros(nt-1), |
| 70 | + 'wind': power_arrays['wind'][:,:-1]} |
| 71 | + |
| 72 | + # loop over pred_data |
| 73 | + for t in range(nt-1): |
| 74 | + |
| 75 | + for datatype in ['fopt', 'fgpt', 'fwpt', 'fwit']: |
| 76 | + sim_data[datatype][:,t] = get_data(t, datatype) |
| 77 | + |
| 78 | + # days in time-step |
| 79 | + sim_data['days'][t] = (report_dates[t+1] - report_dates[t]).days |
| 80 | + |
| 81 | + # get maximum well head pressure (for each ensemble member) |
| 82 | + thp_keys = [k for k in keys_opt['datatype'] if 'wthp' in k] # assume only injection wells |
| 83 | + thp_vals = [] |
| 84 | + for key in thp_keys: |
| 85 | + thp_vals.append(pred_data[t][key].squeeze()) |
| 86 | + |
| 87 | + sim_data['thp'][:,t] = np.max(np.array(thp_vals), axis=0) |
| 88 | + |
| 89 | + # calculate NPV values |
| 90 | + npv_values = pqdm(array=range(ne), function=npv, n_jobs=keys_opt['parallel'], disable=True) |
| 91 | + |
| 92 | + if not save_emissions: |
| 93 | + os.remove('co2_emissions.npy') |
| 94 | + |
| 95 | + # clear energy arrays |
| 96 | + np.savez(kwargs['power']+'.npz', wind=np.zeros((ne, nt)), ren=np.zeros((ne,nt)), gas=np.zeros((ne,nt))) |
| 97 | + |
| 98 | + scaling = 1.0 |
| 99 | + if 'obj_scaling' in const: |
| 100 | + scaling = const['obj_scaling'] |
| 101 | + |
| 102 | + return np.asarray(npv_values)/scaling |
| 103 | + |
| 104 | + |
| 105 | +def emissions(yaml_file="ecalc_config.yaml"): |
| 106 | + |
| 107 | + from libecalc.application.energy_calculator import EnergyCalculator |
| 108 | + from libecalc.common.time_utils import Frequency |
| 109 | + from libecalc.presentation.yaml.model import YamlModel |
| 110 | + |
| 111 | + # Config |
| 112 | + model_path = HERE / yaml_file |
| 113 | + yaml_model = YamlModel(path=model_path, output_frequency=Frequency.NONE) |
| 114 | + |
| 115 | + # Compute energy, emissions |
| 116 | + model = EnergyCalculator(graph=yaml_model.graph) |
| 117 | + consumer_results = model.evaluate_energy_usage(yaml_model.variables) |
| 118 | + emission_results = model.evaluate_emissions(yaml_model.variables, consumer_results) |
| 119 | + |
| 120 | + # print power from pump |
| 121 | + co2 = [] |
| 122 | + for identity, component in yaml_model.graph.nodes.items(): |
| 123 | + if identity in emission_results: |
| 124 | + co2.append(emission_results[identity]['co2_fuel_gas'].rate.values) |
| 125 | + |
| 126 | + co2 = np.sum(np.asarray(co2), axis=0) |
| 127 | + return co2 |
| 128 | + |
| 129 | + |
| 130 | +def npv(n): |
| 131 | + |
| 132 | + days = sim_data['days'] |
| 133 | + |
| 134 | + # config eCalc |
| 135 | + pd.DataFrame( {'dd-mm-yyyy' : report_dates[1:], |
| 136 | + 'OIL_PROD' : sim_data['fopt'][n]/days, |
| 137 | + 'GAS_PROD' : sim_data['fgpt'][n]/days, |
| 138 | + 'WATER_INJ' : sim_data['fwit'][n]/days, |
| 139 | + 'THP_MAX' : sim_data['thp'][n], |
| 140 | + 'WIND_POWER' : sim_data['wind'][n]*(-1) |
| 141 | + } ).to_csv(f'ecalc_input_{n}.csv', index=False) |
| 142 | + |
| 143 | + ecalc_yaml_file = kwargs['yamlfile']+'.yaml' |
| 144 | + new_yaml = duplicate_yaml_file(filename=ecalc_yaml_file, member=n) |
| 145 | + |
| 146 | + #calc emissions |
| 147 | + co2 = emissions(new_yaml)*days |
| 148 | + |
| 149 | + # save emissions |
| 150 | + try: |
| 151 | + en_co2 = np.load('co2_emissions.npy') |
| 152 | + en_co2[n] = co2 |
| 153 | + np.save('co2_emissions', en_co2) |
| 154 | + except: |
| 155 | + import time |
| 156 | + time.sleep(1) |
| 157 | + |
| 158 | + #calc npv |
| 159 | + gain = const['wop']*sim_data['fopt'][n] + const['wgp']*sim_data['fgpt'][n] |
| 160 | + loss = const['wwp']*sim_data['fwpt'][n] + const['wwi']*sim_data['fwit'][n] + const['wem']*co2 |
| 161 | + disc = (1+const['disc'])**(days/365) |
| 162 | + |
| 163 | + npv_value = np.sum( (gain-loss)/disc ) |
| 164 | + |
| 165 | + # delete dummy files |
| 166 | + os.remove(new_yaml) |
| 167 | + os.remove(f'ecalc_input_{n}.csv') |
| 168 | + |
| 169 | + return npv_value |
| 170 | + |
| 171 | + |
| 172 | +def duplicate_yaml_file(filename, member): |
| 173 | + |
| 174 | + try: |
| 175 | + # Load the YAML file |
| 176 | + with open(filename, 'r') as yaml_file: |
| 177 | + data = yaml.safe_load(yaml_file) |
| 178 | + |
| 179 | + input_name = data['TIME_SERIES'][0]['FILE'] |
| 180 | + data['TIME_SERIES'][0]['FILE'] = input_name.replace('.csv', f'_{member}.csv') |
| 181 | + |
| 182 | + # Write the updated content to a new file |
| 183 | + new_filename = filename.replace(".yaml", f"_{member}.yaml") |
| 184 | + with open(new_filename, 'w') as new_yaml_file: |
| 185 | + yaml.dump(data, new_yaml_file, default_flow_style=False) |
| 186 | + |
| 187 | + except FileNotFoundError: |
| 188 | + print(f"File '{filename}' not found.") |
| 189 | + |
| 190 | + return new_filename |
| 191 | + |
| 192 | + |
| 193 | + |
| 194 | + |
| 195 | + |
| 196 | + |
0 commit comments