def run_scenario(scenario): # scenario name sce = scenario.__name__ sce_nice_name = sce.replace('_', ' ').title() # prepare input data data = rivus.read_excel(data_spreadsheet) vertex = pdshp.read_shp(vertex_shapefile) edge = prepare_edge(edge_shapefile, building_shapefile) # apply scenario function to input data data, vertex, edge = scenario(data, vertex, edge) # create & solve model model = rivus.create_model(data, vertex, edge) prob = model.create() optim = SolverFactory('gurobi') optim = setup_solver(optim) result = optim.solve(prob, tee=True) prob.load(result) # create result directory if not existent result_dir = os.path.join('result', os.path.basename(base_directory)) if not os.path.exists(result_dir): os.makedirs(result_dir) # report rivus.report(prob, os.path.join(result_dir, 'report.xlsx')) # plots for com, plot_type in [('Elec', 'caps'), ('Heat', 'caps'), ('Gas', 'caps'), ('Elec', 'peak'), ('Heat', 'peak')]: # two plot variants for plot_annotations in [False, True]: # create plot fig = rivus.plot(prob, com, mapscale=False, tick_labels=False, plot_demand=(plot_type == 'peak'), annotations=plot_annotations) plt.title('') # save to file for ext, transp in [('png', True), ('png', False), ('pdf', True)]: transp_str = ('-transp' if transp and ext != 'pdf' else '') annote_str = ('-annote' if plot_annotations else '') # determine figure filename from scenario name, plot type, # commodity, transparency, annotations and extension fig_filename = '{}-{}-{}{}{}.{}'.format( sce, plot_type, com, transp_str, annote_str, ext) fig_filename = os.path.join(result_dir, fig_filename) fig.savefig(fig_filename, dpi=300, bbox_inches='tight', transparent=transp) return prob
def run_scenario(input_file, timesteps, scenario, result_dir, plot_periods={}): """ run an urbs model for given input, time steps and scenario Args: input_file: filename to an Excel spreadsheet for urbs.read_excel timesteps: a list of timesteps, e.g. range(0,8761) scenario: a scenario function that modifies the input data dict result_dir: directory name for result spreadsheet and plots Returns: the urbs model instance """ # scenario name, read and modify data for scenario sce = scenario.__name__ data = urbs.read_excel(input_file) data = scenario(data) # create model model = urbs.create_model(data, timesteps) prob = model.create() # refresh time stamp string and create filename for logfile now = prob.created log_filename = os.path.join(result_dir, '{}.log').format(sce) # solve model and read results optim = SolverFactory('glpk') # cplex, glpk, gurobi, ... optim = setup_solver(optim, logfile=log_filename) result = optim.solve(prob, tee=True) prob.load(result) # copy input file in result directory cdir = os.getcwd() respath = os.path.join(cdir, result_dir) shutil.copy(input_file,respath) # write report to spreadsheet urbs.report( prob, os.path.join(result_dir, '{}.xlsx').format(sce), prob.com_demand, prob.sit) # store optimisation problem for later re-analysis urbs.save( prob, os.path.join(result_dir, '{}.pgz').format(sce)) urbs.result_figures( prob, os.path.join(result_dir, '{}'.format(sce)), plot_title_prefix=sce.replace('_', ' ').title(), periods=plot_periods) return prob
def run_scenario(input_file, timesteps, scenario, result_dir, plot_periods={}): """ run an urbs model for given input, time steps and scenario Args: input_file: filename to an Excel spreadsheet for urbs.read_excel timesteps: a list of timesteps, e.g. range(0,8761) scenario: a scenario function that modifies the input data dict result_dir: directory name for result spreadsheet and plots Returns: the urbs model instance """ # scenario name, read and modify data for scenario sce = scenario.__name__ data = urbs.read_excel(input_file) data = scenario(data) # create model model = urbs.create_model(data, timesteps) prob = model.create() # refresh time stamp string and create filename for logfile now = prob.created log_filename = os.path.join(result_dir, '{}.log').format(sce) # solve model and read results optim = SolverFactory('glpk') # cplex, glpk, gurobi, ... optim = setup_solver(optim, logfile=log_filename) result = optim.solve(prob, tee=True) prob.load(result) # copy input file in result directory cdir = os.getcwd() respath = os.path.join(cdir, result_dir) shutil.copy(input_file, respath) # write report to spreadsheet urbs.report(prob, os.path.join(result_dir, '{}.xlsx').format(sce), prob.com_demand, prob.sit) # store optimisation problem for later re-analysis urbs.save(prob, os.path.join(result_dir, '{}.pgz').format(sce)) urbs.result_figures(prob, os.path.join(result_dir, '{}'.format(sce)), plot_title_prefix=sce.replace('_', ' ').title(), periods=plot_periods) return prob
def run_scenario(scenario, result_dir): # scenario name sce = scenario.__name__ sce_nice_name = sce.replace('_', ' ').title() # prepare input data data = rivus.read_excel(data_spreadsheet) vertex = pdshp.read_shp(vertex_shapefile) edge = prepare_edge(edge_shapefile, building_shapefile) # apply scenario function to input data data, vertex, edge = scenario(data, vertex, edge) log_filename = os.path.join(result_dir, sce+'.log') # create & solve model model = rivus.create_model( data, vertex, edge, peak_multiplier=lambda x:scale_peak_demand(x, peak_demand_prefactor)) # scale peak demand according to pickled urbs findings #reduced_peak = scale_peak_demand(model, peak_demand_prefactor) #model.peak = reduced_peak prob = model.create() optim = SolverFactory('gurobi') optim = setup_solver(optim, logfile=log_filename) result = optim.solve(prob, tee=True) prob.load(result) # report rivus.save(prob, os.path.join(result_dir, sce+'.pgz')) rivus.report(prob, os.path.join(result_dir, sce+'.xlsx')) # plot without buildings rivus.result_figures(prob, os.path.join(result_dir, sce)) # plot with buildings and to_edge lines more_shapefiles = [{'name': 'to_edge', 'color': rivus.to_rgb(192, 192, 192), 'shapefile': to_edge_shapefile, 'zorder': 1, 'linewidth': 0.1}] rivus.result_figures(prob, os.path.join(result_dir, sce+'_bld'), buildings=(building_shapefile, False), shapefiles=more_shapefiles) return prob
def run_scenario(input_file, timesteps, scenario, result_dir): """ run an urbs model for given input, time steps and scenario Args: input_file: filename to an Excel spreadsheet for urbs.read_excel timesteps: a list of timesteps, e.g. range(0,8761) scenario: a scenario function that modifies the input data dict result_dir: directory name for result spreadsheet and plots Returns: the urbs model instance """ # scenario name, read and modify data for scenario sce = scenario.__name__ data = urbs.read_excel(input_file) data = scenario(data) # create model, solve it, read results model = urbs.create_model(data, timesteps) prob = model.create() optim = SolverFactory('glpk') # cplex, glpk, gurobi, ... result = optim.solve(prob, tee=True) prob.load(result) # refresh time stamp string now = prob.created # write report to spreadsheet urbs.report( prob, os.path.join(result_dir, '{}-{}.xlsx').format(sce, now), prob.com_demand, prob.sit) # store optimisation problem for later re-analysis urbs.save( prob, os.path.join(result_dir, '{}-{}.pgz').format(sce, now)) # add or change plot colors my_colors = { 'Vled Haven': (230, 200, 200), 'Stryworf Key': (200, 230, 200), 'Qlyph Archipelago': (200, 200, 230), 'Jepid Island': (215,215,215)} for country, color in my_colors.iteritems(): urbs.COLORS[country] = color # create timeseries plot for each demand (site, commodity) timeseries for sit, com in prob.demand.columns: # create figure fig = urbs.plot(prob, com, sit) # change the figure title ax0 = fig.get_axes()[0] nice_sce_name = sce.replace('_', ' ').title() new_figure_title = ax0.get_title().replace( 'Energy balance of ', '{}: '.format(nice_sce_name)) ax0.set_title(new_figure_title) # save plot to files for ext in ['png', 'pdf']: fig_filename = os.path.join( result_dir, '{}-{}-{}-{}.{}').format(sce, com, sit, now, ext) fig.savefig(fig_filename, bbox_inches='tight') return prob
scenario_co2_limit, scenario_co2_limit_and_storage_expensive] # MAIN for scenario in scenarios: # scenario name, read and modify data for scenario sce = scenario.__name__ data = vicus.read_excel(filename) scenario(data) # create model, solve it, read results model = vicus.create_model(data, timesteps) prob = model.create() optim = SolverFactory('glpk') # cplex, glpk, gurobi, ... result = optim.solve(prob, tee=True) prob.load(result) # write report to spreadsheet vicus.report(prob, '{}.xlsx'.format(sce), ['ElecAC', 'ElecDC']) # example: customise color of commodity vicus.COLOURS['ElecDC'] = (0, 121, 239) # timeseries plot for each commodity for co in ['ElecAC', 'ElecDC']: fig = vicus.plot(prob, co=co) for ext in ['png', 'pdf']: fig_filename = '{}-{}.{}'.format(sce, co, ext)
def run_scenario(input_file, timesteps, scenario, result_dir): """ run an urbs model for given input, time steps and scenario Args: input_file: filename to an Excel spreadsheet for urbs.read_excel timesteps: a list of timesteps, e.g. range(0,8761) scenario: a scenario function that modifies the input data dict result_dir: directory name for result spreadsheet and plots Returns: the urbs model instance """ # scenario name, read and modify data for scenario sce = scenario.__name__ data = urbs.read_excel(input_file) data = scenario(data) # create model, solve it, read results model = urbs.create_model(data, timesteps) prob = model.create() optim = SolverFactory('glpk') # cplex, glpk, gurobi, ... result = optim.solve(prob, tee=True) prob.load(result) # refresh time stamp string now = prob.created # write report to spreadsheet urbs.report(prob, os.path.join(result_dir, '{}-{}.xlsx').format(sce, now), prob.com_demand, prob.sit) # store optimisation problem for later re-analysis urbs.save(prob, os.path.join(result_dir, '{}-{}.pgz').format(sce, now)) # add or change plot colors my_colors = { 'South': (230, 200, 200), 'Mid': (200, 230, 200), 'North': (200, 200, 230) } for country, color in my_colors.iteritems(): urbs.COLORS[country] = color # create timeseries plot for each demand (site, commodity) timeseries for sit, com in prob.demand.columns: # create figure fig = urbs.plot(prob, com, sit) # change the figure title ax0 = fig.get_axes()[0] nice_sce_name = sce.replace('_', ' ').title() new_figure_title = ax0.get_title().replace( 'Energy balance of ', '{}: '.format(nice_sce_name)) ax0.set_title(new_figure_title) # save plot to files for ext in ['png', 'pdf']: fig_filename = os.path.join(result_dir, '{}-{}-{}-{}.{}').format( sce, com, sit, now, ext) fig.savefig(fig_filename, bbox_inches='tight') return prob
# 3. fill missing values with 0 edge = pdshp.read_shp(edge_shapefile) edge = edge.set_index('Edge') edge = edge.join(total_area) edge = edge.fillna(0) # load nodes vertex = pdshp.read_shp(vertex_shapefile) # load spreadsheet data data = rivus.read_excel(data_spreadsheet) # create and solve model model = rivus.create_model(data, vertex, edge) prob = model.create() solver = SolverFactory('gurobi') result = solver.solve(prob, tee=True) prob.load(result) # load results costs, Pmax, Kappa_hub, Kappa_process = rivus.get_constants(prob) source, flows, hub_io, proc_io, proc_tau = rivus.get_timeseries(prob) result_dir = os.path.join('result', os.path.basename(base_directory)) # create result directory if not existing already if not os.path.exists(result_dir): os.makedirs(result_dir) rivus.save(prob, os.path.join(result_dir, 'prob.pgz')) rivus.report(prob, os.path.join(result_dir, 'report.xlsx'))
import time from coopr.pyomo import * from coopr.opt.base import SolverFactory from coopr.opt.parallel import SolverManagerFactory from recem.dice import createDICE2007 from recem.dice import DICE_results_writer #from DICE2007 import createDICE2007 #from DICEutils import DICE_results_writer global start_time start_time = time.time() dice = createDICE2007() dice.doc = 'OPTIMAL SCENARIO' opt = SolverFactory('ipopt', solver_io='nl') tee = False options = """ halt_on_ampl_error=yes""" # constr_viol_tol=1e-5 # acceptable_compl_inf_tol=1e-3 # acceptable_dual_inf_tol=1e-3 # tol=1e-4 # max_iter=2000 # """ solver_manager = SolverManagerFactory('serial') # #//////////////////// OPTIMAL SCENARIO ///////////////////////////////// # print '[%8.2f] create model %s OPTIMAL SCENARIO\n' % (time.time() - start_time,
scenario_base, scenario_storage_expensive, scenario_co2_limit, scenario_co2_limit_and_storage_expensive ] # MAIN for scenario in scenarios: # scenario name, read and modify data for scenario sce = scenario.__name__ data = vicus.read_excel(filename) scenario(data) # create model, solve it, read results model = vicus.create_model(data, timesteps) prob = model.create() optim = SolverFactory('glpk') # cplex, glpk, gurobi, ... result = optim.solve(prob, tee=True) prob.load(result) # write report to spreadsheet vicus.report(prob, os.path.join('results', '{}.xlsx').format(sce), ['ElecAC', 'ElecDC']) # example: customise color of commodity vicus.COLOURS['ElecDC'] = (0, 121, 239) # timeseries plot for each commodity for co in ['ElecAC', 'ElecDC']: fig = vicus.plot(prob, co=co)
# 3. fill missing values with 0 edge = pdshp.read_shp(edge_shapefile) edge = edge.set_index('Edge') edge = edge.join(total_area) edge = edge.fillna(0) # load nodes vertex = pdshp.read_shp(vertex_shapefile) # load spreadsheet data data = rivus.read_excel(data_spreadsheet) # create and solve model model = rivus.create_model(data, vertex, edge) prob = model.create() solver = SolverFactory('gurobi') result = solver.solve(prob, tee=True) prob.load(result) # load results costs, Pmax, Kappa_hub, Kappa_process = rivus.get_constants(prob) source, flows, hub_io, proc_io, proc_tau = rivus.get_timeseries(prob) result_dir = os.path.join('result', os.path.basename(base_directory)) # create result directory if not existing already if not os.path.exists(result_dir): os.makedirs(result_dir) rivus.save(prob, os.path.join(result_dir, 'prob.pgz'))
try: # Coopr 3.5.8787 (old) import coopr.environ from coopr.opt.base import SolverFactory except ImportError: # Pyomo 4 (new) import pyomo.environ from pyomo.opt import SolverFactory import bacon input_filename = 'input.xlsx' data = bacon.read_excel(input_filename) model = bacon.create_model(data) prob = model.create() optim = SolverFactory('glpk') result = optim.solve(prob, tee=True) prob.load(result) # result statistics print(result) # all variables prob.display() # custom print example for actors in prob.flow: if prob.flow[actors].value > 0: print("{} -> {}".format(actors[0], actors[1]))