def test_simulation_iter(): with Simulation(MODEL_WEIR_SETTING_PATH) as sim: c1c2 = Links(sim)["C1:C2"] sim.step_advance(300) for ind, step in enumerate(sim): print(c1c2.flow, c1c2.target_setting) if c1c2.flow > 9.19: c1c2.target_setting = 0.9
def test_links_3(): with Simulation(MODEL_WEIR_SETTING_PATH) as sim: print("\n\n\nLINKS\n") c1c2 = Links(sim)["C1:C2"] sim.step_advance(300) for ind, step in enumerate(sim): if ind > 15: c1c2.flow_limit = 1 if ind > 30: c1c2.flow_limit = 0 if ind > 16 and ind <= 30: assert (c1c2.flow == 1)
def test_links_3(): with Simulation(MODEL_WEIR_SETTING_PATH) as sim: print("\n\n\nLINKS\n") c1c2 = Links(sim)["C1:C2"] sim.step_advance(300) for ind, step in enumerate(sim): if ind > 15: c1c2.flow_limit = 1 if ind > 30: c1c2.flow_limit = 0 if ind > 16 and ind <= 30: assert (c1c2.flow == 1)
def test_CSTR_load(): dict1 = {'Tank': {0: [-0.2, 1.0, 0.0]}} conc = [] conc1 = [] flow = [] flow1 = [] with Simulation("./inps/tank_constantinflow_notreatment.inp") as sim: CS = Node_Quality(sim, dict1) Tank = Nodes(sim)["Tank"] Valve = Links(sim)["Valve"] for index, step in enumerate(sim): CS.CSTR_solver(index) c = Tank.pollut_quality conc.append(c['P1']) c1 = Valve.pollut_quality conc1.append(c1['P1']) flow.append(sim._model.getNodeResult("Tank", 0)) flow1.append(sim._model.getLinkResult("Valve", 0)) load = [a * b for a, b in zip(conc, flow)] cum_load = np.cumsum(load) load1 = [a * b for a, b in zip(conc1, flow1)] cum_load1 = np.cumsum(load1) error = (cum_load1[-1] / cum_load[-1]) / cum_load1[-1] print(error) assert error <= 0.03
def test_CoRemoval_load(): dict1 = {'Culvert': {0: [0.75, 0.15]}} dict2 = {'Culvert': {1: 0.15}} conc = [] conc1 = [] flow = [] flow1 = [] with Simulation("./inps/LinkTest_variableinflow2.inp") as sim: CR = Link_Quality(sim, dict1) culvert = Links(sim)["Culvert"] outlet = Nodes(sim)["Outlet"] for step in sim: CR.CoRemoval() c = culvert.pollut_quality conc.append(c['P1']) c1 = outlet.pollut_quality conc1.append(c1['P1']) flow.append(sim._model.getLinkResult("Culvert", 0)) flow1.append(sim._model.getNodeResult("Outlet", 0)) load = [a * b for a, b in zip(conc, flow)] cum_load = np.cumsum(load) load1 = [a * b for a, b in zip(conc1, flow1)] cum_load1 = np.cumsum(load1) error = (cum_load1[-1] / cum_load[-1]) / cum_load1[-1] print(error) assert error <= 0.03
def test_Erosion_load(): dict1 = {'Channel': {0: [10.0, 0.001, 2.68, 0.7]}} conc = [] conc1 = [] flow = [] flow1 = [] with Simulation("./inps/LinkTest_variableinflow.inp") as sim: ER = Link_Quality(sim, dict1) channel = Links(sim)["Channel"] tailwater = Nodes(sim)["TailWater"] for step in sim: ER.Erosion() c = channel.pollut_quality conc.append(c['P1']) c1 = tailwater.pollut_quality conc1.append(c1['P1']) flow.append(sim._model.getLinkResult("Channel", 0)) flow1.append(sim._model.getNodeResult("Tailwater", 0)) load = [a * b for a, b in zip(conc, flow)] cum_load = np.cumsum(load) load1 = [a * b for a, b in zip(conc1, flow1)] cum_load1 = np.cumsum(load1) error = (cum_load1[-1] / cum_load[-1]) / cum_load1[-1] print(error) assert error <= 0.03
def test_CoRemoval_load(): dict1 = {'Culvert': {'pollutant': 1, 'method': 'ConstantRemoval', 'parameters': {'R': 0.15}},\ 'Culvert': {'pollutant': 0, 'method': 'CoRemoval', 'parameters': {'R1': 0.75, 'R2': 0.15}}, } conc = [] conc1 = [] flow = [] flow1 = [] with Simulation("./tests/inps/LinkTest_variableinflow2.inp") as sim: CR = waterQuality(sim, dict1) culvert = Links(sim)["Culvert"] outlet = Nodes(sim)["Outlet"] for step in sim: CR.updateWQState() c = culvert.pollut_quality conc.append(c['P1']) c1 = outlet.pollut_quality conc1.append(c1['P1']) flow.append(sim._model.getLinkResult("Culvert", 0)) flow1.append(sim._model.getNodeResult("Outlet", 0)) load = [a * b for a, b in zip(conc, flow)] cum_load = np.cumsum(load) load1 = [a * b for a, b in zip(conc1, flow1)] cum_load1 = np.cumsum(load1) error = (cum_load1[-1] / cum_load[-1]) / cum_load1[-1] print(error) assert error <= 0.03
def reset(self): self.sim.close() self.sim = Simulation(self.input_file) # self.fcst = np.genfromtxt(self.fcst_file, delimiter=',') # read forecast file as array self.fcst = pd.read_csv(self.fcst_file, index_col="datetime", infer_datetime_format=True, parse_dates=True) self.sim.step_advance(self.control_time_step) # set control time step node_object = Nodes(self.sim) # init node object self.St1 = node_object["st1"] self.St2 = node_object["st2"] self.St3 = node_object["F134101"] link_object = Links(self.sim) # init link object self.R1 = link_object["R1"] self.R2 = link_object["R2"] self.R3 = link_object["R3"] self.sim.start() self.t = 1 if self.sim.current_time == self.sim.start_time: self.R1.target_setting = 0.5 self.R2.target_setting = 1 self.R3.target_setting = 0.5 # self.state = np.concatenate([np.asarray([self.St1.depth, self.St3.depth, self.St1.flooding, self.St3.flooding, # self.R1.current_setting, self.R3.current_setting]), self.fcst[self.t]]) current_fcst = self.fcst.iloc[self.fcst.index.get_loc(self.sim.current_time, method='nearest')] rain_fcst = sum(current_fcst[:int(len(current_fcst) / 2)]) # total rainfall in forecast tide_fcst = np.mean(current_fcst[int(len(current_fcst) / 2):]) # mean tide in forecast # self.state = np.asarray([self.St1.depth, self.St3.depth, self.St1.flooding, self.St3.flooding, # self.R1.current_setting, self.R3.current_setting, # rain_fcst, tide_fcst]) self.state = np.asarray([self.St1.depth, self.St3.depth, self.St1.flooding, self.St3.flooding, self.R1.current_setting, self.R3.current_setting, self.R1.pollut_quality['TSS'], self.R3.pollut_quality['TSS'], rain_fcst, tide_fcst]) return self.state
def updateWQState(self): """ Runs the selected water quality method (except CSTR) and updates the pollutant concentration during a SWMM simulation. """ nodes = Nodes(self.sim) links = Links(self.sim) for asset_ID, asset_info in self.config.items(): for node in nodes: attribute = self.config[asset_ID]['method'] if node.nodeid == asset_ID: self.flag = 0 self.method[attribute](asset_ID, \ self.config[asset_ID]['pollutant'], \ self.config[asset_ID]['parameters'], self.flag) for link in links: attribute = self.config[asset_ID]['method'] if link.linkid == asset_ID: self.flag = 1 self.method[attribute](asset_ID, \ self.config[asset_ID]['pollutant'], \ self.config[asset_ID]['parameters'], self.flag)
def test_links_2(): with Simulation(MODEL_WEIR_SETTING_PATH) as sim: link_names = ["C1", "C1:C2", "C2", "C3"] for link in Links(sim): assert (link.linkid in link_names) link.flow_limit = 10 assert (link.flow_limit == 10)
def reset(self): """Reset state. """ # state = np.random.random(size=(1,)) self.sim.close() self.sim = Simulation(self.modelfile) self.sim.step_advance(self.controlstep) node_object = Nodes(self.sim) self.P1 = node_object["P1"] self.P2 = node_object["P2"] self.P1.depth = self.depth self.P2.depth = self.depth link_object = Links(self.sim) self.L8 = link_object["8"] self.L8.flow = self.flow self.sim.start() if self.sim.current_time == self.sim.start_time: self.L8.target_setting = 0 self.state = np.concatenate([ np.asarray([ self.P1.depth, self.P2.depth, self.L8.flow, self.P1.flooding, self.P2.flooding, self.O1.current_setting, self.O2.current_setting ]) ]) return self.state
def __init__(self, inp_file, fcst_file, depth=4.61): # initialize simulation self.input_file = inp_file self.sim = Simulation(self.input_file) # read input file self.fcst_file = fcst_file self.fcst = np.genfromtxt(self.fcst_file, delimiter=',') # read forecast file as array self.control_time_step = 900 # control time step in seconds self.sim.step_advance(self.control_time_step) # set control time step node_object = Nodes(self.sim) # init node object self.St1 = node_object["St1"] self.St2 = node_object["St2"] self.J1 = node_object["J1"] self.depth = depth self.St1.full_depth = self.depth self.St2.full_depth = self.depth link_object = Links(self.sim) # init link object self.R1 = link_object["R1"] self.R2 = link_object["R2"] self.sim.start() if self.sim.current_time == self.sim.start_time: self.R1.target_setting = 0.5 self.R2.target_setting = 0.5 sim_len = self.sim.end_time - self.sim.start_time self.T = int(sim_len.total_seconds()/self.control_time_step) self.t = 1 self.state = np.concatenate([np.asarray([self.St1.depth, self.St2.depth, self.J1.depth, self.St1.flooding, self.St2.flooding, self.J1.flooding, self.R1.current_setting, self.R2.current_setting]), self.fcst[self.t]]) self.action_space = spaces.Box(low=np.array([0, 0]), high=np.array([1, 1]), dtype=np.float32) self.observation_space = spaces.Box(low=0, high=1000, shape=(len(self.state),), dtype=np.float32)
def test_CSTR_load(): dict1 = { 'Tank': { 'pollutant': 0, 'method': 'CSTR', 'parameters': { 'k': -0.2, 'n': 1.0, 'c0': 10.0 } } } conc = [] conc1 = [] flow = [] flow1 = [] with Simulation("./tests/inps/tank_constantinflow_notreatment.inp") as sim: CS = waterQuality(sim, dict1) Tank = Nodes(sim)["Tank"] Valve = Links(sim)["Valve"] for index, step in enumerate(sim): CS.updateWQState_CSTR(index) c = Tank.pollut_quality conc.append(c['P1']) c1 = Valve.pollut_quality conc1.append(c1['P1']) flow.append(sim._model.getNodeResult("Tank", 0)) flow1.append(sim._model.getLinkResult("Valve", 0)) load = [a * b for a, b in zip(conc, flow)] cum_load = np.cumsum(load) load1 = [a * b for a, b in zip(conc1, flow1)] cum_load1 = np.cumsum(load1) error = (cum_load1[-1] / cum_load[-1]) / cum_load1[-1] print(error) assert error <= 0.03
def reset(self): self.sim.close() self.sim = Simulation(self.input_file) self.fcst = np.genfromtxt(self.fcst_file, delimiter=',') # read forecast file as array self.sim.step_advance(self.control_time_step) # set control time step node_object = Nodes(self.sim) # init node object self.St1 = node_object["St1"] self.St2 = node_object["St2"] self.J1 = node_object["J1"] link_object = Links(self.sim) # init link object self.R1 = link_object["R1"] self.R2 = link_object["R2"] self.St1.full_depth = self.depth self.St2.full_depth = self.depth self.sim.start() self.t = 1 if self.sim.current_time == self.sim.start_time: self.R1.target_setting = 0.5 self.R2.target_setting = 0.5 self.state = np.concatenate([ np.asarray([ self.St1.depth, self.St2.depth, self.J1.depth, self.St1.flooding, self.St2.flooding, self.J1.flooding, self.R1.current_setting, self.R2.current_setting ]), self.fcst[self.t] ]) return self.state
def reset(self): self.sim.close() self.sim = Simulation(swmm_inp) self.sim.step_advance(self.control_time_step) # set control time step node_object = Nodes(self.sim) # init node object self.St1 = node_object["St1"] self.St2 = node_object["St2"] self.J1 = node_object["J1"] link_object = Links(self.sim) # init link object self.R1 = link_object["R1"] self.R2 = link_object["R2"] self.St1.full_depth = self.depth self.St2.full_depth = self.depth self.sim.start() self.t = 1 if self.sim.current_time == self.sim.start_time: self.R1.target_setting = 0.5 self.R2.target_setting = 0.5 self.state = np.asarray([ self.St1.depth, self.St2.depth, self.J1.depth, self.St1.flooding, self.St2.flooding, self.J1.flooding ]) return self.state
def test_GravitySettling_load(): dict1 = { 'Culvert': { 'pollutant': 0, 'method': 'GravitySettling', 'parameters': { 'k': 0.01, 'C_s': 10.0 } } } conc = [] conc1 = [] flow = [] flow1 = [] with Simulation("./tests/inps/LinkTest_variableinflow.inp") as sim: GS = waterQuality(sim, dict1) culvert = Links(sim)["Culvert"] outlet = Nodes(sim)["Outlet"] for step in sim: GS.updateWQState() c = culvert.pollut_quality conc.append(c['P1']) c1 = outlet.pollut_quality conc1.append(c1['P1']) flow.append(sim._model.getLinkResult("Culvert", 0)) flow1.append(sim._model.getNodeResult("Outlet", 0)) load = [a * b for a, b in zip(conc, flow)] cum_load = np.cumsum(load) load1 = [a * b for a, b in zip(conc1, flow1)] cum_load1 = np.cumsum(load1) error = (cum_load1[-1] / cum_load[-1]) / cum_load1[-1] print(error) assert error <= 0.03
def __init__(self,depth=5): # initialize simulation self.sim = Simulation(swmm_inp) # read input file self.control_time_step = 900 # control time step in seconds self.sim.step_advance(self.control_time_step) # set control time step node_object = Nodes(self.sim) # init node object self.St1 = node_object["St1"] self.St2 = node_object["St2"] self.J3 = node_object["J3"] self.depth = depth self.St1.full_depth = self.depth self.St2.full_depth = self.depth link_object = Links(self.sim) # init link object self.R1 = link_object["R1"] self.R2 = link_object["R2"] self.sim.start() if self.sim.current_time == self.sim.start_time: self.R1.target_setting = 0.5 self.R2.target_setting = 0.5 sim_len = self.sim.end_time - self.sim.start_time self.T = int(sim_len.total_seconds()/self.control_time_step) self.t = 1 #print('T=', self.T) self.state = np.asarray([self.St1.depth, self.St2.depth, self.J3.depth, self.St1.flooding, self.St2.flooding, self.J3.flooding]) self.action_space = spaces.Box(low=np.array([0,0]),high=np.array([1,1]), dtype=np.float32) self.observation_space = spaces.Box(low=0, high = 1000, shape=(len(self.state),),dtype=np.float32)
def test_links_2(): with Simulation(MODEL_WEIR_SETTING_PATH) as sim: for link in Links(sim): print(link) print(link.linkid) print(link.flow_limit) link.flow_limit = 10 print(link.flow_limit)
def test_links_7(): with Simulation(MODEL_STORAGE_PUMP) as sim: print("\n\n\nPUMPS\n") link = Links(sim)["P1"] sim.step_advance(300) for ind, step in enumerate(sim): if ind % 1000 == 0: print(link.pump_statistics)
def test_links_6(): with Simulation(MODEL_STORAGE_PUMP) as sim: print("\n\n\nConduits\n") link = Links(sim)["C2"] sim.step_advance(300) for ind, step in enumerate(sim): if ind % 1000 == 0: print(link.conduit_statistics)
def run_swmm(): #======================================= # setup all the nodes before starting #======================================= sim = Simulation('./pipe_test.inp') #======================================= # Start the simulation #======================================= print(sim._isStarted) sim.start() print(sim._isStarted) node_names = ['Inlet', 'Outlet'] link_names = ['Culvert'] nodes = [Nodes(sim)[names] for names in node_names] links = [Links(sim)[names] for names in link_names] # type, area, length, orifice_coeff, free_weir_coeff, submerged_weir_coeff opening0 = nodes[0].create_opening(4, 1.0, 1.0, 0.6, 1.6, 1.0) opening0 = nodes[1].create_opening(4, 1.0, 1.0, 0.6, 1.6, 1.0) print("\n") print("n0 is coupled? ", nodes[0].is_coupled) print("n1 is coupled? ", nodes[1].is_coupled) nodes[0].overland_depth = 1.0 nodes[0].coupling_area = 1.0 # This step_advance should be an integer multiple of the routing step # which is set in the ,inp file. Currently set to 1s. # Should be able to interrogate sim to find out what the # routing stepsize is. Maybe should issue a warning if # step_advance is set lower than the routing step size. # Indeed maybe step_advance should just allow advance n routing steps? for i in range(50): ids = dict() volumes = sim.coupling_step(1.0) print("Step:", i) print("Current time:", sim.current_time) #print("volumes:",volumes) #print(volumes) for flows in volumes: #print(flows) vols = flows[1] for key in vols: print("Volume total at node", key, "at time", flows[0], ":", vols[key])
def step(self, action): self.current_step += 1 self.settings, self.depths, self.flooding = [], [], [] self.node_object = Nodes(self.sim) self.link_object = Links(self.sim) x = 0 for i in self.links: self.link_object[i].target_setting = action[x] self.eps_action[x].append(action[x]) x += 1 self.sim.__next__() for i in self.links: self.settings.append(self.link_object[i].current_setting) ii = 0 for i in self.nodes: self.depths.append(self.node_object[i].depth) self.flooding.append(self.node_object[i].flooding) self.eps_depths[ii].append(self.node_object[i].depth) ii += 1 self.floodings += sum(self.flooding) self.flood.append(sum(self.flooding)) self.reward = reward_function(self.depths, self.flooding) self.eps_reward += self.reward state = [] state = self.settings.copy() state.extend(self.depths) state.extend(self.flooding) time = str(self.sim.current_time).split(" ") time = time[1].split(":") cur = self.day[int(time[0])].split(" ")[3] if (int(time[0]) < 23): nxt = self.day[int(time[0]) + 1].split(" ")[3] else: nxt = 0 cur = int(float(cur) * random.uniform(.95, 1.05)) nxt = int(float(nxt) * random.uniform(.85, 1.15)) state.extend([cur, nxt]) xx = [] for x in state: xx.append(float(x) * random.uniform(0.9, 1.1)) return state, self.reward, self.done #, {} # {} is debugging information
def reset(self): # make this dynamic later self.swmm_inp = "data/simple3.inp" self.sim = Simulation(self.swmm_inp) self.sim.step_advance(self.control_time_step) # set control time step self.node_object = Nodes(self.sim) self.link_object = Links(self.sim) self.total_rewards.append(self.eps_reward) self.eps_reward = 0 self.global_current_step += 1 self.current_step = 0 self.done = False self.sim.start() self.sim_len = self.sim.end_time - self.sim.start_time self.T = self.sim_len.total_seconds() // self.control_time_step for i in range(1, self.R + 1): self.link_object['R' + str(i)].target_setting = random.randrange(1) self.settings = [ self.link_object['R' + str(i)].current_setting for i in range(1, self.R + 1) ] # one for loop would be faster but less readable # making new lists all the time is probably bad self.depths = [ self.node_object['St' + str(i)].depth for i in range(1, self.R + 1) ] self.depths.extend([ self.node_object['J' + str(i)].depth for i in range(2, self.J + 1) ]) self.flooding = [ self.node_object['St' + str(i)].flooding for i in range(1, self.R + 1) ] self.flooding.extend([ self.node_object['J' + str(i)].flooding for i in range(2, self.J + 1) ]) self.reward = reward_function(self.depths, self.flooding) self.eps_reward += self.reward return np.asarray(self.settings + self.depths + self.flooding)
def swmm_run(k=k, pctImperv_c=pctImperv_c, pctImperv_l=pctImperv_l, slope=slope, nPerv=nPerv, nImperv=nImperv, stoPerv=stoPerv, rain=rain, stoImperv=stoImperv, infi=infi,imd=imd): #def swmm_run(k=k, slope=slope): #sublist = [] lawn = ['s31', 's32', 's33', 's34', 's41', 's42', 's43', 's59', 's60', 's61', 's62', 's63', 's64'] simflow = [] i = 0 flow_temp = 0 with Simulation('tianheful_backup625.inp') as sim: #with Simulation('tianheful_backup1.inp') as sim: subcatchments = Subcatchments(sim) #for sub in subcatchments: # sublist.append(sub.subcatchmentid) for sub in subcatchments: sub.width = k / 100 * np.sqrt(sub.area * 10000) sub.percent_impervious = pctImperv_c / 100 sub.slope = slope / 100 sub.perv_n = nPerv / 100 sub.imperv_n = nImperv / 100 sub.perv_sto = stoPerv / 100 sub.imperv_sto = stoImperv / 100 sub.Ks = infi / 100 sub.IMD = imd / 100 sub.rainMulti = rain / 100 #for j in range(len(sublist)): # subcatchments[sublist[j]].width = k / 100 * np.sqrt(subcatchments[sublist[j]].area * 10000) # subcatchments[sublist[j]].slope = slope[j] / 100 # subcatchments[sublist[j]].Ks = infi / 100 # subcatchments[sublist[j]].IMD = imd / 100 for sublawn in lawn: subcatchments[sublawn].percent_impervious = pctImperv_l / 100 #print(sublawn) #print(subcatchments[sublawn].percent_impervious) links = Links(sim) #for link in links: # link.con_roughness = roughness / 100 l29 = links['l29'] #print(l29.con_roughness) for step in sim: flow_temp += l29.flow # integrate 30s data to 1min i += 1 if i > 1: #print(i) simflow.append(flow_temp / 2) i = 0 flow_temp = 0 #simflow.append(l29.flow) #print(sim.current_time) #print(sim.flow_routing_error) return simflow
def run_no_control_sim(controlDict, upstreamDict, downstreamDict, dsKeys, swmmINP, performanceDict): with Simulation(swmmINP) as sim: freq = '12s' timesteps = pd.date_range(sim.start_time, sim.end_time, freq=freq) price = [] PDemand = [] nodes = Nodes(sim) links = Links(sim) for point in controlDict: controlDict[point]['pyswmmVar'] = links[point] for point in upstreamDict: upstreamDict[point]['pyswmmVar'] = links[point] for point in downstreamDict: downstreamDict[point]['pyswmmVar'] = links[point] for point in performanceDict: if performanceDict[point]['type'] == 'outfall' or performanceDict[ point] == 'junction' or performanceDict[point] == 'storage': performanceDict[point]['pyswmmVar'] = nodes[point] elif performanceDict[point]['type'] == 'link': performanceDict[point]['pyswmmVar'] = links[point] print('running simulation...') for step in sim: for point in controlDict: controlDict[point]['pyswmmVar'].target_setting = 1.0 for point in upstreamDict: upstreamDict[point]['ts'].append( upstreamDict[point]['pyswmmVar'].depth / upstreamDict[point]['max_depth']) for point in downstreamDict: downstreamDict[point]['ts_flow'].append( downstreamDict[point]['pyswmmVar'].flow / downstreamDict[point]['max_flow']) downstreamDict[point]['ts_depth'].append( downstreamDict[point]['pyswmmVar'].depth / downstreamDict[point]['max_depth']) for point in performanceDict: try: performanceDict[point]['ts_flow'].append( performanceDict[point]['pyswmmVar'].flow) except: pass try: performanceDict[point]['ts_flow'].append( performanceDict[point]['pyswmmVar'].total_inflow) except: pass print('done ...')
def main(): with Simulation(os.path.join(project_dir, "cmac_temp/temp_inp.inp")) as sim: sim.step_advance(control_time_step) node_object = Nodes(sim) # init node object St1 = node_object["St1"] St2 = node_object["St2"] J1 = node_object["J1"] J2 = node_object["J2"] Out1 = node_object["Out1"] St1.full_depth = 4.61 St2.full_depth = 4.61 link_object = Links(sim) # init link object C2 = link_object["C2"] C3 = link_object["C3"] R1 = link_object["R1"] R2 = link_object["R2"] # set initial conditions def init_conditions(): St1.initial_depth = init_df[0] St2.initial_depth = init_df[1] J1.initial_depth = init_df[2] J2.initial_depth = init_df[3] Out1.initial_depth = init_df[4] C2.initial_flow = init_df[5] C3.initial_flow = init_df[6] R1.target_setting = init_df[7] R2.target_setting = init_df[8] sim.initial_conditions(init_conditions) for step in sim: pass flood_dict = { "St1": (St1.statistics['flooding_volume'] ), # volume in ft^3, multiply by 7.481 for gallons "St2": (St2.statistics['flooding_volume']), "current_dt": str(sim.current_time) } flood_json = json.dumps(flood_dict) sim.close() # save results data # result_list = [St1_flooding, St2_flooding, current_dt] # results_df = pd.DataFrame(result_list).transpose() # results_df.to_csv("C:/swmm_opti_cmac/cmac_temp/temp_flood.csv", index=False) return flood_json
def test_links_1(): with Simulation(MODEL_WEIR_SETTING_PATH) as sim: print("\n\n\nLINKS\n") c1c2 = Links(sim)["C1:C2"] assert (c1c2.linkid == "C1:C2") assert (c1c2.is_conduit() == True) assert (c1c2.is_pump() == False) assert (c1c2.is_orifice() == False) assert (c1c2.is_weir() == False) assert (c1c2.is_outlet() == False) assert (c1c2.connections == ("J1", "J2")) assert (c1c2.inlet_node == "J1") assert (c1c2.outlet_node == "J2")
def test_links_1(): with Simulation(MODEL_WEIR_SETTING_PATH) as sim: print("\n\n\nLINKS\n") c1c2 = Links(sim)["C1:C2"] print(c1c2.flow) print(c1c2.is_conduit()) print(c1c2.is_pump()) print(c1c2.is_orifice()) print(c1c2.is_weir()) print(c1c2.is_outlet()) print(c1c2.connections) print(c1c2.inlet_node) print(c1c2.outlet_node) print(c1c2.average_head_loss) sim.step_advance(300) for ind, step in enumerate(sim): if c1c2.flow > 9.19: c1c2.target_setting = 0.9
def test_links_1(): with Simulation(MODEL_WEIR_SETTING_PATH) as sim: print("\n\n\nLINKS\n") c1c2 = Links(sim)["C1:C2"] assert (c1c2.linkid == "C1:C2") assert (c1c2.is_conduit() == True) assert (c1c2.is_pump() == False) assert (c1c2.is_orifice() == False) assert (c1c2.is_weir() == False) assert (c1c2.is_outlet() == False) assert (c1c2.connections == ("J1", "J2")) assert (c1c2.inlet_node == "J1") assert (c1c2.outlet_node == "J2")
def Initial_State(): sim = Simulation(r"./test.inp") links = Links(sim) nodes = Nodes(sim) Linkname = ["C1", "C2", "O1", "O2"] Nodename = ["St1", "St2", "J1", "J2"] T = len(Linkname) + len(Nodename) Current_States = np.zeros([T, 1]) t = 0 for link in Linkname: a2 = links[link] Current_States[t][0] = a2.initial_flow t = t + 1 for node in Nodename: a1 = nodes[node] Current_States[t][0] = a1.initial_depth t = t + 1 sim.close() return Current_States
def create_network(inputfilename=FileSettings.settingsdict['inputfilename']): """ This function creates the system-wide NetworkX DiGraph that contains every node and connection. :param inputfilename: :return: """ global sim linklist = [] with Simulation(inputfilename) as sim: for sub in Subcatchments(sim): network.add_node(sub.subcatchmentid) for nodes in Nodes(sim): network.add_node(nodes.nodeid) for link in Links(sim): linklist.append(link.connections) network.add_edges_from(linklist) for sub in Subcatchments(sim): network.add_edge(sub.subcatchmentid, sub.connection[1]) return
def fit_func(nest, My_Current_step, CONTROL_RULES, Current_States): sim = Simulation(r"./test.inp") Linkname = ["C1", "C2", "O1", "O2"] Nodename = ["St1", "St2", "J1", "J2"] links = Links(sim) nodes = Nodes(sim) t = 0 for link in Linkname: a2 = links[link] a2.initial_flow = Current_States[t][0] t = t + 1 for node in Nodename: a1 = nodes[node] a1.initial_depth = Current_States[t][0] t = t + 1 flood1 = np.array([]) flood2 = np.array([]) flood3 = np.array([]) flood4 = np.array([]) o1 = Links(sim)["O1"] o2 = Links(sim)["O2"] j1 = Nodes(sim)["J1"] j2 = Nodes(sim)["J2"] j3 = Nodes(sim)["St1"] j4 = Nodes(sim)["St2"] sim.start_time = my_Start_time + datetime.timedelta( minutes=My_timestep * (My_Current_step)) sim.end_time = my_Start_time + datetime.timedelta( minutes=My_timestep * (My_Current_step + HorizonLength + 1)) sim.step_advance(My_timestep * 60) CONTROL_RULES[My_Current_step:My_Current_step + HorizonLength] = nest.reshape([4, -1]) i = 0 for step in sim: o1.target_setting = CONTROL_RULES[i + My_Current_step][0] o2.target_setting = CONTROL_RULES[i + My_Current_step][1] i = i + 1 flood1 = np.append(flood1, [j1.flooding]) flood2 = np.append(flood2, [j2.flooding]) flood3 = np.append(flood3, [j3.flooding]) flood4 = np.append(flood4, [j4.flooding]) sim.close() return mytrape(flood1, 60 * My_timestep) + mytrape( flood2, 60 * My_timestep) + mytrape( flood3, 60 * My_timestep) + mytrape(flood4, 60 * My_timestep)
def test_links_5(): with Simulation(MODEL_WEIR_SETTING_PATH) as sim: weir_pump_rate = 5 #cfs print("\n\n\nWEIR\n") c3 = Links(sim)["C3"] sim.step_advance(300) for ind, step in enumerate(sim): #setting adjustment if ind == 15: c3.target_setting = 0.9 if ind == 20: c3.target_setting = 0.8 if ind == 25: c3.target_setting = 0.7 if ind == 30: c3.target_setting = 0.6 if ind == 35: c3.target_setting = 0.5 if ind == 40: c3.target_setting = 0.4 if ind == 45: c3.target_setting = 0.3 if ind == 50: c3.target_setting = 0.2 if ind == 55: c3.target_setting = 0.1 if ind == 60: c3.target_setting = 0.0 if ind == 65: c3.target_setting = 1.0 #Check Results if ind == 16: assert (c3.target_setting == 0.9) assert (c3.flow >= 0.9 * weir_pump_rate) if ind == 21: assert (c3.target_setting == 0.8) assert (c3.flow >= 0.8 * weir_pump_rate) if ind == 26: assert (c3.target_setting == 0.7) assert (c3.flow >= 0.7 * weir_pump_rate) if ind == 31: assert (c3.target_setting == 0.6) assert (c3.flow >= 0.6 * weir_pump_rate) if ind == 36: assert (c3.target_setting == 0.5) assert (c3.flow >= 0.5 * weir_pump_rate) if ind == 41: assert (c3.target_setting == 0.4) assert (c3.flow >= 0.4 * weir_pump_rate) if ind == 46: assert (c3.target_setting == 0.3) assert (c3.flow >= 0.3 * weir_pump_rate) if ind == 51: assert (c3.target_setting == 0.2) assert (c3.flow >= 0.15 * weir_pump_rate) if ind == 56: assert (c3.target_setting == 0.1) assert (c3.flow >= 0.05 * weir_pump_rate) if ind == 61: assert (c3.target_setting == 0.0) assert (c3.flow == 0.0 * weir_pump_rate) if ind == 66: assert (c3.target_setting == 1.0) assert (c3.flow >= 1.0 * weir_pump_rate)
def test_links_4(): with Simulation(MODEL_PUMP_SETTINGS_PATH) as sim: peak_pump_rate = 20 #cfs print("\n\n\nLINKS\n") c3 = Links(sim)["C3"] sim.step_advance(300) for ind, step in enumerate(sim): #setting adjustment if ind == 15: c3.target_setting = 0.9 if ind == 20: c3.target_setting = 0.8 if ind == 25: c3.target_setting = 0.7 if ind == 30: c3.target_setting = 0.6 if ind == 35: c3.target_setting = 2.0 if ind == 40: c3.target_setting = 0.4 if ind == 45: c3.target_setting = 0.3 if ind == 50: c3.target_setting = 0.2 if ind == 55: c3.target_setting = 0.1 if ind == 60: c3.target_setting = 0.0 if ind == 65: c3.target_setting = 1.0 #Check Results if ind == 16: assert (c3.target_setting == 0.9) assert (c3.flow == 0.9 * peak_pump_rate) if ind == 21: assert (c3.target_setting == 0.8) assert (c3.flow == 0.8 * peak_pump_rate) if ind == 26: assert (c3.target_setting == 0.7) assert (c3.flow == 0.7 * peak_pump_rate) if ind == 31: assert (c3.target_setting == 0.6) assert (c3.flow == 0.6 * peak_pump_rate) if ind == 36: assert (c3.target_setting == 2.0) assert (c3.flow >= peak_pump_rate) if ind == 41: assert (c3.target_setting == 0.4) assert (c3.flow == 0.4 * peak_pump_rate) if ind == 46: assert (c3.target_setting == 0.3) assert (c3.flow == 0.3 * peak_pump_rate) if ind == 51: assert (c3.target_setting == 0.2) assert (c3.flow == 0.2 * peak_pump_rate) if ind == 56: assert (c3.target_setting == 0.1) assert (c3.flow == 0.1 * peak_pump_rate) if ind == 61: assert (c3.target_setting == 0.0) assert (c3.flow == 0.0 * peak_pump_rate) if ind == 66: assert (c3.target_setting == 1.0) assert (c3.flow == 1.0 * peak_pump_rate)