How to use wntr - 10 common examples

To help you get started, we’ve selected a few wntr examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github USEPA / WNTR / examples / timing_tests_epanet.py View on Github external
import wntr
import pandas as pd
import time
import cProfile, pstats, StringIO

# Create a water network model
#inp_file = 'networks/Net6_mod_scipy.inp'
inp_file = 'networks/Net3_timing.inp'
wn = wntr.network.WaterNetworkModel(inp_file)

# Simulate using Epanet
print "-----------------------------------"
print "EPANET SIMULATOR: "
pr = cProfile.Profile()
pr.enable()
sim = wntr.sim.EpanetSimulator(wn)
results = sim.run_sim()
pr.disable()
print "-----------------------------------"
s = StringIO.StringIO()
sortby = 'cumulative'
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats(20)
print s.getvalue()

s = StringIO.StringIO()
sortby = 'tottime'
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats(20)
print s.getvalue()
github USEPA / WNTR / examples / timing_tests.py View on Github external
import wntr
import pandas as pd
import time

# Create a water network model
#inp_file = 'networks/Net6_mod_scipy.inp'
#inp_file = 'networks/Net3_timing.inp
inp_file = 'networks/Net3_easy_copy.inp'
wn = wntr.network.WaterNetworkModel(inp_file)

# Simulate using Epanet
print "-----------------------------------"
print "EPANET SIMULATOR: "
t0 = time.time()
epa_sim = wntr.sim.EpanetSimulator(wn)
t1 = time.time()
results = epa_sim.run_sim()
t2 = time.time()
total_epanet_time = t2 - t0
epanet_obj_creation_time = t1-t0
epanet_run_sim_time = t2-t1
print "-----------------------------------"

# Simulate using Scipy
print "-----------------------------------"
print "SCIPY SIMULATOR: "
t0 = time.time()
sci_sim = wntr.sim.ScipySimulator(wn)
t1 = time.time()
results = sci_sim.run_sim()
t2 = time.time()
github USEPA / WNTR / examples / timing_tests_scipy_v2.py View on Github external
import wntr
import pandas as pd
import time
import cProfile, pstats, StringIO

# Create a water network model
#inp_file = 'networks/Net6_mod_scipy.inp'
inp_file = 'networks/Net3_easy.inp'
wn = wntr.network.WaterNetworkModel(inp_file)

# Simulate using Epanet
print "-----------------------------------"
print "SCIPY SIMULATOR V2: "
pr = cProfile.Profile()
pr.enable()
sim = wntr.sim.ScipySimulatorV2(wn)
results = sim.run_sim()
pr.disable()
print "-----------------------------------"
s = StringIO.StringIO()
sortby = 'cumulative'
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats(20)
print s.getvalue()

s = StringIO.StringIO()
sortby = 'tottime'
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats(20)
print s.getvalue()
github USEPA / WNTR / examples / timing_tests.py View on Github external
print "SCIPY SIMULATOR: "
t0 = time.time()
sci_sim = wntr.sim.ScipySimulator(wn)
t1 = time.time()
results = sci_sim.run_sim()
t2 = time.time()
total_scipy_time = t2 - t0
scipy_obj_creation_time = t1-t0
scipy_run_sim_time = t2-t1
print "-----------------------------------"

# Simulate using Pyomo
print "-----------------------------------"
print "PYOMO SIMULATOR: "
t0 = time.time()
pyo_sim = wntr.sim.PyomoSimulator(wn)
t1 = time.time()
results = pyo_sim.run_sim()
t2 = time.time()
total_pyomo_time = t2 - t0
pyomo_obj_creation_time = t1-t0
pyomo_run_sim_time = t2-t1
print "-----------------------------------"


print('{0:<30s}{1:<12s}{2:<12s}{3:<12s}'.format('Category','Epanet','Scipy','Pyomo'))
print('{0:<30s}{1:<12.4f}{2:<12.4f}{3:<12.4f}'.format('Total Sim Time',total_epanet_time,total_scipy_time, total_pyomo_time))
print('{0:<30s}{1:<12.4f}{2:<12.4f}{3:<12.4f}'.format('Sim obj creation time',epanet_obj_creation_time,scipy_obj_creation_time, pyomo_obj_creation_time))
print('{0:<30s}{1:<12.4f}{2:<12.4f}{3:<12.4f}'.format('run_sim time',epanet_run_sim_time,scipy_run_sim_time, pyomo_run_sim_time))
print('{0:<30s}{1:<12.4f}{2:<12.4f}{3:<12.4f}'.format('Prep time before main loop',epa_sim.prep_time_before_main_loop, sci_sim.prep_time_before_main_loop, pyo_sim.prep_time_before_main_loop))
print('{0:<30s}{1:<12.4f}{2:<12.4f}{3:<12.4f}'.format('Total solve time',sum(epa_sim.solve_step[i] for i in epa_sim.solve_step.keys()),sum(sci_sim.solve_step[i] for i in sci_sim.solve_step.keys()), sum(pyo_sim.solve_step[i] for i in pyo_sim.solve_step.keys())))
print('{0:<30s}{1:<12.4s}{2:<12.4s}{3:<12.4f}'.format('Build pyomo model time','n/a','n/a', sum(pyo_sim.build_model_time[i] for i in pyo_sim.build_model_time.keys())))
github USEPA / WNTR / wntr / epanet / io.py View on Github external
current = line.split()
            if current == []:
                continue
            link_name = current[1]
            link = self.wn.get_link(link_name)
            if current[5].upper() != 'TIME' and current[5].upper() != 'CLOCKTIME':
                node_name = current[5]
            current = [i.upper() for i in current]
            current[1] = link_name # don't capitalize the link name

            # Create the control action object

            status = current[2].upper()
            if status == 'OPEN' or status == 'OPENED' or status == 'CLOSED' or status == 'ACTIVE':
                setting = LinkStatus[status].value
                action_obj = wntr.network.ControlAction(link, 'status', setting)
            else:
                if isinstance(link, wntr.network.Pump):
                    action_obj = wntr.network.ControlAction(link, 'speed', float(current[2]))
                elif isinstance(link, wntr.network.Valve):
                    if link.valve_type == 'PRV' or link.valve_type == 'PSV' or link.valve_type == 'PBV':
                        setting = to_si(self.flow_units, float(current[2]), HydParam.Pressure)
                    elif link.valve_type == 'FCV':
                        setting = to_si(self.flow_units, float(current[2]), HydParam.Flow)
                    elif link.valve_type == 'TCV':
                        setting = float(current[2])
                    elif link.valve_type == 'GPV':
                        setting = current[2]
                    else:
                        raise ValueError('Unrecognized valve type {0} while parsing control {1}'.format(link.valve_type, line))
                    action_obj = wntr.network.ControlAction(link, 'setting', setting)
                else:
github USEPA / WNTR / wntr / epanet / io.py View on Github external
def add_action_on_true(self, action, prefix=' THEN'):
        """Add a "then" action from an IfThenElseControl"""
        if isinstance(action, ControlAction):
            fmt = '{} {} {} {} = {}'
            attr = action._attribute
            val_si = action._repr_value()
            if attr.lower() in ['demand']:
                value = '{:.6g}'.format(from_si(self.inp_units, val_si, HydParam.Demand))
            elif attr.lower() in ['head', 'level']:
                value = '{:.6g}'.format(from_si(self.inp_units, val_si, HydParam.HydraulicHead))
            elif attr.lower() in ['flow']:
                value = '{:.6g}'.format(from_si(self.inp_units, val_si, HydParam.Flow))
            elif attr.lower() in ['pressure']:
                value = '{:.6g}'.format(from_si(self.inp_units, val_si, HydParam.Pressure))
            elif attr.lower() in ['setting']:
                if isinstance(action._target_obj_ref, Valve):
                    if action._target_obj_ref.valve_type.upper() in ['PRV', 'PBV', 'PSV']:
                        value = from_si(self.inp_units, val_si, HydParam.Pressure)
                    elif action._target_obj_ref.valve_type.upper() in ['FCV']:
                        value = from_si(self.inp_units, val_si, HydParam.Flow)
                    else:
                        value = val_si
                else:
                    value = val_si
                value = '{:.6g}'.format(value)
            else: # status
                value = val_si
            clause = fmt.format(prefix, action._target_obj_ref.__class__.__name__,
                                action._target_obj_ref.name, action._attribute,
                                value)
github USEPA / WNTR / wntr / epanet / io.py View on Github external
def _write_valves(self, f, wn):
        f.write('[VALVES]\n'.encode('ascii'))
        f.write(_VALVE_LABEL.format(';ID', 'Node1', 'Node2', 'Diameter', 'Type', 'Setting', 'Minor Loss').encode('ascii'))
        lnames = list(wn._valves.keys())
        lnames.sort()
        for valve_name in lnames:
            valve = wn._valves[valve_name]
            E = {'name': valve_name,
                 'node1': valve.start_node,
                 'node2': valve.end_node,
                 'diam': from_si(self.flow_units, valve.diameter, HydParam.PipeDiameter),
                 'vtype': valve.valve_type,
                 'set': valve._base_setting,
                 'mloss': valve.minor_loss,
                 'com': ';'}
            valve_type = valve.valve_type
            if valve_type in ['PRV', 'PSV', 'PBV']:
                valve_set = from_si(self.flow_units, valve._base_setting, HydParam.Pressure)
            elif valve_type == 'FCV':
                valve_set = from_si(self.flow_units, valve._base_setting, HydParam.Flow)
            elif valve_type == 'TCV':
                valve_set = valve._base_setting
            elif valve_type == 'GPV':
                valve_set = valve._base_setting
            E['set'] = valve_set
            f.write(_VALVE_ENTRY.format(**E).encode('ascii'))
        f.write('\n'.encode('ascii'))
github USEPA / WNTR / wntr / epanet / io.py View on Github external
attr = condition._source_attr
            val_si = condition._repr_value(attr, condition._threshold)
            if attr.lower() in ['demand']:
                value = '{:.6g}'.format(from_si(self.inp_units, val_si, HydParam.Demand))
            elif attr.lower() in ['head', 'level']:
                value = '{:.6g}'.format(from_si(self.inp_units, val_si, HydParam.HydraulicHead))
            elif attr.lower() in ['flow']:
                value = '{:.6g}'.format(from_si(self.inp_units, val_si, HydParam.Flow))
            elif attr.lower() in ['pressure']:
                value = '{:.6g}'.format(from_si(self.inp_units, val_si, HydParam.Pressure))
            elif attr.lower() in ['setting']:
                if isinstance(condition._source_obj, Valve):
                    if condition._source_obj.valve_type.upper() in ['PRV', 'PBV', 'PSV']:
                        value = from_si(self.inp_units, val_si, HydParam.Pressure)
                    elif condition._source_obj.valve_type.upper() in ['FCV']:
                        value = from_si(self.inp_units, val_si, HydParam.Flow)
                    else:
                        value = val_si
                else:
                    value = val_si
                value = '{:.6g}'.format(value)
            else: # status
                value = val_si
            clause = fmt.format(prefix, condition._source_obj.__class__.__name__,
                                condition._source_obj.name, condition._source_attr,
                                condition._relation.symbol, value)
            self.add_if(clause)
        else:
            raise ValueError('Unknown ControlCondition for EPANET Rules')
github USEPA / WNTR / wntr / epanet / io.py View on Github external
from_si(self.flow_units,
                                                   tank.bulk_rxn_coeff,
                                                   QualParam.BulkReactionCoeff,
                                                   mass_units=self.mass_units,
                                                   reaction_order=wn.options.quality.bulk_rxn_order)).encode('ascii'))
        for pipe_name, pipe in wn.links(Pipe):
            if pipe.bulk_rxn_coeff is not None:
                f.write(entry_float.format('BULK',pipe_name,
                                           from_si(self.flow_units,
                                                   pipe.bulk_rxn_coeff,
                                                   QualParam.BulkReactionCoeff,
                                                   mass_units=self.mass_units,
                                                   reaction_order=wn.options.quality.bulk_rxn_order)).encode('ascii'))
            if pipe.wall_rxn_coeff is not None:
                f.write(entry_float.format('WALL',pipe_name,
                                           from_si(self.flow_units,
                                                   pipe.wall_rxn_coeff,
                                                   QualParam.WallReactionCoeff,
                                                   mass_units=self.mass_units,
                                                   reaction_order=wn.options.quality.wall_rxn_order)).encode('ascii'))
        f.write('\n'.encode('ascii'))
github USEPA / WNTR / wntr / epanet / io.py View on Github external
if current[0].upper() == 'GLOBAL':
                if current[1].upper() == 'PRICE':
                    self.wn.options.energy.global_price = from_si(self.flow_units, float(current[2]), HydParam.Energy)
                elif current[1].upper() == 'PATTERN':
                    self.wn.options.energy.global_pattern = current[2]
                elif current[1].upper() in ['EFFIC', 'EFFICIENCY']:
                    self.wn.options.energy.global_efficiency = float(current[2])
                else:
                    logger.warning('Unknown entry in ENERGY section: %s', line)
            elif current[0].upper() == 'DEMAND':
                self.wn.options.energy.demand_charge = float(current[2])
            elif current[0].upper() == 'PUMP':
                pump_name = current[1]
                pump = self.wn._pumps[pump_name]
                if current[2].upper() == 'PRICE':
                    pump.energy_price = from_si(self.flow_units, float(current[2]), HydParam.Energy)
                elif current[2].upper() == 'PATTERN':
                    pump.energy_pattern = current[2]
                elif current[2].upper() in ['EFFIC', 'EFFICIENCY']:
                    curve_name = current[3]
                    curve_points = []
                    for point in self.curves[curve_name]:
                        x = to_si(self.flow_units, point[0], HydParam.Flow)
                        y = point[1]
                        curve_points.append((x, y))
                    self.wn.add_curve(curve_name, 'EFFICIENCY', curve_points)
                    curve = self.wn.get_curve(curve_name)
                    pump.efficiency = curve
                else:
                    logger.warning('Unknown entry in ENERGY section: %s', line)
            else:
                logger.warning('Unknown entry in ENERGY section: %s', line)