Skip to content

Instantly share code, notes, and snippets.

@ewsterrenburg
Created May 27, 2015 18:34
Show Gist options
  • Save ewsterrenburg/70a1609c289d031b1bbb to your computer and use it in GitHub Desktop.
Save ewsterrenburg/70a1609c289d031b1bbb to your computer and use it in GitHub Desktop.
import re
import ppygis
import psycopg2
SRID = 3003
schema = 'pytest'
# TODO SECTOR_ID
# TODO STORAGE CURVE PARAMS TESTEN!, INFILTRATION PARAMS?!
# TODO "HAAKJES in subcatchments)
# TODO ARCCAT, ARCMAT, Z1, Z2!!!
# TODO RAINGAGE datasource (timeseries_id vs file + eigenschappen)
# TODO X-SECT : curve_id, transect, barrels, id obv shape (gebeurt al, maar gaat fundamenteel vaudt :(
# TODO OPTIONS: datum mm/dd/yyyy --> dd/mm/yyyyH
# TODO INVERT MAX DEPTH vs invert elevation
class Vertex(object):
"""
This is a Vertex
"""
def __init__(self, ident, x, y):
"""
Constructor
"""
self.ID = ident
self.X = float(x)
self.Y = float(y)
self.Geometry = ppygis.Point(self.X, self.Y, srid=SRID)
class Node(Vertex):
"""
This is a node
"""
def __init__(self, node_ident, x, y):
"""
Constructor
"""
Vertex.__init__(self, node_ident, x, y)
self.SectorID = None # ignore for now, to be examined later
def insert_values(self):
return self.ID, self.SectorID, self.Geometry.write_ewkb()
class Link(object):
"""
This is a Link
"""
def __init__(self, link_ident, inlet_node, outlet_node, vertices):
"""
Constructor
"""
self.LinkID = link_ident
self.SectorID = None # ignore for now, to be examined later
vertex_geometries = [inlet_node.Geometry]
vertex_geometries.extend([ppygis.Point(v.X, v.Y, srid=SRID) for v in vertices])
vertex_geometries.append(outlet_node.Geometry)
self.Geometry = ppygis.LineString(vertex_geometries, srid=SRID)
def insert_values(self):
return self.LinkID, self.SectorID, self.Geometry.write_ewkb()
class Polygon(object):
"""
This is a Link
"""
def __init__(self, poly_ident, vertex):
"""
Constructor
"""
self.PolyID = poly_ident
self.SectorID = None # ignore for now, to be examined later
self.Vertices = [vertex]
def geometry(self):
vertex_geometries = [ppygis.Point(v.X, v.Y, srid=SRID) for v in self.Vertices]
return (ppygis.MultiPolygon([ppygis.Polygon([ppygis.LineString(vertex_geometries, srid=SRID)], srid=SRID)],
srid=SRID))
def insert_values(self):
return self.PolyID, self.SectorID, self.geometry().write_ewkb()
class Raingage(Node):
"""
This is a Raingage
"""
insert_table = 'raingage'
insert_fields = '(rg_id, the_geom, form_type, intvl, scf, rgage_type, timser_id, fname, sta, units)'
insert_query = r'INSERT INTO "{0}"."{1}" {2} VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s);'.format(schema,
insert_table,
insert_fields)
def __init__(self, node, rain_type, time_intrvl, snow_catch, data_src):
"""
Constructor
"""
# Node.__init__(self, GageID, X, Y)
self.SectorID = None # ignore for now, to be examined later
self.RainType = rain_type
self.TimeIntrvl = time_intrvl
self.SnowCatch = snow_catch
self.DataSource = data_src
def insert_values(self):
return (self.ID, self.SectorID, self.Geometry.write_ewkb(),
self.RainType, self.TimeIntrvl, self.SnowCatch, self.DataSource)
class Subcatchment(Polygon):
"""
This is a Subcatchment
"""
insert_table = 'subcatchment'
insert_fields = '''(subc_id, sector_id, the_geom, node_id, rg_id, area, imperv, width, slope, clength, snow_id,
nimp, nperv, simp, sperv, zero, routeto, rted, maxrate, minrate, decay, drytime, maxinfil, suction,
conduct, initdef, curveno, conduct_2, drytime_2)
'''
insert_query = '''INSERT INTO "{0}"."{1}" {2} VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s,
%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);
'''.format(schema, insert_table, insert_fields)
def __init__(self, poly_ident, vertex):
"""
Constructor
"""
Polygon.__init__(self, poly_ident, vertex)
self.Raingage = None
self.Outlet = None
self.TotalArea = None
self.PcntImperv = None
self.Width = None
self.PcntSlope = None
self.CurbLength = None
self.SnowPack = None
self.NImperv = None
self.NPerv = None
self.SImperv = None
self.SPerv = None
self.PctZero = None
self.RouteTo = None
self.PctRouted = None
self.HMaxRate = None
self.HMinRate = None
self.HDecay = None
self.HDryTime = None
self.HMaxInfill = None
self.GASuction = None
self.GAHydCon = None
self.GAIMDmax = None
self.CNCurveNum = None
self.CNHydCon = None
self.CNDryTime = None
def set_attributes_subcatchment(self, raingage, outlet, total_area,
pcnt_imperv, width, pcnt_slope, curb_length, snow_pack):
self.Raingage = raingage
self.Outlet = outlet
self.TotalArea = total_area
self.PcntImperv = pcnt_imperv
self.Width = width
self.PcntSlope = pcnt_slope
self.CurbLength = curb_length
self.SnowPack = snow_pack
def set_attributes_subarea(self, n_imperv, n_perv, s_imperv, s_perv, pct_zero,
route_to, pct_routed):
self.NImperv = n_imperv
self.NPerv = n_perv
self.SImperv = s_imperv
self.SPerv = s_perv
self.PctZero = pct_zero
self.RouteTo = route_to
self.PctRouted = pct_routed
def set_attributes_infiltration_horton(self, h_max_rate, h_min_rate,
h_decay, h_dry_time, h_max_infill):
self.HMaxRate = h_max_rate
self.HMinRate = h_min_rate
self.HDecay = h_decay
self.HDryTime = h_dry_time
self.HMaxInfill = h_max_infill
def set_attributes_infiltration_greenampt(self, ga_suction, ga_hyd_con, ga_imd_max):
self.GASuction = ga_suction
self.GAHydCon = ga_hyd_con
self.GAIMDmax = ga_imd_max
def set_attributes_infiltration_cn(self, cn_curve_num, cn_hyd_con, cn_dry_time):
self.CNCurveNum = cn_curve_num
self.CNHydCon = cn_hyd_con
self.CNDryTime = cn_dry_time
@property
def insert_values(self):
return Polygon.insert_values(self) + (self.Outlet, self.Raingage,
self.TotalArea, self.PcntImperv, self.Width, self.PcntSlope,
self.CurbLength, self.SnowPack, self.NImperv, self.NPerv,
self.SImperv, self.SPerv, self.PctZero, self.RouteTo,
self.PctRouted, self.HMaxRate, self.HMinRate, self.HDecay,
self.HDryTime, self.HMaxInfill, self.GASuction, self.GAHydCon,
self.GAIMDmax, self.CNCurveNum, self.CNHydCon, self.CNDryTime)
class CrossSection(Link):
"""
This is a CrossSection
"""
insert_table = 'cat_arc'
insert_fields = '(id, shape, geom1, geom2, geom3, geom4)'
insert_query = r'INSERT INTO "{0}"."{1}" {2} VALUES (%s, %s, %s, %s, %s, %s);'.format(schema, insert_table,
insert_fields)
def __init__(self, ident, shape, geom1, geom2, geom3, geom4, barrels):
"""
Constructor
"""
self.ID = ident
self.Shape = shape
self.Geom1 = geom1
self.Geom2 = geom2
self.Geom3 = geom3
self.Geom4 = geom4
self.Barrels = barrels
@property
def insert_values(self):
return self.ID, self.Shape, self.Geom1, self.Geom2, self.Geom3, self.Geom4
class Conduit(Link):
"""
This is a Link
"""
link_type_name = "conduits"
link_nr_attrs = 9
insert_table = 'v_inp_edit_conduit'
insert_fields = '(arc_id, sector_id, the_geom, z1, z2, q0, qmax, arccat_id, matcat_id)'
insert_query = r'INSERT INTO "{0}"."{1}" {2} VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s);'.format(schema,
insert_table,
insert_fields)
def __init__(self, link_ident, inlet_node, outlet_node, vertices, lenght, manning_n,
inlet_offset, outlet_offset, init_flow, max_flow):
"""
Constructor
"""
Link.__init__(self, link_ident, inlet_node, outlet_node, vertices)
self.ManningN = manning_n
self.InletOffset = inlet_offset
self.OutletOffset = outlet_offset
self.InitFlow = init_flow
self.MaxFlow = max_flow
self.ArcCatID = "ROUND500"
self.MatCatID = "CONCRETE"
@property
def insert_values(self):
# ArcCatID, ArcMatID
return Link.insert_values(self) + (self.InletOffset,
self.OutletOffset, self.InitFlow, self.MaxFlow,
self.ArcCatID, self.MatCatID)
class Pump(Link):
link_type_name = "pumps"
link_nr_attrs = 7
"""
This is a Link
"""
def __init__(self, link_ident, inlet_node, outlet_node, vertices, pump_curve,
init_status, startup_depth, shutoff_depth):
"""
Constructor
"""
Link.__init__(self, link_ident, inlet_node, outlet_node, vertices)
self.PumpCurve = pump_curve
self.InitStatus = init_status
self.StartupDepth = startup_depth
self.ShutoffDepth = shutoff_depth
@property
def insert_values(self):
# ArcCatID, ArcMatID
return Link.insert_values(self) + (self.PumpCurve,
self.InitStatus, self.StartupDepth, self.ShutoffDepth)
class Orifice(Link):
link_type_name = "orifices"
link_nr_attrs = 8
"""
This is a Link
"""
def __init__(self, link_ident, inlet_node, outlet_node, vertices, orifice_type,
crest_height, disch_coeff, flap_gate, open_close_time):
"""
Constructor
"""
Link.__init__(self, link_ident, inlet_node, outlet_node, vertices)
self.OrificeType = orifice_type
self.CrestHeight = crest_height
self.DischCoeff = disch_coeff
self.FlapGate = flap_gate
self.OpenCloseTime = open_close_time
@property
def insert_values(self):
# ArcCatID, ArcMatID
return Link.insert_values(self) + (self.OrificeType,
self.CrestHeight, self.DischCoeff, self.FlapGate,
self.OpenCloseTime)
class Weir(Link):
link_type_name = "weirs"
link_nr_attrs = 9
"""
This is a Link
"""
def __init__(self, link_ident, inlet_node, outlet_node, vertices, weir_type,
crest_height, disch_coeff, flap_gate, end_con, end_coeff):
"""
Constructor
"""
Link.__init__(self, link_ident, inlet_node, outlet_node, vertices)
self.WeirType = weir_type
self.CrestHeight = crest_height
self.DischCoeff = disch_coeff
self.FlapGate = flap_gate
self.EndCon = end_con
self.EndCoeff = end_coeff
@property
def insert_values(self):
# ArcCatID, ArcMatID
return Link.insert_values(self) + (self.WeirType,
self.CrestHeight, self.DischCoeff, self.FlapGate,
self.EndCon, self.EndCoeff)
class Outlet(Link):
link_type_name = "outlets"
link_nr_attrs = 8
"""
This is a Link
"""
insert_table = 'v_inp_edit_outlet'
insert_fields = '(arc_id, sector_id, the_geom, z1, z2, q0, qmax, arccat_id, matcat_id)'
insert_query = r'INSERT INTO "{0}"."{1}" {2} VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s);'.format(schema,
insert_table,
insert_fields)
def __init__(self, link_ident, inlet_node, outlet_node, vertices, outflow_height,
outlet_type, qcoeff_qtable, qexpon, flap_gate):
"""
Constructor
"""
Link.__init__(self, link_ident, inlet_node, outlet_node, vertices)
self.OutflowHeight = outflow_height
self.OutletType = outlet_type
self.QcoeffQTable = qcoeff_qtable
self.Qexpon = qexpon
self.FlapGate = flap_gate
@property
def insert_values(self):
# ArcCatID, ArcMatID
return Link.insert_values(self) + (self.OutflowHeight,
self.OutletType, self.QcoeffQTable, self.Qexpon,
self.FlapGate)
class Junction(Node):
"""
This is a Junction
"""
node_type_name = "junctions"
node_nr_attrs = 6
insert_table = 'v_inp_edit_junction'
insert_fields = '(node_id, sector_id, the_geom, top_elev, ymax, y0, ysur, apond)'
insert_query = r'INSERT INTO "{0}"."{1}" {2} VALUES (%s, %s, %s, %s, %s, %s, %s, %s);'.format(schema, insert_table,
insert_fields)
def __init__(self, node, invert_elev, max_depth, init_depth, surcharge_depth, ponded_area):
"""
Constructor
"""
Node.__init__(self, node.ID, node.X, node.Y)
self.InvertElev = invert_elev
self.MaxDepth = max_depth
self.InitDepth = init_depth
self.SurchargeDepth = surcharge_depth
self.PondedArea = ponded_area
@property
def insert_values(self):
return Node.insert_values(self) + (self.InvertElev,
self.MaxDepth, self.InitDepth, self.SurchargeDepth,
self.PondedArea)
class Outfall(Node):
"""
This is a Outfall
"""
node_type_name = "outfalls"
node_nr_attrs = 5
insert_table = 'v_inp_edit_outfall'
insert_fields = '(node_id, sector_id, the_geom, top_elev, ymax, outfall_type, stage, curve_id, timser_id, gate)'
insert_query = r'INSERT INTO "{0}"."{1}" {2} VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s);'.format(schema,
insert_table,
insert_fields)
def __init__(self, node, invert_elev, outfall_type, boundary_condition, tide_gate):
"""
Constructor
"""
Node.__init__(self, node.ID, node.X, node.Y)
self.InvertElev = invert_elev
self.OutfallType = outfall_type
self.CurveID = None
self.TimSerID = None
self.Stage = None
self.MaxDepth = 0
if self.OutfallType == "FIXED":
self.Stage = boundary_condition
elif self.OutfallType == "TIDAL":
self.CurveID = boundary_condition
elif self.OutfallType == "TIMESERIES":
self.TimSerID = boundary_condition
self.BoundaryCondition = boundary_condition
self.TideGate = tide_gate
@property
def insert_values(self):
return Node.insert_values(self) + (self.InvertElev, self.MaxDepth,
self.OutfallType, self.Stage, self.CurveID, self.TimSerID,
self.TideGate)
class Storage(Node):
"""
This is a Storage
"""
node_type_name = "storage"
node_nr_attrs = 13
insert_table = 'v_inp_edit_storage'
insert_fields = '''(node_id, sector_id, the_geom, top_elev, ymax, y0, storage_type, a1, a2, a0, apond, fevap,
sh, hc, imd)
'''
insert_query = '''INSERT INTO "{0}"."{1}" {2} VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s,
%s);'''.format(schema, insert_table, insert_fields)
def __init__(self, node, invert_elev, max_depth, init_depth,
storage_curve, curve_param1, curve_param2, curve_param3,
ponded_area, evap_frac, inf_param1, inf_param2, inf_param3):
"""
Constructor
"""
Node.__init__(self, node.ID, node.X, node.Y)
self.InvertElev = invert_elev
self.MaxDepth = max_depth
self.InitDepth = init_depth
self.StorageCurve = storage_curve
self.CurveParam1 = curve_param1
self.CurveParam2 = curve_param2
self.CurveParam3 = curve_param3
self.PondedArea = ponded_area
self.EvapFrac = evap_frac
self.GSuction = inf_param1
self.GHydCon = inf_param2
self.GIMDmax = inf_param3
@property
def insert_values(self):
return Node.insert_values(self) + (self.InvertElev,
self.MaxDepth, self.InitDepth, self.StorageCurve,
self.CurveParam1, self.CurveParam2, self.CurveParam3,
self.PondedArea, self.EvapFrac, self.GSuction,
self.GHydCon, self.GIMDmax)
class Divider(Node):
"""
This is a Divider
"""
node_type_name = "dividers"
node_nr_attrs = 9
def __init__(self, node, invert_elev, diverted_link,
divider_type, param1, param2, param3, param4, param5):
"""
Constructor
"""
Node.__init__(self, node.ID, node.X, node.Y)
self.InvertElev = invert_elev
self.DivertedLink = diverted_link
self.DividerType = divider_type
self.Param1 = param1
self.Param2 = param2
self.Param3 = param3
self.Param4 = param4
self.Param5 = param5
@property
def insert_values(self):
return Node.insert_values(self) + (self.InvertElev,
self.DivertedLink, self.DividerType, self.Param1,
self.Param2, self.Param3, self.Param4, self.Param5)
class InpFile(object):
"""inpFile is a helper class to read the inp-file
and stores the information given in the file in its contents"""
def __init__(self, filepath):
self.filepath = filepath
self.sections = dict()
self.title = ''
self.options = dict()
self.nodes = dict()
self.symbols = dict()
self.vertices = dict()
self.subcatchments = dict()
self.raingages = dict()
self.evaporation = dict()
self.report = dict()
self.timeseries = dict()
self.xsections = dict()
self.links = dict()
def read_sections(self):
"""Reads the inp-file"""
f = open(self.filepath, 'r')
data = f.read()
f.close()
psections = re.compile(r"(\[.*?\])")
msections = re.findall(psections, data)
for i in range(len(msections) - 1):
pstart = re.compile(r"(\[{0}\])".format(msections[i][1:-1]))
pend = re.compile(r"(\[{0}\])".format(msections[i + 1][1:-1]))
mstart = re.search(pstart, data)
mend = re.search(pend, data)
data_section = data[mstart.end():mend.start()]
self.sections[msections[i]] = [line.split('\t') for line
in data_section.splitlines() if line and line[0] != ';']
data_section = data[mend.end()::]
self.sections[msections[-1]] = [line.split('\t') for line
in data_section.splitlines() if line and line[0] != ';']
def read_nodes(self):
self.read_node_coordinates()
for node_type in [Junction, Outfall, Storage, Divider]:
node_type_name = node_type.node_type_name
node_nr_attrs = node_type.node_nr_attrs
node_type_section = "[{0}]".format(node_type_name.upper())
if node_type_section in self.sections:
for c in self.sections[node_type_section]:
node_id = c[0].strip()
node = self.nodes[node_id]
node_attrs = [e.strip() for e in c[1:node_nr_attrs]]
if len(c) == 10 and node_type == Storage:
node_attrs.extend([None, None, None])
self.nodes[node_id] = node_type(node, *node_attrs)
else:
print "unable to read section {0}".format(node_type_section)
def read_links(self):
self.read_vertices()
for link_type in [Conduit, Weir, Outlet, Pump, Orifice]:
link_type_name = link_type.link_type_name
link_nr_attrs = link_type.link_nr_attrs
link_type_section = "[{0}]".format(link_type_name.upper())
if link_type_section in self.sections:
for c in self.sections[link_type_section]:
link_id = c[0].strip()
inlet_node_id = c[1].strip()
inlet_node = self.nodes[inlet_node_id]
outlet_node_id = c[2].strip()
outlet_node = self.nodes[outlet_node_id]
if link_id in self.vertices:
vertices = self.vertices[link_id]
else:
vertices = []
self.links[link_id] = link_type(link_id, inlet_node,
outlet_node, vertices, *[e.strip() for e in c[3:link_nr_attrs]])
else:
print "unable to read section {0}".format(link_type_section)
def read_options(self):
for c in self.sections['[OPTIONS]']:
option, value = [e.strip() for e in c[0:2]]
self.options[option] = value
title_section = self.sections['[TITLE]']
self.title = [s for l in title_section for s in l]
for c in self.sections['[EVAPORATION]']:
print c
option = c[0].strip()
value = [float(e.strip()) for e in c[1::]]
# hackish voor ontbreken tab hier...
if not value:
a = option.split(' ')
option = a[0]
value = a[-1]
self.evaporation[option] = value
for c in self.sections['[REPORT]']:
option, value = [e.strip() for e in c[0:2]]
self.report[option] = value
for c in self.sections['[TIMESERIES]']:
option, value = [e.strip() for e in c[0:2]]
self.timeseries[option] = value
def read_cross_sections(self):
n = 1
next_xsection_id = "Profile_" + str(n)
xsection_attrs_read = []
for c in self.sections['[XSECTIONS]']:
link_id = c[0].strip()
shape = c[1].strip().upper()
geom1, geom2, geom3, geom4 = [float(e.strip()) for e in c[2:6]]
try:
barrels = int(c[6].strip())
except:
barrels = None
xsection_attrs = [shape, geom1, geom2, geom3, geom4, barrels]
if xsection_attrs not in xsection_attrs_read:
xsection = CrossSection(next_xsection_id, *xsection_attrs)
self.xsections[next_xsection_id] = xsection
xsection_attrs_read.append(xsection_attrs)
n += 1
next_xsection_id = "Profile_" + str(n)
# nog beter, self.links aanhouden ipv self.conduits e.d.?
try:
self.links[link_id].CrossSection = xsection
except:
pass
try:
self.links[link_id].CrossSection = xsection
except:
pass
def read_node_coordinates(self):
for c in self.sections['[COORDINATES]']:
node_id, x, y = [e.strip() for e in c[0:3]]
self.nodes[node_id] = Node(node_id, x, y)
for c in self.sections['[SYMBOLS]']:
sym_id, x, y = [e.strip() for e in c[0:3]]
self.symbols[sym_id] = Node(sym_id, x, y)
def read_vertices(self):
for c in self.sections['[VERTICES]']:
link_id, x, y = [e.strip() for e in c[0:3]]
if link_id not in self.vertices:
self.vertices[link_id] = [Vertex(link_id, x, y)]
else:
self.vertices[link_id].append(Vertex(link_id, x, y))
def read_polygons(self):
for c in self.sections['[Polygons]']:
poly_id, x, y = [e.strip() for e in c[0:3]]
if poly_id not in self.subcatchments:
self.subcatchments[poly_id] = Subcatchment(poly_id, Vertex(poly_id, x, y))
else:
self.subcatchments[poly_id].Vertices.append(Vertex(poly_id, x, y))
def read_subcatchments(self):
self.read_polygons()
if "[SUBCATCHMENTS]" in self.sections:
for c in self.sections["[SUBCATCHMENTS]"]:
poly_id = c[0].strip()
rain_gage_id = c[1].strip()
if rain_gage_id == "*":
rain_gage_id = None
outlet_id = c[2].strip()
if outlet_id == "*":
outlet_id = None
self.subcatchments[poly_id].set_attributes_subcatchment(rain_gage_id,
outlet_id, *[e.strip() for e in c[3:9]])
for c in self.sections["[SUBAREAS]"]:
poly_id = c[0].strip()
subarea_attrs = [e.strip() for e in c[1:9]]
if len(c) == 7:
subarea_attrs.extend([None])
self.subcatchments[poly_id].set_attributes_subarea(*subarea_attrs)
for c in self.sections["[INFILTRATION]"]:
poly_id = c[0].strip()
if self.options["INFILTRATION"] == "HORTON":
if len(c) == 3:
c.extend(['', ''])
self.subcatchments[poly_id].set_attributes_infiltration_horton(*[e.strip() for e in c[1:6]])
elif self.options["INFILTRATION"] == "GREEN_AMPT":
self.subcatchments[poly_id].set_attributes_infiltration_greenampt(*[e.strip() for e in c[1:4]])
elif self.options["INFILTRATION"] == "CURVE_NUMBER":
self.subcatchments[poly_id].set_attributes_infiltration_cn(*[e.strip() for e in c[1:4]])
else:
print "unable to read section [SUBCATCHMENTS]"
return False
def read_raingages(self):
for c in self.sections['[RAINGAGES]']:
sym_id = c[0].strip()
node = self.symbols[sym_id]
self.raingages[sym_id] = Raingage(node, *[e.strip() for e in c[1:5]])
def main():
# check the number of given arguments
# if len(sys.argv) != 3:
# print 'USAGE: convertor.py <"characteristic points file"> <"path to calculations">'
# sys.exit(1)
# remember the pathname
# pathname = sys.argv[2]
# assign needed files
# stifilepath = sys.argv[1]
# inpfile_path = "tutorial.inp"
inpfile_path = "sc_07.inp"
# read inp-file
inpfile = InpFile(inpfile_path)
inpfile.read_sections()
inpfile.read_nodes()
inpfile.read_links()
inpfile.read_options()
# inpfile.read_polygons()
inpfile.read_subcatchments()
inpfile.read_raingages()
inpfile.read_cross_sections()
# for k,v in inpfile.subcatchments.iteritems():
# print v.geometry()
# a = v.geometry().write_ewkb()
# print a
sql_report = 'pytest.sql'
outf = open(sql_report, 'w')
conn = psycopg2.connect('dbname=giswater_ddb user=postgres port=5431')
cur = conn.cursor()
# for k,v in inpfile.nodes.iteritems():
# if type(v) == Storage:
# outf.write(cur.mogrify(v.insert_query, v.insert_values))
# outf.write('\n')
for k, v in inpfile.links.iteritems():
if type(v) == Conduit:
outf.write(cur.mogrify(v.insert_query, v.insert_values))
outf.write('\n')
# for k,v in inpfile.xsections.iteritems():
# if type(v) == Conduit:
# outf.write(cur.mogrify(v.insert_query, v.insert_values))
# outf.write('\n')
print [k for k, v in inpfile.options.iteritems()]
insert_fields = ', '.join([k for k, v in inpfile.options.iteritems()])
insert_values = [v for k, v in inpfile.options.iteritems()]
insert_table = 'inp_options'
insert_query = r'INSERT INTO "{0}"."{1}" ( {2} ) VALUES ({3});'.format(schema, insert_table, insert_fields,
','.join(['%s'] * len(insert_values)))
print insert_query
print insert_values
print cur.mogrify(insert_query, insert_values)
outf.write(cur.mogrify(insert_query, insert_values))
outf.write('\n')
outf.close()
del cur
conn.close()
return 0
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment