utils package

Submodules

utils.dataframes module

swmmio.utils.dataframes.create_dataframe_multi_index(inp_path, section='CURVES')[source]
swmmio.utils.dataframes.dataframe_from_bi(bi_path, section='[CONDUITS]')[source]

given a path to a build instructions file, create a dataframe of data in a given section

swmmio.utils.dataframes.dataframe_from_inp(inp_path, section, additional_cols=None, quote_replace=' ', **kwargs)[source]

create a dataframe from a section of an INP file :param inp_path: :param section: :param additional_cols: :param skip_headers: :param quote_replace: :return:

swmmio.utils.dataframes.dataframe_from_rpt(rpt_path, section, element_id=None)[source]

create a dataframe from a section of an RPT file

Parameters:
  • rpt_path – path to rep file

  • section – title of section to extract

  • element_id – type of element when extracting time series data

Returns:

pd.DataFrame

swmmio.utils.dataframes.get_inp_options_df(inp_path)[source]

Parse ONLY the OPTIONS section of the inp file into a dataframe :param inp_path: path to inp file :return: pandas.DataFrame >>> from swmmio.tests.data import MODEL_FULL_FEATURES_XY >>> ops = get_inp_options_df(MODEL_FULL_FEATURES_XY) >>> ops[:3]

Value

Key FLOW_UNITS CFS INFILTRATION HORTON FLOW_ROUTING DYNWAVE

for use in an df.apply, to get coordinates of a conduit/link

swmmio.utils.dataframes.nodexy(row)[source]

utils.functions module

swmmio.utils.functions.find_network_trace(model, start_node, end_node, include_nodes=None, include_links=None)[source]

This function searches for a path between two nodes. In addition, since SWMM allows multiple links (edges) between nodes, the user can specify a list of both nodes, and links to include in the path. It will return a single path selection.

Parameters:
  • model – swmmio.Model object

  • start_node – string of Node Name

  • end_node – string of Node Name

  • include_nodes – list of node name strings

  • include_links – list of link name strings

Returns:

Network Path Trace Tuple

swmmio.utils.functions.format_inp_section_header(string)[source]

Ensure a string is in the inp section header format: [UPPERCASE], except in the case of the [Polygons] section with is capitalized case :param string: :return: string

swmmio.utils.functions.merge_dicts(*dict_args)[source]

Given any number of dicts, shallow copy and merge into a new dict, precedence goes to key value pairs in latter dicts.

swmmio.utils.functions.model_to_networkx(model, drop_cycles=True)[source]

Networkx MultiDiGraph representation of the model

swmmio.utils.functions.random_alphanumeric(n=6)[source]
swmmio.utils.functions.remove_braces(string)[source]
swmmio.utils.functions.rotate_model(m, rads=0.5, origin=None)[source]

rotate a model (its coordinates) >>> from swmmio.tests.data import MODEL_FULL_FEATURES_XY_B >>> import swmmio >>> mb = swmmio.Model(MODEL_FULL_FEATURES_XY_B) >>> mc = rotate_model(mb, rads=0.75, origin=(2748515.571, 1117763.466)) >>> mc.inp.coordinates

swmmio.utils.functions.summarize_model(model)[source]
swmmio.utils.functions.trace_from_node(conduits, startnode, mode='up', stopnode=None)[source]

trace up and down a SWMM model given a start node and optionally a stop node.

swmmio.utils.functions.trim_section_to_nodes(inp, node_ids=None, node_type='junctions', drop=True)[source]

utils.modify_model module

swmmio.utils.modify_model.replace_inp_section(inp_path, modified_section_header, new_data)[source]

modify an existing inp file by passing in new data (Pandas Dataframe) and the section header that should be modified. This function will overwrite all data in the old section with the passed data

Parameters:
  • inp_path – path to inp file to be changed

  • modified_section_header – section for which data should be change

  • new_data – pd.DataFrame of data to overwrite data in the modified section

Returns:

swmmio.Model instantiated with modified inp file

utils.spatial module

swmmio.utils.spatial.centroid_and_bbox_from_coords(coords)[source]

return a bounding box that encapsulates all coordinates :param coords: pd.Series of coordinates :return: boudning list of coordinates

swmmio.utils.spatial.change_crs(series, in_crs, to_crs)[source]

Change the projection of a series of coordinates :param series: :param to_crs: :param in_crs: :return: series of reprojected coordinates >>> import swmmio >>> m = swmmio.Model(MODEL_FULL_FEATURES_XY) >>> proj4_str = ‘+proj=tmerc +lat_0=36.16666666666666 +lon_0=-94.5 +k=0.9999411764705882 +x_0=850000 +y_0=0 +datum=NAD83 +units=us-ft +no_defs’ #”+init=EPSG:102698” >>> m.crs = proj4_str >>> nodes = m.nodes() >>> change_crs(nodes[‘coords’], proj4_str, “EPSG:4326”) Name J3 [(39.236286854940964, -94.64346373821752)] 1 [(39.23851590020802, -94.64756446847099)] 2 [(39.2382157223383, -94.64468629488778)] 3 [(39.23878251491925, -94.64640342340165)] 4 [(39.238353081411915, -94.64603818939938)] 5 [(39.23797714290924, -94.64589184224722)] J2 [(39.23702605103406, -94.64543916929885)] J4 [(39.23633648359375, -94.64190240294558)] J1 [(39.23723558954326, -94.64583338271147)] Name: coords, dtype: object

swmmio.utils.spatial.coords_series_to_geometry(coords, geomtype='linestring', dtype='geojson')[source]

Convert a series of coords (list of list(s)) to a series of geometry objects. :param coords: series of lists of xy coordinates :param geomtype: geometry type of target :param dtype: format of geometry objects to be created (‘geojson’, ‘shapely’) :return: series of geometry objects >>> import swmmio >>> model = swmmio.Model(MODEL_FULL_FEATURES_XY) >>> nodes = model.nodes() >>> geoms = coords_series_to_geometry(nodes[‘coords’], geomtype=’point’) >>> geoms.iloc[0] {“coordinates”: [2748073.3060000003, 1117746.087], “type”: “Point”}

swmmio.utils.spatial.read_shapefile(shp_path)[source]

Read a shapefile into a Pandas dataframe with a ‘coords’ column holding the geometry information. This uses the pyshp package

swmmio.utils.spatial.write_geojson(df, filename=None, geomtype='linestring', drop_na=True)[source]

convert dataframe with coords series to geojson format :param df: target dataframe :param filename: optional path of new file to contain geojson :param geomtype: geometry type [linestring, point, polygon] :param drop_na: whether to remove properties with None values :return: geojson.FeatureCollection

>>> from swmmio.examples import philly
>>> geoj = write_geojson(philly.links.dataframe, drop_na=True)
>>> print(json.dumps(geoj['features'][0]['properties'], indent=2))
{
  "InletNode": "J1-025",
  "OutletNode": "J1-026",
  "Length": 309.456216,
  "Roughness": 0.014,
  "InOffset": 0,
  "OutOffset": 0.0,
  "InitFlow": 0,
  "MaxFlow": 0,
  "Shape": "CIRCULAR",
  "Geom1": 1.25,
  "Geom2": 0,
  "Geom3": 0,
  "Geom4": 0,
  "Barrels": 1,
  "Name": "J1-025.1"
}
>>> print(json.dumps(geoj['features'][0]['geometry'], indent=2))
{
  "type": "LineString",
  "coordinates": [
    [
      2746229.223,
      1118867.764
    ],
    [
      2746461.473,
      1118663.257
    ]
  ]
}
swmmio.utils.spatial.write_shapefile(df, filename, geomtype='line', prj=None)[source]

create a shapefile given a pandas Dataframe that has coordinate data in a column called ‘coords’.

utils.text module

swmmio.utils.text.extract_section_of_file(file_path, start_strings, end_strings, comment=';', **kwargs)[source]

Extract a portion of a file found between one or more start strings and the first encountered end string.

file_pathstr

Path to the source file.

start_stringsstr or list of str

String or list of strings from which to start extracting.

end_stringsstr or list of str

String or list of strings at which to stop extracting.

commentstr, optional

Comment string used to ignore parts of the source file. Defaults to ‘;’.

**kwargs

Other keyword arguments.

str

String extracted from source file.

>>> from swmmio.tests.data import MODEL_FULL_FEATURES_XY
>>> s = extract_section_of_file(MODEL_FULL_FEATURES_XY, '[EVAPORATI', '[', comment=None)
>>> print(s.strip())
[EVAPORATION]
;;Data Source    Parameters
;;-------------- ----------------
CONSTANT         0.0
DRY_ONLY         NO
swmmio.utils.text.find_byte_range_of_section(path, start_string)[source]

returns the start and end “byte” location of substrings in a text file

swmmio.utils.text.get_inp_sections_details(inp_path, include_brackets=False)[source]

creates a dictionary with all the headers found in an INP file (which varies based on what the user has defined in a given model) and updates them based on the definitions in inp_header_dict this ensures the list is comprehensive :param inp_path: :param include_brackets: whether to parse sections including the [] :return: OrderedDict >>> from swmmio.tests.data import MODEL_FULL_FEATURES_XY >>> headers = get_inp_sections_details(MODEL_FULL_FEATURES_XY) >>> [header for header, cols in headers.items()][:4] [‘TITLE’, ‘OPTIONS’, ‘EVAPORATION’, ‘RAINGAGES’] >>> headers[‘SUBCATCHMENTS’][‘columns’] [‘Name’, ‘Raingage’, ‘Outlet’, ‘Area’, ‘PercImperv’, ‘Width’, ‘PercSlope’, ‘CurbLength’, ‘SnowPack’]

swmmio.utils.text.get_rpt_metadata(file_path)[source]

Scan rpt file and extract meta data

Parameters:

file_path – path to rpt file

Returns:

dict of metadata

swmmio.utils.text.get_rpt_sections_details(rpt_path)[source]
Parameters:
  • rpt_path

  • include_brackets

Returns:

# >>> MODEL_FULL_FEATURES__NET_PATH

swmmio.utils.text.get_rpt_value(file_path, value_type)[source]

scan rpt file and find the line starting with value_type and return the last numeric value

swmmio.utils.text.inline_comments_in_inp(filepath, overwrite=False)[source]

with an existing INP file, shift any comments that have been placed above the element (behavoir from saving in GUI) and place them to the right, inline with the element. To improve readability

Module contents