Esempio n. 1
0
def test_CSTR_steadystate():
    dict1 = {
        'Tank': {
            'pollutant': 0,
            'method': 'CSTR',
            'parameters': {
                'k': -0.2,
                'n': 1.0,
                'c0': 10.0
            }
        }
    }
    conc2 = []
    vol = []
    flow = []
    with Simulation("./tests/inps/tank_constantinflow_notreatment.inp") as sim:
        Tank = Nodes(sim)["Tank"]
        for index, step in enumerate(sim):
            v = Tank.volume
            vol.append(v)
            q = Tank.total_inflow
            flow.append(q)
    with Simulation("./tests/inps/tank_constantinflow_notreatment.inp") as sim:
        CS = waterQuality(sim, dict1)
        Tank = Nodes(sim)["Tank"]
        for index, step in enumerate(sim):
            CS.updateWQState_CSTR(index)
            c = Tank.pollut_quality
            conc2.append(c['P1'])
    C_steadystate = dict1['Tank']['parameters']['c0'] / (
        (1 -
         (dict1['Tank']['parameters']['k'] *
          (np.mean(vol) / np.mean(flow))))**dict1['Tank']['parameters']['n'])
    error = (C_steadystate - conc2[-1]) / C_steadystate
    assert error <= 0.03
Esempio n. 2
0
    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
Esempio n. 3
0
def test_ConstantRemoval_conc():
    dict1 = {
        'Tank': {
            'pollutant': 0,
            'method': 'ConstantRemoval',
            'parameters': {
                'R': 0.5
            }
        }
    }
    conc = []
    con = []
    with Simulation("./tests/inps/tank_variableinflow_notreatment.inp") as sim:
        CR = waterQuality(sim, dict1)
        Tank = Nodes(sim)["Tank"]
        for step in sim:
            CR.updateWQState()
            c = Tank.pollut_quality
            conc.append(c['P1'])
    with Simulation(
            "./tests/inps/tank_variableinflow_constantremoval.inp") as sim:
        Tank = Nodes(sim)["Tank"]
        for step in sim:
            co = Tank.pollut_quality
            con.append(co['P1'])
    error = mse(con, conc[1:])
    print(error)
    assert error <= 0.03
Esempio n. 4
0
def test_NthOrderReaction_conc():
    dict1 = {
        'Tank': {
            'pollutant': 0,
            'method': 'NthOrderReaction',
            'parameters': {
                'k': 0.01,
                'n': 2.0
            }
        }
    }
    conc = []
    con = []
    with Simulation("./tests/inps/tank_variableinflow_notreatment.inp") as sim:
        NOR = waterQuality(sim, dict1)
        Tank = Nodes(sim)["Tank"]
        for step in sim:
            NOR.updateWQState()
            c = Tank.pollut_quality
            conc.append(c['P1'])
    with Simulation(
            "./tests/inps/tank_variableinflow_nthorderreaction.inp") as sim:
        Tank = Nodes(sim)["Tank"]
        for step in sim:
            co = Tank.pollut_quality
            con.append(co['P1'])
    error = mse(con, conc[1:])
    print(error)
    assert error <= 0.03
Esempio n. 5
0
def test_outfalls_8_mgd():
    ''' pytest pyswmm/tests/test_nodes.py -k `test_outfalls_8_mgd` '''
    sim = Simulation(MODEL_STORAGE_PUMP_MGD)
    print("\n\n\nOUTFALL\n")
    outfall = Nodes(sim)["J3"]
    storage = Nodes(sim)["SU1"]
    junction = Nodes(sim)["J2"]

    for ind, step in enumerate(sim):
        pass
    stats = outfall.outfall_statistics
    outfall_cuinflow = outfall.cumulative_inflow
    sim.close()

    assert (stats['total_periods'] == approx(208796, rel=UT_PRECISION))
    assert (stats['pollutant_loading']['test'] == approx(1305.25,
                                                         rel=UT_PRECISION))
    assert (stats['pollutant_loading']['test'] == approx(1305.75,
                                                         rel=UT_PRECISION))
    assert (stats['average_flowrate'] == approx(4.3, rel=UT_PRECISION))
    assert (stats['average_flowrate'] == approx(4.32, rel=UT_PRECISION))
    assert (stats['peak_flowrate'] == approx(4.33, rel=UT_PRECISION))
    assert (stats['peak_flowrate'] == approx(4.34, rel=UT_PRECISION))
    assert (outfall_cuinflow == approx(1395293, rel=UT_PRECISION))
    assert (outfall_cuinflow == approx(1395299, rel=UT_PRECISION)
            and outfall_cuinflow == approx(1395350, rel=UT_PRECISION))
Esempio n. 6
0
def test_GravitySettling_conc():
    dict1 = {
        'Tank': {
            'pollutant': 0,
            'method': 'GravitySettling',
            'parameters': {
                'k': 0.01,
                'C_s': 10.0
            }
        }
    }
    conc = []
    con = []
    with Simulation("./tests/inps/tank_variableinflow_notreatment.inp") as sim:
        GS = waterQuality(sim, dict1)
        Tank = Nodes(sim)["Tank"]
        for step in sim:
            GS.updateWQState()
            c = Tank.pollut_quality
            conc.append(c['P1'])
    with Simulation(
            "./tests/inps/tank_variableinflow_gravsettling.inp") as sim:
        Tank = Nodes(sim)["Tank"]
        for step in sim:
            co = Tank.pollut_quality
            con.append(co['P1'])
        error = mse(con, conc[1:])
        print(error)
        assert error <= 0.03
Esempio n. 7
0
def test_CoRemoval_load():
    dict1 = {'Tank': {'pollutant': 1, 'method': 'ConstantRemoval', 'parameters': {'R': 0.15}},\
        'Tank': {'pollutant': 0, 'method': 'CoRemoval', 'parameters': {'R1': 0.75, 'R2': 0.15}}}
    conc = []
    conc1 = []
    flow = []
    flow1 = []
    with Simulation("./tests/inps/tank_variableinflow_notreatment.inp") as sim:
        CO = waterQuality(sim, dict1)
        Outfall = Nodes(sim)["Outfall"]
        for step in sim:
            CO.updateWQState()
            c = Outfall.pollut_quality
            conc.append(c['P1'])
            flow.append(sim._model.getNodeResult("Outfall", 0))
        load = [a * b for a, b in zip(conc, flow)]
        cum_load = np.cumsum(load)
    with Simulation("./tests/inps/tank_variableinflow_coremoval.inp") as sim:
        Outfall = Nodes(sim)["Outfall"]
        for step in sim:
            c = Outfall.pollut_quality
            conc1.append(c['P1'])
            flow1.append(sim._model.getNodeResult("Outfall", 0))
        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
Esempio n. 8
0
def test_EventMeanConc_conc():
    dict1 = {
        'Tank': {
            'pollutant': 0,
            'method': 'EventMeanConc',
            'parameters': {
                'C': 5.0
            }
        }
    }
    conc = []
    con = []
    with Simulation("./tests/inps/tank_variableinflow_notreatment.inp") as sim:
        EMC = waterQuality(sim, dict1)
        Tank = Nodes(sim)["Tank"]
        for step in sim:
            EMC.updateWQState()
            c = Tank.pollut_quality
            conc.append(c['P1'])
    with Simulation("./tests/inps/tank_variableinflow_emc.inp") as sim:
        Tank = Nodes(sim)["Tank"]
        for step in sim:
            co = Tank.pollut_quality
            con.append(co['P1'])
    error = mse(con, conc)
    print(error)
    assert error <= 0.03
 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)
Esempio n. 10
0
    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
Esempio n. 11
0
def simul_nodes(i,filename):
    '''
    Function to be iterated using parallelisation
    Filename needs to be changed every time that the storm is changed
    
    Input
    -----
    list of subcatchments where GI will be implemented

    Output
    ------
    resilience index pandas dataframe
    '''
    from pyswmm import Simulation
    
    area = 500
    
    LIDsubcat_area(filename,i)

    fin=filename+str(hash(''.join(i)))+f'area_{area}'

    sim=Simulation('Res_files/'+fin+'.inp')
    sim.execute()

    res=resilienceindex_nodes_sys(fin)
    print('Resilience Index Calculated')

    os.remove('Res_files/'+fin+'.inp')
    os.remove('Res_files/'+fin+'.out')
    os.remove('Res_files/'+fin+'.rpt')

    print('Files removed!')

    return res
Esempio n. 12
0
def test_nodes_6():
    ''' pytest pyswmm/tests/test_nodes.py -k `test_nodes_6` '''
    sim = Simulation(MODEL_WEIR_SETTING_PATH)
    print("\n\n\nNODES\n")
    J5 = Nodes(sim)["J5"]

    for ind, step in enumerate(sim):
        pass
    
    assert(J5.statistics['peak_total_inflow'] >= 0.478)
    assert(J5.statistics['average_depth'] >= 0.00018)
    assert(J5.statistics['surcharge_duration'] >= 0.0)
    assert(J5.statistics['max_ponded_volume'] >= 0.0)
    assert(J5.statistics['courant_crit_duration'] >= 0.0)
    assert(J5.statistics['peak_lateral_inflowrate'] >= 0.0)
    assert(J5.statistics['flooding_duration'] >= 0.0)
    assert(J5.statistics['peak_flooding_rate'] >= 0.0)
    assert(J5.statistics['lateral_infow_vol'] >= 0.0)
    assert(J5.statistics['max_flooding_date'] >= 42309)
    assert(J5.statistics['max_depth_date'] >= 42309)
    assert(J5.statistics['max_inflow_date'] >= 42309)
    assert(J5.statistics['max_depth'] >= 0.0292)
    assert(J5.statistics['flooding_volume'] >= 0.0)
    assert(J5.statistics['max_report_depth'] >= 0.0286)
    sim.close()
Esempio n. 13
0
    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
Esempio n. 14
0
def test_ConstantRemoval_load():
    dict1 = {'Tank': {0: 0.5}}
    conc = []
    conc1 = []
    flow = []
    flow1 = []
    with Simulation("./inps/tank_variableinflow_notreatment.inp") as sim:
        CR = Node_Quality(sim, dict1)
        Outfall = Nodes(sim)["Outfall"]
        for step in sim:
            CR.ConstantRemoval()
            c = Outfall.pollut_quality
            conc.append(c['P1'])
            flow.append(sim._model.getNodeResult("Outfall", 0))
        load = [a * b for a, b in zip(conc, flow)]
        cum_load = np.cumsum(load)
    with Simulation("./inps/tank_variableinflow_constantremoval.inp") as sim:
        Outfall = Nodes(sim)["Outfall"]
        for step in sim:
            c = Outfall.pollut_quality
            conc1.append(c['P1'])
            flow1.append(sim._model.getNodeResult("Outfall", 0))
        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
Esempio n. 16
0
    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)
Esempio n. 17
0
def test_EventMeanConc_load():
    dict1 = {
        'Tank': {
            'pollutant': 0,
            'method': 'EventMeanConc',
            'parameters': {
                'C': 5.0
            }
        }
    }
    conc = []
    conc1 = []
    flow = []
    flow1 = []
    with Simulation("./tests/inps/tank_variableinflow_notreatment.inp") as sim:
        EMC = waterQuality(sim, dict1)
        Outfall = Nodes(sim)["Outfall"]
        for step in sim:
            EMC.updateWQState()
            c = Outfall.pollut_quality
            conc.append(c['P1'])
            flow.append(sim._model.getNodeResult("Outfall", 0))
        load = [a * b for a, b in zip(conc, flow)]
        cum_load = np.cumsum(load)
    with Simulation("./tests/inps/tank_variableinflow_emc.inp") as sim:
        Outfall = Nodes(sim)["Outfall"]
        for step in sim:
            c = Outfall.pollut_quality
            conc1.append(c['P1'])
            flow1.append(sim._model.getNodeResult("Outfall", 0))
        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
Esempio n. 18
0
def test_outfalls_8():
    sim = Simulation(MODEL_STORAGE_PUMP)
    print("\n\n\nOUTFALL\n")
    outfall = Nodes(sim)["J3"]

    for ind, step in enumerate(sim):
        if ind % 1000 == 0:
            print(outfall.outfall_statistics)
    sim.close()
Esempio n. 19
0
def test_nodes_6():
    sim = Simulation(MODEL_WEIR_SETTING_PATH)
    print("\n\n\nNODES\n")
    J5 = Nodes(sim)["J5"]

    for ind, step in enumerate(sim):
        if ind % 1000 == 0:
            print(J5.statistics)
    sim.close()
Esempio n. 20
0
def test_outfalls_7():
    sim = Simulation(MODEL_STORAGE_PUMP)
    print("\n\n\nSTORAGE\n")
    STOR1 = Nodes(sim)["SU1"]

    for ind, step in enumerate(sim):
        if ind % 1000 == 0:
            print(STOR1.storage_statistics)
    sim.close()
Esempio n. 21
0
def test_storage_7():
    ''' pytest pyswmm/tests/test_nodes.py -k `test_storage_7` '''
    sim = Simulation(MODEL_STORAGE_PUMP)
    print("\n\n\nSTORAGE\n")
    STOR1 = Nodes(sim)["SU1"]

    for ind, step in enumerate(sim):
        pass

    stats = STOR1.storage_statistics
    assert (stats['max_volume'] == approx(5000.0, rel=UT_PRECISION))
    assert (stats['peak_flowrate'] == approx(0.0, rel=UT_PRECISION))
    assert (stats['exfil_loss'] == approx(0.0, rel=UT_PRECISION))
    assert (stats['evap_loss'] == approx(0.0, rel=UT_PRECISION))
    assert (stats['average_volume'] == approx(4979.0, rel=UT_PRECISION))
    assert (stats['average_volume'] == approx(4980.0, rel=UT_PRECISION))
    assert (stats['max_vol_date'] == approx(42309.0, rel=UT_PRECISION))
    assert (stats['max_vol_date'] == approx(42310.0, rel=UT_PRECISION))
    assert (stats['initial_volume'] == approx(0.0, rel=UT_PRECISION))

    stats = STOR1.statistics
    assert (stats['peak_total_inflow'] == approx(2.9, rel=UT_PRECISION))
    assert (stats['peak_total_inflow'] == approx(3.1, rel=UT_PRECISION))

    assert (stats['average_depth'] == approx(4.9, rel=UT_PRECISION))
    assert (stats['average_depth'] == approx(5, rel=UT_PRECISION))

    assert (stats['flooding_duration'] == approx(57, rel=UT_PRECISION))
    assert (stats['flooding_duration'] == approx(58, rel=UT_PRECISION))

    assert (stats['peak_flooding_rate'] == approx(2.9, rel=UT_PRECISION))
    assert (stats['peak_flooding_rate'] == approx(3.1, rel=UT_PRECISION))

    assert (stats['lateral_infow_vol'] == approx(0.0, rel=UT_PRECISION))

    assert (stats['max_flooding_date'] == approx(42309, rel=UT_PRECISION))
    assert (stats['max_flooding_date'] == approx(42310, rel=UT_PRECISION))

    assert (stats['max_depth_date'] == approx(42309, rel=UT_PRECISION))
    assert (stats['max_depth_date'] == approx(42310, rel=UT_PRECISION))

    assert (stats['max_inflow_date'] == approx(42309, rel=UT_PRECISION))
    assert (stats['max_inflow_date'] == approx(42310, rel=UT_PRECISION))

    assert (stats['max_depth'] == approx(4.99, rel=UT_PRECISION))
    assert (stats['max_depth'] == approx(5.01, rel=UT_PRECISION))

    assert (stats['flooding_volume'] == approx(621390, rel=UT_PRECISION))
    assert (stats['flooding_volume'] == approx(621393, rel=UT_PRECISION))

    assert (stats['max_report_depth'] == approx(4.99, rel=UT_PRECISION))
    assert (stats['max_report_depth'] == approx(5.01, rel=UT_PRECISION))

    print(STOR1.statistics)

    sim.close()
Esempio n. 22
0
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])
Esempio n. 23
0
def test_lib_5():
    """Testing SWMM Path as argument to Simulation Object.

    On Windows for now."""
    if os.name == 'nt':
        print(WIN_SWMM_LIB_PATH)
        sim = Simulation(MODEL_WEIR_SETTING_PATH,
                         swmm_lib_path=WIN_SWMM_LIB_PATH)
        sim.execute()
        pyswmm.lib.use(WIN_SWMM_LIB_PATH)
Esempio n. 24
0
def test_storage_7():
    ''' pytest pyswmm/tests/test_nodes.py -k `test_storage_7` '''
    sim = Simulation(MODEL_STORAGE_PUMP)
    print("\n\n\nSTORAGE\n")
    STOR1 = Nodes(sim)["SU1"]

    for ind, step in enumerate(sim):
        pass

    stats = STOR1.storage_statistics
    assert(stats['max_volume'] ==  5000.0)
    assert(stats['peak_flowrate'] ==  0.0)
    assert(stats['exfil_loss'] ==  0.0)
    assert(stats['evap_loss'] ==  0.0)
    assert(stats['average_volume'] >=  4979.0)
    assert(stats['average_volume'] <=  4980.0)
    assert(stats['max_vol_date'] >=  42309.0)
    assert(stats['max_vol_date'] <=  42310.0)
    assert(stats['initial_volume'] ==  0.0)

    stats = STOR1.statistics
    assert(stats['peak_total_inflow'] >= 2.9)
    assert(stats['peak_total_inflow'] <= 3.1)
    
    assert(stats['average_depth'] >= 4.9)
    assert(stats['average_depth'] <= 5)

    assert(stats['flooding_duration'] >= 57)
    assert(stats['flooding_duration'] <= 58)
    
    assert(stats['peak_flooding_rate'] >= 2.9)
    assert(stats['peak_flooding_rate'] <= 3.1)
    
    assert(stats['lateral_infow_vol'] == 0.0)
    
    assert(stats['max_flooding_date'] >= 42309)
    assert(stats['max_flooding_date'] <= 42310)
    
    assert(stats['max_depth_date'] >= 42309)
    assert(stats['max_depth_date'] <= 42310)
    
    assert(stats['max_inflow_date'] >= 42309)
    assert(stats['max_inflow_date'] <= 42310)

    assert(stats['max_depth'] >= 4.99)
    assert(stats['max_depth'] <= 5.01)
    
    assert(stats['flooding_volume'] >= 621390)
    assert(stats['flooding_volume'] <= 621393)
    
    assert(stats['max_report_depth'] >= 4.99)
    assert(stats['max_report_depth'] <= 5.01)

    print(STOR1.statistics)
    sim.close()
Esempio n. 25
0
class Env:
    def __init__(self, input_file):
        self.input_file = input_file
        self.sim = Simulation(self.input_file)
        self.sim.start()
        self.time = 1.0

    def step(self):
        if self.time > 0:
            done = False
            self.time = self.sim._model.swmm_step()
        else:
            done = True
            print("Simulation Ended")
        return done

    def terminate(self):
        self.sim._model.swmm_end()
        self.sim._model.swmm_close()

    def depthN(self, node_id):
        return self.sim._model.getNodeResult(node_id, 5)

    def depthL(self, link_id):
        return self.sim._model.getLinkResult(link_id, 1)

    def flow(self, link_id):
        return self.sim._model.getLinkResult(link_id, 0)

    def get_precip(self, subcatchment_id):
        pass

    def set_precip(self, subcatchment_id):
        pass

    def get_gate(self, orifice):
        return self.sim._model.getLinkResult(orifice, 6)

    def set_gate(self, orifice, gate):
        self.sim._model.setLinkSetting(orifice, gate)

    def get_pollutant_node(self, node):
        return self.sim._model.getNodeResult(node, 100)

    def get_pollutant_link(self, link):
        return self.sim._model.getLinkResult(link, 100)

    def reset(self):
        self.sim._model.swmm_end()
        self.sim._model.swmm_close()
        # Start the next simulation
        self.sim._model.swmm_open()
        self.sim._model.swmm_start()
        self.time = 1.0
Esempio n. 26
0
    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)
Esempio n. 27
0
def test_nodes_5():
    sim = Simulation(MODEL_WEIR_SETTING_PATH)
    print("\n\n\nNODES\n")
    J5 = Nodes(sim)["J5"]

    for ind, step in enumerate(sim):
        if ind == 7:
            J5.generated_inflow(544.0)
        if ind > 8:
            assert (J5.lateral_inflow >= 543.9)
            print(J5.lateral_inflow)
    sim.close()
Esempio n. 28
0
def test_nodes_5():
    sim = Simulation(MODEL_WEIR_SETTING_PATH)
    print("\n\n\nNODES\n")
    J5 = Nodes(sim)["J5"]

    for ind, step in enumerate(sim):
        if ind == 7:
            J5.generated_inflow(544.0)
        if ind > 8:
            assert (J5.lateral_inflow == approx(543.9, rel=UT_PRECISION))
            if ind % 1000 == 0:
                print(J5.lateral_inflow)
    sim.close()
Esempio n. 29
0
def test_nodes_11():
    ''' pytest pyswmm/tests/test_nodes.py -k `test_outfalls_8_mgd` '''
    sim = Simulation(MODEL_STORAGE_PUMP_MGD)
    print("\n\n\nOUTFALL\n")
    outfall = Nodes(sim)["J3"]

    for ind, step in enumerate(sim):
        pass
    stats = outfall.outfall_statistics
    outfall_cuinflow = outfall.cumulative_inflow
    sim.close()
    assert (outfall_cuinflow == approx(1395293, rel=UT_PRECISION))
    assert (outfall_cuinflow == approx(1395299, rel=UT_PRECISION)
            and outfall_cuinflow == approx(1395350, rel=UT_PRECISION))
Esempio n. 30
0
def test_simulation_1():
    sim = Simulation(MODEL_WEIR_SETTING_PATH)
    for ind, step in enumerate(sim):
        print(step.getCurrentSimulationTime())
        sim.step_advance(randint(300, 900))

    sim.report()
    sim.close()