Exemplo n.º 1
0
 def test_running_with_nonsensical_swmm_input_file(self):
     """ should raise a SWMM5Error exception"""
     self.assertRaises(SWMM5Error,SWMM5Simulation,"foo-bar-bat-box.inp")
     try:
         SWMM5Simulation("foo-bar-bat-box.inp")
         pass
     except SWMM5Error as e:
         pass
         self.assertEqual(str(e),'67: \n  ERROR 303: cannot open input file.')
Exemplo n.º 2
0
def runswmm(model1, lidname, runParamList, swmmInpFile, simulation_date,
            sub_i):
    # read inp file and change Lid's ksat value

    # Write out the model to a new file because SWMM must have a file
    Catchment = ['UrbanLand', 'UrbanComplex', 'Manor']
    subcat = Catchment[sub_i]
    f = open('SWMM_modified.inp', 'w')
    swmmInputFileStr = model1.output()
    f.write(swmmInputFileStr
            )  # write out the swmmInputFileStr for modified problem
    f.close()

    # show the Impervious Treated Percentage of GI in subwatersheds
    imperv_i = [0, 0, 0]
    imperv_i[0] = swmmInputFileStr.find('UrbanLand\t' + lidname + '\t')
    imperv_i[1] = swmmInputFileStr.index('UrbanComplex\t' + lidname + '\t')
    imperv_i[2] = swmmInputFileStr.index('Manor\t' + lidname + '\t')
    imperv_treated = [0, 0, 0]
    for i in range(0, 3):
        lineList = swmmInputFileStr[imperv_i[i]:].split(
            '\n', 1)  ## lists of lines from .inp, split by '\n'
        wordList = lineList[0].split()
        imperv_treated[i] = wordList[6]
#    print('impervious treated = ', imperv_treated)

# Run the new model file
    startTime = datetime.now()  # obtain the starting time of the run
    #    startTimeStr = str(startTime)
    st = SWMM5Simulation("SWMM_modified.inp", "SWMM_modified.txt")

    endTime = datetime.now()  # obtain the ending time of the run
    elapsedTime = endTime - startTime
    minAndSec = divmod(elapsedTime.total_seconds(), 60)
    elapsedTimeStr = "%s min, %0.2f sec" % minAndSec
    area = runParamList[sub_i]['Area']
    N_GI = runParamList[sub_i]['Number']
    print(elapsedTimeStr)
    (peak, volume, lidDict) = read_report("SWMM_modified.txt")
    if lidname == "RainBarrel" and N_GI > 0:
        vol_in = (float(lidDict[subcat + ' ' + lidname]['Total Inflow']) -
                  float(lidDict[subcat + ' ' + lidname]['Surface Outflow']))

        vol_re_MG = vol_in / 12.0 * area * N_GI * 7.48 / 1000000  # runoff reduction
        volume = volume - vol_re_MG

    run = {
        "peak": peak,
        "volume": volume,
        "lidDict": lidDict,
        "runParamList": runParamList,
        "imperv_treated": imperv_treated
    }
    return (run)
    def runSWMM1(self):
        """Runs swmm and obtain some results"""
        ss = SWMM5Simulation("swmm5/examples/simple/swmm5Example.inp")
        self.assertEquals(ss.Flow_Units(), 'LPS')
        self.assertEquals(ss.entityList(), ['SUBCATCH', 'NODE', 'LINK', 'SYS'])
        g = ss.Results('SYS', 'SYS', 1)
        [next(g) for x in range(7)]
        self.assertAlmostEqual(next(g), 7.600000858306885)
        self.assertAlmostEqual(next(g), 8.000000000000000)
        ss.getFiles()

        return
Exemplo n.º 4
0
def replace_and_run(values):
    # Open the template file
    with open("small_case.template", "r") as inf:
        txt = inf.read()
    # replace template variable
    result = Template(txt).substitute(a1imp=value)
    #write the result to a INP file
    with open("case.inp", "w") as ouf:
        ouf.write(result)
    res = SWMM5Simulation("case.inp")
    maxfl = max(list(res.Results('NODE', 'N1', 4)))
    return maxfl
Exemplo n.º 5
0
    def runSWMM2(self):
        """Runs swmm and obtain some results"""

        ss = SWMM5Simulation("swmm5/examples/waterquality/Example5-EXP.inp")
        self.assertEquals(ss.Flow_Units(), 'CFS')
        self.assertEquals(ss.entityList(), ['SUBCATCH', 'NODE', 'LINK', 'SYS'])
        g = ss.Results('SUBCATCH', 'S3', 8)
        self.assertAlmostEqual(next(g), 0.00)
        self.assertAlmostEqual(next(g), 0.00)
        self.assertAlmostEqual(next(g), 0.00)
        self.assertAlmostEqual(next(g), 0.00)
        self.assertAlmostEqual(next(g), 0.00)
        self.assertAlmostEqual(next(g), 13.44666862487793)
        self.assertAlmostEqual(next(g), 14.10814380645752)
        self.assertAlmostEqual(next(g), 14.707027435302734)
        self.assertAlmostEqual(next(g), 15.237997055053711)
        ss.getFiles()
        return
Exemplo n.º 6
0
    def upload2(self, ufile):
        # Either save the file to the directory where server.py is
        # or save the file to a given path:
        # upload_path = '/path/to/project/data/'
        upload_path = os.path.dirname(__file__)

        # Save the file to a predefined filename
        # or use the filename sent by the client:
        # upload_filename = ufile.filename
        upload_filename = 'saved.txt'

        upload_file = os.path.normpath(
            os.path.join(upload_path, upload_filename))

        upload_file = '../data/saved.inp'

        size = 0
        with open(upload_file, 'wb') as out:
            while True:
                data = ufile.file.read(8192)
                if not data:
                    break
                out.write(data)
                size += len(data)



        import pdb;pdb.set_trace()       
        st=SWMM5Simulation(upload_file)
        version = st.SWMM5_Version()
        nodes = st.SWMM_Nnodes

        out = '''
File received.
Filename: {}
Length: {}
Mime-type: {}
SVMM-version : {}
''' .format(ufile.filename, size, ufile.content_type, version, data)
        return out
Exemplo n.º 7
0
 def run_swmm(self):
     if self.working_dir != None:
         os.chdir(self.working_dir)
     try:
         self.st = SWMM5Simulation(self.swmm_filename)  # run a simulation
         return True
     except Exception as e:
         print(str(e))
         if str(e).strip() == '303:':
             print(
                 str(e) +
                 ' Arquivo {} nao encontrado.'.format(self.swmm_filename))
         if str(e).strip() == '317:' or str(e).strip() == '313:':
             print(
                 str(e) +
                 ' Erro ao carregar dados {}.'.format(self.swmm_filename))
         if self.temp_file:
             os.remove(self.swmm_filename)
         sys.exit()
     finally:
         if self.working_dir != None:
             os.chdir(self.root_dir)
Exemplo n.º 8
0
    def index(self):

        st = SWMM5Simulation('../data/CS_H.inp')

        import pdb
        pdb.set_trace()

        return 'OKK'

        rep = open('./data/CS_H.rpt', 'r')
        Lines = rep.readlines()
        count = 0
        html = ""
        # Strips the newline character
        for line in Lines:
            if line.strip() == "LID Control Summary":
                prt = 1
            elif line.strip() == "":
                prt = 0
            if prt:
                html = html + line.strip() + '<br />'

        return html
Exemplo n.º 9
0
    def simulazione(self,
                    schema_id='',
                    imp='15',
                    regime='CAM',
                    anni='2',
                    drwh='',
                    convpp='',
                    convtv='',
                    callback='',
                    _=''):

        self.callback = callback
        inpPath = "/apps/trigeau/data"

        self.result_id = datetime.today().strftime("%Y%m%d%H%M%S")

        #self.path = inpPath

        #se drwh richiamo la stesa funzione per modificare il drwh
        #if drwh and drwh!="DRWH_OK":

        #apro il file di base e sostituisco i valori
        if drwh == 'SI':
            if int(imp) < 30:
                return self.render(result=dict(
                    success=0,
                    message='Superficie impermeabile deve essere > 15%'))

            dxresult = self.simulazione(schema_id=schema_id,
                                        imp=imp,
                                        regime=regime,
                                        anni=anni,
                                        drwh='DX',
                                        callback=callback)
            #drwh='DX'
            #print 'DRWH SI'
            fileName = "%s/%s.inp" % (inpPath, schema_id)

        elif drwh == 'DX':
            #print 'DRWH DX'
            fileName = "%s/%s_drwh.inp" % (inpPath, schema_id)
            imp = int((int(imp) - 30) / 0.7)
        else:
            #print 'DRWH NO'
            fileName = "%s/%s.inp" % (inpPath, schema_id)

        zona = "Chicago"

        rsRandom = randomString()

        #mi calcolo l'extent
        ret = self.getExtent(schema_id=schema_id)
        xCenter = 0
        yCenter = 0
        if ret:
            xCenter = ret["x"]
            yCenter = ret["y"]

        sxInpFile = "/tmp/%s_%s_sx.inp" % (schema_id, rsRandom)
        dxInpFile = "/tmp/%s_%s_dx.inp" % (schema_id, rsRandom)

        llsx = []
        lldx = []
        leadUsage = []  #array co i leadusage calcolati

        html = ''

        fileInp = open(fileName, 'r')
        lines = fileInp.readlines()
        index = 0
        for line in lines:
            if line.strip() == '[RAINGAGES]':
                idxRainGages = index
            if line.strip() == '[SUBCATCHMENTS]':
                idxSubCatchments = index
            if line.strip() == '[LID_CONTROLS]':
                idxLidControls = index
            if line.strip() == '[LID_USAGE]':
                idxLidUsage = index
            if line.strip() == '[ADJUSTMENTS]':
                idxAdjustments = index

            llsx.append(line)
            index = index + 1

        #cambio le righe a sx
        v = self.parseRow(lines[idxRainGages + 3], 'RG')
        s = '"%s/raingage/%s-%s%sY.txt"' % (inpPath, regime, zona, anni)
        s = s.ljust(255, ' ')
        v[5] = str(s)
        s = "RG_%s" % regime
        s = s.ljust(13, ' ')
        v[6] = str(s)
        llsx[idxRainGages + 3] = "".join(v)

        index = idxSubCatchments + 3
        v = self.parseRow(lines[index], 'SC')
        summAreaLid = dict()
        areaPP = areaTV = 0
        while v != []:
            if v[0][:1] == "S":
                #cambio la riga su file sx
                s = "%s.0000" % imp
                s = s.ljust(13, ' ')
                v[4] = str(s)

                #genero i dati per LID_USAGE
                if convpp:
                    areaPP = self.getArea(imp, "pp", v[3], convpp)
                    areaLid = '{:.4f}'.format(areaPP)
                    lid = [
                        v[0], "PP".ljust(17, ' '), "1".ljust(13, ' '),
                        areaLid.ljust(19, ' '), "5.0000".ljust(13, ' '),
                        "5.0000".ljust(13, ' '), "0.0000".ljust(13, ' '),
                        "0".ljust(13, ' '), " ".ljust(13, ' ')
                    ]
                    leadUsage.append(lid)

                if convtv:
                    areaTV = self.getArea(imp, "tv", v[3], convtv)
                    areaLid = '{:.4f}'.format(areaTV)
                    lid = [
                        v[0], "TV".ljust(17, ' '), "1".ljust(13, ' '),
                        areaLid.ljust(19, ' '), "11.0000".ljust(13, ' '),
                        "30.0000".ljust(13, ' '), "0.0000".ljust(13, ' '),
                        "0".ljust(13, ' '), " ".ljust(13, ' ')
                    ]
                    leadUsage.append(lid)

                summAreaLid[v[0]] = areaPP + areaTV

            llsx[index] = "".join(v) + "\n"
            index = index + 1
            v = self.parseRow(lines[index], 'SC')

        try:
            fsx = open(sxInpFile, 'w')
            fsx.writelines(llsx)
            fsx.close()
        except IOError as err:
            return self.render(result=dict(success=0,
                                           message='IOError:%s %s' %
                                           (err.args[-1], sxInpFile)))

        #SIMULAZIONE FILE DI SX
        try:
            st = SWMM5Simulation(str(sxInpFile))
            files = st.getFiles()
            if isfile(files[1]):
                print(files[1])
                sxdx = 'sx'
                if drwh == 'DX':
                    sxdx = 'dx'
                sxresult = self.parseReport(schema_id, sxdx, files[1],
                                            sxInpFile)
        except Exception as err:
            return self.render(result=dict(
                success=0, message='SWMM5Error:%s %s' % (err, sxInpFile)))

        #SE DRWH ESCO
        if drwh == 'DX':
            print 'RITORNO SXRESULT'
            return sxresult
        elif drwh == 'SI':
            return self.render(result=dict(success=1,
                                           schema=schema_id,
                                           x=xCenter,
                                           y=yCenter,
                                           resultid=self.result_id,
                                           sxresult=sxresult,
                                           dxresult=dxresult))

        #ALTRIMENTI SE NON PASSO NE PP NE TV ESCO
        elif not convpp + convtv:
            return self.render(result=dict(success=0, message='MANCA PP O TV'))

        print 'FILE DI DX'
        #genero le righe di dx partendo dalle modifiche a sx
        #copio il file di sx fino a LID_CONTROLS
        for i in range(0, idxLidControls + 3):
            lldx.append(llsx[i])

        #cambio le righe subcatchment
        index = idxSubCatchments + 3
        v = self.parseRow(lines[index], 'SC')
        while v != []:
            if v[0][:1] == "S":
                #cambio la riga su file dx
                area = float(v[3]) * pow(10, 4)
                areaimp = (area * float(imp)) / 100
                impdx = int(((areaimp - summAreaLid[v[0]]) /
                             (area - summAreaLid[v[0]])) * 100)
                s = "%s.0000" % impdx
                s = s.ljust(13, ' ')
                v[4] = str(s)

            lldx[index] = "".join(v) + "\n"
            index = index + 1
            v = self.parseRow(lines[index], 'SC')

        #aggiungo la sezione costante dei lid_controls
        #import pdb;pdb.set_trace()
        flead = open(inpPath + '/lead_controls.inp', 'r')
        lldx = lldx + flead.readlines()
        flead.close()

        #aggiungo LID_USAGE nuovo calcolato
        for row in leadUsage:
            lldx.append("".join(row) + "\n")

        #copio le ultime righe da 2 righe prima di adjusteents alla fine
        for i in range(idxAdjustments - 2, len(lines) - 1):
            lldx.append(lines[i])

        try:
            fdx = open(dxInpFile, 'w')
            fdx.writelines(lldx)
            fdx.close()
        except IOError as err:
            return self.render(result=dict(success=0,
                                           message='IOError:%s %s' %
                                           (err.args[-1], dxInpFile)))

        try:
            st = SWMM5Simulation(str(dxInpFile))
            files = st.getFiles()
            if isfile(files[1]):
                print(files[1])
                dxresult = self.parseReport(schema_id, 'dx', files[1],
                                            dxInpFile)
        except Exception as err:
            return self.render(result=dict(
                success=0, message='SWMM5Error:%s %s' % (err, dxInpFile)))

        return self.render(result=dict(success=1,
                                       schema=schema_id,
                                       x=xCenter,
                                       y=yCenter,
                                       resultid=self.result_id,
                                       sxresult=sxresult,
                                       dxresult=dxresult))
Exemplo n.º 10
0
def runSimulation(structure, index, resultType, inp_file_path, out_file_path):
    '''
  description: run a swmm5 simulation
  :param structure: <[string] | string> type of structure,such as 'SUBCATCH', 'NODE', 'LINK', 'SYS'
  :param index: <[string] | string> index of specified structure of which the result will be written into result.csv
  :param resultType <[int] | int> type of the  result data
    NOTE: the following document from https://pypi.org/project/SWMM5/
    for 'SUBCATCH':
      0 Rainfall (in/hr or mm/hr)
      1 Snow depth (in or mm)
      2 Evaporation loss (in/hr or mm/hr)
      3 Infiltration loss (in/hr or mm/hr)
      4 Runoff rate (flow units)
      5 Groundwater outflow rate (flow units)
      6 Groundwater water table elevation (ft or m)
      7 Soil Moisture (volumetric fraction, less or equal tosoil porosity)
      8 Runoff concentration of TSS (mg/l)
    for 'NODE':
      0 Depth of water above invert (ft or m)
      1 Hydraulic head (ft or m)
      2 Volume of stored + ponded water (ft3 or m3)
      3 Lateral inflow (flow units)
      4 Total inflow (lateral + upstream) (flow units)
      5 Flow lost to flooding (flow units)
      6 Concentration of TSS (mg/l)
    for 'LINK':
      0 Flow rate (flow units)
      1 Flow depth (ft or m)
      2 Flow velocity (ft/s or m/s)
      3 Froude number
      4 Capacity (fraction of conduit filled)
      5 Concentration of TSS (mg/l)
    for 'SYS':
      0 Air temperature (deg. F or deg. C)
      1 Rainfall (in/hr or mm/hr)
      2 Snow depth (in or mm)
      3 Evaporation + infiltration loss rate (in/hr or mm/hr)
      4 Runoff flow (flow units)
      5 Dry weather inflow (flow units)
      6 Groundwater inflow (flow units)
      7 RDII inflow (flow units)
      8 User supplied direct inflow (flow units)
      9 Total lateral inflow (sum of variables 4 to 8) (flow units)
      10 Flow lost to flooding (flow units)
      11 Flow leaving through outfalls (flow units)
      12 Volume of stored water (ft3 or m3)
      13 Evaporation rate (in/day or mm/day)
  :param inp_file_path: <string> absolute path of inp file
  :param out_file_path: <string> absolute path of output file
    the  output file will be like:
    INDEX   VALUE   TIME   DATE         TYPE
    1       1.324   00:30  01/01/2020   LEVEL(m)
    2       1.484   01:00  02/01/2020   LEVEL(m)
    ...
    i       0.482   00:30  01/01/2020   FLOW(LPS)
    ...
  
  :return: <generator object SWMM5Simulation.Results at 0x00000207600ED660>
  :output: generate the result.csv to save the result if the output path specified
  '''
    # preprocess the params
    structure, index, resultType
    if not isinstance(structure, list):
        structure = [structure]
    if not isinstance(index, list):
        index = [index]
    if not isinstance(resultType, list):
        resultType = [resultType]
    # run the simulation
    st = SWMM5Simulation(inp_file_path)
    # validate the params
    if len(structure) != len(index) or len(structure) != len(resultType):
        raise Exception('length of structure and index don\'t match')
        return st
    # if need to generate result.csv
    if out_file_path:
        if not os.path.exists(os.path.split(out_file_path)[0]):
            os.makedirs(os.path.split(out_file_path)[0])
        # some setting infos
        infoDict = configInp(inp_file_path,
                             '',
                             options=[
                                 'REPORT_START_DATE', 'REPORT_START_TIME',
                                 'END_DATE', 'END_TIME'
                             ],
                             values=[])
        step = st.SWMM_ReportStep  # the report time step of the unit:min
        reportStartDate = infoDict['REPORT_START_DATE']
        reportStartTime = infoDict['REPORT_START_TIME']
        endDate = infoDict['END_DATE']
        endTime = infoDict['END_TIME']
        reportStartTimeStamp = time.mktime(
            time.strptime(reportStartDate + ' ' + reportStartTime,
                          '%m/%d/%Y %H:%M:%S'))
        endTimeStamp = time.mktime(
            time.strptime(endDate + ' ' + endTime, '%m/%d/%Y %H:%M:%S'))
        # dict that save the result
        result = {'INDEX': [], 'VALUE': [], 'TIME': [], 'DATE': [], 'TYPE': []}
        # for every structure
        for i in range(len(structure)):
            if structure[i] == 'NODE':
                vals = list(st.Results('NODE', str(index[i]), resultType[i]))
                result['VALUE'] += vals
                curTimeStamp = 0
                for j in range(len(vals)):
                    curTimeStamp = reportStartTimeStamp + 30 * 60 * 1000 * i
                    result['INDEX'].append(index[i])
                    result['TIME'].append(
                        time.strftime('%H:%M:%S',
                                      time.localtime(curTimeStamp)))
                    result['DATE'].append(
                        time.strftime('%m/%d/%Y',
                                      time.localtime(curTimeStamp)))
                    result['TYPE'].append(NODE_RESULT_TYPE[resultType[i]])
            elif structure[i] == 'LINK':
                vals = list(st.Results('LINK', str(index[i]), resultType[i]))
                result['VALUE'] += vals
                curTimeStamp = 0
                for j in range(len(vals)):
                    curTimeStamp = reportStartTimeStamp + 30 * 60 * 1000 * i
                    result['INDEX'].append(index[i])
                    result['TIME'].append(
                        time.strftime('%H:%M:%S',
                                      time.localtime(curTimeStamp)))
                    result['DATE'].append(
                        time.strftime('%m/%d/%Y',
                                      time.localtime(curTimeStamp)))
                    result['TYPE'].append(LINK_RESULT_TYPE[resultType[i]])
            elif structure[i] == 'SUBCATCH':
                # TODOS
                pass
            elif structure[i] == 'SYS':
                # TODOS
                pass
            else:
                # REMAIN
                pass
        df = pd.DataFrame(result)
        # index = 0 means no index column
        df.to_csv(out_file_path, index=0)
    # finally, return the st object
    return st
Exemplo n.º 11
0
 def test_GetSwmmResult_for_runoff_should_return_correct_runoff(self):
     SWMM5Simulation("swmm5/examples/simple/swmm5Example.inp")
Exemplo n.º 12
0
 def test_SWMM5Simulation_should_have_attributes(self):
     st=SWMM5Simulation("swmm5/examples/simple/swmm5Example.inp")
     st.SWMM_Nperiods
Exemplo n.º 13
0
def swmm_plot():
    output_file("layout.html")
    spreadsheet_name = 'data/dados-calib.xlsx'
    swmm_filename = 'results/partial.inp'

    st = SWMM5Simulation(swmm_filename)  # run a simulation

    wb = openpyxl.load_workbook(spreadsheet_name)
    abas = wb.sheetnames

    observado_todos = np.array([], dtype=np.float)
    simulado_todos = np.array([], dtype=np.float)

    for aba in abas:
        sheet = wb[aba]
        sheet.cell(row=1, column=4).value = 'Nivel_simulado'

        # lendo o nivel medido
        nivel_medido = np.array([], dtype=np.float)
        for i in range(2, sheet.max_row + 1):
            nivel_medido = np.append(nivel_medido,
                                     sheet.cell(row=i, column=3).value)

        # pegando o simulado do swmm
        nivel_simulado = np.array(list(st.Results('NODE', aba, 0)))

        # escrevendo o simulado no excel
        ndados = st.SWMM_Nperiods
        for i in range(2, np.size(nivel_simulado) + 2):
            sheet.cell(row=i, column=4).value = nivel_simulado[i - 2]

        observado_todos = np.concatenate((observado_todos, nivel_medido))
        simulado_todos = np.concatenate((simulado_todos, nivel_simulado))

    data = np.array([], dtype=np.float)
    hora = np.array([], dtype=np.float)
    datahora = np.array([], dtype=np.datetime64)
    for i in range(2, sheet.max_row + 1):
        data = np.append(data, sheet.cell(row=i, column=1).value)
        hora = np.append(hora, sheet.cell(row=i, column=2).value)
        #print(sheet.cell(row=i,column=2).value)
        diazin = sheet.cell(row=i, column=1).value
        horinha = sheet.cell(row=i, column=2).value
        datahora = np.append(
            datahora, diazin + timedelta(seconds=60 * 60 * horinha.hour +
                                         60 * horinha.minute + horinha.second))

    observado_todos = np.array(observado_todos, dtype=np.float)
    simulado_todos = simulado_todos * 100

    wb.save(spreadsheet_name)

    num = np.nansum((observado_todos - simulado_todos)**2)
    den = np.nansum((observado_todos - np.nanmean(observado_todos))**2)

    numlog = np.nansum((np.log(observado_todos) - np.log(simulado_todos))**2)
    denlog = np.nansum(
        (np.log(observado_todos) - np.log(np.nanmean(observado_todos)))**2)

    if den == 0:
        den = 0.0000001
    if denlog == 0:
        denlog = 0.0000001

    print('Nash: %.4f' % (1 - num / den))
    print('Log-Nash: %4f' % (1 - numlog / denlog))

    observado_todos = observado_todos.reshape(
        int(len(observado_todos) / ndados), ndados)
    simulado_todos = simulado_todos.reshape(int(len(simulado_todos) / ndados),
                                            ndados)
    simulado_todos = simulado_todos / 100
    x = datahora
    yobs = observado_todos
    ysim = simulado_todos

    nash = {}
    nashlog = {}
    for i, aba in enumerate(abas):
        num = np.nansum((yobs[i] - ysim[i])**2)
        den = np.nansum((yobs[i] - np.nanmean(yobs[i]))**2)
        numlog = np.nansum((np.log(yobs[i]) - np.log(ysim[i]))**2)
        denlog = np.nansum((np.log(yobs[i]) - np.log(np.nanmean(yobs[i])))**2)
        if den == 0:
            den = 0.0000001
        if denlog == 0:
            denlog = 0.0000001
        nash[aba] = 1 - num / den
        nashlog[aba] = 1 - numlog / denlog

    figuras = {}
    headers = {}
    for i, aba in enumerate(abas):
        headers[aba] = 'Nash: %.4f' % nash[
            aba] + ' | ' + 'Log-Nash: %.4f' % nashlog[aba]
        figuras[aba] = figure(width=2100,
                              plot_height=500,
                              title=aba + ' | ' + headers[aba],
                              x_axis_type="datetime")
        figuras[aba].title.text_font_size = '16pt'
        figuras[aba].xaxis.axis_label_text_font_size = '14pt'
        figuras[aba].yaxis.axis_label_text_font_size = '14pt'
        figuras[aba].circle(x, yobs[i], fill_color=None, line_color="navy")
        figuras[aba].line(x, yobs[i], color='navy')
        figuras[aba].line(x, ysim[i], color='firebrick')

    figs = [[figuras[figura]] for figura in abas]
    grid = gridplot(figs)
    show(grid)
Exemplo n.º 14
0
 def test_running_with_good_input_file(self):
     """should not raise exceptoins"""
     SWMM5Simulation("swmm5/examples/simple/swmm5Example.inp")
Exemplo n.º 15
0
 def run_swmm(self):
     self.st = SWMM5Simulation(self.swmm_filename) # run a simulation
Exemplo n.º 16
0
import numpy as np
import matplotlib # we need matplotlib for plotting later
matplotlib.use('Qt5Agg') # Not esential. But QtAgg backend seems to work better for plotting
import matplotlib.pyplot as plt # for plotting later

from swmm5.swmm5tools import SWMM5Simulation
from string import Template


area2=75
area3=90
maxfs=[]

for area1 in range(0,100,5):
    with open("small_case.template", 'r') as inf:
        with open("trial.inp", 'w') as outf:
            ins=inf.read()
            ins=Template(ins)
            outs=ins.substitute(a1=area1, a2=area2, a3=area3)
            outf.write(outs)
    #now run
    st=SWMM5Simulation("trial.inp")
    maxf=max(st.Results('NODE','N1', 4))
    print (maxf)
    maxfs.append(maxf)
    ggplot( aesthetics= aes(x = 'weight', y = 'hindfoot_length'), data = surveys_complete)

plt.plot()

Exemplo n.º 17
0
import matplotlib  # we need matplotlib for plotting later
matplotlib.use(
    'Qt5Agg'
)  # Not esential. But QtAgg backend seems to work better for plotting
import matplotlib.pyplot as plt  # for plotting later

from swmm5.swmm5tools import SWMM5Simulation

st = SWMM5Simulation("small_case.inp")
print("Version = ", st.SWMM5_Version())
print("Number of nodes = ", st.SWMM_Nnodes)
# get the flow in conduit LO3
flow = st.Results(
    "LINK", "LO3", 0
)  # 0 is the code for flow in a link (see docs: https://pypi.org/project/SWMM5/
flow = list(flow)  # convert the results to a list.
# calculate time list
time = [st.SWMM_ReportStep * x / 3600. for x in range(st.SWMM_Nperiods)]
ax = plt.plot(time, flow, 'r', marker="^")  # plot press against daias
plt.xlabel("Time (h)")  # set axes labels
plt.ylabel("Flow in LO3 (m$^3$/s)")

plt.show()  # show the plot.
Exemplo n.º 18
0
    def simulazione(self,rete='CS',schema='H',imp='15',regime='CAM',anni='2',convpp='',convtv='',callback='',_=''):

        #apro il file di base e sostituisco i valori
        filePath = "/apps/trigeau/data"
        fileName = "%s/%s_%s.inp" %(filePath,rete,schema)
        fileName = "%s/%s_%s.inp" %(filePath,rete,schema)

        zona="Chicago"

        rsRandom = randomString()

        sxInpFile = "/tmp/%s_%s_%s_sx.inp" %(rete,schema,rsRandom)
        dxInpFile = "/tmp/%s_%s_%s_dx.inp" %(rete,schema,rsRandom)

        sxInpFile = "/tmp/%s_%s_sx.inp" %(rete,schema)
        dxInpFile = "/tmp/%s_%s_dx.inp" %(rete,schema)

        llsx=[]
        lldx=[]
        leadUsage=[]#array co i leadusage calcolati

        html=''

        fileInp = open(fileName, 'r') 
        lines = fileInp.readlines()
        index=0
        for line in lines:
            if line.strip()=='[RAINGAGES]':
                idxRainGages = index
            if line.strip()=='[SUBCATCHMENTS]':
                idxSubCatchments = index
            if line.strip()=='[LID_USAGE]':
                idxLidUsage = index
            if line.strip()=='[ADJUSTMENTS]':
                idxAdjustments = index


            llsx.append(line)
            index=index+1


        #cambio le righe a sx
        v=self.parseRow(lines[idxRainGages+3],'RG')
        s='"%s/%s-%s%sY.txt"'%(filePath,regime,zona,anni)
        s=s.ljust(255,' ')
        v[5]=str(s)
        s="%s-RG"%regime
        s=s.ljust(13,' ')
        v[6]=str(s)
        llsx[idxRainGages+3]="".join(v)

        index = idxSubCatchments+3
        v=self.parseRow(lines[index],'SC')
        summArea=0
        while v!=[]:
            if v[0][:1] == "S":
                #cambio la riga su file sx                        
                s="%s.0000"%imp
                s=s.ljust(13,' ')
                v[4]=str(s)

                #genero i dati per LID_USAGE
                if convpp:
                    area=self.calcoloArea(imp,"pp",v[3])*float(convpp)
                    summArea=summArea+area
                    area='{:.4f}'.format(area)
                    lid=[
                        v[0],
                        "PP".ljust(17,' '),
                        "2".ljust(13,' '),
                        area.ljust(19,' '),
                        "5.0000".ljust(13,' '),
                        "10.0000".ljust(13,' '),                                
                        "0.0000".ljust(13,' '),
                        "0".ljust(13,' '),
                        " ".ljust(13,' ')
                    ]
                    leadUsage.append(lid)

                if convtv:
                    area=self.calcoloArea(imp,"tv",v[3])*float(convtv)
                    summArea=summArea+area
                    area='{:.4f}'.format(area)
                    lid=[
                        v[0],
                        "TV".ljust(17,' '),
                        "1".ljust(13,' '),
                        area.ljust(19,' '),
                        "11.0000".ljust(13,' '),
                        "30.0000".ljust(13,' '),
                        "0.0000".ljust(13,' '),
                        "0".ljust(13,' '),
                        " ".ljust(13,' ')
                    ]
                    leadUsage.append(lid)

            llsx[index]="".join(v)+"\n"
            index=index+1
            v=self.parseRow(lines[index],'SC')

        fsx = open(sxInpFile, 'w')
        fsx.writelines(llsx)
        fsx.close() 

        #FILE DI DX
        #genero le righe di dx partendo dalle modifiche a sx
        #copio iol file di sx fino a LID_USAGE
        for i in range(0,idxLidUsage+3):
            lldx.append(llsx[i])

        #cambio le righe subcatchment
        index = idxSubCatchments+3
        v=self.parseRow(lines[index],'SC')
        while v!=[]:
            if v[0][:1] == "S":
                #cambio la riga su file dx       
                area=float(v[3])*pow(10,4)
                impdx=66#(area*imp-summArea)/(area-summArea)                
                s="%s.0000"%impdx
                s=s.ljust(13,' ')
                v[4]=str(s)

            lldx[index]="".join(v)+"\n"
            index=index+1
            v=self.parseRow(lines[index],'SC')
 
        
        #aggiungo LID_USAGE nuovo calcolato
        for row in leadUsage:
            lldx.append("".join(row)+"\n")

        #copio le ultime righe da 2 righe prima di adjusteents alla fine
        for i in range(idxAdjustments-2,len(lines)-1):
            lldx.append(lines[i])

        fdx = open(dxInpFile, 'w')
        fdx.writelines(lldx)
        fdx.close() 


        result=dict(success=0)

        st=SWMM5Simulation(str(sxInpFile))
        files=st.getFiles()
        if isfile(files[1]):
            print files[1]
            result["sx"]=self.parseReport(files[1])

        st=SWMM5Simulation(str(dxInpFile))
        files=st.getFiles()
        if isfile(files[1]):
            print files[1]
            result["dx"]=self.parseReport(files[1])
Exemplo n.º 19
0
RDII = 84  # LPS
if __name__ == "__main__":
    # 0. set a mock example-case.inp (DONE)
    # setFlowOnAverage([['37', 48, '03:00','10:30'],['53', 36, '03:00','10:30']],
    #                 out_file_path = os.path.join(config['publicPath'], 'mock', 'observed', 'example-case.inp'))
    # 1. get the try-case result (DONE)
    # exampleCaseInpPath = os.path.join(config['publicPath'], 'mock', 'observed', 'example-case.inp')
    # exampleCaseOutPath = os.path.join(config['publicPath'], 'mock', 'observed', 'result.csv')
    # runSimulation(['NODE'] * 4, ['13', '36', '57', '64'], [0, 0, 0, 4], exampleCaseInpPath, exampleCaseOutPath)

    # 2. start GLUE
    inpFilePath = os.path.join(config['publicPath'], 'mock', 'random',
                               'try-case.inp')
    outFilePath = os.path.join(config['publicPath'], 'mock', 'random',
                               'result.csv')
    st = SWMM5Simulation(
        os.path.join(config['publicPath'], 'static', 'baseline.inp'))
    links = st.Link()

    cnt = 0
    startTime = ['03:00'] * len(links)
    endTime = ['10:30'] * len(links)

    # log Nash-Sutcliffe efficiency coefficient of every iteration
    NS_log = []
    # log scenario coefficient of every iteration
    scenario_log = []
    while cnt < ITERATION_TIMES:
        # 2.1 parameter sampling (prior distribution: uniform distribution)
        scenario = splitRDIIRandomlyIntoPipes(RDII=RDII,
                                              pipes=links,
                                              startTime=startTime,
Exemplo n.º 20
0
from swmm5.swmm5tools import SWMM5Simulation

st = SWMM5Simulation("small_case.INP")
print("")
print(st.SWMM5_Version())
print(st.Subcatch())
Exemplo n.º 21
0
from swmm5.swmm5tools import SWMM5Simulation
st = SWMM5Simulation("swmm5/examples/simple/swmm5Example.inp")
Exemplo n.º 22
0
import xlrd

from bokeh.io import output_file, show
from bokeh.layouts import gridplot
from bokeh.palettes import Viridis3
from bokeh.plotting import figure, ColumnDataSource
from bokeh.models import HoverTool
from datetime import datetime, timedelta
from collections import OrderedDict
import time
output_file("layout.html")

spreadsheet_name = 'output.xlsx'
swmm_filename = 'sao_carlos.inp'

st = SWMM5Simulation(swmm_filename)  # run a simulation

wb = openpyxl.load_workbook(spreadsheet_name)
abas = wb.get_sheet_names()

observado_todos = np.array([], dtype=np.float)
simulado_todos = np.array([], dtype=np.float)

for aba in abas:
    sheet = wb.get_sheet_by_name(aba)
    sheet.cell(row=1, column=4).value = 'simulated_depth'

    # lendo o nivel medido
    nivel_medido = np.array([], dtype=np.float)
    for i in range(2, sheet.max_row + 1):
        nivel_medido = np.append(nivel_medido,
Exemplo n.º 23
0
def swmmRun(swmminputfile, parameters):
    st = SWMM5Simulation(swmminputfile, clean=True)
    results = np.array(list(st.Results(*parameters.swmmResultCodes)))
    return results