def all_prolif_qty(path, qty, eqn_type, file=None): file_list = make_list(path) qty_df = pd.DataFrame() agent_df = pd.DataFrame() for f in file_list: db = cym.dbopen(f) weapon_progress = cym.root_metric(name='WeaponProgress') evaluator = cym.Evaluator(db) frame = evaluator.eval('WeaponProgress', conds=[('Decision', '==', 1), ('EqnType', '==', eqn_type)]) qty_df = pd.concat([qty_df, frame[:][qty]], ignore_index=True) agent_entry = cym.root_metric(name='AgentEntry') evaluator2 = cym.Evaluator(db) agent_frame = evaluator2.eval('AgentEntry', conds=[('Kind', '==', 'Inst')]) agent_df = pd.concat( [agent_df, agent_frame[:][['AgentId', 'Prototype']]], ignore_index=True) if (file != None): qty_df.to_csv(path + file, sep='\t') agent_df.to_csv(path + 'agent_' + file, sep='\t') return else: return qty_df
def objective(sim): with cym.dbopen(sim) as db: evaler = cym.Evaluator(db) elec_gen = evaler.eval('FcoElectricityGenerated') elec_gen = elec_gen[-200:] demand = demand_curve(90, 0.01, 200) score = sum((elec_gen.Power - demand).abs()) return score
def main(): global timestep if len(sys.argv) != 3: print("missing argument !!") quit() db = cym.dbopen(sys.argv[2]) ev = cym.Evaluator(db=db, write=False) input_list = read_input(sys.argv[1]) process(ev, input_list)
def stock_analysis(filename): """Runs stock analysis utilities.""" global EVALER for fig in FIGS: fig.close() FIGS.clear() db = cym.dbopen(filename) evaler = EVALER = cym.Evaluator(db) plot_fco_egen() #plot_fco_umined() plot_builds()
def InvFrac(file, facility, nucs1=(), nucs2=(), factor1=1, factor2=1): ''' Return the fraction nucs1 / (nucs1+nucs2) the inventory of the facilities (fac), weighting factor can be added on nucs1 and nucs2 ''' db = cym.dbopen(file) ev = cym.Evaluator(db=db, write=False) df1 = tm.inventories(ev, facilities=facility, nucs=nucs1) df2 = tm.inventories(ev, facilities=facility, nucs=nucs2) df_r = df2 df_r[df_r.columns[1]] = (df2[df2.columns[1]] / factor2) / \ (df1[df1.columns[1]] / factor1 + df2[df2.columns[1]] / factor2) return df_r
def Trans(file, rec=(), send=(), nucs_=(), coms=()): ''' Return the transactions between senders (send) and receivers (rec), filtered by nuclide (nucs) and commodities (coms) ''' db = cym.dbopen(file) ev = cym.Evaluator(db=db, write=False) df1 = tm.transactions(ev, receivers=rec, senders=send, nucs=nucs_, commodities=coms) return df1
def extract_gwe(simid, T, dbname=OPT_H5, **state): """Computes the annual GWe for a simulation.""" zero_gwe = pd.DataFrame({'GWe': np.zeros(T)}, index=np.arange(T)) zero_gwe.index.name = 'Time' with cym.dbopen(dbname) as db: evaler = cym.Evaluator(db) raw = evaler.eval('TimeSeriesPower', conds=[('SimId', '==', uuid.UUID(simid))]) ano = pd.DataFrame({'Time': raw.Time.apply(month_to_year), 'GWe': raw.Value.apply(mwe_month_to_gwe_year)}) gwe = ano.groupby('Time').sum() gwe = (gwe + zero_gwe).fillna(0.0) return np.array(gwe.GWe)
def facility_input(dbname): db = cym.dbopen(dbname) frame = cym.eval('TransactionQuantity', db) ids = frame[:]['ReceiverId'].unique() ids.sort() it = 0 for cur_id in ids: cur_frame = cym.eval('TransactionQuantity', db, conds=[('ReceiverId', '==', cur_id)]) raw_time = cur_frame[:]['TimeCreated'] raw_data = cur_frame[:]['Quantity'] n_entries = raw_time.size n_times = raw_time[n_entries - 1]+1 # if not every time step is represented in the dataframe if n_entries != n_times: index = np.arange(n_times) time_col = ['TimeCreated'] data_col = ['Quantity'] corr_time = pd.DataFrame(columns=time_col, index=index) corr_data = pd.DataFrame(columns=data_col, index=index) i_last = 0 for elem, val in raw_time.iteritems(): # if the current index is not equal to the current timestep if val != i_last: n_missing = val - i_last for t_miss in xrange(1 - n_missing, 0): corr_time.ix[val + t_miss] = val + t_miss corr_data.ix[val + t_miss] = 0 i_last+= n_missing corr_time.ix[val] = val corr_data.ix[val] = raw_data[elem] else: corr_time.ix[val] = raw_time[elem] corr_data.ix[val] = raw_data[elem] else: corr_data = raw_data corr_time = raw_time if it == 0: big_frame = corr_time big_frame = pd.concat([big_frame, corr_data], axis=1) it += 1 str_fac = map(str,ids) big_frame.columns = ['TimeCreated']+str_fac big_frame.fillna(0) # in case one time series ends earlier than the others return big_frame
def first_prolif_qty(path, qty, csv=None): file_list = make_list(path) qty_df = pd.DataFrame() for f in file_list: db = cym.dbopen(f) weapon_progress = cym.root_metric(name='WeaponProgress') evaluator = cym.Evaluator(db) frame = evaluator.eval('WeaponProgress', conds=[('Decision', '==', 1)]) qty_df = pd.concat([qty_df, frame[:1][qty]], ignore_index=True) if (csv != None): qty_df.to_csv(path + csv, sep='\t') return else: return qty_df
def idle_cap(): """ This function uses cymetric to read the output_sqlite file for total idle capacity value. """ f = open('output_name.txt', 'r') if f.mode == 'r': output_sqlite = f.read() f.close() ev = cym.Evaluator(db=cym.dbopen(output_sqlite), write=True) val, val2, val3 = oup.idlecap(ev, '(60000+250*t/12.0)/1000.0') f = open('idlecap.txt', 'w+') f.write(str(val)) f.close() return val
def dep_u(): """ This function uses cymetric to read the output_sqlite file for final depleted u value. """ f = open('output_name.txt', 'r') if f.mode == 'r': output_sqlite = f.read() f.close() ev = cym.Evaluator(db=cym.dbopen(output_sqlite), write=True) val = cym.timeseries.transactions(ev, commodities=['enrichmentwaste'])['Mass'].cumsum().iloc[-1] print(val) f = open('depu.txt', 'w+') f.write(str(val)) f.close() return val
def hlw(): """ This function uses cymetric to read the output_sqlite file for final hlw value. """ f = open('output_name.txt', 'r') if f.mode == 'r': output_sqlite = f.read() f.close() ev = cym.Evaluator(db=cym.dbopen(output_sqlite), write=True) val = cym.timeseries.transactions(ev, commodities=['lwrreprocessingwaste', 'moxreprocessingwaste', 'frreprocessingwaste'])[ 'Mass'].cumsum().iloc[-1] with open('hlw.txt', 'w') as f: f.write(str(val)) return val
def fill_tree(parameter_list, file_list): # Loop on Cyclus DB global T, P, var for file_name in file_list: db = cym.dbopen(file_name) evaler = cym.Evaluator(db=db, write=False) # Reset Variables reset_var() T += evaler.eval('TimeList')['TimeStep'].tolist() P += cytim.get_power(evaler)['Value'].tolist() # Read variable print(file_name) for i, parameter in enumerate(parameter_list): var[i].clear() val = get_val(evaler, parameter) var[i] += val # Update Ttree t.Fill() # Close cyclus DB db.close() del evaler
def TransFrac(file='', ev=None, rec=(), send=(), nucs1=(), nucs2=(), factor1=1, factor2=1): ''' Return the fraction nucs1 / (nucs1+nucs2) in the transaction between senders and receivers, weighting factor can be added on nucs1 and nucs2 ''' if (file != ''): db = cym.dbopen(file) ev = cym.Evaluator(db=db, write=False) elif (ev == None): print('Need either a Filename or a cymetric evaler....') return None df1 = tm.transactions(ev, receivers=rec, senders=send, nucs=nucs1) df2 = tm.transactions(ev, receivers=rec, senders=send, nucs=nucs2) df_r = df2 df_r[df_r.columns[1]] = (df2[df2.columns[1]] / factor2) / \ (df1[df1.columns[1]] / factor1 + df2[df2.columns[1]] / factor2) return df_r
def get_sqlite_evaluator(): outputfile = cymetric.dbopen(test_sqlite_path) evaluate = cymetric.Evaluator(outputfile) return evaluate
#! /usr/bin/env python import cymetric as cym import pandas as pd import numpy as np import matplotlib.pyplot as plt db = cym.dbopen('recycle.sqlite') evaler = cym.Evaluator(db) comm = evaler.eval('CommissioningSeries') decomm = evaler.eval('DecommissioningSeries') # make exit counts negative for plotting purposes neg = -decomm['Count'] decomm = decomm.drop('Count', axis=1) decomm = pd.concat([decomm, neg], axis=1) # for later merge, rename time columns comm.rename(columns={'EnterTime' : 'Time'}, inplace=True) decomm.rename(columns={'ExitTime' : 'Time'}, inplace =True) # pivot tables for plotting purposes, and merge tables c = comm.pivot('Time', 'Prototype')['Count'].reset_index() d = decomm.pivot('Time', 'Prototype')['Count'].reset_index() cd = pd.merge(c, d, left_on='Time', right_on='Time', how='outer', sort=True, suffixes=('_enter', '_exit')).fillna(0) # pandas always changes everything to floats in the presence of NaNs, so change # the TimeStep column back to integer cd.Time = cd.Time.astype(int)
def read_db(filename): db = cym.dbopen(filename) return db
def __init__(self, filename): db = cym.dbopen(filename) self.db = db
#! /usr/bin/env python import cymetric as cym import pandas as pd import numpy as np import matplotlib.pyplot as plt db = cym.dbopen('recycle.sqlite') evaler = cym.Evaluator(db) comm = evaler.eval('BuildSeries') decomm = evaler.eval('DecommissionSeries') # make exit counts negative for plotting purposes neg = -decomm['Count'] decomm = decomm.drop('Count', axis=1) decomm = pd.concat([decomm, neg], axis=1) # for later merge, rename time columns comm.rename(columns={'EnterTime': 'Time'}, inplace=True) decomm.rename(columns={'ExitTime': 'Time'}, inplace=True) # pivot tables for plotting purposes, and merge tables c = comm.pivot('Time', 'Prototype')['Count'].reset_index() d = decomm.pivot('Time', 'Prototype')['Count'].reset_index() cd = pd.merge(c, d, left_on='Time', right_on='Time', how='outer', sort=True, suffixes=('_enter', '_exit')).fillna(0)
def MakeFlowGraph(file, label=''): ''' Generate the transaction flow graph between facilities ''' db_ = cym.dbopen(file) ev_ = cym.Evaluator(db=db_, write=False) return cgr.flow_graph(evaler=ev_, label=label)