Skip to content

Commit

Permalink
added .in<->shp function "convert_stations" to station
Browse files Browse the repository at this point in the history
  • Loading branch information
lily-tomkovic-DWR committed Jun 21, 2024
1 parent 002cba6 commit fab5823
Showing 1 changed file with 94 additions and 4 deletions.
98 changes: 94 additions & 4 deletions schimpy/station.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
import os
import sys
import pandas as pd
import geopandas as gpd
import shapefile
from shapely.geometry import Point
from vtools.functions.unit_conversions import *
from dms_datastore.dstore_config import *

Expand Down Expand Up @@ -99,9 +102,99 @@ def read_staout(fname,station_infile,reftime,ret_station_in = False,multi=False,
return (staout, station_infile) if ret_station_in else staout


def convert_stations(input, output, write_sta_var='all'):
"""Read a station shapefile/.in file and write to a .in/shapefile
Parameters
----------
input : fname
Path to input station.in style file or station.shp style file with station id, x, y, z, name and subloc fields
output : fname
Path to input station.in style file or station.shp style file with station id, x, y, z, name and subloc fields
write_sta_var : 'all' or list(str)
List of variables to put in output request from the choices 'elev', 'air pressure', 'wind_x', 'wind_y', 'temp', 'salt', 'u', 'v', 'w'
or 'all' to include them all
Returns
-------
Result : DataFrame
DataFrame with hierarchical index (id,subloc) and columns x,y,z,name
"""
stations = read_pointstrings(input)
write_pointstrings(output, stations, request=write_sta_var)
print(f"\tInput: {input} converted and written to Output: {output}")

def read_pointstrings(fpath):
if fpath.endswith(".in"):
return read_station_in(fpath)
elif fpath.endswith(".shp"):
return read_station_shp(fpath)
else:
raise ValueError("Not supported file type")

def write_pointstrings(fpath, station_in, request='all'):
if fpath.endswith(".in"):
return write_station_in(fpath, station_in, request=request)
elif fpath.endswith(".shp"):
return write_station_shp(fpath, station_in)
else:
raise ValueError("Not supported file type")

def read_station_shp(fpath, pop_xy=True):
"""Read a shapefile and convert into a pandas DataFrame
Parameters
----------
fpath : fname
Path to input point shapefile - has station id, x, y, z, name and subloc labels (id is the station id, index will be autogenerated)
pop_xy : bool
Repopulate the x & y fields with point coordinates?
Returns
-------
Result : DataFrame
DataFrame that has station id, x, y, z, name and subloc labels (id is the station id, index will be autogenerated)
"""

if os.path.exists(fpath):
sf = shapefile.Reader(fpath)
fields = [x[0] for x in sf.fields][1:]
records = [y[:] for y in sf.records()]
shps = [s.points[0] for s in sf.shapes()]

df = pd.DataFrame(columns=fields, data=records)

if pop_xy:
for index, row in df.iterrows():
df.loc[index,'x'] = round(shps[index][0], 2)
df.loc[index,'y'] = round(shps[index][1], 2)

return df

else:
raise ValueError("File not found")

def write_station_shp(fpath, station_in):
"""Write a point Shapefile file given a pandas DataFrame of metadata
Parameters
----------
fpath : fname
Path to output station.in file
station_in : DataFrame
DataFrame that has station id, x, y, z, name and subloc labels (id is the station id, index will be autogenerated)
"""

station_in['geometry'] = station_in.apply(lambda x: Point((float(x.x), float(x.y))), axis=1)

gdf = gpd.GeoDataFrame(station_in, geometry='geometry')

gdf.to_file(fpath, driver='ESRI Shapefile')

def read_station_in(fpath):
"""Read a SCHISM station.in file into a pandas DataFrame
Expand Down Expand Up @@ -630,7 +723,4 @@ def main():

if __name__ == '__main__':
#example()
main()



main()

0 comments on commit fab5823

Please sign in to comment.