schimpy package
Submodules
schimpy.base_io module
This module is a simple common base for text file IO. @outhor: Kijin Nam, knam@water.ca.gov
schimpy.batch_metrics module
Create metrics plots in batch mode
- schimpy.batch_metrics.generate_metricsplots(main_inputfile)
Create metrics plots in batch mode.
MAIN_INPUTFILE: Path to the main input YAML file.
schimpy.bctide module
Generate SCHISM bctides.in files from a YAML boundary description.
All elevation, velocity, temperature, salinity and tracer boundary types read
by SCHISM (schism_init.F90) are supported. Each open boundary lists its
variables; each variable names a source keyword that maps one-to-one
onto a SCHISM type code. A numeric source (or a list of numbers for a
tracer module) means a constant (code 2). Omitting a variable means code 0.
Source keywords
- elevation (
iettype) th_text(1,elev.th), number (2),tidal(3),th_nc(4,elev2D.th.nc),tidal_th_nc(5, tides added toelev2D.th.nc).- velocity (
ifltype) th_text(1,flux.th), number (2, discharge, negative is inflow),tidal(3),th_nc(4,uv3D.th.nc),tidal_th_nc(5),th_nc_relaxed(-4),tidal_th_nc_relaxed(-5),flather_1(-1),discharge_relation(-2).- temperature, salinity (
itetype,isatype) and tracers (itrtype) th_text(1), number or list of numbers (2),initial_profile(3),th_nc(4,TEM_3D.th.nc,SAL_3D.th.ncor[MOD]_3D.th.nc). Each requiresnudgein [0, 1].
See the “Boundary conditions (bctides)” chapter of the schimpy documentation for the complete YAML reference and examples.
schimpy.bound_linear module
- schimpy.bound_linear.bound_linear(z, z_low, z_high, val_low, val_high)
schimpy.cencoos_download module
- schimpy.cencoos_download.cencoos_schism_opendap(lat_lo, lon_lo, lat_hi, lon_hi, file_base, to_cache, from_cache)
Download cencoos opendap data for all time based on a bounding set of lat/lon file_base : str prefix for files to_cache : bool whether to stash data in numpy arrays to make it easier next time from_cache : use cache rather than download)
The strategy for this download may change with time. When the script was originally written, blocking the query in time was very inefficient
- schimpy.cencoos_download.merc_to_latlon(x, y)
- schimpy.cencoos_download.time_block_report(message, told)
This routine is for reporting incremental timing of parts of the script
schimpy.check_mesh_skewness module
Calculate skewness of elements form gr3 file
- schimpy.check_mesh_skewness.calculate_skewness(mesh, normalize=True, mask_tri=False)
Calculate skewness of elements
- Parameters:
- mesh: schism_mesh
- normalize: bool, optional
Normalize skewness if True.
- mask_tri: bool, optional
If true, mask skewness of triangular elements with zero
- schimpy.check_mesh_skewness.check_skewness(meshfile, propfile, mask_tri, normalize)
Calculate skewness of elements from gr3 file.
- schimpy.check_mesh_skewness.write_prop(fpath, data)
Write a prop file with a prop vector
schimpy.check_vgrid module
Validate a SCHISM LSC2 vgrid.in file.
Checks
Padding consistency: -9.0 sentinel appears exactly at levels < kbp.
Strict monotonicity: sigma values increase from kbp to nvrt.
Output-precision monotonicity: sigma survives %14.6f rounding.
Thin-layer detection: flag layers thinner than a fraction of uniform.
Side-midpoint monotonicity: the z-check SCHISM actually performs.
Designed for use as both a CLI (check_vgrid) and in test suites:
from schimpy.check_vgrid import check_vgrid
issues = check_vgrid("vgrid.in", hgrid="hgrid.gr3", eta=1.5)
assert len(issues) == 0, issues
- class schimpy.check_vgrid.VgridIssue(check: str, node: int, level: int = -1, detail: str = '', x: float = nan, y: float = nan)
Bases:
objectSingle validation failure.
- schimpy.check_vgrid.check_vgrid(vgrid_path, *, vgrid_version='5.10', hgrid=None, eta=0.0, thin_fraction=0.1, max_report=50) List[VgridIssue]
Validate a vgrid.in file and return a list of issues.
- Parameters:
- vgrid_pathstr or Path
Path to vgrid.in.
- vgrid_versionstr
‘5.8’ or ‘5.10’.
- hgridstr or Path, optional
Path to hgrid.gr3. Required for thin-layer and side-midpoint checks.
- etafloat
Reference free-surface elevation for depth computation.
- thin_fractionfloat
Flag layers thinner than
thin_fraction * depth / nlayers.- max_reportint
Cap on issues per check category.
- Returns:
- list of VgridIssue
schimpy.clip_dems module
- schimpy.clip_dems.bounding_coords(image)
Compute bounding coordinates (upper-left and lower-right) of a GDAL-readable raster.
- Parameters:
- imagestr
Path to an image/DEM readable by GDAL.
- Returns:
- (xlo, xhi)tuple[tuple[float, float], tuple[float, float]]
xlo is (ulx, uly); xhi is (lrx, lry) in the raster’s coordinate system.
- schimpy.clip_dems.clip_dem(xlo, xhi, demlist='dem.txt', outformat='AAIGrid', hshift=False, prefix='dem_clip', verbose=False, merge=False)
Clip each DEM that intersects the requested bounding box, producing numbered outputs.
- Parameters:
- xlo, xhituple[float, float]
Upper-left (xlo) and lower-right (xhi) coordinates for the clipping box.
- demliststr
Path to DEM list YAML spec (see load_dem_list).
- outformatstr
GDAL output format name (e.g. ‘AAIGrid’, ‘GTiff’, ‘PNG’, …).
- hshiftbool
Deprecated SMS < 11.1 half-cell shift option.
- prefixstr
Output filename prefix; outputs are {prefix}_{i}.{ext}.
- verbosebool
If True, print details and show GDAL command.
- mergebool
If True, merge all clipped DEMs into a single output respecting priority order.
- schimpy.clip_dems.load_dem_list(dem_spec_yaml)
Load a prioritized DEM list from a SCHISM-YAML spec (via schism_yaml).
- The YAML must contain either:
dem_list: […]
or dem: { dem_list: […] }
- Parameters:
- dem_spec_yamlstr
Path to YAML file.
- Returns:
- list[str]
DEM filenames in priority order (high → low).
- Raises:
- FileNotFoundError
If dem_spec_yaml does not exist.
- KeyError
If no dem_list can be found in the supported locations.
- TypeError
If the dem_list is not a list of strings.
- ValueError
If the list is empty.
schimpy.combine_consume module
- schimpy.combine_consume.appears_done(wdir, fb, exten, firstblock, lastblock)
Decide if entire file block already appears to have been combined based on existence of combined file. Date not checked
- schimpy.combine_consume.archive_blocks(ar_file, tbase, blocks_per_day=1, ndxmin=1, ndxmax=None)
- schimpy.combine_consume.combine(wdir, blocks, fbase, combine_exe, consume=True, assume_done=True)
- schimpy.combine_consume.combine_consume(start, dir, fbase, hotstart, hotstart_only, consume, assume_done, combiner, hot_combiner, sndx, endx, sndx_hot, endx_hot, datefile, blocks_per_day, is_test=False)
- schimpy.combine_consume.combine_hotstart(wdir, combine_hotstart_exe, minstep=0, maxstep=99999999, consume=True)
- schimpy.combine_consume.detect_min_max_index(wdir, sample_fbase)
- schimpy.combine_consume.do_combine(wdir, begin, end, filebase)
- schimpy.combine_consume.do_combine_hotstart(wdir, step)
- schimpy.combine_consume.failed_incomplete(e)
- schimpy.combine_consume.gather_ppf_names(wdir, blocks)
- schimpy.combine_consume.prune_ppf_files(wdir, blocks, fbase, list_only=False)
- schimpy.combine_consume.setup(wdir, filebase)
- schimpy.combine_consume.split(alist, n)
- schimpy.combine_consume.touch(fname, times=None)
schimpy.combine_flux module
Command line tool to merge possibly overlapping flux.dat files from hotstart runs
- schimpy.combine_flux.combine_flux(infiles, outfile, prefer_last=False)
Merge possibly overlapping flux.dat files from hostart runs
- schimpy.combine_flux.test_combine_flux()
schimpy.contour_smooth module
This module contains tools for a smoother for DEMs (currently tiff format) based on curvature flow The algorithm is based on one by Malladi and Sethian, and results in a simplification of contours while allowing sharp gradients as long as they are persistent. So it is not a cure for pressure gradient errors a la Hannah. The script shows some artefacts of a time when it wasn’t particularly stable and could run out of memory. In particular, the algorithm dumps out intermediate arrays as it goes along and these have to be visualized or saved using the appropriate subcommands or functions. Stability is no longer an issue. it has been good for quite a while. Not so sure about memory. We’ve not tested a big problem yet on a big DEM on 64bit python.
- class schimpy.contour_smooth.RasterWrapper(filename)
Bases:
objectMethods
write_copy
- write_copy(filename, data)
- schimpy.contour_smooth.calc_f(t, data, width_shape)
Right hand side of the semi-discretized operator (in space) so that it can be integrated in time
- schimpy.contour_smooth.contour_smooth(input, scales, max_time, nstep, report_interval, fill_val=2.0, **kwargs)
Driver function for smoothing a DEM
- schimpy.contour_smooth.contour_smooth2d(dem, scales, max_time, nstep, report_interval)
- schimpy.contour_smooth.save_smooth(dumpfile, original, outfile, **kwargs)
- schimpy.contour_smooth.view_smooth(file0, file1, levels, vmin, vmax, **kwargs)
View the dumped files to graphically explore smoothing progress
schimpy.convert_linestrings module
Command line tool to convert SCHISM line strings in YAML to Shapefile and vice versa
- schimpy.convert_linestrings.convert_linestrings_main(input_fn, output_fn, envvar=None)
Function for converting line string files.
- schimpy.convert_linestrings.convert_structures_main(input_yaml, output_fn)
Function for converting line string files from a structures yaml
schimpy.convert_mesh module
Mesh converter
- schimpy.convert_mesh.convert_mesh(input, output, crs)
Converts mesh files to a new format (e.g., shapefile, gr3, etc.).
schimpy.convert_points module
Command line tool to convert SCHISM points (source and sink) in YAML to Shapefile
- schimpy.convert_points.main(input, output)
Function for converting SCHISM points.
- schimpy.convert_points.points_to_bp(fpath, points)
Convert a DataFrame to a SCHISM build points (.bp) file.
- schimpy.convert_points.points_to_shp(fpath, points)
Convert a DataFrame to a Shapefile using geopandas.
- schimpy.convert_points.points_to_yaml(fpath, points)
- schimpy.convert_points.read_points(fpath)
Read points from a YAML file.
- schimpy.convert_points.shp_to_df(fpath)
Read a point shapefile using geopandas and return a DataFrame with ‘sites’, ‘stype’, ‘x’, and ‘y’ columns.
- schimpy.convert_points.write_points(fpath, points)
Write points to a Shapefile.
schimpy.convert_polygons module
Command line tool to convert SCHISM polygons in YAML to Shapefile and vice versa
- schimpy.convert_polygons.convert_polys(input, output, yaml_root=None, envvar=None)
schimpy.convert_sav_class_to_number module
- schimpy.convert_sav_class_to_number.convert_sav_class_to_number(mesh, density, target, output)
Convert SAV class to number and process density data.
- schimpy.convert_sav_class_to_number.read_density_tiff(fpath_densitiy_tiff)
Read geotiff values for density It is assumed that the projected regular coordinates.
- Parameters:
- fpath_densitiy_tiff: str
filename for SAV desity diff
- Returns:
- numpy.ndarray
3D array containing x’s, y’s, and density. The shape is (n_x, n_y, 3)
schimpy.create_mesh_n_levels module
Create a mesh file with the number of vertical levels as nodal value
- schimpy.create_mesh_n_levels.create_mesh_n_levels(hgrid, vgrid, output)
Create a mesh file with the number of vertical levels as nodal values. This function reads a horizontal grid (hgrid) and vertical grid (vgrid), calculates the number of active vertical levels at each node, and writes the result to an output file with the level counts as nodal attributes. Parameters ———- hgrid : str or Path
Path to the horizontal grid file.
- vgridstr or Path
Path to the vertical grid file.
- outputstr or Path
Path to the output mesh file where the mesh with vertical level counts will be written.
Returns
- None
The function writes the output to a file and returns nothing.
Notes
- The number of vertical levels at each node is calculated as:
n_levels = total_vertical_levels - kbp
where kbp is the bottom index for each node. Examples ——– >>> create_mesh_levels(‘hgrid.gr3’, ‘vgrid.in’, ‘mesh_levels.gr3’)
schimpy.create_station_output module
- schimpy.create_station_output.create_station_output(hotstart, run_start, hot_date, input_type, old_input, new_input, out_dir, overwrite_existing, target)
- schimpy.create_station_output.generate_elapsed_time(run_start, hot_date, dt_in_sec, index_unit)
- schimpy.create_station_output.read_staout_lite(fname, station_infile)
Read a SCHISM staout_* file into a pandas DataFrame A “light” version of read_staout from schimpy. The original read_staout requires reftime, which requires a prior knowledge of the start time.
- Parameters:
- fnamefile path
Path to input staout file or a variable name in [“elev”, “air pressure”, “wind_x”, “wind_y”, “temp”, “salt”, “u”, “v”, “w”] whose 1-index will be mapped to a name like staout_1 for elev
- station_infilestr or DataFrame
Path to station.in file or DataFrame from read_station_in
schimpy.create_vgrid_lsc2 module
Create LSC2 vertical grid lsc2.py
The min and max layers can be specified in polygons in yaml or shp with minlayer and maxlayer attributes.
- schimpy.create_vgrid_lsc2.create_vgrid_lsc2(hgrid, vgrid, minmaxregion, ngen, eta, plot_transects, archive_nlayer, nlayer_gr3, vgrid_version)
Create LSC2 vertical grid
- Parameters:
- hgridstr
hgrid file name
- vgridstr
vgrid output file name
- minmaxregionstr
Polygon file that contains min and max layer information
- ngenint
Number of iterations for layer simplification
- etafloat
Reference surface elevation
- plot_transectsstr, optional
Filename or glob prefix of transects to plot
- archive_nlayerstr
Output directory for nlayer files
- nlayer_gr3str
nlayer.gr3 output file name
- vgrid_versionstr
SCHISM version number as string (e.g. ‘5.8’ or ‘5.10’)
- schimpy.create_vgrid_lsc2.plot_vgrid(hgrid_file, vgrid0_file, vgrid_file, vgrid_version, eta, transectfiles, out_dir='.')
- schimpy.create_vgrid_lsc2.vgrid_gen(hgrid, vgrid_out, vgrid_version, eta, minmaxlayerfile, archive_nlayer='out', nlayer_gr3='nlayer.gr3', diagnostics_dir=None)
schimpy.create_vgrid_lsc2_v2 module
Create LSC2 v2 vertical grid (BETA).
This module implements the v2 vertical grid generator for SCHISM, using the LSC2 v2 pipeline (locally adaptive, globally smooth).
It can be called from prepare_schism (dict-based YAML config) or standalone via the CLI entry point.
The v2 generator is currently in beta. For the stable legacy generator, use vgrid_generator_version: v1.
- schimpy.create_vgrid_lsc2_v2.vgrid_gen_v2(hgrid, vgrid_out, vgrid_version, eta, *, depth_function=None, algorithm=None, region_constraints=None, dz_scale_gr3=None, diagnostics=False, diagnostics_dir=None, debug_prefix=None, pileup_log=None, **kwargs)
Generate a SCHISM vgrid using the LSC2 v2 pipeline (BETA).
This is the v2 counterpart of
vgrid_genincreate_vgrid_lsc2.py. It accepts the same top-level parameters (hgrid, vgrid_out, vgrid_version, eta) plus v2-specific nested dicts for depth_function, algorithm, and region_constraints.- Parameters:
- hgridstr or SchismMesh
Path to hgrid.gr3 or an already-loaded mesh object.
- vgrid_outstr
Output vgrid filename.
- vgrid_versionstr
SCHISM version string (‘5.8’ or ‘5.10’).
- etafloat
Reference free-surface elevation.
- depth_functiondict, optional
{name: ..., params: {...}}- algorithmdict, optional
Nested dict with
hysteresisandfitsub-dicts.- region_constraintsdict, optional
Dict with
polygonskey (from YAMLinclude:expansion).- dz_scale_gr3str, optional
Path to a scalar GR3 for per-node dz scaling.
- diagnosticsbool or dict, optional
If True, write the standard LSC2 v2 diagnostic GR3 files and pileup CSV. A dict may be used as
{enabled: true, dir: <path>}.- diagnostics_dirstr, optional
Directory for standard diagnostics when diagnostics is True.
- debug_prefixstr, optional
Legacy prefix path for debug GR3 snapshots. Still supported.
- pileup_logstr, optional
Legacy path for CSV log of fixed pileup nodes. Still supported.
schimpy.cruise module
- schimpy.cruise.cruise_plot(data_path, start, schism_output_path)
Loop over USGS polaris cruise water quality data, extract SCHISM model salinity, and plot observed vs model transect salinity profiles.
USGS polaris cruise data should have CSV format:
Date,Time,Station Number,Depth,Salinity,Temperature MM/DD/YYYY,24 hr.,,[meters],[psu],[°C] 6/22/2017,7:20,2,1,0.14,22.48 …
Example:
cruise.py –data_path ./ –start 04/18/2017 –schism_output_path I:itphist_2017
- schimpy.cruise.cruise_xyt(path, station_data, base_time, outfile)
- schimpy.cruise.do_depth_plot(station, cruise_data, surrounding_profiles, ax, xlabel, ylabel, add_legend=False)
- schimpy.cruise.gen_profile_plot(base_date, cruise_time, survey_file, model_file, station_file, xytfile)
- schimpy.cruise.gen_station_xyt(base_date, cruise_time, survey_file, station_file, xytfile)
- schimpy.cruise.longitudinal(cruise_data, station_data, ax, context_label=None, add_labels=False, xlabel=None, xmin=None, xmax=None, max_depth=None)
- schimpy.cruise.main(base_date, cruise_time, obs_file, model_file, station_file, xytfile)
- schimpy.cruise.match_cruise(time, station, x, z, times, data)
- schimpy.cruise.model_data_for_longitude(cruise_data, station_data, x, z, times, model_data, base_date)
- schimpy.cruise.process_cruise(path)
- schimpy.cruise.process_stations(station_file)
- schimpy.cruise.process_xyt(path, casts, base_time)
schimpy.cut_mesh module
Functions to cut certain parts in the mesh by cutting lines.
- schimpy.cut_mesh.cut_mesh(fpath_gr3_in, lines, fpath_gr3_out, cut_side='left')
Remove elements of a mesh in one side of cutting polyline segments. A mesh is read in from a gr3, and a result mesh is written in another gr3 file.
A user needs to be careful that line segments forms a closed division. Otherwise, all elements would be deleted.
- Parameters:
- fpath_gr3_in
Filename of the input grid in gr3
- lines: array-like
An array of coordinates of line segments specifying the location of cuts
- fpath_gr3_out
Filename of the output grid in gr3
- cut_side: str, optional
If cut_side is ‘left,’ which is default, the left side of cutting lines when one sees the second point from the first point of a line will be removed. If this value is ‘right,’ the right side will be removed.
- schimpy.cut_mesh.read_lines(fpath)
Read coordinates of cutting line segments from a plain text file.
The expected format is:
x1 y1 x2 y2
in each line.
- Parameters:
- fpath
Name of a file containing coordinates of cutting lines
- Returns:
- list
List of coordinates of cutting lines
- schimpy.cut_mesh.read_lines_from_shapefile(fpath)
Read coordinates of cutting line segments from a ESRI Shapefile containing line features.
- Parameters:
- fpath
Name of a file containing coordinates of cutting lines
- Returns:
- list
List of coordinates of cutting lines
schimpy.download_hrrr module
Created on Fri Jan 20 09:07:50 2023 Download NOAA High-Resolution Rapid Refresh (HRRR) Model using AWS bucket service
- schimpy.download_hrrr.download_hrr(start_date, rnday, pscr, bbox)
- schimpy.download_hrrr.download_hrr_clip(start_date, destination, rnday, latitude_min, latitude_max, longitude_min, longitude_max)
Download NOAA High-Resolution Rapid Refresh (HRRR) Model using AWS bucket service.
START_DATE: Starting date of HRRR data (format: MM/DD/YYYY, e.g., 09/19/2018)
DESTINATION: Path to store downloaded HRRR data
RNDAY: Number of days of data to be downloaded
LATITUDE_MIN: Minimal latitude of bounding box
LATITUDE_MAX: Maximal latitude of bounding box
LONGITUDE_MIN: Minimal longitude of bounding box
LONGITUDE_MAX: Maximal longitude of bounding box
Example:
download_hrrr 01/01/2023 g:temp 15 37.3 39.0 -123.15 -121.1
schimpy.ellipse module
- schimpy.ellipse.ellipse(x, y, z, pt1_xy, pt2_xy, min_depth=None, max_depth=None, major_axis_len=1200.0)
Return depth floor based on distance from an oriented ellipse center.
The minor axis follows pt1->pt2 and the major axis is perpendicular. Inside the ellipse, target depth decays quadratically from max_depth at the center to min_depth at the boundary. Outside the ellipse, target depth is clamped at min_depth. The return value is never shallower than z.
schimpy.embed_raster module
Embed finer gridded data in coarser, using curvature flow smoothing to reconcile
Main function is called embed_fine
- schimpy.embed_raster.embed_raster(input_fg, input_bg, output, nsmooth_init=2, nsmooth_final=1, plot=False, max_time_init=3, max_time_final=1, nstep=50, report_interval=1, **kwargs)
Embed a smoother DEM in a coarser
The two inputs and output are filenames. The basic plans is this: 1. Smooth the fine data enough to resample without aliasing or distortion 2. Interpolate/resample the result to the coarser mesh 3. Where the result of 1-2 has good data, replace coarser data 4. Smooth the final grid lightly to remove kinks/discontinuity
The smoothing is done with contour_smooth2d
schimpy.gaussian_quadrature module
Gaussian quadrature in 2D space
- class schimpy.gaussian_quadrature.GaussianQuadrature(order)
Bases:
objectAbstract base class of GaussianQuadrature
Methods
average(vertices, values)Calculate the average of the value over the domain.
Calculate quadrature points and weights
domain_size(vertices)Abstract method to calculate the size of the domain
integrate(vertices[, values])Integrate values over a quad element
jacobian_det(vertices)Determinant of Jacobian at quadrature points
Get the number of quadrature points
quadrature_vector(vertices)Create a quadrature matrix for quadrature integration Taking a dot product this quadrature matrix and the values at the quadrature points will result in quadrature
shape(pts)Abstract shape function
shape_derivative(pts)Abstract shape derivative function
values_at_quadrature_points(values)Get quadrature points
- average(vertices, values)
Calculate the average of the value over the domain.
- Parameters:
- vertices: numpy.array
coordinates of vertices (or nodes) The shape needs to be (:, 2) or more columns. The values in the first two columns will be used.
- Returns:
- float
the length of the line
- calculate_quadrature_points_and_weights()
Calculate quadrature points and weights
- Parameters:
- pts: np.ndarray
Coordinates of the nodes
- Returns:
- ptsreal
quadrature points
- domain_size(vertices)
Abstract method to calculate the size of the domain
- integrate(vertices, values=None)
Integrate values over a quad element
- Parameters:
- vertices: numpy.array
coordinates of vertices (or nodes) with values. The shape needs to be (:, 2)
- values: numpy.array, optional
A value vector at vertices If it is not provided, the thrid column will be used as values
- Returns:
- float
result of integration
- jacobian_det(vertices)
Determinant of Jacobian at quadrature points
- Parameters:
- vertices: numpy.array
coordinates of vertices (or nodes) The shape needs to be (:, 2) or more columns. The values in the first two columns will be used.
- Returns:
- numpy.array
array of determinant ant quadrature points
- number_of_quadrature_points()
Get the number of quadrature points
- Returns:
- int
Number of quadrature points
- quadrature_vector(vertices)
Create a quadrature matrix for quadrature integration Taking a dot product this quadrature matrix and the values at the quadrature points will result in quadrature
- Parameters:
- vertices: numpy.array
coordinates of vertices (or nodes) with values. The shape needs to be (:, 2)
- Returns:
- numpy.array
two-dimensional matrix of quadrature matrix
- shape(pts)
Abstract shape function
- Parameters:
- pts: np.ndarray
Coordinates of the nodes
- shape_derivative(pts)
Abstract shape derivative function
- Parameters:
- pts: np.ndarray
Coordinates of the nodes
- values_at_quadrature_points(values)
Get quadrature points
- Parameters:
- values: numpy.array
values at quadrature points
- Returns:
- numpy.array
values of Gaussian quadrature points
- class schimpy.gaussian_quadrature.GaussianQuadratureLine2(order)
Bases:
GaussianQuadratureGaussian quadrature on line with two end points in 2-D space
Methods
average(vertices, values)Integrate values over a quad element
Calculate quadrature points and weights
domain_size(vertices)Size of domian, which is the length of the line in this case
integrate(vertices[, values])Integrate values over a quad element
jacobian_det(vertices)Determinant of Jacobian at quadrature points, 1-D version
number_of_quadrature_points()Get the number of quadrature points
quadrature_vector(vertices)Create a quadrature matrix for quadrature integration Taking a dot product this quadrature matrix and the values at the quadrature points will result in quadrature
shape(pts)Shape functions Ordering is counter-clockwise direction
shape_derivative(pts)Derivatives of shape functions
values_at_quadrature_points(values)Get quadrature points
- average(vertices, values)
Integrate values over a quad element
- Parameters:
- vertices: numpy.array
coordinates of vertices (or nodes) with values. The shape needs to be (-1, 2)
- values: numpy.array
The values at vertices
- Returns:
- averagefloat
result of integration
- calculate_quadrature_points_and_weights()
Calculate quadrature points and weights
- Parameters:
- pts: np.ndarray
Coordinates of the nodes
- Returns:
- ptsreal
quadrature points
- domain_size(vertices)
Size of domian, which is the length of the line in this case
- Parameters:
- vertices: numpy.array
coordinates of vertices (or nodes) The shape needs to be (2, 2) or more columns. The values in the first two columns will be used.
- Returns:
- float
the length of the line
- jacobian_det(vertices)
Determinant of Jacobian at quadrature points, 1-D version
- Parameters:
- vertices: numpy.array
coordinates of vertices (or nodes) The shape needs to be (-1, 2) or more columns. The values in the first two columns will be used.
- Returns:
- numpy.array
array of determinant ant quadrature points
- shape(pts)
Shape functions Ordering is counter-clockwise direction
- Parameters:
- pts: numpy.array
Local coordinates.
- Returns:
- numpy.array
matrix of shape function value at the given points
- class schimpy.gaussian_quadrature.GaussianQuadratureQuad4(order)
Bases:
GaussianQuadratureGaussian Quadrature for a quadrilateral with four nodes
Methods
average(vertices, values)Calculate the average of the value over the domain.
Calculate quadrature points and weights
domain_size(vertices)Size of domain, which is the area of the quadrilateral in this case.
integrate(vertices[, values])Integrate values over a quad element
jacobian(vertices[, local_coord])Create a Jacobian matrix or matrixes at the given local coordinates
jacobian_det(vertices)Determinant of Jacobian at quadrature points
number_of_quadrature_points()Get the number of quadrature points
quadrature_vector(vertices)Create a quadrature matrix for quadrature integration Taking a dot product this quadrature matrix and the values at the quadrature points will result in quadrature
shape(pts)Shape functions Ordering is counter-clockwise direction
shape_derivative(pts)Derivatives of shape functions
values_at_quadrature_points(values)Get quadrature points
- calculate_quadrature_points_and_weights()
Calculate quadrature points and weights
- domain_size(vertices)
Size of domain, which is the area of the quadrilateral in this case. The area is calculated with shoelace equation.
- Parameters:
- vertices: numpy.array
coordinates of vertices (or nodes) The shape needs to be (4, 2) or more columns. The values in the first two columns will be used.
- Returns:
- ret_size: float
the length of the line
- jacobian(vertices, local_coord=None)
Create a Jacobian matrix or matrixes at the given local coordinates
- Parameters:
- vertices: numpy.array
coordinates of vertices (or nodes) The shape needs to be (4, 2) or more columns. The values in the first two columns will be used.
- local_coord: numpy.array
local coordinates where a Jacobian is calculated
- Returns:
- numpy.array
Jacobian matrix
- shape(pts)
Shape functions Ordering is counter-clockwise direction
- Parameters:
- pts: numpy.array
Local coordinates. The dimension is (-1, 2)
- Returns:
- numpy.array
matrix of shape function value at (xi, eta)
- class schimpy.gaussian_quadrature.GaussianQuadratureTri3(order)
Bases:
GaussianQuadratureGaussian Quadrature for triangles with three nodes
Methods
average(vertices, values)Calculate the average of the value over the domain.
Calculate quadrature points and weights
domain_size(vertices)Size of domian, which is the area of the quadrilateral in this case.
integrate(vertices[, values])Integrate values over a quad element
jacobian(vertices[, local_coord])Create a Jacobian matrix or matrixes at the given local coordinates
jacobian_det(vertices)Determinant of Jacobian at quadrature points
number_of_quadrature_points()Get the number of quadrature points
quadrature_vector(vertices)Create a quadrature matrix for quadrature integration Taking a dot product this quadrature matrix and the values at the quadrature points will result in quadrature
shape(pts)Shape functions Ordering is counter-clockwise direction
shape_derivative(pts)Derivatives of shape functions
values_at_quadrature_points(values)Get quadrature points
- calculate_quadrature_points_and_weights()
Calculate quadrature points and weights
- domain_size(vertices)
Size of domian, which is the area of the quadrilateral in this case. The area is calculated with shoelace equation.
- Parameters:
- vertices: numpy.array
coordinates of vertices (or nodes) The shape needs to be (3, 2) or more columns. The values in the first two columns will be used.
- Returns:
- float
the length of the line
- jacobian(vertices, local_coord=None)
Create a Jacobian matrix or matrixes at the given local coordinates
- Parameters:
- vertices: numpy.array
coordinates of vertices (or nodes) The shape needs to be (4, 2) or more columns. The values in the first two columns will be used.
- local_coord: numpy.array
local coordinates where a Jacobian is calculated
- Returns:
- numpy.array
Jacobian matrix
- jacobian_det(vertices)
Determinant of Jacobian at quadrature points
- Parameters:
- vertices: numpy.array
coordinates of vertices (or nodes) but it is not used
- Returns:
- numpy.array
array of determinant ant quadrature points
- shape(pts)
Shape functions Ordering is counter-clockwise direction
- Parameters:
- pts: numpy.array
Local coordinates. Not used
- Returns:
- numpy.array
matrix of shape function value at (xi, eta)
schimpy.geo_tools module
- schimpy.geo_tools.FindMultiPoly(poly_array)
- schimpy.geo_tools.Polylen(poly)
- schimpy.geo_tools.geometry2coords(geo_obj)
- schimpy.geo_tools.geometry2coords_points(geo_obj)
- schimpy.geo_tools.ic_to_gpd(fn, crs=None)
Read ic yaml file and convert the polygons to geopandas format
- schimpy.geo_tools.ll2utm(lonlat, crs=None)
lonlat can be numpy arrays. lonlat = np.asarray([lon,lat]) default crs = epsg:26910
- schimpy.geo_tools.partition_check(mesh, poly_fn, regions, centering='node', crs=None, allow_overlap=False, allow_incomplete=False)
Check if the schism mesh division by the polygon features in poly_fn is unique and complete. The partition check is based on either node or element, and the function checks:
if there are any orphaned nodes, and
if any nodes/elems were assigned to multiple polygons.
- schimpy.geo_tools.project_fun(crs=None)
- schimpy.geo_tools.shapely_to_geopandas(features, crs=None, shp_fn=None)
Convert shapely features to geopandas and generate shapefiles as needed
- schimpy.geo_tools.shp2yaml(shp_fn, yaml_fn=None, crs=None)
Convert a shapefile to yaml file
- Parameters:
- shp_fnstr
Input shape filename
- yaml_fnstr
Output yaml filename
- crsstr, optional
Output projection. The default is None.
- Returns:
- None.
- schimpy.geo_tools.utm2ll(utm_xy, crs=None)
utm_xy can be numpy arrays. utm_xy = np.asarray([utm_x,utm_y]) default crs = epsg:26910
- schimpy.geo_tools.yaml2shp(fn, shp_fn=None, crs=None)
schimpy.gr3 module
Package to read a mesh in GR3 format.
- class schimpy.gr3.Gr3IO(logger=None)
Bases:
BaseIOA class that manages I/O of GR3 files
- Attributes:
- linecounter
Methods
read([gr3_fname, mode])Read in a hgrid.gr3 file.
write(mesh, fname[, node_attr, boundary])Write a GR3 format grid.
- read(gr3_fname='hgrid.gr3', mode=0)
Read in a hgrid.gr3 file. If mode is 1, it does not read in boundary information.
- write(mesh, fname, node_attr=None, boundary=False)
Write a GR3 format grid. mesh = SCHISM mesh (schism_mesh) instance fname = output file name node_attr = a list of node attribute boundary = If true, boundary information will be added. Otherwise, it will not be appended.
schimpy.grid_opt module
Routines to perform grid optimization for volumetric consistency with finer DEM
There are two methods:
lsqr without constraint to solve \(Ax=b\) (scipy.sparse.linalg.lsqr)
minimize function \(1/2*||Ax-b||^2\) using the L-BFGS-B algorithm (scipy.optimize.fmin_l_bfgs_b)
where
x is depth at nodes with respect to a nominal reference surface (which may be greater than sea level in upstream locations).
Regularization:
close to the original values for all nodes: damp
minimize the 1st derivative of node elevation along land boundaries: damp_shoreline
Notes:
The function cal_z_ref only applies to the Bay Delta grid and need to be modified for other grids.
This script create an optimized gr3 file (_opt.gr3) only when one set of optimization parameters is specified.
- class schimpy.grid_opt.GridOptimizer(**kwargs)
Bases:
objectGrid optimizer class
Methods
assemble_element_matrix(areas)Build a matrix for element optimization
assemble_face_matrix(edges)Build a matrix for face optimization The order of the quadrature is fixed
build_boundary_equations(ref_surf_at_nodes)Build a matrix and vector of land boundary constraints
build_global_matrix_and_vector(params, ...)Build a global matrix and vector for optimization
Calculate depth at quad points
calculate_depth_at_face_quad_points(edges, ...)Calculate depth at quad points
calculate_edge_lengths(edges)Calculate areas of all edges
Calculate areas of all elements
calculate_element_volumes_w_dem(depth_at_quads)Calculate volumes of elements based on DEM
calculate_face_areas_w_dem(edges, depth_at_quads)Calculate area of faces based on DEM
Calculate maximum elevation in a ball from a node
calculate_reference_surface(coords)Define reference water surface at locations specified in nodes based on the assumptions, which only applicable to Bay Delta grid
Calculate reference surface at quadrature points
Create reference surface elevation at individual nodes
Calculate total number of quadrature points of the mesh with the given order
Calculate values at quadrature points
Calculate values at quadrature points
collect_edges([exclude_land_boundaries])Collect edges for the optimization
Collect all quadrature points to calculate volumes of elements with DEM
Collect all quadrature points to calculate areas of faces with DEM
Count how many boundary constraint equations there are
get_dem_elevation(list_of_points)Get elevations from DEM
integrate_over_edges(edges, values)Integrate over edges with the values at nodes
integrate_over_elements(values)Integrate over elements with the values at nodes
optimize(params[, solver])Perform a grid optimization
select_solver(solver)Select solver
show_parameters(solver, param)Show optimization parameters
- assemble_element_matrix(areas)
Build a matrix for element optimization
- Parameters:
- areas: numpy.array
areas of the elements
- assemble_face_matrix(edges)
Build a matrix for face optimization The order of the quadrature is fixed
- Parameters:
- edges: numpy.array
list of edges
- Returns:
- lil_matrix
matrix for face (edge) optimization
- build_boundary_equations(ref_surf_at_nodes)
Build a matrix and vector of land boundary constraints
- Returns:
- numpy.sparse.lil_matrix
Matrix of land boundary equations
- numpy.array
Vector of land boundary equations
- build_global_matrix_and_vector(params, mat_elem, mat_face, vec_elem, vec_face, mat_bnd, vec_bnd, depths_at_nodes, solver='L-BFGS-B')
Build a global matrix and vector for optimization
- Parameters:
- params: dict
Dict of optimization parameters
- solver: str, optional
solver name
- Returns:
- numpy.sparce.lil_matrix
- calculate_depth_at_element_quad_points(elev_at_quads, ref_surf_at_nodes)
Calculate depth at quad points
This depth is calculated by subtracting bottom elevation at quadrature points from the reference surface at quadrature points that is calculated by reference elevation at nodes with shape functions.
- Parameters:
- elev_at_quads: numpy.array
Elevation vector at quadrature points
- ref_surf_at_nodes: numpy.array
Reference elevation at nodes
- Returns:
- numpy.array
Vector of depth at quadrature points
- calculate_depth_at_face_quad_points(edges, elev_at_quads, ref_surf_at_nodes)
Calculate depth at quad points
This depth is calculated by subtracting bottom elevation at quadrature points from the reference surface at quadrature points that is calculated by reference elevation at nodes with shape functions.
- Parameters:
- elev_at_quads: numpy.array
Elevation vector at quadrature points
- ref_surf_at_nodes: numpy.array
Reference elevation at nodes
- Returns:
- numpy.array
Vector of depth at quadrature points
- calculate_edge_lengths(edges)
Calculate areas of all edges
- Returns:
- numpy.array
array of the areas of edges
- calculate_element_areas()
Calculate areas of all elements
- Returns:
- numpy.array
array of the areas of elements
- calculate_element_volumes_w_dem(depth_at_quads)
Calculate volumes of elements based on DEM
- Parameters:
- depth_at_quad: numpy.array
Vector of depth at the quadrature points
- Returns:
- numpy.array
Volumes of elements
- calculate_face_areas_w_dem(edges, depth_at_quads)
Calculate area of faces based on DEM
- Parameters:
- edges: numpy.array
- depth_at_quad: numpy.array
Vector of depth at the quadrature points
- Returns:
- numpy.array
Areas of faces
- calculate_max_elevation_in_balls(elev)
Calculate maximum elevation in a ball from a node
- Parameters:
- elev: numpy.array
array of elevation at nodes
- Returns:
- numpy.array
maximum elevation at nodes
- calculate_reference_surface(coords)
Define reference water surface at locations specified in nodes based on the assumptions, which only applicable to Bay Delta grid
The surface elevation increases linearly from west (ocean) to east
east of (x_old_river, y_old_river), the elevation increases linearly towards the south
NOTE: This is Bay-Delta Specific. Coordinates for the calculation are hard-wired.
- Parameters:
- coords: numpy.array
Coordinates to calculate reference surface The dimension of the array is (-1, 2) or more columns. The first two columns are used.
- Returns:
- numpy.array
Reference water surface for Bay-Delta
- calculate_reference_surface_at_face_quadarture_points(ref_surf)
Calculate reference surface at quadrature points
- calculate_reference_surface_maximum()
Create reference surface elevation at individual nodes
Steps:
derive max elevation within connected elements
compare with the reference calculated by calculate_reference_surface() and use the higher value between the two
- Returns:
- numpy.array
Vector of reference elevation at nodes
- calculate_total_number_of_quadrature_points()
Calculate total number of quadrature points of the mesh with the given order
- Returns:
- int
Total number of quadrature points of the mesh
- calculate_values_at_element_quadarture_points(values)
Calculate values at quadrature points
- Parameters:
- values: numpy.array
A vector of nodal values
- Returns:
- numpy.array
A vector of values at quadrature points
- calculate_values_at_face_quadarture_points(edges, values)
Calculate values at quadrature points
- Parameters:
- values: numpy.array
A vector of nodal values
- Returns:
- numpy.array
A vector of values at quadrature points
- collect_edges(exclude_land_boundaries=False)
Collect edges for the optimization
- Parameters:
- exclude_land_boundaries: bool, optional
Switch to exclude land edges
- Returns:
- numpy.array
matrix of nodal indices of edges
- collect_element_quadrature_points_for_dem()
Collect all quadrature points to calculate volumes of elements with DEM
- Returns:
- numpy.array
Quadrature points of all elements
- collect_face_quadrature_points_for_dem(edges)
Collect all quadrature points to calculate areas of faces with DEM
- Parameters:
- edges: numpy.array
list of edges containing indices of the two end nodes
- Returns:
- numpy.array
Quadrature points of faces
- count_boundary_equations()
Count how many boundary constraint equations there are
- get_dem_elevation(list_of_points)
Get elevations from DEM
Do this once to save time
- Parameters:
- list_of_points: list of numpy.array
array of coordinate matrices of points to get DEM elevations
- Returns:
- listnp.ndarray
list of elevation vectors
- integrate_over_edges(edges, values)
Integrate over edges with the values at nodes
- Parameters:
- values: numpy.array
Values at nodes to integrate
- Returns:
- numpy.array
Vector of integration over each edge
- integrate_over_elements(values)
Integrate over elements with the values at nodes
- Parameters:
- values: numpy.array
Values at nodes to integrate
- Returns:
- numpy.array
Vector of integration over each element
- optimize(params, solver='L-BFGS-B')
Perform a grid optimization
Two solvers are available:
L-BFGS-B (default): minimize function \(1/2*||Ax-b||^2\)
linear least square solver (Ax=b).
- Parameters:
- params: dict
Dict of optimization parameters
- solver: str, optional
solver name
- Returns:
- numpy.array
optimized elevation
- select_solver(solver)
Select solver
- Parameters:
- solver: str
Name of a solver for the optimization
- show_parameters(solver, param)
Show optimization parameters
- Parameters:
- solver: str
solver name
- param: dict
parameters for the optimization
- schimpy.grid_opt.fprime(x, A, b)
The gradient of the objective function with respect to the heights. This gradient is a vector the same size as x.
- schimpy.grid_opt.grid_opt_with_args(filename, demfile, optparam, optfile, na_fill=None, solver='L-BFGS-B')
Optimize grid with arguments
- schimpy.grid_opt.init_logger()
- schimpy.grid_opt.object_func(x, A, b)
Objective function for the optimization for L-BFGS-B
schimpy.hotstart_fix module
Targeted repairs for SCHISM-generated hotstart files.
- schimpy.hotstart_fix.fix_hotstart_wet_dry(input_hotstart, output_hotstart, hgrid, h0=0.01)
Copy a hotstart and force geometrically impossible wet states dry.
Existing dry node, side, and element states are preserved. Only wet nodes with
dp + eta2 <= h0and the sides and elements incident to those nodes are changed.- Parameters:
- input_hotstartpath-like
SCHISM hotstart file to repair.
- output_hotstartpath-like
New hotstart file to create. It must not already exist.
- hgridpath-like
Exact horizontal grid used by the run that wrote the hotstart.
- h0float, optional
SCHISM wetting and drying threshold.
- Returns:
- dict
Counts of corrected nodes, sides, and elements.
schimpy.hotstart_inventory module
- schimpy.hotstart_inventory.expected_hotstarts(run_start, dt, nday, hot_freq)
Generate expected hotstarts based on run parameters.
- Parameters:
- run_startdatetime
The start time of the simulation run.
- dtint
The time step in seconds.
- ndayint
The number of days for the simulation run.
- hot_freqpandas.tseries.offsets.DateOffset
The frequency at which hotstarts are generated.
- Returns:
- pandas.DataFrame
A DataFrame with a DatetimeIndex representing the expected hotstart times and a column “iteration” indicating the corresponding iteration numbers.
Notes
This function calculates the expected hotstart times and their corresponding iteration numbers based on the provided simulation parameters. It does not perform any file inventory or check for existing hotstart files.
- schimpy.hotstart_inventory.hotstart_inventory(run_start=None, dt=None, nday=None, workdir='.', paramfile=None, hot_freq=None, expected=False)
Create an inventory of existing hotstarts or expected hotstarts.
Whether the inventory is for existing or expected hotstarts depends on whether the workdir is an outputs directory or a study directory.
- Parameters:
- run_startstr or pandas.Timestamp, optional
The start time of the simulation run in ISO-like format (e.g., ‘2013-12-03’).
- dtint, optional
The time step in seconds of the model. Default is None.
- ndayint, optional
The number of days in the simulation run or the maximum to catalog. Default is None.
- workdirstr, optional
The working directory, which may be a launch or outputs directory. Default is ‘.’.
- paramfilestr, optional
The name of the param.nml file if it is used to infer runtime. Default is None.
- hot_freqstr or pandas.tseries.offsets.DateOffset, optional
The hotstart frequency in pandas frequency terms (e.g., ‘5D’). Default is None.
- expectedbool, optional
Flag to generate expected hotstarts instead of an inventory of existing files. Default is False.
- Returns:
- pandas.DataFrame or None
A DataFrame containing the inventory of hotstarts with a DatetimeIndex and a column “iteration”. If no hotstarts are found and expected is False, returns None.
- schimpy.hotstart_inventory.hotstart_inventory_exist(start, dt=90, workdir='.', do_print=True)
Check for the existence of hotstart inventory files and generate a DataFrame mapping iterations to corresponding datetime values.
- Parameters:
- startstr or pandas.Timestamp
The start time as a string or pandas.Timestamp object.
- dtint, optional
Time step in seconds between iterations (default is 90).
- workdirstr, optional
Directory to search for hotstart files (default is ‘.’).
- do_printbool, optional
Whether to print the iterations and corresponding times (default is True).
- Returns:
- pandas.DataFrame
A DataFrame with datetime as the index and iteration numbers as the column.
Notes
The function searches for hotstart files in the specified workdir directory.
If no files are found in workdir, it searches in the current directory.
The function assumes hotstart files follow the naming pattern “hotstart_000000_<iteration>.nc”.
schimpy.hrr3 module
adapted from pyschism, original work of Linlin Cui.
- class schimpy.hrr3.AWSGrib2Inventory(start_date: datetime = None, record=1, pscr=None, product='conus')
Bases:
object- Attributes:
- bucket
- files
- output_interval
- s3
- tmpdir
- property bucket
- property files
- property s3
- property tmpdir
- class schimpy.hrr3.HRRR(start_date=None, rnday=None, pscr=None, record=1, bbox=None)
Bases:
objectMethods
gen_sflux
modified_latlon
- gen_sflux(date, record, pscr)
- modified_latlon(grbfile)
- schimpy.hrr3.localize_datetime(d)
- schimpy.hrr3.nearest_cycle(input_datetime=None, period=6, method='floor')
schimpy.interp_2d module
invdisttree.py: inverse-distance-weighted interpolation using KDTree
- class schimpy.interp_2d.Invdisttree(x, nnear=10, leafsize=10)
Bases:
objectInverse-distance-weighted interpolation using KDTree
Methods
interp(obs[, ninterp])Perform interpolation
weights(node_xy[, eps, p, weights])Find the nearest neighbors and assign weights to each neibors
Examples
tree = interp_2d.Invdisttree(obs_xy) # initialize KDTree with observational points tree.weights(node_xy) # calculate weights for each node. values_v = tree.interp(obs.temperature.values) # perform spatial interpolation with the calculated weights from the previous step
- interp(obs, ninterp=6)
Perform interpolation
- Parameters:
- obsnp.ndarray
observational values; nan values are allowed and will be ignored.
- ninterppositive int, ninterp<=nnear
The number of nearest points to perform interpolation The default is 6.
- Returns:
- val_interpnp.ndarray
interpolated values
- weights(node_xy, eps=0, p=2, weights=None)
Find the nearest neighbors and assign weights to each neibors
- Parameters:
- node_xynp.ndarray, shape (n,2)
Coordinates of the query points n is the number of query points
- epspositive float, optional
approximate nearest, dist <= (1 + eps) * true nearest. The default is 0.
- ppositive int, optional
power. The default is 2.
- weightsfloat, optional
optional multiplier for weights, same dimension as node_xy The default is None.
- Returns:
- None.
schimpy.interpolate_structure module
- schimpy.interpolate_structure.ensure_offset(arg)
- schimpy.interpolate_structure.interpolate_structure(template_th, output_th, dt=None, int_cols=['install', 'ndup_weir', 'ndup_culvert', 'ndup_pipe'])
Interpolate a dated th “template” for a structure The interpolation adds time detail, maintain data types. Comments are removed and floating precision is hardwired to two digits
The input template file must have a header and time stamps that are neat with respect to dt. This is checked.
- Parameters:
- template_thstr
Path to the template file
- output_thstr
Name of the output file
- dtinterval_type
Number of hours between changes, default is 1 hour. Can be any time (string, delta, offset) that can be coerced to offset
- int_colslist
List of column names that should be integers. This can be a superset, and it shouldn’t change much if you name your template columns the standard way.
- schimpy.interpolate_structure.test_date_label_correct(fname_th)
Make sure that the date column in the file doens’t have comment marker and raise error if it does
- schimpy.interpolate_structure.test_template_times(template, dt)
schimpy.inundate_island module
Generate preprocessor inputs for gradually inundating restored islands.
A breach is described by a pathway along the levee, ordered looking into the
island, and optionally a shorter gate_span naming the part of it the
hydraulic structure actually occupies. Two points are the common case and may be
given as left/right instead. From the gate span the generator derives one
polygon per breach and reuses it verbatim across every artifact, so the dredge,
the initial pool and the hotstart region cannot drift apart. The full pathway is
what holds the island fill in.
The pool level follows from the dredge. schimpy.ellipse.ellipse() clamps its
radial term at 1, so every node inside a breach polygon ends up at min_depth or
deeper; -min_depth - freeboard is therefore a constant water level that meets
the island’s -z-freeboard exactly at the ellipse rim.
A breach that names a breach_date also gets an operating schedule written as a
.th pair, dated and elapsed. The date belongs to the breach, because a run
spanning several years may combine restoration sites that come online years apart.
It may also be set once on the island or once at the top of the file, and the
narrowest setting wins: breach, then island, then file, then --breach-date.
- schimpy.inundate_island.breach_axes(left, right)
Return the centre and unit axes of a breach.
- Parameters:
- left, rightarray_like
The two levee points, ordered looking into the island.
- Returns:
- centernumpy.ndarray
Midpoint of the two points.
- alongnumpy.ndarray
Unit vector from left to right, the ellipse minor axis.
- intonumpy.ndarray
Unit vector perpendicular to
along, pointing into the island.
- Raises:
- ValueError
If the two points coincide.
- schimpy.inundate_island.breach_polygon(left, right, major_axis_len, n_points=24)
Return a closed ring enclosing the dredge ellipse for a breach.
The ring is the ellipse itself scaled out slightly, so it encloses the taper without sweeping in the corners a bounding box would.
- Parameters:
- left, rightarray_like
The two levee points, ordered looking into the island.
- major_axis_lenfloat
Full length of the axis perpendicular to
left-right.- n_pointsint, optional
Number of ring vertices.
- Returns:
- list of list of float
Vertices, first repeated as last.
- schimpy.inundate_island.build_breach_schedule(schedule, epoch_start='2005-01-01', ramp_hours=24.0, ramp_steps=12, ramp_target=0.6)
Build the operating schedule for one breach as a dated table.
The structure holds its configured setting from
epoch_startuntilramp_hoursbefore the breach, opens overramp_stepsevenly spaced increments, and is then deinstalled at the breach itself. Deinstalling returns the block elements to the momentum solve; ramping first keeps that switch small, andblock_nudgerelaxes what is left.- Parameters:
- scheduledict
One entry from
artifacts['schedules'], carryingname,type,configurationandbreach_date.- epoch_startstr or datetime, optional
First row, standing in for “infinitely in the past”.
- ramp_hoursfloat, optional
Length of the opening ramp before the breach.
- ramp_stepsint, optional
Number of increments in the ramp.
- ramp_targetfloat, optional
Value the ramped column reaches at the end of the ramp.
- Returns:
- pandas.DataFrame
Indexed by datetime, with one column per scheduled field.
- schimpy.inundate_island.build_inundation_artifacts(islands, mesh, edge_length_factor=3.0, freeboard=0.01, ambient=0.96, breach_date=None)
Build the preprocessor inputs for a set of restoration islands.
- Parameters:
- islandslist of dict
Island specifications. Each needs
name,breachesandpolygon. The polygon is either the wordinfer, or a mapping in the same form the preprocessor polygon files use, carrying at leastvertices. Each breach needsname,min_depth,max_depthand its geometry as eitherpathwayorleft/right. Apathwayof more than two points also needsgate_span, the straight chord the structure occupies.major_axis_len,structureandbreach_dateare optional;breach_datemay also be given once per island.- meshschimpy.schism_mesh.SchismMesh
Mesh the breaches sit on, used to size the dredge footprint.
- edge_length_factorfloat, optional
Dredge penetration each way from the levee line, as a multiple of the local edge length. The ellipse major axis is twice this.
- freeboardfloat, optional
Depth the initial surface sits below the bed on dry ground.
- ambientfloat, optional
Water level away from the islands, used for the domain entry of the elevation file.
- Returns:
- dict
Maps artifact name to a structure ready for yaml serialization:
structures,depth_enforcement,elevationandregions.
- Raises:
- ValueError
If a specification is incomplete or geometrically inconsistent.
- schimpy.inundate_island.generate_inundation_inputs(config_file, hgrid_file, out_dir, prefix=None, edge_length_factor=3.0, freeboard=0.01, ambient=0.96, validate=True, breach_date=None, run_start=None, th_dir='th_files', epoch_start='2005-01-01', ramp_hours=24.0, ramp_steps=12, ramp_target=0.6, logger=None)
Read a breach configuration and write the preprocessor inputs.
- Parameters:
- config_filestr
Breach configuration yaml, carrying an
islandslist.- hgrid_filestr
Mesh the breaches sit on.
- out_dirstr
Directory to write into.
- prefixstr, optional
Prepended to each output filename.
- edge_length_factorfloat, optional
Dredge penetration each way from the levee line, as a multiple of the local edge length. The ellipse major axis is twice this.
- freeboardfloat, optional
Depth the initial surface sits below the bed on dry ground.
- ambientfloat, optional
Water level away from the islands.
- validatebool, optional
Build the structures and confirm they resolve inside their polygons.
- breach_datestr or datetime, optional
Last-resort breach moment for breaches that name neither their own nor their island’s. A breach with no date resolves to no time series.
- run_startstr or datetime, optional
Model time origin. Required to write the elapsed
.thfiles.- th_dirstr, optional
Subdirectory for
dated/andelapsed/.- epoch_start, ramp_hours, ramp_steps, ramp_target
Passed through to
build_breach_schedule().- loggerlogging.Logger, optional
- Returns:
- dict
Maps artifact name to the path written.
- schimpy.inundate_island.infer_island_polygon(mesh, breaches, logger=None)
Derive an island outline by filling inward from its breaches.
Every breach line is a barrier, so a set of breaches together pens in the restoration area even where no single one of them closes it. The whole pathway blocks, not just the gated part of it, so a short gate in a long levee still holds. Each breach contributes the reference node the structure itself will use on its island side, and the fill from every one of them must come out identical and must never reach the far side of any breach. If it does, the breaches disagree about which side the island is on, or the barrier they form has a gap.
- Parameters:
- meshschimpy.schism_mesh.SchismMesh
Mesh to walk.
- breacheslist of dict
Resolved breaches carrying
pathway,left,rightandname.- loggerlogging.Logger, optional
- Returns:
- list of list of float
Outline vertices, first repeated as last.
- Raises:
- ValueError
If a breach has no island-side element, or the breaches disagree.
- schimpy.inundate_island.local_edge_length(mesh, center, radius)
Return the median mesh edge length near a point.
- Parameters:
- meshschimpy.schism_mesh.SchismMesh
Mesh to measure.
- centerarray_like
Point to measure around.
- radiusfloat
Search radius.
- Returns:
- float
- Raises:
- ValueError
If no edge midpoint falls within
radius.
- schimpy.inundate_island.validate_structures(artifacts, hgrid_file, logger=None)
Check that each generated structure resolves inside its own breach polygon.
Builds the structures the way the preprocessor will, then confirms the node pairs and the reference pair land inside the polygon that dredges the opening. A reference node outside it would sit on undredged ground and could go dry.
- Parameters:
- artifactsdict
Output of
build_inundation_artifacts().- hgrid_filestr
Mesh the structures are placed on.
- loggerlogging.Logger, optional
Passed to the setup so failures report through the usual channel.
- Returns:
- dict
Maps structure name to the number of nodes checked.
- Raises:
- ValueError
If a structure cannot be built, or a node falls outside its polygon.
- schimpy.inundate_island.write_breach_timeseries(schedules, out_dir, run_start, th_dir='th_files', epoch_start='2005-01-01', ramp_hours=24.0, ramp_steps=12, ramp_target=0.6, logger=None)
Write dated and elapsed
.thfiles for every scheduled breach.- Parameters:
- scheduleslist of dict
artifacts['schedules'].- out_dirstr
Directory the artifacts were written into.
- run_startstr or datetime
Model time origin the elapsed files are measured from.
- th_dirstr, optional
Subdirectory holding
dated/andelapsed/.- epoch_start, ramp_hours, ramp_steps, ramp_target
Passed through to
build_breach_schedule().- loggerlogging.Logger, optional
- Returns:
- dict
Maps structure name to
(dated_path, elapsed_path).
- schimpy.inundate_island.write_inundation_inputs(artifacts, out_dir, prefix=None)
Write generated artifacts as yaml.
- Parameters:
- artifactsdict
Output of
build_inundation_artifacts().- out_dirstr
Directory to write into. Created if absent.
- prefixstr, optional
Prepended to each filename.
- Returns:
- dict
Maps artifact name to the path written.
schimpy.laplace_smooth_data module
- schimpy.laplace_smooth_data.laplace_smooth_data2(mesh, data, kappa=0.05, dt=1.0, iter_total=150)
Apply Laplacian smoothing to a scalar field on a mesh using explicit diffusion.
This function performs iterative smoothing by updating each node’s value toward the average of its neighbors. It corresponds to forward Euler integration of the diffusion equation.
- Parameters:
- meshobject
A mesh object with a nodes array and a method get_neighbor_nodes(ndx) returning neighbor node indices for a given node.
- datandarray of shape (N,)
Initial scalar field values at each mesh node.
- kappafloat, optional
Diffusivity coefficient. Controls the rate of smoothing. Default is 0.05.
- dtfloat, optional
Timestep used for each smoothing iteration. Default is 1.0.
- iter_totalint, optional
Number of smoothing iterations to perform. Default is 150.
- Returns:
- smooth_datandarray of shape (N,)
The smoothed scalar field after iter_total iterations.
- schimpy.laplace_smooth_data.laplace_smooth_data2_slow(mesh, data, kappa=0.05, dt=1.0, iter_total=150)
Apply Laplacian smoothing to a scalar field on a mesh using explicit diffusion.
DEPRECATED. Use the version without _slow in the name
This function performs iterative smoothing by updating each node’s value toward the average of its neighbors. It corresponds to forward Euler integration of the diffusion equation.
- Parameters:
- meshobject
A mesh object with a nodes array and a method get_neighbor_nodes(ndx) returning neighbor node indices for a given node.
- datandarray of shape (N,)
Initial scalar field values at each mesh node.
- kappafloat, optional
Diffusivity coefficient. Controls the rate of smoothing. Default is 0.05.
- dtfloat, optional
Timestep used for each smoothing iteration. Default is 1.0.
- iter_totalint, optional
Number of smoothing iterations to perform. Default is 150.
- Returns:
- smooth_datandarray of shape (N,)
The smoothed scalar field after iter_total iterations.
- schimpy.laplace_smooth_data.laplace_smooth_with_vel2(mesh, data, vel, kappa=0.05, dt=1.0, iter_total=1)
Apply Laplacian smoothing with additive forcing to a scalar field on a mesh.
This function performs iterative diffusion of data while incorporating a source or forcing term vel at each node. It evolves the field using explicit Euler integration of the PDE:
∂u/∂t = κ ∇²u + vel
- Parameters:
- meshobject
A mesh object with a nodes array and a method get_neighbor_nodes(ndx) returning neighbor node indices for a given node.
- datandarray of shape (N,)
Initial scalar field values at each mesh node.
- velndarray of shape (N,)
Additive source or forcing term to apply at each node.
- kappafloat, optional
Diffusivity coefficient. Default is 0.05.
- dtfloat, optional
Timestep used for each smoothing iteration. Default is 1.0.
- iter_totalint, optional
Number of smoothing iterations to perform. Default is 1.
- Returns:
- smooth_datandarray of shape (N,)
The smoothed and forced scalar field after iter_total iterations.
- schimpy.laplace_smooth_data.laplace_smooth_with_vel3(mesh, nlayer, data, vel, kappa=0.05, dt=1.0, iter_total=1)
Apply layer-aware Laplacian smoothing with forcing to a scalar field on a mesh.
This function diffuses values across mesh nodes but restricts neighbor contributions to those from the same or deeper layers. Shallower neighbors are excluded from smoothing influence, preserving stratification or flow directionality.
- Parameters:
- meshobject
A mesh object with a nodes array and a method get_neighbor_nodes(ndx) returning neighbor node indices for a given node.
- nlayerndarray of shape (N,)
Integer layer index for each node. Smoothing ignores neighbors with shallower layer values.
- datandarray of shape (N,)
Initial scalar field values at each mesh node (used as fallback for excluded neighbors).
- velndarray of shape (N,)
Additive source or forcing term applied at each node.
- kappafloat, optional
Diffusivity coefficient. Default is 0.05.
- dtfloat, optional
Timestep used for each smoothing iteration. Default is 1.0.
- iter_totalint, optional
Number of smoothing iterations to perform. Default is 1.
- Returns:
- smooth_datandarray of shape (N,)
The smoothed scalar field after iter_total iterations with layer-aware filtering and forcing.
- schimpy.laplace_smooth_data.smooth_kernel_numba(data, neighbors, kappa, dt, iter_total)
schimpy.logging_config module
- class schimpy.logging_config.LoggingConfig(package_name: 'str', level: 'int' = 20, console: 'bool' = True, logdir: 'Optional[Path]' = None, logfile_prefix: 'str' = 'run', include_pid_in_filename: 'bool' = True, clear_handlers: 'bool' = True, propagate: 'bool' = False, include_third_party: 'bool' = False)
Bases:
object- Attributes:
- logdir
- schimpy.logging_config.configure_logging(*, package_name: str, level: int = 20, console: bool = True, logdir: Path | None = None, logfile_prefix: str = 'run', include_pid_in_filename: bool = True, clear_handlers: bool = True, propagate: bool = False, include_third_party: bool = False) Path | None
- schimpy.logging_config.configure_logging_config(cfg: LoggingConfig) Path | None
Configure logging for a package + (optionally) a logfile.
Contract: - Only configures the package logger tree rooted at cfg.package_name. - Safe to call multiple times (when cfg.clear_handlers=True). - Returns logfile path if a file handler is created; otherwise returns None.
- schimpy.logging_config.resolve_loglevel(*, debug: bool = False, quiet: bool = False, verbose: int = 0, loglevel: str | None = None) tuple[int, bool]
Convert common CLI flags into a logging level + console enable flag.
quiet controls console only (file logging remains available via logdir)
explicit loglevel overrides debug/verbose
schimpy.lsc2 module
Methods for generating local sigma coordinates These routines are meant to be called a pair. First, default_num_layers is called to obtain the recommended number of layers for each node based on depth. Then, gen_sigma is called to generate the actual local sigma values at each level (nlevels = nlayers+1).
Note that in this script eta is the “reference” free surface at which the mesh is conditioned, which can be a global scalar or array of local nodal values. Using a medium-higher value (2-4 depending on typical flood levels) usually does’t hurt the final product in low water. The example() shows how to visualize a mesh generated on one ref water surface on another surface.
The major user parameters are already set at their defaults. It is mildly important to realize that the S coordinate parameters have the same qualitative interpretation, but that the S system is really just used as a heuristic and everything is manipulated locally.
Besides theta (refinement to the surface) the mostly likely item to manipulate will be minlayer and maxlayer. These can be supplied locally (if these are given as arrays) or globally (if provided as scalars).
- class schimpy.lsc2.BilinearMeshDensity
Bases:
objectMethods
density
depth
- density(z, h, x)
- depth(t, h, x)
- class schimpy.lsc2.CubicLSC2MeshFunction
Bases:
objectMethods
density
depth
- density(x, tlev)
- depth(x, tlev)
- schimpy.lsc2.default_num_layers(x, eta, h0, minlayer, maxlayer, dz_target, meshfun, maxlev=100)
Returns the number of layers that, according to meshfun, gives a depth matching eta + h0 In the (likely) case of inexact fit) the lower bound n- of the number of layers not yet outfitted for variation in x
- schimpy.lsc2.default_num_layers0(total_ref_depth, minlayer, maxlayer)
- schimpy.lsc2.example()
- schimpy.lsc2.example2()
- schimpy.lsc2.example3()
- schimpy.lsc2.flip_sigma(sigma)
Flip the ordering of non-nan sigma values.
The output of get_sigma starts from 0.0, but sigma in vgrid.in from -0.1. So it needs to be flipped for further use.
- Parameters:
- sigma: numpy.ndarray
- Returns:
- numpy.ndarray
New sigma array that has flipped ordering.
- schimpy.lsc2.gen_sigma(nlayer, minlayer, maxlayer, eta, h, mesh, meshfun, nsmoothlay=0, out_dir='./')
“ Generate local sigma coordinates based on # layers, reference surface and depth
- Parameters:
- nlayer: ndarray
Veector of size np (number of nodes) giving desired # layers for each node in the mesh
- eta: ndarray or float
reference water level heights at each node at which generation is to occur.
- h: ndarray
unperturbed depth for each node in the mesh
- meshfloat
maximum theta to use in S calculations. This is interpreted the same as a standard S grid theta although it will be varied according to depth
- meshfun: float
S coordinate parameter b
- nsmoothlay: how many layers to smooth on the bottom
- out_dir: Path
- hc: float
S coordinate parameter hc (do not alter)
- schimpy.lsc2.label_components(mesh, nlayer, thresh, exclude)
- schimpy.lsc2.lowest_layer_height(htrans, nlevel, klev=0)
- schimpy.lsc2.mesh_function_depths(nlayer, depth, mesh, meshfun)
- schimpy.lsc2.plot_mesh(ax, x, zcor, startvis, stopvis, c='black', linewidth=1)
- schimpy.lsc2.process_orphans(mesh, nlayer, depth, hcor)
- schimpy.lsc2.process_orphans2(mesh, nlayer, depth, hcor)
- schimpy.lsc2.sigma_z(sigma, eta, h)
- schimpy.lsc2.smooth_bed(mesh, eta, h, hcor, nlevel, speed, out_dir='./')
- schimpy.lsc2.szcoord(s, h, eta, theta, b, hc)
- schimpy.lsc2.z_sigma(zcor)
schimpy.lsc2_v2 module
LSC2 v2: Fully local + globally smooth vertical mesh construction for SCHISM.
- This module implements the Step A–E pipeline:
Compute continuous desired levels L* from a vertical size function.
Quantize to integer levels with hysteresis and spatial gating.
Build per-node target interface depths from the size function.
Fit bottom & mid interfaces to targets with screened-Poisson smoothing, explicit bottom-thickness anchoring, and ordering/min-thickness guards.
Final tiny stretch to match exact depth.
It preserves the idea of a general “vertical size function” abstraction.
- Dependencies expected in the environment:
schimpy.schism_mesh: read_mesh, write_mesh
schimpy.schism_vertical_mesh: SchismLocalVerticalMesh, write_vmesh
laplace_smooth_data: smooth kernels (used here in wrappers)
- class schimpy.lsc2_v2.BilinearDensitySizeFunction
Bases:
objectMethods
Minimal nint such that H(nint; D) >= D for bilinear mapping H(ell; D) = (m/n) * (exp(n*ell) - 1), m = a + b*D, n = c + d*D.
continuous_index_for_depth
density
depth
- density(z, h, x)
- depth(levels, depth, xycoords=None)
- class schimpy.lsc2_v2.BoundaryPriors(upstream_nodes: 'Optional[np.ndarray]' = None, upstream_target_levels: 'int' = 2, upstream_rings: 'int' = 5, ocean_nodes: 'Optional[np.ndarray]' = None, ocean_target_levels: 'Optional[int]' = None, ocean_rings: 'int' = 8)
Bases:
object- Attributes:
- ocean_nodes
- ocean_target_levels
- upstream_nodes
- class schimpy.lsc2_v2.FitParams(kappa: 'float' = 0.35, dt: 'float' = 0.5, iters_bottom: 'int' = 25, iters_mid: 'int' = 18, lam_D: 'float' = 1.0, lam_B: 'float' = 6.0, K_bottom: 'int' = 3, tmin: 'float' = 0.35, keep_top_thin: 'int' = 2, top_relax: 'float' = 0.2, no_collapse_ratio: 'float' = 0.5, dump_presmooth_npz: 'str' = 'pre_smooth.npz', debug_smoother_only: 'bool' = False, sm_alpha_top: 'float' = 0.35, sm_alpha_bot: 'float' = 0.02, sm_power: 'float' = 1.2, sm_print_delta: 'bool' = True, sm_iters: 'int' = 4)
Bases:
object
- class schimpy.lsc2_v2.HysteresisParams(delta_up: 'float' = 0.7, delta_down: 'float' = 0.7, Jmax: 'int' = 1, eps_depth: 'float' = 0.75, max_sweeps: 'int' = 6, do_median_cleanup: 'bool' = True)
Bases:
object
- class schimpy.lsc2_v2.PipelineParams(priors: 'Optional[BoundaryPriors]' = None, L_smooth_passes: 'int' = 2, L_smooth_kappa: 'float' = 0.5, L_smooth_method: 'str' = 'isotropic', L_smooth_L_scale: 'float' = 1.25, L_smooth_depth_scale: 'float' = 4.0, L_smooth_length_power: 'float' = 0.0, constraint_diffusion_enable: 'bool' = False, constraint_diffusion_passes: 'int' = 40, constraint_diffusion_weight: 'float' = 0.6, constraint_diffusion_method: 'str' = 'same', constraint_diffusion_L_scale: 'Optional[float]' = None, constraint_diffusion_depth_scale: 'Optional[float]' = None, constraint_diffusion_length_power: 'Optional[float]' = None, constraint_diffusion_tol: 'float' = 0.0, integer_cleanup_enable: 'bool' = False, integer_cleanup_max_nodes: 'int' = 6, integer_cleanup_max_passes: 'int' = 5, hysteresis: 'HysteresisParams' = <factory>, fit: 'FitParams' = <factory>, n_min: 'Optional[np.ndarray]' = None, n_max: 'Optional[np.ndarray]' = None)
Bases:
object- Attributes:
- constraint_diffusion_L_scale
- constraint_diffusion_depth_scale
- constraint_diffusion_length_power
- n_max
- n_min
- priors
- hysteresis: HysteresisParams
- priors: BoundaryPriors | None = None
- class schimpy.lsc2_v2.ScaledByFieldSizeFunction(base: VerticalSizeFunction, scale_field: ndarray)
Bases:
VerticalSizeFunctionMultiplies the level-to-depth mapping by a per-node scale factor. scale[i] > 1.0 => smaller dz (more levels) because cumulative depth grows slower.
Methods
depth(levels, depth[, xycoords])Return cumulative depth (down from surface) at the provided level indices. Parameters ---------- levels : np.ndarray (int or float) Level indices (0 at surface; last ~= total levels-1 at/near bed). depth : float Local total depth D (positive down). x : float, optional Extra parameter if needed by a custom function.
- depth(levels: ndarray, depth: float, xycoords=None) ndarray
Return cumulative depth (down from surface) at the provided level indices. Parameters ———- levels : np.ndarray (int or float)
Level indices (0 at surface; last ~= total levels-1 at/near bed).
- depthfloat
Local total depth D (positive down).
- xfloat, optional
Extra parameter if needed by a custom function.
- class schimpy.lsc2_v2.SigmaCapSizeFunction(dz_max: float = 1.5)
Bases:
VerticalSizeFunction,_ShapeAwareCountMixinPure-σ spacing with a per-node dz cap. N-1 = ceil(D/dz_max); H(ell) = D * (ell/(N-1)).
- Attributes:
- count_spec
Methods
depth(levels, depth[, xycoords])Return cumulative depth (down from surface) at the provided level indices. Parameters ---------- levels : np.ndarray (int or float) Level indices (0 at surface; last ~= total levels-1 at/near bed). depth : float Local total depth D (positive down). x : float, optional Extra parameter if needed by a custom function.
required_intervals
set_count_spec
- depth(levels: ndarray, depth: float, xycoords=None) ndarray
Return cumulative depth (down from surface) at the provided level indices. Parameters ———- levels : np.ndarray (int or float)
Level indices (0 at surface; last ~= total levels-1 at/near bed).
- depthfloat
Local total depth D (positive down).
- xfloat, optional
Extra parameter if needed by a custom function.
- set_count_spec(spec)
- class schimpy.lsc2_v2.SigmaPowerSizeFunction(dz_max: float = 1.5, p: float = 0.7)
Bases:
VerticalSizeFunction,_ShapeAwareCountMixinσ spacing with dz cap and exponent p in (0,1) to bias toward bed.
- Attributes:
- count_spec
Methods
depth(levels, depth[, xycoords])Return cumulative depth (down from surface) at the provided level indices. Parameters ---------- levels : np.ndarray (int or float) Level indices (0 at surface; last ~= total levels-1 at/near bed). depth : float Local total depth D (positive down). x : float, optional Extra parameter if needed by a custom function.
required_intervals
set_count_spec
- class schimpy.lsc2_v2.SigmaSBlendSizeFunction(dz_max=1.5, theta_b=0.4, theta_f=3.0, alpha=1.0, Hc=6.0, W=4.0)
Bases:
VerticalSizeFunction,_ShapeAwareCountMixin- σ→S blend (depth-from-surface return):
Choose N so nominal dz <= dz_max.
Build uniform σ levels s∈[0,1] (0=surface).
Compute S-stretch C(s; θb, θf) (normalized to [0,1]).
Blend: ψ(s) = (1−w)*s + w*S_norm(s), w = smoothstep((D−Hc)/W) clamped to [0,1], scaled by alpha.
Return depths = D * ψ(s), strictly monotone in [0,D].
- Attributes:
- count_spec
Methods
depth(levels, depth[, xycoords])Return cumulative depth H(levels; D) for the S-blend mapping.
Top-anchored count: choose smallest nint s.t.
set_count_spec
- depth(levels, depth, xycoords=None)
Return cumulative depth H(levels; D) for the S-blend mapping. IMPORTANT: interval count N is taken from the provided levels (i.e., from the upstream Nlevels decision), not from dz_max.
- required_intervals(D: float) int
Top-anchored count: choose smallest nint s.t. dz_top <= tau, where tau is specified (once) via count_spec = {‘anchor’:’top’,’value’: tau}.
- set_count_spec(spec)
- class schimpy.lsc2_v2.SigmaTwoZoneSizeFunction(dz_max: float = 1.5, dz_bottom: float = 0.8, K_bottom: int | None = None, frac_bottom: float = 0.25)
Bases:
VerticalSizeFunctionReserve K bottom interfaces at dz_bottom (if possible), fill the rest linearly.
Methods
depth(levels, depth[, xycoords])Return cumulative depth (down from surface) at the provided level indices. Parameters ---------- levels : np.ndarray (int or float) Level indices (0 at surface; last ~= total levels-1 at/near bed). depth : float Local total depth D (positive down). x : float, optional Extra parameter if needed by a custom function.
- depth(levels: ndarray, depth: float, xycoords=None) ndarray
Return cumulative depth (down from surface) at the provided level indices. Parameters ———- levels : np.ndarray (int or float)
Level indices (0 at surface; last ~= total levels-1 at/near bed).
- depthfloat
Local total depth D (positive down).
- xfloat, optional
Extra parameter if needed by a custom function.
- class schimpy.lsc2_v2.VerticalSizeFunction
Bases:
objectAbstract base: maps level index -> cumulative depth for a given local depth. Implementations must be monotone in level index and approach D as level -> N.
Methods
depth(levels, depth[, xycoords])Return cumulative depth (down from surface) at the provided level indices. Parameters ---------- levels : np.ndarray (int or float) Level indices (0 at surface; last ~= total levels-1 at/near bed). depth : float Local total depth D (positive down). x : float, optional Extra parameter if needed by a custom function.
- depth(levels: ndarray, depth: float, xycoords=None) ndarray
Return cumulative depth (down from surface) at the provided level indices. Parameters ———- levels : np.ndarray (int or float)
Level indices (0 at surface; last ~= total levels-1 at/near bed).
- depthfloat
Local total depth D (positive down).
- xfloat, optional
Extra parameter if needed by a custom function.
- class schimpy.lsc2_v2.WrapLegacyMeshFun(legacy_meshfun)
Bases:
VerticalSizeFunctionWraps the legacy meshfun from lsc2.py which had signature depth(levels, depth, x).
Methods
depth(levels, depth[, xycoords])Return cumulative depth (down from surface) at the provided level indices. Parameters ---------- levels : np.ndarray (int or float) Level indices (0 at surface; last ~= total levels-1 at/near bed). depth : float Local total depth D (positive down). x : float, optional Extra parameter if needed by a custom function.
- depth(levels: ndarray, depth: float, xycoords=None) ndarray
Return cumulative depth (down from surface) at the provided level indices. Parameters ———- levels : np.ndarray (int or float)
Level indices (0 at surface; last ~= total levels-1 at/near bed).
- depthfloat
Local total depth D (positive down).
- xfloat, optional
Extra parameter if needed by a custom function.
- schimpy.lsc2_v2.apply_boundary_priors_to_Ltilde(mesh, Ltilde: ndarray, priors: BoundaryPriors | None) ndarray
Blend Ltilde toward boundary target levels over a few rings (soft, shock-free).
- schimpy.lsc2_v2.apply_interface_smoother_only(mesh, h_in: ndarray, Nlevels: ndarray, depth: ndarray, alpha_top: float = 0.25, alpha_bot: float = 0.05, power: float = 1.0, print_delta: bool = True)
Run ONLY the interface-level smoother on a frozen snapshot (h_in, Nlevels, depth), and return the smoothed h plus a per-level max|Δh| diagnostic.
No fitting, no guards. Use this to iterate gains quickly.
- schimpy.lsc2_v2.build_sigma_from_interfaces(depth: ndarray, h: ndarray, valid: ndarray, Nlevels: ndarray) ndarray
Compute per-node sigma values (0..1) with right padding for SCHISM.
sigma[i, :Ni] = h[i, :Ni] / depth[i] Remaining entries are filled with NaN; writers will convert to -9.0 as needed.
- schimpy.lsc2_v2.build_target_interfaces(sizefun: VerticalSizeFunction, depth: ndarray, Nlevels: ndarray, eta: float = 0.0, mesh=None, uniform_sigma_mask: ndarray | None = None) Tuple[ndarray, ndarray]
Compute target interface depths per node (down from surface).
- Parameters:
- uniform_sigma_maskoptional bool array (n_nodes,)
If True for a node, use equal-spacing (uniform sigma) targets instead of the size-function profile. Used for nodes where Nlevels exceeds the global-tmin feasibility cap.
- Returns:
- hhat(n_nodes, maxN) array with per-node valid range [0..N_i-1]
- valid_maskboolean array same shape, True where defined
- schimpy.lsc2_v2.cleanup_integer_components(mesh, Nlevels: ndarray, max_component_nodes: int = 6, max_passes: int = 5, n_min: ndarray | None = None, n_max: ndarray | None = None) ndarray
Remove small strict-extremum components in integer level counts.
This is a post-quantization topological simplification of the integer
Nlevelsfield. It repeatedly finds exact-value connected components whose node count is small, but removes them only when they are strict local extrema relative to their exterior boundary:hill: component value > every boundary value
dip: component value < every boundary value
Small components that form a legitimate transition band are preserved. For example, a small
22component between exterior21and23values is not removed. This avoids eroding stepped ramps into cliffs.The operation is scale-free: “small” is measured in mesh-node count, relying on the mesh adaptation to encode physical scale. It is also constraint-aware: if polygon n_min/n_max arrays are present, candidate replacement values that would violate any node in the component are ignored.
- schimpy.lsc2_v2.compute_Lstar(depth: ndarray, sizefun: VerticalSizeFunction, max_levels_cap: int = 80, mesh=None) ndarray
Compute real-valued desired number of levels L*(x) from the size function.
Strategy: for each node i with depth D_i, evaluate cumulative depth H(ell; D_i) on a dense grid of ell (0..Lcap-1), then invert by linear interpolation to find real ell such that H(ell; D_i) == D_i.
- Returns:
- Lstarnp.ndarray (float)
Real-valued desired count of levels at each node (>=2).
- schimpy.lsc2_v2.diffuse_Ltilde_with_constraints(mesh, Ltilde: ndarray, depth: ndarray, n_min: ndarray | None = None, n_max: ndarray | None = None, passes: int = 40, weight: float = 0.6, method: str = 'isotropic', L_scale: float = 1.25, depth_scale: float = 4.0, length_power: float = 0.0, tol: float = 0.0) ndarray
Diffuse continuous level counts while respecting polygon constraints.
Fixed constraints (
n_min == n_max) are treated as Dirichlet nodes and are re-imposed every iteration. Range/min/max constraints are box constraints: after each screened diffusion update, constrained nodes are projected back into their allowed interval. Unconstrained nodes are free except for the global two-level minimum.This stage is intended to run after the ordinary L* smoother. Unlike the legacy inside-polygon clip, fixed constrained regions continue to act as sources during smoothing, so their influence can propagate into adjacent range polygons and unconstrained transition zones.
- schimpy.lsc2_v2.fit_interfaces(mesh, depth: ndarray, Nlevels: ndarray, hhat: ndarray, valid: ndarray, tbottom: ndarray, params: FitParams = FitParams(kappa=0.35, dt=0.5, iters_bottom=25, iters_mid=18, lam_D=1.0, lam_B=6.0, K_bottom=3, tmin=0.35, keep_top_thin=2, top_relax=0.2, no_collapse_ratio=0.5, dump_presmooth_npz='pre_smooth.npz', debug_smoother_only=False, sm_alpha_top=0.35, sm_alpha_bot=0.02, sm_power=1.2, sm_print_delta=True, sm_iters=4), tmin_arr: ndarray | None = None, uniform_sigma_mask: ndarray | None = None) Tuple[ndarray, ndarray]
Fit interfaces h_k(x) to targets with smoothing, bottom anchoring, and guards.
- Parameters:
- tmin_arroptional float array (n_nodes,)
Per-node minimum layer thickness. If None, uses params.tmin everywhere.
- uniform_sigma_maskoptional bool array (n_nodes,)
If True for a node, reassert uniform sigma spacing in finalization (protects shallow exception nodes from smoother cliff-pressure).
- Returns:
- h(n_nodes, maxN) float array of final interfaces
- maskboolean valid mask per node / per level
- schimpy.lsc2_v2.fix_sigma_pileups(sigma: ndarray, Nlevels: ndarray, depth: ndarray, tmin, mesh=None) tuple[ndarray, ndarray, DataFrame]
- Inputs:
sigma: left-justified σ in [0,1], padded with NaN on the right
Nlevels: per-node level counts (includes bed & surface)
depth: total depth D (m). Only used to evaluate bottom thickness.
tmin: minimum bottom-cell thickness — scalar float or per-node array
mesh: optional, for x/y coordinates logging (mesh.nodes[:,0:2])
Always checks/fixes; returns (sigma_fixed, Nlevels_fixed, log_df). Sweep rule: try to make the bottom cell ≥ tmin; if blocked by the next interface, drop that interface and try again; stop at first success.
- schimpy.lsc2_v2.quantize_levels_with_hysteresis(mesh, Ltilde: ndarray, depth: ndarray, params: HysteresisParams = HysteresisParams(delta_up=0.7, delta_down=0.7, Jmax=1, eps_depth=0.75, max_sweeps=6, do_median_cleanup=True)) ndarray
Convert real-valued desired levels to integers with hysteresis and spatial gate.
Returns integer levels N (not layers).
- schimpy.lsc2_v2.run_pipeline(mesh, depth: ndarray, sizefun: VerticalSizeFunction, eta: float, pp: PipelineParams = PipelineParams(priors=None, L_smooth_passes=2, L_smooth_kappa=0.5, L_smooth_method='isotropic', L_smooth_L_scale=1.25, L_smooth_depth_scale=4.0, L_smooth_length_power=0.0, constraint_diffusion_enable=False, constraint_diffusion_passes=40, constraint_diffusion_weight=0.6, constraint_diffusion_method='same', constraint_diffusion_L_scale=None, constraint_diffusion_depth_scale=None, constraint_diffusion_length_power=None, constraint_diffusion_tol=0.0, integer_cleanup_enable=False, integer_cleanup_max_nodes=6, integer_cleanup_max_passes=5, hysteresis=HysteresisParams(delta_up=0.7, delta_down=0.7, Jmax=1, eps_depth=0.75, max_sweeps=6, do_median_cleanup=True), fit=FitParams(kappa=0.35, dt=0.5, iters_bottom=25, iters_mid=18, lam_D=1.0, lam_B=6.0, K_bottom=3, tmin=0.35, keep_top_thin=2, top_relax=0.2, no_collapse_ratio=0.5, dump_presmooth_npz='pre_smooth.npz', debug_smoother_only=False, sm_alpha_top=0.35, sm_alpha_bot=0.02, sm_power=1.2, sm_print_delta=True, sm_iters=4), n_min=None, n_max=None), debug: Dict[str, str] | None = None) Tuple[ndarray, ndarray, ndarray, ndarray]
Run the full A–E pipeline and return sigma, Nlevels, h, and tmin_arr.
- Returns:
- sigma(n, maxN) float
- Nlevels(n,) int
- h(n, maxN) float
- tmin_arr(n,) float — per-node minimum layer thickness
- If debug is a dict of filenames, optional GR3s will be written for inspection.
- Diagnostics are emitted as soon as their source quantity is available:
- Lstar/Ltilde/Nmin/Nmax/Nlevels/Nlayers/uniform_sigma/tbottom are written
- before interface fitting; bottom_thickness is written after fitted interfaces
- exist.
- schimpy.lsc2_v2.set_count_spec(self, spec)
- schimpy.lsc2_v2.smooth_Lstar_on_mesh(mesh, Lstar: ndarray, depth: ndarray, method: str = 'isotropic', passes: int = 2, kappa: float = 0.5, dt: float = 1.0, L_scale: float = 1.25, depth_scale: float = 4.0, length_power: float = 0.0) ndarray
Smooth L* using either the legacy isotropic or edge-aware method.
- schimpy.lsc2_v2.smooth_bottom_thickness(depth: ndarray, hhat: ndarray, valid: ndarray, tmin: float, mesh) ndarray
Build and lightly smooth the target bottom thickness field t_b(x).
- schimpy.lsc2_v2.smooth_interfaces_onepass_with_bed_fill_sparse(mesh, h: ndarray, Nlevels: ndarray, depth: ndarray, alpha_top: float = 0.8, alpha_bot: float = 0.1, power: float = 1.0) None
One Jacobi pass of interface-level smoothing across neighbors using a row-stochastic CSR averaging matrix (SciPy).
- Ghost-fill rule:
If neighbor j lacks level k (k >= Nlevels[j]), use depth[j] (bed) as its value.
Only nodes that have level k (k < Nlevels[i]) are updated. In-place update of h.
- schimpy.lsc2_v2.smooth_scalar_on_mesh(mesh, field: ndarray, passes: int = 2, kappa: float = 0.5, dt: float = 1.0) ndarray
Light isotropic Laplacian smoothing on a scalar field defined on mesh nodes.
This is the legacy LSC2-v2 smoother. It is intentionally retained so existing control files reproduce previous behavior unless the caller explicitly selects an edge-aware method.
schimpy.material_poly module
- schimpy.material_poly.create_poly(shapefile, dsetname, keyfile, polyfile, type, default=None)
Converts a polygon shapefile to the yaml input of the preprocessor
- schimpy.material_poly.read_keyfile(keyfile)
Reads a file pairing labels and values
schimpy.merge_th module
- schimpy.merge_th.merge_th(th_spec)
- schimpy.merge_th.read_data(fname, variable)
- schimpy.merge_th.read_locations_from_input(fname, role)
- schimpy.merge_th.read_th_spec(fname)
- schimpy.merge_th.write_th(df, fname, elapsed, ref_time=None)
Write a time-series to a .th file using common th_io formatting.
- schimpy.merge_th.write_th_merge(df, fname, elapsed, ref_time=None)
Write a time-series to a .th file using common th_io formatting.
schimpy.mesh_volume_tvd module
- class schimpy.mesh_volume_tvd.AdaptiveElementQuadrature(A9: float = 60.0, A16: float = 200.0)
Bases:
objectAdaptive quadrature for tri/quad elements.
Triangles use a fixed symmetric 6-point rule. Quads use tensor Gauss–Legendre nodes (3×3, 4×4, or 5×5) chosen by polygon area.
- Parameters:
- A9float, optional
Area threshold (m^2) below which quads use 3×3 rule, by default 60.0.
- A16float, optional
Area threshold for 4×4 rule (5×5 above), by default 200.0.
Methods
quad_points
- class schimpy.mesh_volume_tvd.FloodFillResult(wet_elems_stage1: 'np.ndarray', edge_labels_stage1: 'Dict[int, str]', wet_elems_stage2: 'np.ndarray', edge_labels_stage2: 'Dict[int, str]')
Bases:
object- wet_elems_stage1: ndarray
- wet_elems_stage2: ndarray
- class schimpy.mesh_volume_tvd.FloorOptions(filter: 'str' = 'max', window: 'int' = 5, enforce_floor: 'bool' = False, reg_weight: 'float' = 0.0)
Bases:
object
- class schimpy.mesh_volume_tvd.FlowOptions(n_steps: int = 25, dt: float | None = None, cfl: float = 0.25, mu: float = 1.0, lambda_l2: float = 1.0, cfl_target: float = 1.0, clipping_eps: float | None = None, rel_eta: float = 0.001, max_backtracks: int = 4, tv_weight: float = 1.0, l2_weight: float = 0.2)
Bases:
objectOptions for
run_tvd_variational().- Attributes:
- n_stepsint
Max number of iterations.
- dtOptional[float]
Base time step (meters). If None, a CFL-derived dt is used.
- cflfloat
CFL-like factor if
dtis None.- mufloat
TV step strength (prox gain). Default 1.0.
- lambda_l2float
Scale on the L2 descent increment (separate from
l2_weightin the objective). Default 1.0.- cfl_targetfloat
Target explicit rate cap for TV step. Default 1.0.
- clipping_epsOptional[float]
If not None, clip neighbor-wise with ±
clipping_eps(meters).- rel_etafloat
Required relative drop in the weighted objective per accept.
- max_backtracksint
Maximum backtracks per iteration.
- tv_weightfloat
Weight on TV in the objective.
- l2_weightfloat
Weight on L2(volume) in the objective.
- class schimpy.mesh_volume_tvd.ShorelineData(polylines: List[dict], df: DataFrame, labels_perimeter: Dict[int, str], wet_mask: ndarray)
Bases:
objectContainer for shoreline detection outputs (pure data; no filenames).
- Attributes:
- polylineslist of dict
One dict per merged polyline with keys:
{'poly_id','label','nodes','coords'}.- dfpandas.DataFrame
Per-node table equivalent to the shoreline CSV with columns
['node','x','y','z','poly_id','label'](nodeis 1-based).- labels_perimeterdict[int, str]
Perimeter edge labels (
'shore'or'deep') keyed by edge id.- wet_masknumpy.ndarray (bool)
Mask of elements in the final always-wet region after stage 2/3.
- wet_mask: ndarray
- class schimpy.mesh_volume_tvd.ShorelineOptions(href: 'Union[float, str]' = 0.0, deep_delta: 'float' = 1.0, shore_delta: 'float' = 3.0, seeds: 'Optional[List[Tuple[float, float]]]' = None, use_default_seeds: 'bool' = True, smooth_relax_factor: 'float' = 0.4, smooth_strip_max: 'int' = 24, smooth_eps_deg: 'float' = 55.0, filter_deep: 'bool' = True, epsg: 'int' = 26910, shore_csv: 'Optional[str]' = None, shore_shp: 'Optional[str]' = None)
Bases:
object- Attributes:
- seeds
- shore_csv
- shore_shp
- class schimpy.mesh_volume_tvd.TVDOptions(steps: 'int' = 32, dt: 'float' = 1.0, mu: 'float' = 1.0, lambda_l2: 'float' = 500.0, tv_weight: 'float' = 1.0, l2_weight: 'float' = 5e-05, cfl_target: 'float' = 1.0, clip_eps: 'Optional[float]' = None, rel_eta: 'float' = 0.002, max_backtracks: 'int' = 4)
Bases:
object- Attributes:
- clip_eps
- class schimpy.mesh_volume_tvd.TVL2VolumeEvaluator(mesh: SCHISM_mesh, dem_sampler: Callable[[np.ndarray], np.ndarray] | None = None, quadrature: AdaptiveElementQuadrature | None = None)
Bases:
objectEvaluator for TV energy and DEM-integrated L2 energy with cached quadrature.
- Parameters:
- meshSCHISM_mesh
Mesh with
nodes(n,3),edges(m,2), andelems(list of 3/4-tuples).- dem_samplercallable, optional
Function mapping
(k,2)XY points → DEM depth (+down) array.- quadratureAdaptiveElementQuadrature, optional
Quadrature rule provider.
Methods
global_volume
l2_dem
tv_energy
- class schimpy.mesh_volume_tvd.TVSubgradientOperator(nodes_xy: ndarray, elems: List[ndarray], lump_mass: ndarray, eps: float = 1e-08, enforce_cfl: bool = True, cfl_target: float = 1.0, clipping_eps: float | None = None)
Bases:
objectEdge-TV subgradient step on an unstructured mesh.
TV(z) = sum_{(i,j)} w_ij * |z_i - z_j|, with w_ij = |edge|.
- Parameters:
- nodes_xyndarray, shape (n,2)
Node x,y coordinates.
- elemslist of array_like
Element connectivities (3 or 4 node indices).
- lump_massndarray, shape (n,)
Lumped node areas (for explicit scaling).
- epsfloat, optional
Smoothing parameter in the |·| derivative, by default 1e-8.
- enforce_cflbool, optional
If True, scales the step to keep dt*max_rate <= cfl_target.
- cfl_targetfloat, optional
Target explicit rate cap used when
enforce_cflis True.- clipping_epsOptional[float], optional
If not None, clip the updated node values to each node’s neighbor range ±
clipping_eps. Use None to disable clipping entirely.
Methods
step
- class schimpy.mesh_volume_tvd.VolumeL2Variational(evaluator: TVL2VolumeEvaluator)
Bases:
objectElement-mean variational L2 penalty to DEM.
J_vol(z) = 0.5 * sum_e A_e * ( z̄_e - d̄_e )^2, r_e = z̄_e - d̄_e
Gradient w.r.t. node i: dJ/dz_i = sum_{e∋i} r_e * ∫_e N_i dA
Methods
gradient
residuals_and_energy
- gradient(r: ndarray) ndarray
- schimpy.mesh_volume_tvd.build_shore_floor_from_df(df: DataFrame, n_nodes: int, *, filter_kind: str = 'max', window: int = 5, trim_endpoints: bool = True)
Construct a nodewise shoreline floor from an in-memory DataFrame.
This mirrors the CSV-based implementation but avoids any file I/O.
- Parameters:
- dfpandas.DataFrame
Columns:
node, x, y, z, poly_id, label(nodeis 1-based).- n_nodesint
Total number of mesh nodes.
- filter_kind{‘max’,’median’}, optional
Rolling aggregation applied along each polyline, by default
'max'.- windowint, optional
Odd window size for the rolling aggregation, by default
7.- trim_endpointsbool, optional
Drop endpoints that touch any
'deep'edge, by defaultTrue.
- Returns:
- z_floornumpy.ndarray
Floor elevation per node (length =
n_nodes),-infwhere unset.- masknumpy.ndarray of bool
True where a floor value is defined.
- schimpy.mesh_volume_tvd.detect_shorelines(mesh, *, href: float, deep_delta: float, shore_delta: float, seeds=None, use_default_seeds: bool = True, smooth_relax_factor: float = 1.25, smooth_strip_max: int = 12, smooth_eps_deg: float = 5.0, filter_deep: bool = True, epsg: int = 26910, shore_csv: str | None = None, shore_shp: str | None = None, logger=None) ShorelineData
Detect perimeter shore/deep edges (stages 1–3) and return data only.
Optionally writes diagnostic artifacts if
shore_csv/shore_shpare provided. No filenames are returned.- Parameters:
- meshschimpy.schism_mesh.SchismMesh
Target mesh (
nodesdepths are read but not mutated here).- hreffloat
Reference depth for nodewise tests (positive downward).
- deep_delta, shore_deltafloat
Threshold deltas (m) for deep vs. shore classification.
- seedssequence of (x, y), optional
Seed points for the always-wet floodfill.
- use_default_seedsbool, optional
If True, augment with built-in seeds.
- smooth_relax_factorfloat, optional
Stage-3 relaxed edge criterion factor.
- smooth_strip_maxint, optional
Maximum length of accepted stage-3 strips.
- smooth_eps_degfloat, optional
Corner improvement tolerance in degrees.
- filter_deepbool, optional
Exclude rows labeled
'deep'from CSV export.- epsgint, optional
EPSG code for shapefile/CSV header.
- shore_csv, shore_shpstr or None, optional
Optional paths to write diagnostics. If None, nothing is written.
- loggerlogging.Logger, optional
Logger for INFO/DEBUG emissions.
- Returns:
- ShorelineData
Polylines, per-node DataFrame, perimeter labels, and wet mask.
- schimpy.mesh_volume_tvd.floodfill_always_wet(mesh, seeds_xy: Iterable[Tuple[float, float]], h0_node: ndarray, h0_edge: ndarray, delta0: float, delta1: float) FloodFillResult
- schimpy.mesh_volume_tvd.mesh_volume_tvd(mesh, dem, out, cache, log_level, steps, dt, mu, lambda_l2, tv_weight, l2_weight, cfl_target, clip_eps, href, deep_delta, shore_delta, use_default_seeds, seed, smooth_relax_factor, smooth_strip_max, smooth_eps_deg, filter_deep, epsg, shore_csv, shore_shp, shore_floor_filter, shore_floor_window, reg_weight, enforce_floor, profiles, profiles_dir)
TVD-regularized volume tuning (shoreline + floor + TVD).
- schimpy.mesh_volume_tvd.refine_volume_tvd(mesh: SCHISM_mesh, dem_spec: str | Sequence[str] | Mapping[str, Any], out_dir: str, shoreline: ShorelineOptions | None = None, floor: FloorOptions | None = None, tvd: TVDOptions | None = None, cache_dir: str = './.dem_cache', profiles: Sequence[int] | None = None, profiles_dir: str | None = None, logger: Any | None = None) Dict[str, Any]
Execute the end-to-end shoreline+TVD workflow on an already loaded mesh.
- Parameters:
- meshSCHISM_mesh
Mesh to refine. Boundary info is preserved.
- dem_specstr | sequence | mapping
DEM YAML path or object (anything
create_dem_sampler()accepts).- out_dirstr
Where to write diagnostics (shore CSV/shape, profiles).
- shorelineShorelineOptions, optional
If provided, shorelines are detected and used to build a floor.
- floorFloorOptions, optional
Controls floor regularization and enforcement.
- tvdTVDOptions, optional
Algorithm controls; sensible defaults used if None.
- cache_dirstr
Disk cache for DEM sampler.
- profilessequence of int, optional
poly_id list for which to dump triple profiles.
- profiles_dirstr, optional
Directory where profile PNGs go (defaults to
out_dir).- loggerlogging.Logger, optional
Logger instance for logging progress and messages.
- Returns:
- dict
Keys include: - “z”: final node elevations - “shore_csv”: CSV path if shorelines detected - “z0”: initial DEM point samples
- schimpy.mesh_volume_tvd.run_tvd_variational(mesh: SCHISM_mesh, z0: np.ndarray, dem_sampler: Callable[[np.ndarray], np.ndarray], options: FlowOptions = FlowOptions(n_steps=25, dt=None, cfl=0.25, mu=1.0, lambda_l2=1.0, cfl_target=1.0, clipping_eps=None, rel_eta=0.001, max_backtracks=4, tv_weight=1.0, l2_weight=0.2), z_floor: np.ndarray = None, floor_mask: np.ndarray = None, reg_weight: float = 0.0, enforce_floor: bool = False, logger: logging.Logger = None) Dict[str, np.ndarray]
TV-prox + variational L2 descent with backtracking.
The iteration performs an explicit L2 descent step followed by a TV subgradient “prox” step. Acceptance is based on a relative drop in the weighted objective \(w_{tv} TV + w_{l2} J_{vol}\).
- Parameters:
- meshSCHISM_mesh
Mesh object providing
nodes,edges, andelems.- z0ndarray, shape (n_nodes,)
Initial node elevations (meters). Use DEM samples if your incoming mesh has been manipulated away from the DEM and you want a safer start.
- dem_samplercallable
Function mapping XY→depth(+down). See
create_dem_sampler().- optionsFlowOptions, optional
Algorithm options (see
FlowOptions).
- Returns:
- dict
Keys: -
"z": final node elevations. -"history": (k+1, n_nodes) stack of accepted iterates.
- schimpy.mesh_volume_tvd.stage3_single_pass_entry_exit(mesh, in_region_before: ndarray, elem_edges: List[List[int]], edge_mean_d: ndarray, h0_node: ndarray, h0_edge: ndarray, delta0: float, delta1: float, relax_factor: float, strip_nmax: int, angle_eps_deg: float, debug_nodes: List[int] | None = None)
schimpy.metricsplot module
Metrics plot
- schimpy.metricsplot.plot_comparison(*args, style_palette, **kwargs)
Create a simple comparison plot without metrics calculation
- Parameters:
- *args: variable number of TimeSeries
- Returns:
- matplotlib.pyplot.figure.Figure
- schimpy.metricsplot.plot_metrics(obs, tssim, style_palette, **kwargs)
Create a metrics plot
- Parameters:
- *args: variable number of TimeSeries
- Returns:
- matplotlib.pyplot.figure.Figure
schimpy.model_time module
Script to make model date conversion convenient, converting elapsed model seconds to or from dates
- schimpy.model_time.describe_elapsed(times, start, dt=None)
- schimpy.model_time.describe_timestamps(timestamps, start, dt=None)
- schimpy.model_time.elapsed_to_timestamp(input, time_basis, elapsed_unit='s')
Take input dataframe or th file and convert to timestamp, returns dataframe
- schimpy.model_time.file_to_elapsed(infile, start, outpath=None, annotate=False, skip_nan=False)
- schimpy.model_time.file_to_timestamp(infile, start, outpath=None, annotate=False, elapsed_unit='s', time_format='%Y-%m-%dT%H:%M ')
- schimpy.model_time.get_headers(infile, no_index=True)
- schimpy.model_time.multi_file_to_elapsed(input_files, output, start, name_transform='prune_dated')
- schimpy.model_time.prune_dated(name)
- schimpy.model_time.read_elapsed(input)
Take input dataframe or th filename, returns dataframe
If the file contains inline comments (after #), they are stored in a ‘__comment__’ column.
schimpy.nc_bc_compatible module
Check whether SCHISM NetCDF boundary forcing can be reused on another mesh.
- schimpy.nc_bc_compatible.check_nc_bc_compatible(forcing_file, *, reference_hgrid, candidate_hgrid, reference_vgrid, candidate_vgrid, reference_bctides, candidate_bctides, tolerance=0.1, vgrid_version='5.10')
Return incompatibilities between the boundary nodes of two SCHISM meshes.
The file name selects the
bctides.inboundary-condition slot: elevation forelev2D.th.ncand velocity foruv3D.th.nc. Coordinates are compared in open-boundary node order, and vertical level counts are calculated asnvrt - kbp.
schimpy.nml module
- class schimpy.nml.Namelist(d)
Bases:
objectThe Namelist class simply creates an attribute for each key-value pair in the dictionary.
- class schimpy.nml.TopLevelNamelist(d)
Bases:
objectTopLevelNamelist is a class for the top-level elements of the dictionary, and Namelist is a class for all other nested elements. The TopLevelNamelist class creates attributes for each key-value pair in the dictionary and, if the value is itself a dictionary, creates a new Namelist object with the nested dictionary.
- schimpy.nml.map_to_dict(obj)
This function takes an object of type TopLevelNamelist as input and returns a dictionary representation of the object. The function uses the vars built-in function to get a dictionary of attributes and values for the object, and then iterates over the key-value pairs in the dictionary. If the value is an instance of the Namelist class, it recursively maps the Namelist object to a dictionary using the map_to_dict function. If the value is not an instance of the Namelist class, it simply adds the key-value pair to the dictionary. This way, you can easily map an object of type TopLevelNamelist back to a dictionary representation, preserving the structure of the original dictionary.
- schimpy.nml.map_to_object(d)
In this example, TopLevelNamelist is a class for the top-level elements of the dictionary, and Namelist is a class for all other nested elements. The TopLevelNamelist class creates attributes for each key-value pair in the dictionary and, if the value is itself a dictionary, creates a new Namelist object with the nested dictionary. The Namelist class simply creates an attribute for each key-value pair in the dictionary.
The map_to_object function takes a dictionary d as input and returns a new TopLevelNamelist object with the values from d.
This way, you can easily map the dictionary returned by parse_namelist to objects, with different classes for the top-level and nested elements, and access the values in the dictionary as attributes of the objects.
- schimpy.nml.parse(file_content)
Here’s a simple implementation of a parser for the Fortran namelist format If there’s a line starting with !, the parser will store it as the full_line_comment and attach it to the next key-value pair it encounters. If there’s an inline comment starting with !, it will be stored as inline_comment.
For the most part this parser is comment preserving; you might notice some whitespace and blank line(s) being eliminated in the round trip through write method below. NOTE: If a comment block is preceded by a blank line, this fact is now preserved and used when writing back out.
- schimpy.nml.write(namelist_data)
writes out the namelist dictionary from the parse method to a string. The comments are preserved but not the whitespace or indentations.
If a comment block (either namelist-level or per-key full-line comment) was preceded by a blank line in the original file, a single blank line is written before that comment block.
schimpy.nudging module
Created on Tue Jun 8 10:19:56 2021
@author: zzhang To be implemented: other weights function (length scale) from OI in additional to gaussian
- class schimpy.nudging.Nudging(input, envvar=None, **kwargs)
Bases:
objectA class to create schism nudging
- Attributes:
- mesh_gpd
- z
Methods
create_nudging([create_file])read yaml and load mesh grid
concatenate_nudge
construct_weights
create_region_nudging
gaussian_weights
gen_nudge_3dfield
gen_nudge_obs
gen_region_weight
get_nudging_comb
in_vertices
organize_nudging
plot
read_data
reorder_variables
signa
- concatenate_nudge(weights_var, values_var, imap_var, var_newlist, create_file=True)
- construct_weights(attribute, x, y, x0, y0, norm_factor)
- create_nudging(create_file=True)
- Parameters:
- create_fileTYPE, optional
Options to create nudging files. The default is True.
- Returns
- ——-
- None.
- create_region_nudging(region_info)
- static gaussian_weights(xy, xyc, attribute)
- gen_nudge_3dfield(region_info)
- gen_nudge_obs(region_info)
- gen_region_weight(attribute, vertices)
- get_nudging_comb()
- in_vertices(vertices)
- property mesh_gpd
- organize_nudging(weights_comb, values_comb, imap_comb)
- plot(imap, values, **kwargs)
- read_data(data)
- read_yaml()
read yaml and load mesh grid
- static reorder_variables(var_info, var_ordered_list)
- static signa(x1, x2, x3, y1, y2, y3)
- property z
schimpy.param module
- schimpy.param.PARAM_ALIASES: Dict[str, ParamAlias] = {'hotstart_freq': ParamAlias(target='hotstart_freq', kind='property', description='Wall-clock interval between writing hotstart.nc files. Implemented via nhot and nhot_write; nhot_write must be a multiple of the nc_out_file_span or, more directly in schism-speak, nhot must be a multiple of ihfskip ', value_hint="'5d', '12h', or 'none'"), 'hotstart_mode': ParamAlias(target='ihot', kind='raw', description='Hotstart option: 0 = cold start; 1 = restart from hotstart.nc but reset model time to 0; 2 = restart and continue from the time stored in hotstart.nc.', value_hint='0, 1, or 2'), 'nc_out_file_span': ParamAlias(target='nc_stack', kind='property', description='Wall-clock time covered by each history file. Must be a multiple of nc_out_freq. Used to derive ihfskip, the number of (dt) time steps in the file, which is the parameter actually used by SCHISM. nc_out_steps_per_file is an alias that more directly expresses the ihfskip parameter.', value_hint="'1d', '10d', etc."), 'nc_out_steps_per_file': ParamAlias(target='ihfskip', kind='raw', description='Number of model time steps per history file stack (ihfskip). Derived so that ihfskip is a multiple of nspool.', value_hint='integer time steps, e.g. 960'), 'run_nday': ParamAlias(target='run_nday', kind='property', description='Total simulation length in days (maps to CORE::rnday).', value_hint='integer days, e.g. 252'), 'station_freq': ParamAlias(target='station_freq', kind='property', description="Wall-clock interval between samples written to station output files (staout_*). Use 'none' to disable station output.", value_hint="'15min', '1h', etc. or 'none'"), 'station_freq_in_model_steps': ParamAlias(target='nspool_sta', kind='raw', description='Number of model time steps between station outputs (nspool_sta). Only used when station output is enabled (iout_sta != 0).', value_hint='integer time steps')}
Registry of aliases that can be used from code or CLI (set_param)
- class schimpy.param.ParamAlias(target: str, kind: str, description: str, value_hint: str = '')
Bases:
objectMetadata for a user-facing alias.
- Attributes:
- targetstr
Name of the underlying SCHISM parameter or Params property.
- kind{“raw”, “property”}
“raw” -> use Params.__getitem__/__setitem__ with SCHISM name. “property” -> use getattr/setattr on Params (e.g. run_nday, nc_out_freq).
- descriptionstr
Human-readable explanation for help/–help text.
- value_hintstr
Short hint about the value format (e.g. “integer days”, “pandas offset”).
- class schimpy.param.Params(fname, default=None)
Bases:
object- Attributes:
- hotstart_freq
- nc_out_file_span
- nc_out_freq
run_ndayReturn total run length (in days) as an int, based on CORE::rnday.
- run_start
- station_freq
- station_out_freq
Methods
Adjust dt without perturbing variables that depend on it
copy()Return a copy of this Params set
diff(other[, defaults])Compare to another instance of Params
Return total run length (in days) as an int, based on CORE::rnday.
Get tracers types and number of tracers defined in param.nml
process_default(default)Process default parameters
searchfor(key[, section])Search for key.
set_by_name_or_alias(name, value)Set a parameter value using either:
set_freq(name, freq)Set binary output frequency using Pandas offset or string that evaluates as offset
set_run_nday(nday)Set total run length (in days), writing CORE::rnday as an int.
set_station_out_freq(freq)Set station output frequency
update(other[, defaults])Update from another instance of Params in-place
validate()Basic consistency checks for output controls:
get_freq
get_mode
get_run_start
get_station_out_freq
sections
set_hotstart_freq
set_nc_out_file_span
set_nc_out_freq
set_run_start
set_station_freq
to_dataframe
write
- adjust_dt()
Adjust dt without perturbing variables that depend on it
- copy()
Return a copy of this Params set
- diff(other, defaults=False)
Compare to another instance of Params
- Parameters:
- other: str | Params
Can be a string that evaluates to param filename, a Param object
- defaultsbool
Search includes defaults
- Returns:
- diffpd.DataFrame
Data with multi index for section and parameter, including only parameters that are different, including possibly one being absent from one Param set
- get_freq(name)
- get_hotstart_freq()
- get_mode()
- get_nc_out_file_span()
- get_nc_out_freq()
- get_run_nday()
Return total run length (in days) as an int, based on CORE::rnday.
- get_run_start()
- get_station_freq()
- get_station_out_freq()
- get_tracers()
Get tracers types and number of tracers defined in param.nml
- Returns:
- tracersa dict
dictionary whose keys are tracer names defined in param.nml, and values are number of tracers for that tracer type.
- property hotstart_freq
- property nc_out_file_span
- property nc_out_freq
- process_default(default)
Process default parameters
- Parameters:
- defaultstr or Param instance or ‘repo’
If default is ‘repo’, default is the GitHub repo version. If it is a filename, that name is evaluated. If it is a templated version, that version is read. (config part of this not done yet)
- property run_nday
Return total run length (in days) as an int, based on CORE::rnday.
- property run_start
- searchfor(key, section=False)
Search for key. - section == False (default): scan all dict sections; return value - section == True: scan all dict sections; return (section_name, value) - section is a str (e.g., ‘OPT’/’CORE’): only search that section; return value when section == False, else (section_name, value) Raises IndexError if not found.
- sections(defaults=False)
- set_by_name_or_alias(name: str, value: Any) None
Set a parameter value using either:
The original SCHISM name (e.g. ‘ihot’, ‘rnday’, ‘ihfskip’), or
A friendly alias from PARAM_ALIASES (e.g. ‘run_nday’, ‘nc_out_freq’).
Examples
>>> p.set_by_name_or_alias("ihot", 0) >>> p.set_by_name_or_alias("run_nday", 365) >>> p.set_by_name_or_alias("nc_out_freq", "1h")
- set_freq(name, freq)
Set binary output frequency using Pandas offset or string that evaluates as offset
- set_hotstart_freq(freq)
- set_nc_out_file_span(freq)
- set_nc_out_freq(freq)
- set_run_nday(nday)
Set total run length (in days), writing CORE::rnday as an int.
- set_run_start(run_start)
- set_station_freq(freq)
- set_station_out_freq(freq)
Set station output frequency
- Parameters:
- freqoffset or string
Sets output freq for staout files and ensures that output is enabled. If None, frequency will be set using default (or 1 Hour) and station output disabled
- property station_freq
- property station_out_freq
- to_dataframe(defaults=None)
- update(other, defaults=False)
Update from another instance of Params in-place
- Parameters:
- other: str | Params
Can be a string that evaluates to param filename, a Param object
- defaultsbool
Search includes defaults
- validate()
Basic consistency checks for output controls:
nhot_write must be divisible by ihfskip when nhot == 1
if iout_sta != 0, nhot_write must also be divisible by nspool_sta
- write(fname)
- schimpy.param.param_from_template(name)
Returns param based on named template files
- schimpy.param.read_params(fname, default=None)
- schimpy.param.set_param(param_file: Path, pairs: tuple[str, ...], output: Path | None, dry_run: bool)
Set one or more parameters in a SCHISM param.nml file.
PARAM_FILE is the path to the existing param.nml (e.g. param.nml, param.nml.clinic, retro_2013/param.nml).
Remaining arguments must be NAME VALUE pairs:
NAME1 VALUE1 [NAME2 VALUE2 […]]
NAME can be either:
the original SCHISM name (ihot, rnday, ihfskip, nspool_sta, …)
an alias defined in PARAM_ALIASES (run_nday, nc_out_freq, station_out_freq, hotstart_freq, …)
VALUE is a scalar or freq:
integers / floats: 0, 252, 90.0
time freqs: 15min, 1H, 3D (pandas-style offsets)
‘none’ for aliases like hotstart_freq / station_out_freq to disable them
schimpy.plot_default_formats module
Convenient routines to set up and to tweak matplotlib plots.
- schimpy.plot_default_formats.set_color_cycle_dark2()
Set color cycles of Dark2 theme of colorbrewer.org globally. Just calling this function once before finalize a plot is enough to change the color cycles.
- Returns:
- brewer_colors: list
list of the colors
- schimpy.plot_default_formats.set_dual_axes(ax, ts, cell_method='inst')
Create a dual y-axis with unit information in the given time series. It converts SI units to non-SI one.
- Parameters:
- ax: matplotlib.axes
axes of a plot to manage
- ts: vtools.data.TimeSeries
timeseries with unit information
- schimpy.plot_default_formats.set_dual_axes_elev(ax1, filtered=False)
Set dual axes for elevation.
- Parameters:
- ax: matplotlib axes
- schimpy.plot_default_formats.set_dual_axes_salt(ax1, filtered=False)
Set a dual y-axis for salt with a PSU y-axis
- Parameters:
- ax: axis
a Matplotlib axes
schimpy.prepare_schism module
Driver module to prepares input files for a SCHISM run.
- schimpy.prepare_schism.prepare_schism(args, use_logging=True)
schimpy.priority_queue module
- class schimpy.priority_queue.priorityDictionary
Bases:
dictMethods
clear()copy()fromkeys(iterable[, value])Create a new dictionary with keys from iterable and values set to value.
get(key[, default])Return the value for key if key is in the dictionary, else default.
items()keys()pop(key[, default])If the key is not found, return the default if given; otherwise, raise a KeyError.
popitem(/)Remove and return a (key, value) pair as a 2-tuple.
setdefault(key, val)Reimplement setdefault to call our customized __setitem__.
smallest()Find smallest item after removing deleted items from heap.
update([E, ]**F)If E is present and has a .keys() method, then does: for k in E.keys(): D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]
values()- setdefault(key, val)
Reimplement setdefault to call our customized __setitem__.
- smallest()
Find smallest item after removing deleted items from heap.
schimpy.profile_plot module
- schimpy.profile_plot.get_index_bounds()
- schimpy.profile_plot.nearest_neighbor_fill(arr)
- schimpy.profile_plot.profile_plot(x, z, data, ax, context_label=None, add_labels=False, xlabel=None, xmin=None, xmax=None, max_depth=None)
UnTRIM-like profile plot of salinity xmin,xmax are the bounds (in km) of the profile max_depth is the maximum depth, data assumed to be
- schimpy.profile_plot.set_index_bounds(min_station, max_station, max_depth)
- schimpy.profile_plot.vertical_fill(arr)
schimpy.raster_to_nodes module
- schimpy.raster_to_nodes.raster_to_nodes(mesh, nodes_sel, path_raster, bins=None, mapped_values=None, mask_value=None, fill_value=None, band=1, missing_policy='exclude', rasterize_all_touched=True)
Map raster values onto mesh nodes by averaging values over surrounding elements.
This function samples a raster onto an unstructured mesh. Each element polygon is intersected with the raster grid, values are averaged per element, and then element values are aggregated to nodes using an area-weighted mean.
- Parameters:
- meshobject
- Mesh object with the following interface:
mesh.nodes: array of node coordinates (N, >=2), x and y in the first two columns.mesh.elem(i): return node indices for elementi.mesh.get_elems_i_from_node(node_i): return element indices connected to nodenode_i.mesh.areas(): array of element areas indexed by element id.
- nodes_selsequence of int
Node indices at which values will be computed.
- path_rasterstr
Path to a raster file (e.g., GeoTIFF) readable by rasterio.
- binssequence of float, optional
Bin edges used to classify raster values. If provided, the raster values are digitized into bins before aggregation. Length must be
M.- mapped_valuessequence of float, optional
Values assigned to each bin index. Must have length
M+1ifbinsis provided. Typically used to map classes into the interval [0, 1].- mask_valuescalar or sequence of scalars, optional
Additional raster values to treat as missing (in addition to raster NoData). Example:
[0.0, -9999].- fill_valuefloat, optional
Default value for elements with no valid raster pixels in the continuous (non-classified) case. If omitted, defaults to 0.0. Ignored when classification is active.
- bandint, default=1
1-based band index in the raster to sample.
- missing_policy{“exclude”, “as_zero”}, default=”exclude”
Policy for handling missing pixels in the classified case:
"exclude": compute class averages using only valid pixels. Elements with no valid pixels receive the default class value (0.0)."as_zero": missing pixels count as class 0 by including them in the denominator. This dilutes averages toward 0 when coverage is sparse.
Has no effect in the continuous (non-classified) case.
- rasterize_all_touchedbool, default=True
If True, count all raster cells touched by element polygons. If False, count only cells whose centers fall within the polygons.
- Returns:
- ndarray of float
Array of values at each node in
nodes_sel. Length matcheslen(nodes_sel).
Notes
Continuous mode (no
bins): averages raster values directly.Classified mode (with
binsandmapped_values): raster values are digitized into bins, mapped to user-provided class values, then averaged.All aggregation is area-weighted: element values are computed from raster pixels, and node values are weighted by connected element areas.
schimpy.read_output_xyt module
Read outputs from read_output*_xyt and create a neat list of Vtools time series. This module depends on deprecated vtools code and is scheduled for removal
- schimpy.read_output_xyt.read_depth_avg_from_output7b_xyt(fpath, time_basis)
Read output file from read_output7b_xyt and return depth and depth-averaged values in vtools.data.timeseries.
- Parameters:
- fpath: str
master input file name of read_output7b_xyt
- time_basis: datetime.datetime
time base of the outputs
- Returns:
- lists of a set vtools.data.timeseries of depth and depth-averaged values
For scalars, the list has only one set of time series. For vectors, the list has two sets of time series. Each time series has multiple columns of data, and each column is for stations.
schimpy.relocate_source_sink module
Relocate co-located SCHISM source/sink point pairs.
Overview
SCHISM source and sink points that share an element create two problems:
The element can dry, in which case SCHISM silently drops the source.
Co-located withdrawals and discharges short-circuit ambient mixing because the model treats them as cancelling at the same control volume.
This module reads an hgrid.gr3 mesh together with a paired set of source
and sink point YAMLs (one prefix family at a time, delta or suisun)
and offsets every still-co-located pair to nearby distinct elements that
satisfy depth criteria. The deeper of the two chosen elements is assigned to
the sink and the shallower to the source, except that when both candidates
are deep (mean depth >= --random-threshold) the assignment is randomized
so we do not bias the choice on rerun.
Search strategy
The search is in element-ring hops (BFS over element adjacency through shared nodes), not in meters:
--rings-initial(default 3) ring-hops are tried first.If no element satisfies
min-node-depthandmean-depth, the search expands to--rings-fallback(default 10) ring-hops.A physical safety cap
--max-distance(default 100 m) further rejects candidates whose centroid is farther than that radius from the seed centroid (which is the original point when on-grid, or the snapped nearest-element centroid when off-grid).
Off-grid and previously-separated inputs
Each endpoint of every pair is validated independently against the depth
criteria, regardless of whether the pair is co-located or already separated
beyond --separation-tol:
On-grid AND qualifying → coordinate is preserved verbatim.
On-grid but too shallow (
min_node_depth/mean_depthnot met) → the endpoint is relocated via element-ring search to the nearest qualifying element. This matters when a previously-validated source/sink set is re-run on a swapped mesh where prior separation no longer implies prior depth qualification.Off-grid (
mesh.find_elemreturnsNone) → snapped to the nearest element viamesh.find_closest_elems, then the same ring search is applied. The result row carriessnapped_to_mesh: trueand aUserWarningis emitted. Co-located off-grid pairs follow the co-located path; separated pairs with one or both endpoints off-grid relocate each endpoint independently.
A pair therefore becomes status='separated' (true passthrough) only
when both endpoints are on-grid AND qualify with zero ring expansion.
Otherwise it becomes 'relocated' (success) or 'failed'.
Failure handling
A soft failure means no element met the depth criteria within the search
radius, but at least two reachable elements were found. The pair is then
placed at the two deepest elements (sink → deepest, source → second-deepest)
and a min-depth dredge polygon is emitted for each location with
attribute = max(0.5, mean_depth_at_that_element).
A hard failure is the degenerate case of only one reachable element. The pair remains co-located there and a single polygon is emitted.
For separated pairs that fail (e.g. the swap-mesh scenario above), each
failing endpoint contributes its own min-depth polygon, so the user can
dredge each location independently. The pair-level severity is the worse
of the two endpoint severities (hard if either is hard, otherwise
soft).
Outputs
For prefix <P> and --out-dir <D> the run writes:
<D>/<P>_source_relocated.yaml— full source set, drop-in replacement.<D>/<P>_sink_relocated.yaml— full sink set, drop-in replacement.<D>/<P>_relocation_report.yaml— always written; per-pair status, ring-hops used, final coordinates, and (for failures) severity and the mean depth at each chosen element. The canonical sentinel for failures is this file’sfailureslist.<D>/depth_enforcement_<P>_source_sink.yaml— only when failures exist; oneSchismPolygonper failed source / sink location, ready to splice into the project polygon yaml.<D>/<P>_skipped.yaml— only when there were name/pairing skips (entries that did not match(delta|suisun)_(src|sink)_<int>or had no matching partner with the same suffix).
Idempotence
Given the same mesh, parameters, and --seed, the run is deterministic and
idempotent: pairs whose endpoints are already separated and on-grid and
qualify the depth criteria pass through unchanged, so a second run on the
same mesh is a no-op for all successful relocations. Reruns on a different
mesh may legitimately re-trigger relocation or surface new failures.
Dependency convention
The library functions in this module deliberately avoid spatial-stack imports
(geopandas, fiona, GDAL bindings) so that this module can be loaded
by lightweight preprocessor pipelines. Spatial imports are confined to the
optional shapefile-export branch of the CLI; see the maintainer note above
relocate_source_sink_cli().
CLI
Registered as sch relocate_source_sink (and the standalone command
relocate_source_sink).
- exception schimpy.relocate_source_sink.RelocationFailure
Bases:
ExceptionRaised internally when a pair fails the depth criteria within the requested ring radius.
- schimpy.relocate_source_sink.build_pairs(df_source: DataFrame, df_sink: DataFrame, prefix: str) Tuple[List[Tuple[int, str, str]], Dict[str, str]]
Pair sources and sinks by integer suffix for a given
prefix.- Parameters:
- df_sourcepandas.DataFrame
Source points indexed by name (columns
x,y).- df_sinkpandas.DataFrame
Sink points indexed by name (columns
x,y).- prefix{“delta”, “suisun”}
Which family of names to keep. Names from the other family or with unrecognized layouts are reported in
skipped.
- Returns:
- pairslist of tuple
(suffix, source_name, sink_name)for every name pair that shares the prefix and an integer suffix.- skippeddict
Mapping
name -> reasonfor entries excluded from pairing (bad name, wrong prefix/role, or no partner with the same suffix).
- schimpy.relocate_source_sink.read_points_yaml(fpath: str, kind: str) DataFrame
Read a points YAML in either the block or flat layout.
- Parameters:
- fpathstr
Path to the YAML file.
- kind{“sources”, “sinks”}
Which block to extract when the YAML uses the block layout. Ignored for the flat layout.
- Returns:
- pandas.DataFrame
Indexed by point name with float columns
xandy.
- schimpy.relocate_source_sink.relocate_pair(mesh, xs: float, ys: float, xn: float, yn: float, rng: Generator, rings_initial: int = 3, rings_fallback: int = 10, min_node_depth: float = 0.0, mean_depth: float = 1.0, random_threshold: float = 2.0, separation_tol: float = 0.01, always_move_both: bool = True, max_distance: float | None = 100.0) dict
Compute the relocated coordinates for a single source/sink pair.
- Parameters:
- meshschimpy.schism_mesh.SchismMesh
Mesh with positive-down depths in
mesh.nodes[:, 2].- xs, ysfloat
Original source coordinates (mesh units).
- xn, ynfloat
Original sink coordinates (mesh units).
- rngnumpy.random.Generator
Source of randomness for shuffling qualifying candidates and for the deep-water role-assignment tie-breaker.
- rings_initialint, default 3
Initial element-ring search radius (BFS hops).
- rings_fallbackint, default 10
Expanded search radius when the initial radius yields no qualifying elements.
- min_node_depthfloat, default 0.0
Required minimum nodal depth at every node of the chosen element.
- mean_depthfloat, default 1.0
Required mean nodal depth at the chosen element.
- random_thresholdfloat, default 2.0
See
_assign_roles().- separation_tolfloat, default 0.01
Pairs with planar distance above this threshold (m) are considered already separated and pass through unchanged.
- always_move_bothbool, default True
If True, both points relocate to two distinct elements. If False and the seed element qualifies, the source stays at the seed and only the sink moves.
- max_distancefloat or None, default 100.0
Physical cap (mesh units) on how far a candidate centroid may lie from the original co-location point.
Nonedisables the cap.
- Returns:
- dict
Common keys:
status: {‘separated’, ‘relocated’, ‘failed’}source: tuple of float – final(x, y)sink: tuple of float – final(x, y)source_elem,sink_elem: int or Nonerings_used: int
On
'failed'also:severity: {‘soft’, ‘hard’} – ‘hard’ indicates only one reachable element so source and sink remain co-locatedsource_mean,sink_mean: float – mean depths at the two chosen elements
Always present (except for
'separated'where it isFalse):snapped: bool –Trueif the original co-location point lay outside the mesh and was snapped to the nearest element before searching.
- schimpy.relocate_source_sink.relocate_source_sink(hgrid: str, source_yaml: str, sink_yaml: str, prefix: str, out_dir: str = '.', rings_initial: int = 3, rings_fallback: int = 10, min_node_depth: float = 0.0, mean_depth: float = 1.0, random_threshold: float = 2.0, separation_tol: float = 0.01, always_move_both: bool = True, seed: int = 42, max_distance: float | None = 100.0, out_suffix: str = '_adj') dict
End-to-end driver: read inputs, relocate co-located pairs, write outputs.
- Parameters:
- hgridstr
Path to the SCHISM
hgrid.gr3mesh (positive-down depth).- source_yaml, sink_yamlstr
Paths to the paired source and sink YAMLs. Either the
sources:/sinks:block layout or a flatname: [x, y]mapping is accepted.- prefix{“delta”, “suisun”}
Family of names processed in this run; the other family is sent to the skipped report.
- out_dirstr, default “.”
Output directory; created if missing.
- rings_initial, rings_fallbackint
Element-ring search radii (BFS hops). See
relocate_pair().- min_node_depth, mean_depthfloat
Depth criteria. See
relocate_pair().- random_thresholdfloat
Mean-depth threshold above which role assignment is randomized.
- separation_tolfloat
Distance threshold (m) above which a pair is treated as already separated and passes through unchanged.
- always_move_bothbool
Whether to always move both points to distinct elements.
- seedint, default 42
RNG seed (
numpy.random.default_rng) for repeatable runs.- max_distancefloat or None, default 100.0
Physical cap (m) on relocation distance.
- out_suffixstr, default “_adj”
Suffix appended to
prefixin the output filenames, e.g.delta_source_adj.yaml. Change to"_relocated"to keep the previous naming convention.
- Returns:
- dict
Result with the following keys:
counts– dict with keysseparated,relocated,failed,failed_soft,failed_hardn_pairs,n_skipped– intsfailures– list off"{prefix}_pair_{n}"stringssource_yaml,sink_yaml,report_yaml– always-present output pathspolygon_yaml– path orNoneskipped_yaml– path orNonesummary–pandas.DataFramewith one row per processed pair (status, severity, depths, final coordinates)
Notes
The canonical sentinel for failures is
result['failures'](orresult['counts']['failed'] > 0). The<prefix>_relocation_report.yamlfile is always written and contains the same per-pair summary.
- schimpy.relocate_source_sink.write_points_yaml(fpath: str, df: DataFrame, header: str = '') None
Write a flat
name: [x, y]YAML mirroring the input convention.- Parameters:
- fpathstr
Output YAML path.
- dfpandas.DataFrame
Points indexed by name with float columns
xandy. Coordinates are rounded to 4 decimals on write.- headerstr, default “”
Optional comment line(s) to prepend to the file verbatim. Each line should begin with
#.
schimpy.sav_density_raster module
Raster-based sampling utilities for submerged and emergent vegetation attributes.
This module supports two related preprocessing tasks for SCHISM nodes:
Assign a vegetation density value from categorical raster products.
Assign a vegetation canopy height from categorical raster products.
The raster products are treated as integer-valued thematic layers rather than continuous scalar fields. This distinction is important.
For density, the algorithm uses two rasters:
a vegetation type raster
a vegetation density-bin raster
The vegetation type at a node is taken from the pixel containing the node. The density-bin at a node is also taken from the pixel containing the node. A local stencil, typically 3x3 pixels, is then sampled around the node. Within that stencil, only pixels that match both the center vegetation type and the center density bin are considered “like-classified” and contribute to the final density value. This avoids averaging unlike categories together.
For height, the categorical rasters are sampled with 1x1 support. Height is derived from the node’s vegetation type, the node’s density bin, and the node depth. No neighborhood averaging is applied to height because the type and density rasters are categorical and averaging categories produces ambiguous values.
Coverage behavior is controlled by strict:
strict=Trueraises an exception when requested samples fall outside raster coverage.strict=Falsereplaces uncovered or nodata samples with zero. In practice, this means “no vegetation” for the categorical products used here.
The module is intended for use from SCHISM preprocessing YAML expressions, but the lower-level functions are also suitable for direct testing and scripted use.
Notes
The algorithms in this module assume:
the vegetation rasters use integer category codes;
type code 0 means no vegetation;
density bin 0 means no density / no vegetation;
mesh node
zis positive downward when height or depth-based screening is applied.
The density mapping from (type, density_bin) to final density value is
supplied either as a CSV file or as a 2D lookup table.
- schimpy.sav_density_raster.compute_density(xs, ys, z, veg_type_tif, veg_density_tif, *, mapping, stencil=3, depth_limit=3.0, strict=False, chunk_size=200000, return_debug=False)
Compute vegetation density at points from categorical vegetation rasters.
- Parameters:
- xs, ysarray-like of float
Point coordinates in the raster coordinate system.
- zarray-like of float
Node depth values. Positive values indicate deeper nodes.
- veg_type_tifstr or path-like
Vegetation type raster.
- veg_density_tifstr or path-like
Vegetation density-bin raster.
- mappingstr, path-like, or 2D array-like
Mapping from
(type, density_bin)to final density. This may be a CSV file or an in-memory lookup table.- stencilint or (int, int), optional
Neighborhood size used for the local density average.
- depth_limitfloat, optional
Nodes with
z > depth_limitare assigned density 0 after raster sampling and lookup.- strictbool, optional
Controls how uncovered raster samples are handled.
- chunk_sizeint, optional
Number of points processed per chunk during raster sampling.
- return_debugbool, optional
If True, return both the density array and a dictionary containing the sampled center classes, stencil classes, like-mask, depth, and lookup table.
- Returns:
- densndarray of float, shape (n,)
Density at each point.
- debugdict, optional
Returned only when
return_debug=True.
- Raises:
- ValueError
Raised when
xs,ys, andzdo not have the same shape, when stencil dimensions are invalid, or when mapping inputs are invalid.
Notes
The raster sampling and the density calculation are intentionally separated:
vegetation type and density bin are sampled as categorical integers;
the final density value is computed from the lookup table and the like-classified stencil average.
This function is appropriate when coordinates are already available as arrays. For mesh-based workflows, use
sav_density().
- schimpy.sav_density_raster.compute_height(z, center_type, center_bin, *, sav_fractions=(0.0, 0.3, 0.65, 0.9), sav_min_height=0.0, sav_max_height=None, emergent_height=100.0, floating_height=100.0, return_debug=False)
Compute canopy height from node depth and node-centered vegetation classes.
- Parameters:
- zarray-like of float, shape (n,)
Node depth values. Positive values indicate deeper nodes.
- center_typearray-like of int, shape (n,)
Vegetation type at the node center.
- center_binarray-like of int, shape (n,)
Density bin at the node center.
- sav_fractionssequence of float, optional
Multipliers used for submerged aquatic vegetation, indexed by density bin. For example,
(0.0, 0.3, 0.65, 0.9)means light, medium, and heavy SAV heights are 30, 65, and 90 percent of node depth.- sav_min_heightfloat, optional
Lower bound applied to submerged vegetation height after the fraction rule is applied.
- sav_max_heightfloat or None, optional
Upper bound applied to submerged vegetation height after the fraction rule is applied. If None, no upper bound is imposed.
- emergent_heightfloat, optional
Height assigned to emergent vegetation.
- floating_heightfloat, optional
Height assigned to floating vegetation.
- return_debugbool, optional
If True, return both the height array and a dictionary of intermediate masks and inputs.
- Returns:
- heightndarray of float, shape (n,)
Canopy height at each node.
- debugdict, optional
Returned only when
return_debug=True.
- Raises:
- ValueError
Raised when input shapes do not match, when negative class codes are supplied, or when
sav_fractionsdoes not cover the supplied density bins.
Notes
Height is derived from node-centered classes using discrete rules.
- schimpy.sav_density_raster.compute_like_class_mean_density(center_type, center_bin, type_stencil, bin_stencil, lut)
Compute vegetation density from center classes and local stencil samples.
- Parameters:
- center_typendarray of int, shape (n,)
Vegetation type at the node center.
- center_binndarray of int, shape (n,)
Density bin at the node center.
- type_stencilndarray of int, shape (n, k)
Vegetation type sampled over the local stencil for each node.
- bin_stencilndarray of int, shape (n, k)
Density bin sampled over the local stencil for each node.
- lutndarray of float, shape (n_type, n_bin)
Lookup table mapping
(type, density_bin)to final density values.
- Returns:
- densndarray of float, shape (n,)
Density assigned to each node.
- likendarray of bool, shape (n, k)
Mask indicating which stencil cells matched both the center vegetation type and the center density bin.
- Raises:
- ValueError
Raised when the input array dimensions do not align, when negative class codes are supplied, or when class codes exceed the bounds of
lut.
Notes
This function implements the central density algorithm in the module.
The node is first classified by its center vegetation type and center density bin. A stencil around the node is then examined. Only stencil cells that match both the center type and the center density bin are included in the neighborhood average.
This “like-classified” average avoids mixing unlike vegetation classes. For example, a node classified as submerged vegetation with medium density is not influenced by adjacent floating or emergent pixels, and it is not influenced by submerged pixels in a different density bin.
Nodes with either
center_type == 0orcenter_bin == 0are treated as inactive and assigned density 0.The lookup table is applied to stencil classes before averaging. This makes the local average an average of final density values rather than an average of raw density-bin integers.
- schimpy.sav_density_raster.sample_center_pixels(xs, ys, veg_type_tif, veg_density_tif, *, strict=False)
Sample vegetation type and density-bin at point centers using 1x1 support.
- Parameters:
- xs, ysarray-like of float
Point coordinates in the raster coordinate system.
- veg_type_tifstr or path-like
Vegetation type raster.
- veg_density_tifstr or path-like
Vegetation density-bin raster.
- strictbool, optional
Controls how uncovered raster samples are handled.
- Returns:
- type_centerndarray of int, shape (n,)
Vegetation type at each point.
- dens_centerndarray of int, shape (n,)
Density bin at each point.
Notes
This is a convenience function for workflows where only the center class is needed.
It is the appropriate sampling method for categorical inputs used directly as class labels, for example canopy-height logic based on node type and node density bin. In that setting, averaging categories over a neighborhood would blur category boundaries and produce values with no categorical meaning.
- schimpy.sav_density_raster.sample_raster_stencil_int(xy, raster_file, *, stencil=(3, 3), nan_to=0, strict=False, chunk_size=200000)
Sample an integer-valued raster at node centers and over a local stencil.
- Parameters:
- xyndarray, shape (n, 2)
Node coordinates in the raster coordinate system, given as
(x, y).- raster_filestr or path-like
Path to the raster to sample.
- stencilint or (int, int), optional
Stencil size centered on the containing pixel. An integer gives a square stencil. A two-element iterable gives
(n_rows, n_cols). Dimensions must be odd.- nan_toint, optional
Integer value used in place of nodata or uncovered samples when
strict=False.- strictbool, optional
Controls behavior outside raster coverage.
If True, the function raises an exception when a requested sample cannot be represented by the raster.
If False, uncovered center pixels and uncovered stencil cells are replaced with
nan_to.
- chunk_sizeint, optional
Number of points processed per chunk.
- Returns:
- center_outndarray of int, shape (n,)
Raster values for the pixel containing each point.
- stencil_outndarray of int, shape (n, sy*sx)
Flattened stencil values in row-major order for each point.
- rows_outndarray of int, shape (n,)
Raster row index of the containing pixel for each point.
- cols_outndarray of int, shape (n,)
Raster column index of the containing pixel for each point.
- Raises:
- ValueError
Raised when
xydoes not have shape(n, 2), when stencil dimensions are invalid, or when raster coverage is insufficient andstrict=True.
Notes
Sampling is based on the pixel containing the point, not bilinear interpolation. This is intentional.
The rasters used here are thematic rasters with integer class codes. Interpolating between codes such as “submerged”, “floating”, and “emergent” would produce values with no categorical meaning. The correct operation for these products is to identify the containing pixel and then inspect neighboring pixels explicitly.
The returned stencil is flattened in row-major order. For a 3x3 stencil, index 4 is the center cell.
- schimpy.sav_density_raster.sample_stencil(xs, ys, veg_type_tif, veg_density_tif, *, stencil=3, strict=False)
Sample vegetation type and density-bin stencils around point centers.
- Parameters:
- xs, ysarray-like of float
Point coordinates in the raster coordinate system.
- veg_type_tifstr or path-like
Vegetation type raster.
- veg_density_tifstr or path-like
Vegetation density-bin raster.
- stencilint or (int, int), optional
Neighborhood size centered on the containing pixel.
- strictbool, optional
Controls how uncovered raster samples are handled.
- Returns:
- type_stencilndarray of int, shape (n, sy*sx)
Flattened type stencil for each point.
- dens_stencilndarray of int, shape (n, sy*sx)
Flattened density-bin stencil for each point.
Notes
This is mainly a convenience function for testing and inspection. It is useful when verifying that a node sees the expected local categorical neighborhood.
The flattening order is row-major. For a 3x3 stencil, the center cell is index 4.
- schimpy.sav_density_raster.sav_density(mesh, nodes_sel, veg_type_tif, veg_density_tif, *, stencil=3, depth_limit=3.0, mapping, strict=False, chunk_size=200000, return_debug=False)
Compute vegetation density for a selected set of mesh nodes.
- Parameters:
- meshobject
Mesh-like object providing
mesh.nodes[:, :3]asx, y, z.- nodes_selarray-like of int
Indices of nodes to sample.
- veg_type_tifstr or path-like
Vegetation type raster.
- veg_density_tifstr or path-like
Vegetation density-bin raster.
- stencilint or (int, int), optional
Neighborhood size used for the local density average.
- depth_limitfloat, optional
Nodes deeper than this threshold are assigned density 0.
- mappingstr, path-like, or 2D array-like
Mapping from
(type, density_bin)to final density.- strictbool, optional
Controls how uncovered raster samples are handled.
- chunk_sizeint, optional
Number of points processed per chunk during raster sampling.
- return_debugbool, optional
If True, return both the density array and a dictionary of intermediate values.
- Returns:
- densndarray of float, shape (n,)
Density assigned to the selected nodes.
- debugdict, optional
Returned only when
return_debug=True.
Notes
This is the YAML-facing wrapper used in SCHISM preprocessing. It extracts the selected node coordinates from the mesh and delegates the calculation to
compute_density().Typical use from preprocessing YAML is to call this function directly in an
attributeexpression and pass the mapping as a CSV file path.
- schimpy.sav_density_raster.sav_height(mesh, nodes_sel, veg_type_tif, veg_density_tif, *, sav_fractions=(0.0, 0.3, 0.65, 0.9), sav_min_height=0.0, sav_max_height=None, emergent_height=100.0, floating_height=100.0, strict=False, return_debug=False)
Compute canopy height for selected mesh nodes from categorical vegetation rasters.
- Parameters:
- meshobject
Mesh-like object providing
mesh.nodes[:, :3]asx, y, z.- nodes_selarray-like of int
Indices of nodes to sample.
- veg_type_tifstr or path-like
Vegetation type raster.
- veg_density_tifstr or path-like
Vegetation density-bin raster.
- sav_fractionssequence of float, optional
Multipliers applied to depth for submerged vegetation, indexed by density bin.
- sav_min_heightfloat, optional
Lower bound for submerged vegetation height.
- sav_max_heightfloat or None, optional
Upper bound for submerged vegetation height.
- emergent_heightfloat, optional
Height assigned to emergent vegetation.
- floating_heightfloat, optional
Height assigned to floating vegetation.
- strictbool, optional
Controls how uncovered raster samples are handled.
- return_debugbool, optional
If True, return both the height array and a dictionary of intermediate values.
- Returns:
- heightndarray of float, shape (n,)
Height assigned to the selected nodes.
- debugdict, optional
Returned only when
return_debug=True.
Notes
This function samples the type and density-bin rasters with 1x1 support and then computes height from those node-centered classes. This is intentional.
The vegetation rasters are categorical. For canopy height, the correct question is “what class does this node see?” rather than “what is the average category nearby?” Averaging categories over a larger support would blur boundaries and is not appropriate for this use.
This function is the height analogue of
sav_density(), but unlike density it does not use a neighborhood average.
- schimpy.sav_density_raster.sav_node_classes(mesh, nodes_sel, veg_type_tif, veg_density_tif, *, strict=False)
Return the vegetation type and density-bin seen at selected mesh nodes.
- Parameters:
- meshobject
Mesh-like object providing
mesh.nodes[:, :3]asx, y, z.- nodes_selarray-like of int
Indices of nodes to sample.
- veg_type_tifstr or path-like
Vegetation type raster.
- veg_density_tifstr or path-like
Vegetation density-bin raster.
- strictbool, optional
Controls how uncovered raster samples are handled.
- Returns:
- type_centerndarray of int, shape (n,)
Vegetation type at each selected node.
- bin_centerndarray of int, shape (n,)
Density bin at each selected node.
Notes
This helper exposes the node-centered categorical values directly. It is useful when checking which class a node receives, and it is the natural basis for canopy-height calculations where classes should remain discrete.
schimpy.schism_hotstart module
Module for creating a schism hotstart file
Options:
Centering:
node2D: node (2D surface)
node3D: node at whole level
edge: edge center at whole level (mainly for horizontal velocty)
elem: element center at whole level (mainly for vertical velocity)
prism: prism center (for tracers); three different variables tr_el, tr_nd,
- tr_el need to be generated for the hotstart.nc file.
tr_nd = tr_nd0 (on nodes)
tr_el (on element at middle level)
Initializer:
text_init: 2D map input from either *.prop or *.ic files; require input text file.
simple_trend: can either be a number or an equation that depends on x (lat) and y(lon). e.g,: 0.97 + 1.e-5*x
patch_init: regional-based method. Polygon shapefile input required.
extrude_casts: 3D nearest neighbourhood interpolation based on Polaris cruise transects.
obs_points: interpolated from 1D (time series of) observational points.
hotstart_nc: initialize with a previous hotstart output from the same or a different mesh.
schout_nc: initialize with a schism output snapshot.
- Required data files:
param.in
hgrid.gr3
vgrid.in
hotstart.yaml and input files defined in the yaml file.
- class schimpy.schism_hotstart.VariableField(v_meta, vname, mesh, depths, date, crs, tr_mname, hotstart, hotstart_ini=None, **kwargs)
Bases:
objectA class initializing each varaible for the hotstart file
Methods
define_new_grid(mesh)Generating hgrid and vgrid based on centering option for a new grid
elem2node_values(vmap)equation converting 2D values on element to nodes.
extrude_casts([ini_meta, inpoly])get_grid()Getting the number and coordinates of horizontal nodes/elems/edges for different centering options and return them as grid.
Options for input file initializers The input initializer overwrites self.initializer
map_to_3D(v_2d, nz)polulate the 2D map values to 3D by applying the uniform values over dpeth.
obs_points([ini_meta, inpoly])obs_file includes Lat, Lon, and values for the variable.
patch_initializer_options(initializer)Options for patch initializers The input initializer overwrites self.initializer
simple_trend([ini_meta, inpoly])Assigning a spatially uniformed value or an equation that's dependent on lat, lon
text_init([ini_meta, inpoly])Reading 2D map from either a .prop (on element) or a .ic (on node) file If a prop file is read, the element values will need to be converted to node values.
GenerateField
create_dataarray
get_key
get_value
hotstart_nc
interp_from_mesh
node2elem_values
patch_init
schout_nc
var_centering
- GenerateField()
- create_dataarray(var)
- define_new_grid(mesh)
- Generating hgrid and vgrid based on centering option for a new grid
Parameters
- elem2node_values(vmap)
equation converting 2D values on element to nodes.
- extrude_casts(ini_meta=None, inpoly=None)
- get_grid()
Getting the number and coordinates of horizontal nodes/elems/edges for different centering options and return them as grid.
- classmethod get_key(dict_obj)
- classmethod get_value(dict_obj)
- hotstart_nc(ini_meta=None, inpoly=None)
- initializer_options()
Options for input file initializers The input initializer overwrites self.initializer
- interp_from_mesh(hgrid_fn, vin, vgrid_fn=None, vgrid_version='5.10', inpoly=None, dist_th=None, method=None, src_wet=None, source_idry=None, novel_node_tol=0.001, max_blw_bed=None)
- classmethod map_to_3D(v_2d, nz)
polulate the 2D map values to 3D by applying the uniform values over dpeth.
- node2elem_values(vmap)
- obs_points(ini_meta=None, inpoly=None)
obs_file includes Lat, Lon, and values for the variable.
- patch_init(poly_fn=None)
- patch_initializer_options(initializer)
Options for patch initializers The input initializer overwrites self.initializer
- schout_nc(var, ini_meta=None, inpoly=None)
- simple_trend(ini_meta=None, inpoly=None)
Assigning a spatially uniformed value or an equation that’s dependent on lat, lon
- text_init(ini_meta=None, inpoly=None)
Reading 2D map from either a .prop (on element) or a .ic (on node) file If a prop file is read, the element values will need to be converted to node values.
- var_centering()
- schimpy.schism_hotstart.describe_tracers(param_nml, modules=['HYDRO'])
return the number of tracers, the sequence of the tracers and a list of tracer names based on the input list of modules and corresponding input files.
Availabel modules are:
T (default)
S (default)
GEN
AGE
SED3D: SED
EcoSim: ECO
ICM: ICM and/or ICM_PH
CoSiNE: COSINE
Feco: FIB
TIMOR
FABM
The script is mainly translated from schism_ini.F90
- class schimpy.schism_hotstart.hotstart(input=None, modules=None, crs=None, envvar=None)
Bases:
objectA class to generate hotstart initial condition for SCHISM
Methods
get_mesh(hgrid_fn[, vgrid_fn, vgrid_version])Load and cache a SCHISM mesh (hgrid+vgrid), checking consistency between horizontal and vertical grids.
map the hotstart variable to the variable names required by SCHISM hotstart file.
read yaml and load mesh grid
Set wet/dry flags from elevation and compatible initializer flags.
close_hotstart_cache
create_hotstart
generate_3D_field
get_hotstart_data
initialize_netcdf
- close_hotstart_cache()
- create_hotstart(write_visit_nc=False, visit_outname='schout_hotstart.nc', visit_hgrid_fn=None, visit_vgrid_fn=None, visit_vgrid_version=None)
- generate_3D_field(variable)
- get_hotstart_data(path)
- get_mesh(hgrid_fn, vgrid_fn=None, vgrid_version=None)
Load and cache a SCHISM mesh (hgrid+vgrid), checking consistency between horizontal and vertical grids.
- Parameters:
- hgrid_fnstr
Path to the hgrid (horizontal mesh) file.
- vgrid_fnstr or None
Path to the vgrid (vertical grid) file. None if not applicable.
- vgrid_versionint or None
Version of vgrid format if needed.
- Returns:
- meshSchismMesh
Fully loaded and validated mesh object.
- initialize_netcdf(default_turbulence=True)
- map_to_schism()
map the hotstart variable to the variable names required by SCHISM hotstart file.
- read_yaml()
read yaml and load mesh grid
- wet_dry_check()
Set wet/dry flags from elevation and compatible initializer flags.
- schimpy.schism_hotstart.hotstart_to_outputnc(hotstart_fn, init_date, hgrid_fn='hgrid.gr3', vgrid_fn='vgrid.in', vgrid_version=5.8, outname='hotstart_out.nc')
convert hotstart.nc to schism output nc file format that can be read by VisIt.
- schimpy.schism_hotstart.num(s)
- schimpy.schism_hotstart.prepare_schism_hotstart_output(dataset)
Return a model-facing dataset matching SCHISM’s hotstart schema.
- schimpy.schism_hotstart.project_mesh(mesh, new_crs)
- schimpy.schism_hotstart.read_hotstart()
Mock method to read existing hotstart
- schimpy.schism_hotstart.read_param_nml(nml_fn)
read param.in file and generate a dict object with key, value pairs for all the parameters
- schimpy.schism_hotstart.redirect_to_wet_donors(src_xy, src_wet, tgt_xy, indices, dist, tol)
Point target nodes with no source counterpart at the nearest wet source node.
A target node whose nearest source node lies farther than
tolhas no counterpart in the source grid, as happens where a grid is extended into a restoration site. Its donor is reselected from wet source nodes only, because the state stored at a dry source node is vestigial and would otherwise be carried into the new area.- Parameters:
- src_xyarray_like
Source node coordinates, shape (n_source, 2).
- src_wetarray_like of bool
True where the source node holds a meaningful water column.
- tgt_xyarray_like
Target node coordinates, shape (n_target, 2).
- indicesarray_like of int
Donor index into the source nodes for each target node.
- distarray_like of float
Distance from each target node to its current donor.
- tolfloat
Identity tolerance, not a physical distance.
- Returns:
- indicesnumpy.ndarray
Donor indices with novel nodes reassigned. Nodes within
tolkeep the donor they already had, even if that donor is dry.- novelnumpy.ndarray of bool
True where the node had no source counterpart.
- Raises:
- ValueError
If no source node is wet.
schimpy.schism_input module
This module handles SCHISM input data which are a mesh, structures, and sources/sinks. @author: Kijin Nam, knam@water.ca.gov
- class schimpy.schism_input.SchismInput(logger=None)
Bases:
object- Attributes:
- mesh
- nudging
- sources
- structures
- time_start
Methods
add_structure
clear_structures
n_sinks
n_sources
n_structures
- add_structure(value)
- clear_structures()
- property mesh
- n_sinks()
- n_sources()
- n_structures()
- property nudging
- property sources
- property structures
- property time_start
schimpy.schism_linestring module
Line String data based on Shapely LineStrings
- class schimpy.schism_linestring.LineString(coordinates=None, prop=None)
Bases:
LineString- Attributes:
- prop
Methods
__call__(*args, **kwargs)Call self as a function.
- property prop
- class schimpy.schism_linestring.LineStringIo
Bases:
objectMethods
read
write
- read(**kwargs)
- write(**kwargs)
- class schimpy.schism_linestring.LineStringIoFactory
Bases:
objectMethods
get_reader
get_writer
- get_reader(name)
- get_writer(name)
- registered_readers = {'shp': 'LineStringShapefileReader', 'yaml': 'LineStringYamlReader'}
- registered_writers = {'shp': 'LineStringShapefileWriter', 'yaml': 'LineStringYamlWriter'}
- class schimpy.schism_linestring.LineStringShapefileReader
Bases:
LineStringIoMethods
read(fpath[, preserve_zdim])write
- read(fpath, preserve_zdim=False, **kwargs)
- Parameters:
- fpath: str
input file name
- preserve_zdim: bool, optional
Whether to preserve the Z dimension in coordinates if present. Default is False (discard Z dimension and keep 2D).
- Returns:
- lines
list of LineStrings
- class schimpy.schism_linestring.LineStringShapefileWriter
Bases:
LineStringIoMethods
write(fpath, lines[, spatial_reference, ...])read
- write(fpath, lines, spatial_reference=None, driver_name=None, **kwargs)
- Parameters:
- fpath: str
output file name
- lines: array of schism_linestring.LineString
list of LineStrings
- spatial_reference: osgeo.osr.SpatialReference
- default: NAD83, UTM zone 10N, meter
- todo: reference needs to be in api right now hard to use
- class schimpy.schism_linestring.LineStringYamlReader
Bases:
LineStringIoMethods
read
write
- read(fpath, envvar=None, preserve_zdim=False, **kwargs)
- class schimpy.schism_linestring.LineStringYamlWriter
Bases:
LineStringIoWrite line strings from a YAML file
Methods
read
write
- write(fpath, lines)
- schimpy.schism_linestring.read_linestrings(fpath, envvar=None)
- schimpy.schism_linestring.write_linestrings(fpath, lines)
- Parameters:
- fpath: str
output file name
- lines: array of schism_linestring.LineString
list of LineStrings
schimpy.schism_mesh module
3D Version of schism_mesh
- schimpy.schism_mesh.BoundaryType
alias of
Enum
- class schimpy.schism_mesh.SchismMesh
Bases:
TriQuadMeshMemory model of 3D SCHISM mesh
- Attributes:
boundariesAn array of the boundary information
edgesGet the array of edges
elemsArray of node indexes of all elements.
- n_vert_levels
- node2elems
nodesNode array consisting of three-dimensional coordinates of each node.
- vmesh
zGet the elevation of levels at all the nodes
Methods
add_boundary(nodes, btype[, comment])Add one boundary.
allocate(n_elems, n_nodes)Allocate memory for nodes and elems
areas()Get the array of element areas
build_edgecenters()Build centers of sides
build_edges_from_elems([shift])Build edge array from the elements.
build_elem_balls()Build balls of elements around each node
build_z([elev])Build vertical coordinates
Get a Numpy array of element centroids Returns ------- numpy.ndarray
Delete all the current boundary information
compare(mesh)Compare the mesh with another
edge_len()Get a NumPy array of edge lengths The ordering of the edges is decided from triquadmesh.
elem(elem_i)Get connectivity of an element
element2edges(elem_i)Get edge indexes of the give element index
Fill land and island boundaries for boundary edges not assigned to boundaries.
Fill open boundaries for boundary edges not assigned to boundaries.
find_closest_elems(pos[, count])Find indexes of the closet elems with the given position.
find_closest_nodes(pos[, count, boundary])Returns the count closest nodes to the given node in 2D space.
find_edge(nodes[, direction])Find an edge index with the two given node indexes.
find_elem(pos)Find a element index from a coordinate pos = A coordinate (2D) return = element index
find_intersecting_elems_with_line(line_segment)Format of the line segment: start_x, start_y, end_x, end_y
find_neighbors_on_segment(line_segment)Find elements on the line_segment and neighbors that are all to the left (downstream) Format of the line segment: start_x, start_y, end_x, end_y Returns a list of elements on the segment and a list of neighbors.
find_nodes_in_box(box)Find nodes in a bounding box.
find_two_neighboring_node_paths(line_segment)Find two neighboring node paths around a line_segment
Get the array of the centers of the element
Get the array of the centers of the sides
Get the array of each 3-d nodes
get_edges_from_node(node_i)Get edge indexes related to node_i
get_elems_i_from_node(node_i)Get the ball of elements around a node, node_i
get_neighbor_nodes(node_i)Get neighboring node indexes from the given node index.
is_elem_on_boundary(elem_i)Check if the given element with index elem_i is on the boundary
mark_elem_deleted(elem_i)Mark an element as deleted or invalid.
merge all the meshes to create a boundary polygon
n_boundaries([btype])Get the number of boundaries.
n_edges()Get the total number of edges.
n_elems()Get the total number of elements.
n_nodes()Get the total number of nodes.
n_total_boundary_nodes(btype)Get the total node boundary of a given type
node(node_i)Selects a single node
plot_elems(var[, ax, inpoly, plot_nan])Plot variables (1D array on element) based on SCHISM mesh grid.
plot_mesh_boundary([ax, edgecolor])Plot the edge of the computational grid.
plot_open_boundaries([ax, edgecolor])Plot the open boundaries of the computational grid.
renumber()removes duplicate elems and nodes that are not referenced by any element, as well as elems that have been deleted (==-1) This function is lifted and modified slightly from Rusty's code.
set_elem(index, connectivity)Set element connectivity information.
set_node(index, coords)Set one node information.
shortest_path(n1, n2[, boundary_only])Dijkstra on the edge graph from node n1 to n2.
to_geopandas([feature_type, crs, shp_fn, ...])Create mesh polygon and points as geopandas dataframe and shapefiles if Shap_fn file name is supplied.
trim_elems(paths[, left])Given a path, trim all elems to the left of it.
trim_to_left_of_mesh(line_segments)Trim mesh using line_segments.
plot_edges
plot_nodes
- add_boundary(nodes, btype, comment=None)
Add one boundary.
- Parameters:
- nodes: an array of integer
array of inter node indexes in the boundary path
- btype: integer
an integer constant for boundary types.
- comment: optional, string
- areas()
Get the array of element areas
- Returns:
- numpy.ndarray
- property boundaries
An array of the boundary information
- Getter:
Get the array of the boundary information
- build_z(elev=0.0)
Build vertical coordinates
- Returns:
- numpy.ndarray
- centroids()
Get a Numpy array of element centroids Returns ——- numpy.ndarray
- clear_boundaries()
Delete all the current boundary information
- edge_len()
Get a NumPy array of edge lengths The ordering of the edges is decided from triquadmesh. Look edges properties to find out connectivity
- Returns:
- numpy.ndarray
- fill_land_and_island_boundaries()
Fill land and island boundaries for boundary edges not assigned to boundaries.
- fill_open_boundaries()
Fill open boundaries for boundary edges not assigned to boundaries.
- find_two_neighboring_node_paths(line_segment)
Find two neighboring node paths around a line_segment
- Parameters:
- line_segment: array-like
two end points of the line segment, start_x, start_y, end_x, end_y
- Returns:
- up_path: array of int
upstream side of node paths
- down_path: array of int
downstream side of node paths
- get_centers_of_elements()
Get the array of the centers of the element
- Returns:
- numpy.ndarray
Array of 2-d coordinates of the centers of the elements The shape of the array is (n_elems, 2)
- get_centers_of_sides()
Get the array of the centers of the sides
- Returns:
- numpy.ndarray
Array of 3-d coordinates of the centers of the elements The shape of the array is (n_elems, 2)
- get_coordinates_3d()
Get the array of each 3-d nodes
- Returns:
- numpy.ndarray
Array of 3-d coordinates The shape of the array is (n_nodes * n_vert_levels, 3) The points below the most bottom level will be filled with the elevation of the the bottom level
- merged_mesh()
merge all the meshes to create a boundary polygon
- n_boundaries(btype=None)
Get the number of boundaries. If a boundary type is given, it counts only boundaries with the corresponding type.
- Parameters:
- btype: integer, optional
Type of the boundary.
- n_total_boundary_nodes(btype)
Get the total node boundary of a given type
- Parameters:
- btype: integer
Type of the boundary.
- property n_vert_levels
- plot_edges(var, ax=None, size=500, inpoly=None, **kwargs)
- plot_elems(var, ax=None, inpoly=None, plot_nan=False, **kwargs)
Plot variables (1D array on element) based on SCHISM mesh grid. if var is None,just plot the grid.
- plot_mesh_boundary(ax=None, edgecolor='k', **kwargs)
Plot the edge of the computational grid.
- plot_nodes(var, ax=None, inpoly=None, plot_nan=False, **kwargs)
- plot_open_boundaries(ax=None, edgecolor='blue', **kwargs)
Plot the open boundaries of the computational grid.
- to_geopandas(feature_type='polygon', crs=None, shp_fn=None, node_values=None, elem_values=None, edge_values=None, value_name=None, create_gdf=True)
Create mesh polygon and points as geopandas dataframe and shapefiles if Shap_fn file name is supplied.
- trim_to_left_of_mesh(line_segments)
Trim mesh using line_segments. This function trims the mesh on the left sides of the line segments. The left side here means left when you look at the second end point of a line segment from the first one. An actual path to trimming is a nodal path that is on the right side of the line segment. To manage torus like mesh topology, the argument takes an array of line segments. The user need to provides a set of line segments to make sure the left side of the line segments does not cover the whole mesh. To trim multiple parts of a mesh, use this function multiple times. This function clears up any boundary definitions associated with the original grid. It is user’s responsibility to create them again.
line_segments = array of line segments defined by two end points
- property vmesh
- property z
Get the elevation of levels at all the nodes
- Returns:
- numpy.ndarray
Depth array of each levels at the nodes. The shape of the array is (n_nodes, n_vert_levels) The levels below the most bottom level will be filled with the elevation of the bottom level
- schimpy.schism_mesh.read_mesh(fpath_mesh, fpath_vmesh=None, vgrid_version='5.10', **kwargs)
Read a mesh data
- Returns:
- SchismMesh
- schimpy.schism_mesh.write_mesh(mesh, fpath_mesh, node_attr=None, write_boundary=False, crs=None, **kwargs)
Write a horizontal mesh
- Parameters:
- mesh: SchismMesh
Mesh
- fpath_mesh: str
schimpy.schism_polygon module
Polygon data structure with preprocessor-related attributes and converters
- class schimpy.schism_polygon.SchismPolygon(shell=None, holes=None, prop=None)
Bases:
PolygonA polygon class based on shapely.geometry.Polygon. This class has extra information
- Attributes:
- attribute
- name
- prop
- type
Methods
__call__(*args, **kwargs)Call self as a function.
contains(point)Check the polygon contains the point
intersects(val)Check the polygon intersects with the point
- property attribute
- contains(point)
Check the polygon contains the point
- Parameters:
- point: np.ndarray or shapely.geometry.polygon.Polygon
- Returns:
- bool
- intersects(val)
Check the polygon intersects with the point
- Parameters:
- point: np.ndarray or shapely.geometry.polygon.Polygon
- Returns:
- bool
- property name
- property prop
- property type
- class schimpy.schism_polygon.SchismPolygonDictConverter
Bases:
SchismPolygonIoConvert a tree to a list of polygons
Methods
read
- read(data)
- class schimpy.schism_polygon.SchismPolygonIo
Bases:
objectSchismPolygon I/O abstract class
Methods
read
- read(stream)
- class schimpy.schism_polygon.SchismPolygonIoFactory
Bases:
objectA factory class for SchismPolygonIo
Methods
get_reader
get_writer
show_registered_readers
- get_reader(name)
- get_writer(name)
- registered_readers = {'dict': 'SchismPolygonDictConverter', 'shp': 'SchismPolygonShapefileReader', 'yaml': 'SchismPolygonYamlReader'}
- registered_writers = {'shp': 'SchismPolygonShapefileWriter', 'yaml': 'SchismPolygonYamlWriter'}
- show_registered_readers()
- class schimpy.schism_polygon.SchismPolygonShapefileReader
Bases:
SchismPolygonIoRead polygons from a shape file
Methods
read(fpath)Read polygons from a Shapefile and return a list of SchismPolygons.
- read(fpath)
Read polygons from a Shapefile and return a list of SchismPolygons.
- Parameters:
- fpath: str
Filename of a Shapefile containing Polygons with data columns such as name, type, and attribute.
- Returns:
- list
list of SchismPolygons
- class schimpy.schism_polygon.SchismPolygonShapefileWriter
Bases:
SchismPolygonIoMethods
write(fpath, polygons[, spatial_reference, ...])Convert SCHISM polygon YAML file to a shapefile
read
- write(fpath, polygons, spatial_reference=None, driver_name=None)
Convert SCHISM polygon YAML file to a shapefile
- Parameters:
- fpath: str
output file name
- polygons: array of schism_polygon.SchismPolygon
polygons to write
- spatial_reference: osgeo.osr.SpatialReference or crs string
default: NAD83, UTM zone 10N, meter
- driver_name: osgeo.ogr Driver name
default: ESRI Shapefile
- class schimpy.schism_polygon.SchismPolygonYamlReader
Bases:
SchismPolygonIoRead polygons from a SCHISM YAML polygon file
Methods
read
- read(fpath, yaml_root=None, envvar=None)
- class schimpy.schism_polygon.SchismPolygonYamlWriter
Bases:
SchismPolygonIoWrite polygons into a YAML file
Methods
read
write
- write(fpath, polygons)
- schimpy.schism_polygon.read_polygons(fpath, yaml_root=None, envvar=None)
Read a polygon file
- Parameters:
- fpathstr
Path to the polygon file (YAML or Shapefile).
- yaml_rootstr, optional
Dot-separated path to navigate into a nested YAML structure before reading polygons (e.g., ‘mesh.depth_enforcement’).
- schimpy.schism_polygon.write_polygons(fpath, polygons)
schimpy.schism_setup module
Setup and processes SCHISM Inputs
- class schimpy.schism_setup.SchismSetup(logger=None)
Bases:
objectA class to manage SCHISM input data
- Attributes:
- input
meshMesh
Methods
adopt_new_mesh(fname)Adopt a new grid.
apply_polygons(polygons, default[, ...])Partition the grid with the given polygons.
Create a source from a user input
create_flux_regions(linestrings[, out_fname])Create and write flux_regions.gr3 with the given lines
create_node_partitioning(gr3_fname, ...[, ...])Create a gr3 file with node partitioning using polygons in the polygon file.
create_open_boundaries(segments)Create open boundaries with linestrings
create_prop_partitioning(prop_fname, ...[, ...])Create a prop file with element partitioning using polygons in the polygon file.
create_source_sink_in(source_sinks[, out_fname])Create source_sink.in from source/sink location information in_fname = input file name
create_structures(structures[, nudging])Create structures
elements_on_linestring(coords)List elements along linestring
interpolate_tide(time_start, time_end, dt, ...)Interpolate an observed tide time series with the given dt.
load(dir)Read SCHISM input
modify_depth(polygon_data)Modify depth with the polygon information
reorder_open_boundaries(order)Reorder open boundaries with the given order order = list of open boundary names TODO: How to put the name of the boundaries is not settled.
structure_node_paths(name, pathway[, gate_span])Resolve a structure's node paths from a pathway along the barrier.
trim_to_left_of_mesh(line_segments)Trim mesh using line_segments.
write_hgrid(fname[, attr, boundary])Write a hgrid file only.
write_hgrid_ll(fname, boundary[, input_crs, ...])Write a hgrid.ll, lat-long mesh file, of the current mesh.
write_structures([fname])Write a SCHISM structure file fname = output file name
apply_linestring_ops
get_closest_node_i_from_new_mesh
- adopt_new_mesh(fname)
Adopt a new grid. fname = the file name of a new hgrid file
- apply_linestring_ops(default, linestrings, global_imports=None)
- apply_polygons(polygons, default, global_imports=None)
Partition the grid with the given polygons. Each node (not element) will be assigned with an integer ID which is the index of the polygons. If some polygons overlap, the latter one will trump the former one. The area that are not covered by any of the given polygons will have a default negative one attribute.
- Parameters:
- polygons: list
a list of polygon dict (from YAML most of time)
- global_imports: list, optional
list of module paths available to all polygon expressions
- Returns:
- numpy.ndarray
attributes
- creart_sources_from_user_input()
Create a source from a user input
- create_flux_regions(linestrings, out_fname='fluxflag.prop')
Create and write flux_regions.gr3 with the given lines
- Parameters:
- linestrings: list
A list containing information for flux regions. It must contains ‘linestrings.’
- out_fname: str, optional
Output file name
- create_node_partitioning(gr3_fname, polygons, default, smooth, global_imports=None)
Create a gr3 file with node partitioning using polygons in the polygon file. gr3_fname = output gr3 file name polygons = polygons
- create_open_boundaries(segments)
Create open boundaries with linestrings
- create_prop_partitioning(prop_fname, polygons, default, global_imports=None)
Create a prop file with element partitioning using polygons in the polygon file. prop_fname = output prop file name polygons = polygons
- create_source_sink_in(source_sinks, out_fname='source_sink.in')
Create source_sink.in from source/sink location information in_fname = input file name
- create_structures(structures, nudging=None)
Create structures
- elements_on_linestring(coords)
List elements along linestring
- get_closest_node_i_from_new_mesh(mesh, node_i)
- property input
- interpolate_tide(time_start, time_end, dt, in_fname, out_fname)
Interpolate an observed tide time series with the given dt. time_start = start time in Python datetime time_end = end time in Python datetime dt = delta t for the interpolation output in_fname = input file name of tide records out_fname = output file name
- load(dir)
Read SCHISM input
- Parameters:
- dir: String
An directory where the SCHISM inputs reside
- property mesh
Mesh
- Getter:
Return the mesh.
- modify_depth(polygon_data)
Modify depth with the polygon information
- reorder_open_boundaries(order)
Reorder open boundaries with the given order order = list of open boundary names TODO: How to put the name of the boundaries is not settled.
- structure_node_paths(name, pathway, gate_span=None)
Resolve a structure’s node paths from a pathway along the barrier.
A two-point pathway is the familiar
end_pointscase and resolves in one step. A longer pathway is resolved segment by segment and the resulting node pairs stitched, which is what lets a structure follow a bent levee that no single chord can cut.gate_spannames the part of the pathway the structure itself occupies, for a gate shorter than the barrier it sits in. Its two points need only be near the intended ends; each snaps to the nearest node pair and the contiguous run between them is taken.- Parameters:
- namestr
Structure name, used in error messages.
- pathwayarray_like
Two or more points along the barrier, ordered so the structure’s downstream side stays on the same hand throughout.
- gate_spanarray_like, optional
Two points bracketing the gated part of the pathway.
- Returns:
- up_path, down_pathlist of int
- Raises:
- ValueError
If a segment crosses nothing, the segments cannot be stitched, or the result is not a legal structure.
- trim_to_left_of_mesh(line_segments)
Trim mesh using line_segments. This function trims the mesh on the left sides of the line segments. The left side here means left when you look at the second end point of a line segment from the first one. An actual path to trimming is a nodal path that is on the right side of the line segment. To manage torus like mesh topology, the argument takes an array of line segments. The user need to provides a set of line segments to make sure the left side of the line segments does not cover the whole mesh. To trim multiple parts of a mesh, use this function multiple times. This function clears up any boundary definitions associated with the original grid. It is user’s responsibility to create them again.
line_segments = array of line segments defined by two end points
- write_hgrid(fname, attr=None, boundary=True)
Write a hgrid file only. fname = the output file name attr = attribute array in numpy format. If None, original data will be kept. boundary = If True, boundary info will be appended at the end of the file. Otherwise, not appended.
- write_hgrid_ll(fname, boundary, input_crs='EPSG:26910', output_crs='EPSG:4269')
Write a hgrid.ll, lat-long mesh file, of the current mesh.
- Parameters:
- fname: str
the output file name
- input_epsg: int, optional
input EPSG. default value is 26910, NAD83/UTM10N.
- output_epsg: int, optional
output EPSG. default value is 4269, NAD83
- write_structures(fname='hydraulics.in')
Write a SCHISM structure file fname = output file name
- schimpy.schism_setup.check_and_suggest(testees, list_words, logger=None)
Check testees in list_words and if not suggest something if possible
- schimpy.schism_setup.check_similarity(testee, list_words)
Check similarity of a word
- schimpy.schism_setup.create_schism_setup(fname, logger=None)
Read a mesh and return a SCHISM input set-up instance.
- Parameters:
- fname: str
- Returns:
- SCHISM input set-up instance
- schimpy.schism_setup.ensure_outdir(outdir, fname)
- schimpy.schism_setup.load_schism(dir)
A load function
schimpy.schism_source module
- class schimpy.schism_source.SchismSource
Bases:
objectA class to hold structure information
- Attributes:
- coord
- element_id
- note
- type
- property coord
- property element_id
- property note
- property type
- class schimpy.schism_source.SchismSourceIO(input)
Bases:
objectA class to manage source/sink I/O
Methods
read
write
- read(fname)
- write(fname='source_sink.in')
- schimpy.schism_source.read_sources(fname)
schimpy.schism_sources_sinks module
- schimpy.schism_sources_sinks.concat_msource_csv(csv_fn1, csv_fn2, merged_source_sink_in, csv_merged, freq='infer', how='left')
- schimpy.schism_sources_sinks.concat_source_sink_yaml(yaml_fn1, yaml_fn2, new_yaml)
- schimpy.schism_sources_sinks.concat_vsource_sink_csv(csv_fn1, csv_fn2, merged_source_sink_in, csv_type, csv_merged, freq='infer', how='left')
Concatenate source and sink files
- Parameters:
- csv_fn1STR
Filename of the 1st dated vsource.csv or vsink.csv
- csv_fn2STR
Filename of the 2nd dated vsource.csv or vsink.csv
- merged_source_sink_inSTR
Filename of source_sink.in or source_sink.yaml
- csv_typeSTR
Indicate if the files are “sources” or “sinks”
- csv_mergedSTR
Output merged csv filename
- freqSTR, optional
Frequency for the output csv file. The default is ‘infer’.
- howSTR, optional
Options see pandas.join(). The default is ‘left’.
- Returns:
- None.
- Raises:
- NotImplementedError
DESCRIPTION.
- schimpy.schism_sources_sinks.csv2yaml(source_csv, source_yaml)
Converting from source csv to source yaml file
- Parameters:
- source_csvCSV FILENAME
DESCRIPTION.
- source_yamlYAML FILENAME
DESCRIPTION.
- Returns:
- None
- schimpy.schism_sources_sinks.read_source_sink_csv(csv_fn)
- schimpy.schism_sources_sinks.read_source_sink_in(source_sink_in)
Parse source sink.in file
- Parameters:
- source_sink_inSTR
source_sink.in
- Returns
- ——-
- source_dfPANDAS DATAFRAME
a dataframe of source names
- sink_dfTYPE
a dataframe of sink names
- schimpy.schism_sources_sinks.read_source_sink_th(th_fn, source_or_sink_df)
Read source_sink.th file
- Parameters:
- th_fnSTR
*.th file
- source_or_sink_dfPANDAS DATAFRAME
source_df or sink_df produced by read_source_sink_in.
- Returns:
- thPANDAS DATAFRAME
source or sink data frame with time series data of T, S and other variables
- schimpy.schism_sources_sinks.read_source_sink_yaml(yaml_fn)
Read source sink yaml file
- Parameters:
- yaml_fnstr
source_sink.yaml filename.
- Returns:
- df_sourcesPANDAS dataframe
For sources
- df_sinksPANDAS dataframe
For sinks
- schimpy.schism_sources_sinks.unsorted_unique(a)
Find unique elements with no sorting
np.unique automatically sorts the elements. This function performs unique without sorting.
- Parameters:
- aList or array
Input array
- Returns:
- a_uniquearray
Unsorted unique array
- schimpy.schism_sources_sinks.write_source_sink_csv(th, csv_fn)
- schimpy.schism_sources_sinks.write_source_sink_in(source_sink_yaml, hgrid_fn, source_sink_in='source_sink.in')
Create source_sink.in based on hgrid and source_sink.yaml using the create_source_sink_in function in schimpy preprocessor
- Parameters:
- source_sink_yamlSTR
Filename for source_sink.yaml
- hgrid_fnSTR
schism hgrid.gr3
- source_sink_inSTR, optional
Filename for source_sink.in. The default is ‘source_sink.in’.
- Returns:
- None.
- schimpy.schism_sources_sinks.write_source_sink_yaml(df_sources, df_sinks, yaml_fn)
Write source sink to yaml
- Parameters:
- df_sourcesPANDAS dataframe
with colums:[‘x’,’y’]
- df_sinksTYPE
DESCRIPTION.
- yaml_fnTYPE
DESCRIPTION.
- Returns:
- None.
- schimpy.schism_sources_sinks.yaml2csv(source_yaml, source_csv)
Converting source yaml file to source csv file
- Parameters:
- source_yaml :YAML FILENAME
DESCRIPTION.
- source_csvCSV FILENAME
DESCRIPTION.
- Returns:
- None.
- schimpy.schism_sources_sinks.yaml2df(source_yaml)
Converting source yaml file to pandas dataframe
- Parameters:
- source_yaml :YAML FILENAME
- Returns:
- pandas dataframe
schimpy.schism_structure module
- class schimpy.schism_structure.SchismStructure
Bases:
objectA class to hold structure information
- Attributes:
- coords
- n_duplicate
- name
- node_pairs
- properties
- property_names
- reference
- reference_pair
- type
- use_timeseries
Methods
n_node_pairs
- property coords
- property n_duplicate
- n_node_pairs()
- property name
- property node_pairs
- property properties
- property property_names
- property reference
- property reference_pair
- property type
- property use_timeseries
- class schimpy.schism_structure.SchismStructureIO(input)
Bases:
BaseIOA class to manage hydraulic structure I/O files
- Attributes:
- linecounter
Methods
read(fname)Read in 'hydraulics.in' file.
write([fname])Write out 'hydraulics.in' file.
- read(fname)
Read in ‘hydraulics.in’ file.
- write(fname='hydraulics.in')
Write out ‘hydraulics.in’ file.
schimpy.schism_vertical_mesh module
SchismVerticalMesh class with a reader
- schimpy.schism_vertical_mesh.read_vmesh(fpath_vmesh, vgrid_version=None)
Read a vgrid file
schimpy.schism_yaml module
A customized version of YAML parser for SCHISM It stores document in an ordered dict and supports variable substitution.
- schimpy.schism_yaml.dump(data, stream=None, Dumper=<class 'yaml.dumper.Dumper'>, **kwds)
Serialize a Python object into a YAML stream. If stream is None, return the produced string instead.
- schimpy.schism_yaml.load(stream, envvar=None, collapse_nested=True)
Load a schism YAML
schimpy.simulation_timing module
- schimpy.simulation_timing.schism_timing(workdir, start=1, end=None, block_days=1.0)
schimpy.small_areas module
- schimpy.small_areas.small_areas(mesh, warn=10.0, fail=1.0, logger=None, write_out_smalls=False, prepro_output_dir='./')
schimpy.sms2gr3 module
Manage conversion from SMS 2dm format to gr3. Some material borrowed @author: snegusse
- schimpy.sms2gr3.addnode(list)
- schimpy.sms2gr3.convert_2dm(file, outfile=None, elev2depth=False, logger=None)
schimpy.splice_netcdf module
Command line tool to splice two NetCDF time series of nudging data
- schimpy.splice_netcdf.load_nc_series(nc_file, start_date)
Load NetCDF tracer data and convert to pandas DataFrame.
- Parameters:
- nc_filestr
Path to NetCDF file.
- start_datestr
Start date corresponding to time=0 in the NetCDF file.
- Returns:
- dfpandas.DataFrame
DataFrame indexed by datetime with flattened spatial dimensions.
- dsxarray.Dataset
Original dataset used as template.
- schimpy.splice_netcdf.rebuild_dataset(spliced_df, template_ds, start_date)
Convert spliced DataFrame back into xarray Dataset.
- Parameters:
- spliced_dfpandas.DataFrame
Spliced time series data.
- template_dsxarray.Dataset
Template dataset for dimensions and metadata.
- start_datestr
Start date corresponding to time=0.
- Returns:
- xarray.Dataset
Dataset ready to write to NetCDF.
- schimpy.splice_netcdf.splice_two_files(file1, file2, start_date1, start_date2, transition_date, transition)
Splice two NetCDF time series.
- Parameters:
- file1str
First NetCDF file.
- file2str
Second NetCDF file.
- start_date1str
Start date of first dataset.
- start_date2str
Start date of second dataset.
- transition_datestr
Timestamp where splice occurs.
- transition{‘prefer_first’, ‘prefer_last’}
Transition rule passed to ts_splice.
- Returns:
- xarray.Dataset
Spliced dataset.
schimpy.split_quad module
PoC of quad splitting
- schimpy.split_quad.split_all_quads(mesh)
Split all quad elements into triangular ones and return a new triangular mesh. This function maintains the original node indices. Currently this function does not add boundary information to the new mesh.
- Parameters:
- mesh: SchismMesh
a mesh with elements to split
- Returns:
- SchismMesh
A new triangular mesh. It does not contain any extra information, e.g. boundary information.
schimpy.stacked_dem_fill module
Routines to fill elevation (or other scalar) values at points from a prioritized list of rasters
- schimpy.stacked_dem_fill.ParseType(type)
- schimpy.stacked_dem_fill.bilinear(points, gt, raster)
Bilinear interpolated point using data on raster points: npoint x 3 array of (x,y,z points) gt: geotransform information from gdal raster: the data
- schimpy.stacked_dem_fill.create_dem_sampler(dem_list: str | List[str], cache_dir: str = './dem_cache', q: float = 1e-06)
Create a DEM sampler
dem_sampler(xy)with disk caching.The cache key includes: - The list of DEM source names (from the YAML or the provided list). - A daily stamp (YYYYMMDD) to force refresh at least daily. - A compact signature of the request batch: length, quantized centroid, and
quantized bounding box (min/max) of XY.
- Parameters:
- dem_liststr or list of str
Either a YAML file path consumable by
stacked_dem_fill()or a list of DEM file paths.- cache_dirstr, optional
Directory for
diskcachestorage, by default"./dem_cache".- qfloat, optional
Quantization (meters) for the request signature, by default 1e-6.
- Returns:
- callable
dem_sampler(points_xy)mapping(k,2)XY→depth(+down) array.
- schimpy.stacked_dem_fill.filelist_main(demlistfile, pointlistfile, out_dir='./', sep='')
higher level driver routine that parses the names of the DEMs from demfilelist points ( x,y or x,y,z ) from pointlistfile
- schimpy.stacked_dem_fill.fill_2dm(infile, outfile, files, na_fill=2.0)
- schimpy.stacked_dem_fill.fill_gr3(infile, outfile, files, elev2depth=True, na_fill=2.0)
- schimpy.stacked_dem_fill.read_dem_list(dem_source, yaml_root='dem_list', envvar=None)
- Read DEM stack from:
list/tuple of filenames
plain text file, one DEM per line
simple YAML list
YAML mapping at yaml_root, e.g. dem_list or mesh/dem_list
For SCHISM config YAML with includes/substitution, use schism_yaml.load.
- schimpy.stacked_dem_fill.stacked_dem_fill(files, points, out_dir, values=None, negate=False, require_all=True, na_fill=None)
Fill values at an array of points using bilinear interpolation from a prioritized stack of DEMs. This function manages prioritization of the DEMs, gradually filling points that are still marked as nan. Uses a cache to speed up repeated queries.
- Parameters:
- fileslist of str
List of DEM file paths. Existence is checked; raises ValueError if any file is missing.
- pointsnp.ndarray
Numpy array of shape (n_points, 2) containing (x, y) coordinates for interpolation.
- out_dirstr or Path
Directory to write output files and cache.
- valuesnp.ndarray or None, optional
Optional array of initial values at each point. If provided, must be same length as points. Points with NaN values will be filled.
- negatebool, optional
If True, output values will be negated (e.g., convert elevation to depth).
- require_allbool, optional
If True, raises ValueError if the DEMs do not cover all points. In either case, a file dem_misses.txt is created or overwritten with locations of uncovered points.
- na_fillfloat or None, optional
Value to substitute for points that remain NaN after all DEMs are processed. If require_all is True, na_fill must be None.
- Returns:
- np.ndarray
Array of values at the input points, filled from the DEMs.
- Raises:
- ValueError
If any DEM file does not exist, or if require_all is True and not all points are covered.
- schimpy.stacked_dem_fill.stacked_dem_fill_interpolate(filename, demfile, elev2depth, fill)
Fill node elevations in a .2dm SMS mesh or gr3 file using a prioritized list of DEMs.
FILENAME: Name of 2dm or gr3 file.
DEMFILE: File containing list of DEMs (ESRI ascii format or GeoTiffs).
- schimpy.stacked_dem_fill.stacked_dem_source_regions(files, out_dir, output_name='dem_source_regions.gpkg', write_overlap=True, write_gaps=True, overlap_name='dem_overlap_regions.gpkg', gaps_name='dem_gaps.gpkg')
Create polygon layers describing which DEM wins in a prioritized DEM stack.
The source regions mimic stacked_dem_fill priority: earlier DEMs claim areas first; later DEMs only claim areas not already covered by higher-priority bilinear support.
- schimpy.stacked_dem_fill.test_main()
schimpy.station module
- schimpy.station.convert_db_station_in(outfile='station.in', stationdb=None, sublocdb=None, station_request='all', default=-0.5, mask_col=None)
- schimpy.station.convert_stations(input, output, write_sta_var='all')
Read a station shapefile/.in file and write to a .in/shapefile
- Parameters:
- inputfname
Path to input station.in style file or station.shp style file with station id, x, y, z, name and subloc fields
- outputfname
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:
- ResultDataFrame
DataFrame with hierarchical index (id,subloc) and columns x,y,z,name
- schimpy.station.example()
- schimpy.station.flux_stations_from_yaml(inp)
Retrieve station id of fluxlines from yaml file or content
- schimpy.station.merge_station_subloc(station_dbase, station_subloc, default_z)
Merge BayDeltaSCHISM station database with subloc file, producing the union of all stations and sublocs including a default entry for stations with no subloc entry
- Parameters:
- station_dbaseDataFrame
This should be the input that has only the station id as an index and includes other metadata like x,y,
- station_sublocDataFrame
This should have (id,subloc) as an index
- Returns:
- ResultDataFrame
DataFrame that links the information.
- schimpy.station.read_flux_out(fpath, names, reftime)
Read fluxes from a SCHISM flux.out file
- Parameters:
- fpathstr
- Path to the file
- namesstr
- name of file that contains names of flux areas, typically something like flow_xsects.yaml
- reftimestr
- start of simulation, against which relative times will be calculated
- schimpy.station.read_obs_links(fpath)
Read an obs_links csv file which has comma as delimiter and (id,subloc,variable) as index
- schimpy.station.read_pointstrings(fpath)
- schimpy.station.read_staout(fname, station_infile, reftime, ret_station_in=False, multi=False, elim_default=False, time_unit='s')
Read a SCHISM staout_* file into a pandas DataFrame
- Parameters:
- fpathfname
Path to input staout file or a variable name in [“elev”, “air pressure”, “wind_x”, “wind_y”, “temp”, “salt”, “u”, “v”, “w”] whose 1-index will be mapped to a name like staout_1 for elev
- station_infilestr or DataFrame
Path to station.in file or DataFrame from read_station_in
- reftimeTimestampe
Start of simulation, time basis for staout file elapse time
- ret_station_inbool
Return station_in DataFrame for use, which may speed reading of a second file
- multibool
Should the returned data have a multi index for the column with location and sublocation. If False the two are collapsed
- elim_defaultbool
If the MultiIndex is collapsed, stations with subloc “default” will be collapsed. Eg. (“CLC”,”default”) becomes “CLC_default”
- time_unitstring
Convertible to pandas frequency string, this is the timestamp of the file.
- Returns:
- ResultDataFrame
DataFrame with hierarchical index (id,subloc) and columns representing the staout data (collapsed as described above
Examples
>>> staout1,station_in = read_staout("staout_1","station.in",reftime=pd.Timestamp(2009,2,10), ret_station_in = True,multi=False,elim_default=True) >>> staout6 = read_staout("staout_6",station_in,reftime=pd.Timestamp(2009,2,10),multi=False,elim_default=True)
- schimpy.station.read_station_dbase(fpath)
Read a BayDeltaSCHISM station data base csv file into a pandas DataFrame
The BayDelta SCHISM format is open, but expects these columns: index x y z ! id subloc “Name”
- Parameters:
- fpathfname
Path to input dbase style file
- Returns:
- ResultDataFrame
DataFrame with hierarchical index (id,subloc) and columns x,y,z,name
- schimpy.station.read_station_in(fpath)
Read a SCHISM station.in file into a pandas DataFrame
Note
This only reads the tabular part, and assumes the BayDelta SCHISM format with columns: index x y z ! id subloc “Name”
Note that there is no header and the delimiter is a space. Also note that the text beginning with ! is extra BayDeltaSCHISM extra metadata, not required for vanilla SCHISM
- Parameters:
- fpathfname
Path to input station.in style file
- Returns:
- ResultDataFrame
DataFrame with hierarchical index (station_id,subloc) and columns x,y,z,name
- schimpy.station.read_station_out(fpath_base, stationinfo, var=None, start=None)
- schimpy.station.read_station_shp(fpath, pop_xy=True)
Read a shapefile and convert into a pandas DataFrame
- Parameters:
- fpathfname
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_xybool
Repopulate the x & y fields with point coordinates?
- Returns:
- ResultDataFrame
DataFrame that has station id, x, y, z, name and subloc labels (id is the station id, index will be autogenerated)
- schimpy.station.read_station_subloc(fpath)
Read a BayDeltaSCHISM station_sublocs.csv file into a pandas DataFrame
The BayDelta SCHISM format has a header and uses “,” as the delimiter and has these columns: id,subloc,z
The id is the station id, which is the key that joins this file to the station database. ‘subloc’ is a label that describes the sublocation or subloc and z is the actual elevation of the instrument
Example might be: id,subloc,z 12345,upper,-0.5
Other columns are allowed, but this will commonly merged with the station database file so we avoid column names like ‘name’ that might collide
- Parameters:
- fpathfname
Path to input station.in style file
- Returns:
- ResultDataFrame
DataFrame with hierarchical index (id,subloc) and data column z
- schimpy.station.staout_name(var)
- schimpy.station.station_names_from_file(fpath)
- schimpy.station.station_subset(fpath, run_start, locs, extract_freq, convert=None, stationfile=None, isflux='infer', miss='raise')
Extract a subset of stations from an staout file or flux.out file
- Parameters:
- fpathstr
Path to the output file to be read
- run_startpd.Timestamp
Start time (reference time) for the simulation elapsed time
- locspd.DataFrame or str
A DataFrame with rows specifying the data to subset or a string that is the path to such a file. There are a few options. Minimally this file should have either one column called “station_id” or one called “id” and another called “subloc”. If you use station_id, it should be an underscore-connected combination of id and subloc which should be unique, and this will be the treatment of the output. of the station. If you use “subloc” you can use “default” leave the subloc column blank. You can also use another optional column called “alias” and this will become the label used.
- extract_freqstr or pd.tseries.TimeOffset
Frequency to extract. This allows some economies if you want, say, 15min data. Use pandas freq string such as ‘15T’ for 15min
- convert: str or function
A small number of conversions are supported (“ft”, “ec” for uS/cm, “cfs” for flow)
- stationfilestr
Name of station file such as station.in. In the case of flow this will be a yaml file or fluxflag.prop file produced by our preprocessing system. If you leave this None, ‘station.in’ in the same directory as the output file will be assumed for staout files. For flow, a string must be supplied but will be tested first in the directory of execution and then side-by-side in that order.
- isflux‘infer’ | True | False
Is the request for flux.out?
- miss‘raise’ | ‘drop’ | ‘nan’
What to do when a requested station_id does not exist. The default, raise, helps station lists from growing faulty. ‘drop’ will ignore the column and ‘nan’ will return nans for the column.
- Returns:
- ResultDataFrame
DataFrame that returns the converted and subsetted data. Column names will be the ids unless ‘alias’ is provided in locs, in which case those names will be swapped in.
- schimpy.station.station_subset_multidir(dirs, staoutfile, run_start, locs, extract_freq, convert, stationfile=None, names=None, isflux='infer', miss='raise')
Extract a subset of stations from an staout file or flux.out file across a list of directories
- Parameters:
- dirslist(str)
List of directories. The output dataframe will have a column multindex (dir,station_id) where dir is the directory of the output.
- fpathstr
Path to the output file to be read
- run_startpd.Timestamp
Start time (reference time) for the simulation elapsed time
- locspd.DataFrame or str
A DataFrame with rows specifying the data to subset or a string that is the path to such a file. There are a few options for staout station files. Minimally this file should have either one column called “station_id” or one called “id” and another called “subloc”. If you use station_id, it should be an underscore-connected combination of id and subloc and this will be the index treatment of the output. Flux files only have the station_id option. If you use “subloc” you can use “default” leave the subloc column blank. You can also include another optional column called “alias” and this will become the label used.
- extract_freqstr or pd.tseries.TimeOffset
Frequency to extract … this allows some economies if you want, say, 15min data. Use pandas freq string such as ‘15T’ for 15min
- convert: str or function
A small number of conversions are supported (“ft”, “ec” for uS/cm, “cfs” for flow)
- stationfilestr
Name or list of station file such as station.in. You can provide a list of the same length as dirs or a single value which will be assumed to be appropriate for all the directories. In the case of station.in, you can use None and ‘station.in’ in each directory will be assumed for staout files. For flow, a string (yaml file) must be supplied but will be tested first in the directory of execution and then side-by-side in that order.
- isflux‘infer’ | True | False
Is the request for flux.out?
- miss‘raise’ | ‘drop’ | ‘nan’
What to do when a requested station_id does not exist. The default, raise, helps station lists from growing faulty. ‘drop’ will ignore the column and ‘nan’ will return nans for the column.
- Returns:
- ResultDataFrame
DataFrame that returns the converted and subsetted data. Column names will be the ids unless ‘alias’ is provided in locs, in which case those names will be swapped in.
- schimpy.station.u(x)
- schimpy.station.write_pointstrings(fpath, station_in, request='all')
- schimpy.station.write_station_in(fpath, station_in, request=None)
Write a SCHISM station.in file given a pandas DataFrame of metadata
- Parameters:
- fpathfname
Path to output station.in file
- station_inDataFrame
DataFrame that has station id, x, y, z, name and subloc labels (id is the station id, index will be autogenerated)
- request‘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
- schimpy.station.write_station_shp(fpath, station_in)
Write a point Shapefile file given a pandas DataFrame of metadata
- Parameters:
- fpathfname
Path to output station.in file
- station_inDataFrame
DataFrame that has station id, x, y, z, name and subloc labels (id is the station id, index will be autogenerated)
schimpy.subset_schism_output module
schimpy.th_calcs module
- schimpy.th_calcs.calc_net_source_sink(vsource_file='vsource.th', vsink_file='vsink.th', time_basis=None, elapsed_unit='s', vsource_head=None, vsink_head=None, search_term=None, start_date=None, end_date=None)
Calculate the net source/sink terms supplied by the vsource.th and vsink.th files. Files can be specified, elapsed, or timestamped. By default it will look for vsource.th and vsink.th - the default source/sink inputs for SCHISM.
- schimpy.th_calcs.combine_flux(flux, comb_dict, time_basis=None, elapsed_unit='s', flux_head=None, start_date=None, end_date=None)
Combine flux data, comb_dict is a dictionary that combines the headers in the list into a single value with the header of the dictionary key. An example of this would be comb_dict={‘Northern’:[‘this’,’that’,’other’]} Optionally subset by start_date and end_date.
- schimpy.th_calcs.normalize_df(df)
- schimpy.th_calcs.read_flux(flux='flux.th', flux_head=None, time_basis=None, elapsed_unit='s', start_date=None, end_date=None)
Read in the flux.th, use flux_head to assign headers to dataframe. If no flux_head, then the resultant dataframe will have no headers. Optionally subset by start_date and end_date.
- schimpy.th_calcs.struct_open_props(struct, th_data, out_freq='15min', datetime_idx=None)
Determine the structure header properties that are used to determine ‘relative openness’ of the structure For instance, a simple gate might just be (width * height)/(max(width) * max(height))
schimpy.th_io module
I/O utilities for SCHISM .th time-history files.
Provides read_th and write_th as a shared module for model_time, th_calcs, and merge_th.
- schimpy.th_io.get_column_formats(filename)
Extract per-column format strings (e.g., “%.3f”) from .th input.
- Parameters:
- filenamestr
Path to a .th file.
- Returns:
- dict
Mapping column names to printf-style format specifiers.
- schimpy.th_io.is_elapsed(input_path)
Return True if .th file is elapsed seconds format.
- Parameters:
- input_pathstr
Path to a .th file.
- Returns:
- bool
True if the first non-empty, non-comment line is elapsed numeric time.
- schimpy.th_io.read_th(input_path, time_basis=None, to_timestamp=True, elapsed_unit='s', head=None)
Read a SCHISM .th file and return a pandas DataFrame.
Supports both timestamped (datetime index) and elapsed (seconds index) files. Preserves inline or trailing comments in a
__comment__column.- Parameters:
- input_pathstr
Path to .th file.
- time_basisstr or datetime, optional
Reference time for converting elapsed series to timestamps.
- to_timestampbool, default True
Convert elapsed data to timestamp index if True.
- elapsed_unitstr, default “s”
Time units for elapsed files.
- headstr or None
Optional header file to supply data column names for elapsed data.
- Returns:
- pandas.DataFrame
Time-series dataset with datetime index.
- schimpy.th_io.write_th(df, outpath, elapsed=None, ref_time=None, time_format='%Y-%m-%dT%H:%M', float_format='%.2f', elapsed_format='%.1f', include_header=None, index_name=None, source_file=None)
Write time history data to a SCHISM .th file.
- Parameters:
- dfpandas.DataFrame or pandas.Series
Time-indexed input data.
- outpathstr or file-like
Output path or file-like object.
- elapsedbool or None, optional
Force elapsed format (True) or dated format (False). If None, inferred from index.
- ref_timestr or datetime, optional
Reference datetime for elapsed<->timestamp conversions.
- time_formatstr
Datetime format string for dated output.
- float_formatstr
Number formatting for data values.
- elapsed_formatstr
Number formatting for elapsed timestamps.
- include_headerbool or None, optional
Include header row. Defaults to True for dated output.
- index_namestr, optional
Index name for output time column.
- source_filestr, optional
Read source comments and formatting from this file.
- Returns:
- None
schimpy.three_point_linear_norm module
- class schimpy.three_point_linear_norm.ThreePointLinearNorm(linthresh, vmin=None, vmax=None, clip=False)
Bases:
Normalize- Attributes:
clipDetermines the behavior for mapping values outside the range
[vmin, vmax].n_componentsThe number of distinct components supported (1).
vmaxUpper limit of the input data interval; maps to 1.
vminLower limit of the input data interval; maps to 0.
Methods
__call__(value[, clip])Normalize the data and return the normalized data.
autoscale(A)Set vmin, vmax to min, max of A.
autoscale only None-valued vmin or vmax
inverse(value)Maps the normalized value (i.e., index in the colormap) back to image data value.
process_value(value)Homogenize the input value for easy and efficient normalization.
scaled()return true if vmin and vmax set
- autoscale(A)
Set vmin, vmax to min, max of A.
- autoscale_None(A)
autoscale only None-valued vmin or vmax
- inverse(value)
Maps the normalized value (i.e., index in the colormap) back to image data value.
- Parameters:
- value
Normalized value.
- scaled()
return true if vmin and vmax set
schimpy.trimesh module
This is a class to hold an unstructured triangular mesh.
Lots of the codes are copied from Rusty Chris Collerman’s trigrid program and modified a bit to meet our needs.
Prerequisite: Numpy, rtree package, and libspatialindex for rtree
- schimpy.trimesh.BoundaryTypes
alias of
Enum
- schimpy.trimesh.EdgeTypes
alias of
Enum
- class schimpy.trimesh.TriMesh
Bases:
objectClass that holds a triangular mesh information
- Attributes:
Methods
add_boundary(nodes, btype)Add boundary types to an edge with the given array of node indices
allocate(n_elems, n_nodes)Allocate memory for nodes and elems
Build centers of sides
This is a function copied and modified from TriGrid
deepcopy(mesh)Deep copy mesh information.
element2edges(elem_i)Get edge indices from the give element index elem_i = the element index return = generator of found edge indices
find_closest_elems(pos[, count])Find indices of the closet elems with the given position.
find_closest_nodes(pos[, count, boundary])Returns the count closest nodes to the given node in 2D space.
find_elem(pos)Find a element index from a coordinate pos = A coordinate (2D) return = element index
find_elem_with_tolerance(pos, tolerance)Find a element index from a coordinate with some tolerance pos = A coordinate (2D) return = element index
find_nodes_in_box(box)Find nodse in a bounding box box = a numpy array of bounding box, [x_min, x_max, y_min, y_max] return = node indices
get_edges_from_node(node_i)Get edge indices related to node_i
get_elems_i_from_node(node_i)Get neighboring elements indexes of a node, so-called a ball.
get_neighbor_nodes(node_i)Get neighboring node indices from the given node index.
is_elem_on_boundary(elem_i)Check if the given element with index elem_i is on the boundary
n_edges()Get the total number of edges.
n_elems()Get the total nuber of elems.
n_nodes()Get the total number of nodes.
set_elem(index, connectivities)Set element connectivity information.
set_node(index, coords)Set one node information.
shortest_path(n1, n2[, boundary_only])dijkstra on the edge graph from n1 to n2.
trim_to_left(paths)Given a path, trim all elems to the left of it.
- add_boundary(nodes, btype)
Add boundary types to an edge with the given array of node indices
- allocate(n_elems, n_nodes)
Allocate memory for nodes and elems
- Parameters:
- n_elems: integer
Total number of elems
- n_nodes: integer
Total number of nodes
- build_edgecenters()
Build centers of sides
- Returns:
- numpy.array
list of side centers
- build_edges_from_elems()
This is a function copied and modified from TriGrid
- deepcopy(mesh)
Deep copy mesh information.
- property edges
Array of edges
- Getter:
Get the array of the edges.
- Type:
Numpy integer array
- element2edges(elem_i)
Get edge indices from the give element index elem_i = the element index return = generator of found edge indices
- property elems
Array of node indices of each element. The shape of the array is (# of elems, 3). It is assumed that all elems are triangular.
- Getter:
Get the Numpy array of the node indices.
- Type:
Numpy integer array
- find_closest_elems(pos, count=1)
Find indices of the closet elems with the given position. The distance is measured with the element mass center. All triangular elems is assumed. pos = position tuple return = element indices
- find_closest_nodes(pos, count=1, boundary=False)
Returns the count closest nodes to the given node in 2D space. pos = position count = # of nodes to retrieve boundary=1: only choose nodes on the boundary. Copied from TriGrid
- find_elem(pos)
Find a element index from a coordinate pos = A coordinate (2D) return = element index
- find_elem_with_tolerance(pos, tolerance)
Find a element index from a coordinate with some tolerance pos = A coordinate (2D) return = element index
- find_nodes_in_box(box)
Find nodse in a bounding box box = a numpy array of bounding box, [x_min, x_max, y_min, y_max] return = node indices
- get_edges_from_node(node_i)
Get edge indices related to node_i
- get_elems_i_from_node(node_i)
Get neighboring elements indexes of a node, so-called a ball.
- get_neighbor_nodes(node_i)
Get neighboring node indices from the given node index.
- is_elem_on_boundary(elem_i)
Check if the given element with index elem_i is on the boundary
- Parameters:
- elem_iint
element index
- Returns:
- is_on_boundarybool
- True if the element is on the boundary, otherwise False
- n_edges()
Get the total number of edges.
- n_elems()
Get the total nuber of elems.
- n_nodes()
Get the total number of nodes.
- property nodes
Node array consisting of three-dimensional coordinates of each node. The shape of the array is (# of nodes, 3)
- Getter:
Get the array of the nodes.
- Type:
Numpy float array.
- set_elem(index, connectivities)
Set element connectivity information. Memory for elems must be allocated already.
- Parameters:
- index: integer
Zero-based element index
- connectivities: Numpy array
a Numpy array of element connectivity, which means node indies in the element.
- set_node(index, coords)
Set one node information. Memory for nodes must be allocated already.
- Parameters:
- index: integer
Zero-based node index
- coords: Numpy array
a Numpy array of node coordinates
- shortest_path(n1, n2, boundary_only=False)
dijkstra on the edge graph from n1 to n2. copied and modified form Rusty’s code. n1 = node_i for one end of the path n2 = node_i for the other end boundary_only = limit search to edges on the boundary (have a -1 for element2)
- trim_to_left(paths)
Given a path, trim all elems to the left of it. This fuction is lifted and modified slightly from Rusty’s code.
- schimpy.trimesh.enum(**enums)
A enum type definition. Copied from http://stackoverflow.com/questions/36932/how-can-i-represent-an-enum-in-python
schimpy.triquadmesh module
This is a class to hold an unstructured triangular and quad mesh for SCHISM copied and modified from Rusty Holleman’s trigrid.
Prerequisite: Numpy, rtree package, and libspatialindex for rtree
- schimpy.triquadmesh.BoundaryType
alias of
Enum
- schimpy.triquadmesh.EdgeType
alias of
Enum
- schimpy.triquadmesh.NodeType
alias of
Enum
- class schimpy.triquadmesh.TriQuadMesh(logger=None)
Bases:
objectClass that holds a triangular and quadrilateral mesh information
- Attributes:
Methods
add_boundary(nodes, btype)Add boundary types to an edge with the given array of node indexes
allocate(n_elems, n_nodes)Allocate memory for nodes and elems
Build centers of sides
build_edges_from_elems([shift])Build edge array from the elements.
Build balls of elements around each node
compare(mesh)Compare the mesh with another
elem(elem_i)Get connectivity of an element
element2edges(elem_i)Get edge indexes of the give element index
find_closest_elems(pos[, count])Find indexes of the closet elems with the given position.
find_closest_nodes(pos[, count, boundary])Returns the count closest nodes to the given node in 2D space.
find_edge(nodes[, direction])Find an edge index with the two given node indexes.
find_elem(pos)Find a element index from a coordinate pos = A coordinate (2D) return = element index
find_intersecting_elems_with_line(line_segment)Format of the line segment: start_x, start_y, end_x, end_y
find_neighbors_on_segment(line_segment)Find elements on the line_segment and neighbors that are all to the left (downstream) Format of the line segment: start_x, start_y, end_x, end_y Returns a list of elements on the segment and a list of neighbors.
find_nodes_in_box(box)Find nodes in a bounding box.
get_edges_from_node(node_i)Get edge indexes related to node_i
get_elems_i_from_node(node_i)Get the ball of elements around a node, node_i
get_neighbor_nodes(node_i)Get neighboring node indexes from the given node index.
is_elem_on_boundary(elem_i)Check if the given element with index elem_i is on the boundary
mark_elem_deleted(elem_i)Mark an element as deleted or invalid.
n_edges()Get the total number of edges.
n_elems()Get the total number of elements.
n_nodes()Get the total number of nodes.
node(node_i)Selects a single node
renumber()removes duplicate elems and nodes that are not referenced by any element, as well as elems that have been deleted (==-1) This function is lifted and modified slightly from Rusty's code.
set_elem(index, connectivity)Set element connectivity information.
set_node(index, coords)Set one node information.
shortest_path(n1, n2[, boundary_only])Dijkstra on the edge graph from node n1 to n2.
trim_elems(paths[, left])Given a path, trim all elems to the left of it.
- add_boundary(nodes, btype)
Add boundary types to an edge with the given array of node indexes
- allocate(n_elems, n_nodes)
Allocate memory for nodes and elems
- Parameters:
- n_elems: int
Total number of elems
- n_nodes: int
Total number of nodes
- build_edgecenters()
Build centers of sides
- Returns:
- numpy.array
list of side centers
- build_edges_from_elems(shift=1)
Build edge array from the elements.
- Parameters:
- shift:
shift of indexing in edged building. It is introduce to keep the ordering of edges in line with SCHISM Mesh.
- build_elem_balls()
Build balls of elements around each node
- compare(mesh)
Compare the mesh with another
- Parameters:
- mesh: triquadmesh.TriQuadMesh
a mesh to compare
- Returns:
- boolean
True if they have identical node and element array
- property edges
Get the array of edges
- Getter:
Get the array of the edges.
- Type:
Numpy integer array
- elem(elem_i)
Get connectivity of an element
- Parameters:
- elem_i: int
element index
- Returns:
- Numpy int32 array
connectivity of the element (node indexes of the element) None, if the element is marked as deleted
- element2edges(elem_i)
Get edge indexes of the give element index
- Parameters:
- elem_i: int
the element index
- Returns
- ——-
- array of int
edge indexes of the element
- property elems
Array of node indexes of all elements. The shape of the array is (# of elems, 5).
- Returns:
- list of Numpy integer array
list of node indexes for all elements
- find_closest_elems(pos, count=1)
Find indexes of the closet elems with the given position. The distance is measured with the element mass center. All triangular elems is assumed.
- Parameters:
- pos: array-like
2D position
- Returns:
- int or list
element index or indexes
- find_closest_nodes(pos, count=1, boundary=False)
Returns the count closest nodes to the given node in 2D space. Roughly copied from trigrid
- Parameters:
- pos: array-like
position
- count: int
# of nodes to retrieve
- boundary: int 1
only choose nodes on the boundary.
- Returns:
- int or list
nearest node indexes
- find_edge(nodes, direction=False)
Find an edge index with the two given node indexes.
- Parameters:
- nodes: array-like
two node indexes
- direction:
match the ordering of the nodes when an edge is found.
- Returns:
- int
an edge index, None if not found
- find_elem(pos)
Find a element index from a coordinate pos = A coordinate (2D) return = element index
- find_intersecting_elems_with_line(line_segment)
Format of the line segment: start_x, start_y, end_x, end_y
- find_neighbors_on_segment(line_segment)
Find elements on the line_segment and neighbors that are all to the left (downstream) Format of the line segment: start_x, start_y, end_x, end_y Returns a list of elements on the segment and a list of neighbors. The lists are not guarateed to be ordered spatially
- find_nodes_in_box(box)
Find nodes in a bounding box. Note that the box is not interleaved. The backend is based on R-tree.
- Parameters:
- box: array-like
array of bounding box, [x_min, x_max, y_min, y_max]
- Returns:
- set
node indexes
- get_edges_from_node(node_i)
Get edge indexes related to node_i
- Parameters:
- node_i: int
Node index (zero-based)
- Returns
- ——-
- list
a list of edges
- get_elems_i_from_node(node_i)
Get the ball of elements around a node, node_i
- Parameters:
- node_i: int
node index (zero-based)
- Returns:
- set
set of element indexes
- get_neighbor_nodes(node_i)
Get neighboring node indexes from the given node index.
- is_elem_on_boundary(elem_i)
Check if the given element with index elem_i is on the boundary
- Parameters:
- elem_iint
element index
- Returns:
- is_on_boundarybool
- True if the element is on the boundary, otherwise False
- mark_elem_deleted(elem_i)
Mark an element as deleted or invalid.
- Parameters:
- elem_i: int
element index to mark
- n_edges()
Get the total number of edges.
- n_elems()
Get the total number of elements.
- n_nodes()
Get the total number of nodes.
- node(node_i)
Selects a single node
- property node2elems
- property nodes
Node array consisting of three-dimensional coordinates of each node. The shape of the array is (# of nodes, 3)
- Getter:
Get the array of the nodes.
- Type:
Numpy float array.
- renumber()
removes duplicate elems and nodes that are not referenced by any element, as well as elems that have been deleted (==-1) This function is lifted and modified slightly from Rusty’s code.
- Returns:
- dict
- {‘valid_elems’:new_elems, ‘pointmap’:old_indexes,
‘valid_nodes’:active_nodes}
- set_elem(index, connectivity)
Set element connectivity information. Memory for elems must be allocated already.
- Parameters:
- index: integer
Zero-based element index
- connectivity: Numpy array
a Numpy array of element connectivity, which means node indexes in the element.
- set_node(index, coords)
Set one node information. Memory for nodes must be allocated already.
- Parameters:
- index: integer
Zero-based node index
- coords: Numpy array
a Numpy array of node coordinates
- shortest_path(n1, n2, boundary_only=False)
Dijkstra on the edge graph from node n1 to n2. copied and modified form Rusty’s code. Keep in mind that the solution can be non-unique because there are multiple paths that have the same distances.
- Parameters:
- n1: int
node index for one end of the path
- n2: int
node_i for the other end
- boundary_only: boolean
limit search to edges on the boundary
- Returns:
- numpy.ndarray
shortest node indexes or None if it cannot be found
- trim_elems(paths, left=None)
Given a path, trim all elems to the left of it. This function is lifted and modified slightly from Rusty’s code.
- Parameters:
- paths: array of integer array-like
arrays of cut paths in arrays of node indexes
- schimpy.triquadmesh.enum(**enums)
A enum type definition
Copied from http://stackoverflow.com/questions/36932/how-can-i-represent-an-enum-in-python
schimpy.unit_conversions module
schimpy.vgrid_nlayer_to_gr3 module
Create GR3 files with per-node vertical level and layer counts from a SCHISM vgrid.
- schimpy.vgrid_nlayer_to_gr3.vgrid_nlayer_to_gr3(hgrid, vgrid, output_nlevel=None, output_nlayer=None, vgrid_version='5.10')
Write GR3 files for per-node vertical levels and/or layers from a vgrid.
schimpy.vgrid_opt2 module
Package for optimising vgrid smoothness, shape and completeness
- schimpy.vgrid_opt2.example()
- schimpy.vgrid_opt2.fix_depth(zcor, zcornew, x)
- schimpy.vgrid_opt2.gradient_matrix(mesh, sidedist2, sidemasked)
- schimpy.vgrid_opt2.hess_base(xvar, zcorig, mesh, nlayer, ndx, eta, depth, gradmat, sidelen2, nodemasked, sidemasked, ata, dx2fac, curvewgt, foldwgt, foldfrac)
- schimpy.vgrid_opt2.incr_grad(grad, i, k, val, ndx)
- schimpy.vgrid_opt2.index_interior(mat, nodemasked, nlevel=None)
- schimpy.vgrid_opt2.laplace2(mesh, nodemasked, sidemasked)
produces a 2d matrix
- schimpy.vgrid_opt2.mesh_opt(zcor, mesh, nlayer, ndx, eta, depth, gradmat, sidelen2, nodemasked, sidemasked, ata, dx2fac, curvewgt, foldwgt, foldfrac, href_hess, grad_hess, laplace_hess, maxiter=8000)
- schimpy.vgrid_opt2.meshessp(xvar, p, zcorig, mesh, nlayer, ndx, eta, depth, gradmat, sidelen2, nodemasked, sidemasked, ata, dx2fac, curvewgt, foldwgt, foldfrac, href_hess, grad_hess, laplace_hess)
- schimpy.vgrid_opt2.meshgrad(xvar, zcorig, mesh, nlayer, ndx, eta, depth, gradmat, sidelen2, nodemasked, sidemasked, ata, dx2fac, curvewgt, foldwgt, foldfrac, href_hess, grad_hess, laplace_hess)
- schimpy.vgrid_opt2.meshobj(xvar, zcorig, mesh, nlayer, ndx, eta, depth, gradmat, sidelen2, nodemasked, sidemasked, ata, dx2fac, curvewgt, foldwgt, foldfrac, href_hess, grad_hess, laplace_hess)
- schimpy.vgrid_opt2.smooth_heights(zcor, x, wgt=0.2)
- schimpy.vgrid_opt2.targeth2inv(zbar, eta)
- schimpy.vgrid_opt2.test_gradients()
- schimpy.vgrid_opt2.test_vgrid_spacing(zcor, zcorig, nodemasked, foldfrac)
- schimpy.vgrid_opt2.triweight(n)
schimpy.write_ts module
- schimpy.write_ts.cdec_header(fname, ts, tz, var=None, unit=None)
Helper function to create a cdec-like header Requres some metadata like time zone, variable name and unit which will be pulled from series if omitted from input.
- Parameters:
- fname: str
Output file name or path
- ts: :class:`~vtools.data.timeseries.TimeSeries`
The time series to be stored
- tz: string
Time zone of data
- var: string
Variable name
- unit: string
Unit of the time series
- Returns:
- head: string
CDEC-style header
- schimpy.write_ts.write_ts(ts, fname, dateformat='%Y-%m-%d %H:%M', fmt='%.2f', header=None, sep=',')
Estimate missing values within a time series by interpolation.
- Parameters:
- ts: :class:`~vtools.data.timeseries.TimeSeries`
The time series to be stored
- fname: string
Output file name or path
- dateformat: string
Date format compatible with datetime.datetime.strftime
- fmt: string
Value format compatible withy numpy.savetxt
- header: string
Header to add to top of file
- sep: string
Delimieter for fields, often a space or comma
Examples
Writing csv format with date format 2009-03-15 21:00 and space separated values
>>> write_ts(ts,"test.csv","%Y-%m-%d %H:%M","%.2f,%.2f","Datetime,u,v",",")
Write vtide format with same format and space separated values, this time taking advantage of defaults
>>> write_ts(ts,"test_vtide.dat",sep = " ")
Writing cdec format, with csv values and date and time separated. The header is generated with the cdec_header helper function
>>> head = cdec_header("practice.csv",ts,"PST","Wind Vel","m/s") >>> write_ts(ts,"test_cdec.csv",CDECDATEFMT,"%.2f",header=head)
schimpy.yaml_util module
- class schimpy.yaml_util.NamedStringIO(value, name='in_memory.yaml')
Bases:
StringIO- Attributes:
- closed
encodingEncoding of the text stream.
errorsThe error setting of the decoder or encoder.
- line_buffering
newlinesLine endings translated so far.
Methods
close(/)Close the IO object.
detach(/)Separate the underlying buffer from the TextIOBase and return it.
fileno(/)Return underlying file descriptor if one exists.
flush(/)Flush write buffers, if applicable.
getvalue(/)Retrieve the entire contents of the object.
isatty(/)Return whether this is an 'interactive' stream.
read([size])Read at most size characters, returned as a string.
readable(/)Returns True if the IO object can be read.
readline([size])Read until newline or EOF.
readlines([hint])Return a list of lines from the stream.
seek(pos[, whence])Change stream position.
seekable(/)Returns True if the IO object can be seeked.
tell(/)Tell the current file position.
truncate([pos])Truncate size to pos.
writable(/)Returns True if the IO object can be written.
write(s, /)Write string to file.
writelines(lines, /)Write a list of lines to stream.
- schimpy.yaml_util.csv_from_file(filename, envvar=None, **kwargs)
Load a CSV file and substitute environment variables in string fields.
- Parameters:
- filenamestr
Path to the CSV file.
- envvardict, optional
Dictionary of variables to substitute (e.g., {‘calsim_dss’: ‘blah.dss’}).
- kwargspassed to pd.read_csv
- Returns:
- pd.DataFrame
DataFrame with substitutions applied.
- schimpy.yaml_util.write_yaml(data, outfile)
Write a dictionary to a YAML file.
- Parameters:
- datadict
The data to write to the YAML file.
- outfilestr|Path
The path to the output YAML file.
- schimpy.yaml_util.yaml_from_dict(input_dict, envvar=None)
Convert a dictionary to a YAML string with environment variable substitution.
- Parameters:
- input_dictdict
The dictionary to convert to YAML.
- envvardict, optional
Environment variables to substitute in the YAML output.
- Returns:
- str
The YAML representation of the dictionary.
- schimpy.yaml_util.yaml_from_file(filename, envvar=None, raw=False)
Load a YAML file and return its contents.
- Parameters:
- filenamestr|Path
The path to the YAML file.
- envvardict, optional
Variables to substitute into the YAML.
- rawbool, optional
If True, leave every scalar as a string instead of resolving YAML types. Needed where the literal text of a value matters.
- Returns:
- dict
The contents of the YAML file as a dictionary.
- schimpy.yaml_util.yaml_to_yaml(infile, outfile, envvar=None)
Load a YAML file and write its contents to another YAML file.
- Parameters:
- infilestr|Path
The path to the input YAML file.
- outfilestr|Path
The path to the output YAML file.
- envvardict, optional
Environment variables to substitute in the YAML file.