bdschism package
Subpackages
Submodules
bdschism.analyze_dt module
- bdschism.analyze_dt.load_data(ncfile, time_step=None)[source]
Load time step and mesh data from a SCHISM NetCDF file.
- Parameters:
ncfile (str) – Path to the NetCDF file.
time_step (int or None) – Specific time index to select. If None, load all.
- Returns:
Time step values, x-coordinates, y-coordinates.
- Return type:
tuple of (np.ndarray, np.ndarray, np.ndarray)
bdschism.barrier_status module
make_south_delta_barrier_status.py
- Reads four barrier installation files (space-separated, #-commented) with at least:
datetime
install
And for Grant Line, an additional weir elevation column (accepts either ‘elev_weir’ or ‘weir_elev’).
Computes the per-barrier installation status at midnight (last known value strictly BEFORE each midnight) and writes a single CSV with per-barrier status plus an ag_count column.
- Special rule for Grant Line:
If the weir-elevation column exists and is < 0 at a timestamp, treat the instantaneous ‘install’ value as 0.5 (partial). This is applied before computing the midnight state. (So daily ‘grantline’ may be 0, 0.5, or 1.0.)
- ag_count:
Sum of the three ag barriers (oldr_tracy, midr, grantline) using their numeric daily values (so totals like 2.5 are possible). oldr_head is excluded from ag_count.
- Output:
south_delta_barrier_install_and_count_daily.csv Columns: date, oldr_tracy, midr, grantline, oldr_head, ag_count
bdschism.calc_ndoi module
- bdschism.calc_ndoi.calc_indoi(flux_file='flux.th', vsource_file='vsource.th', vsink_file='vsink.th', time_basis=None, elapsed_unit='s', flux_head='/home/runner/work/BayDeltaSCHISM/BayDeltaSCHISM/bdschism/bdschism/../.././data/time_history/flux.th', sink_head='/home/runner/work/BayDeltaSCHISM/BayDeltaSCHISM/bdschism/bdschism/../.././data/channel_depletion/vsink_dated.th', source_head='/home/runner/work/BayDeltaSCHISM/BayDeltaSCHISM/bdschism/bdschism/../.././data/channel_depletion/vsource_dated.th')[source]
Calculate an estimate of Net Delta Outflow from boundary inputs applied to SCHISM
bdschism.ccf_gate_height module
Estimate Clifton Court Forebay Gate opening height.
This module provides functions to estimate the gate opening height for Clifton Court Forebay based on SWP export, eligible intervals for opening, priority level, maximum gate height allowed, OH4 stage level, and CVP pump rate for a given period.
- bdschism.ccf_gate_height.ccf_gate(sdate, edate, dest, astro_ts, swp_ts, cvp_ts, sjr_ts, sffpx_elev_ts, plot=False, save_intermediate=False, diagnostic_output=None, diagnostic_dt='5min')[source]
Generate the predicted gate height for the Clifton Court Forebay.
- Parameters:
sdate (datetime.datetime) – Start date .
edate (datetime.datetime) – End date .
dest (str) – Destination file where the output file will be saved. ex: “ccfb_gate_syn.th”
astro_ts (pd.DataFrame) – Astronomical oh4 tide time series required for processing.
swp_ts (pd.DataFrame) – SWP time series required for height processing.
cvp_ts (pd.DataFrame) – CVP time series required for height processing.
sffpx_elev_ts (pd.DataFrame) – SFFPX elevation time series required for height processing.
plot (bool, optional) – If True, a plot of the predicted gate height will be displayed (default is False).
save_intermediate (bool, optional) – If True, intermediate results will be saved to files (default is False).
- Returns:
The function saves the predicted gate height data to a file and optionally displays a plot.
- Return type:
None
Notes
The output file is saved to the destination file. The function processes the height data, removes continuous duplicates, and adds additional columns for installation, operation, elevation, and width parameters.
- bdschism.ccf_gate_height.create_priority_series(p1, p2, p3, p4, priority, stime, etime)[source]
Choose priorities day-by-day based on the value of the priority argument
- bdschism.ccf_gate_height.flow_to_max_gate(flow, breaks=[-100, 400, 1200, 3000.0, 4000, 99999.0], labels=[3, 5, 8, 10, 16])[source]
Convert export flows to max gate height on numerical brackets with breaks.
- bdschism.ccf_gate_height.flow_to_priority(flow, breaks=[-100, 2000, 4000.0, 9000.0, 99999.0], labels=[1, 2, 3, 4])[source]
Convert export flows to priorities based on numerical brackets with breaks. Labels must be integers
- bdschism.ccf_gate_height.gen_gate_height(export_ts, priority, max_height, oh4_level, cvp_ts, inside_level0, s1, s2, dt)[source]
Estimate Clifton Court Forebay Gate opening height.
This function estimates the opening height of the Clifton Court Forebay (CCFB) radial gates based on SWP export, eligible intervals for opening and priority level, maximum gate height allowed, OH4 stage level, CVP pump rate, and other operational rules for a given period.
Gate Opening Conditions
Priority Eligibility: The gate opens only if priority eligibility criteria are met.
Water Level Difference: The gate opens if the water level outside the forebay is higher than the water level inside.
Early Gate Closure
The gate will close early if the volume of water above the 2 ft contour is sufficient to cover the remaining water allocation for the day. This simulates field operations where operators aim to maintain water elevation as close to 2 ft as possible.
Gate Remains Open
The gate will remain open if the volume of water above the 2 ft contour is insufficient to cover the daily allocation, preventing the water level inside the forebay from dropping too low.
Gate Height Calculation
The default gate height is 16 ft, but a maximum height based on export level is applied.
The height is adjusted to prevent flow from exceeding 12,000 cfs, reflecting operational constraints.
The gate height is calculated using a simplified version of the flow rating equation:
Gate Height = 11 × (Head)^-0.3 - 0.5
where Head = Water level upstream - Water level in the reservoir.
- param export_ts:
Series of SWP pumping rate.
- type export_ts:
pandas.Series
- param priority:
CCFB gate operation priority series, must have ‘priority’ and ‘op’ columns.
- type priority:
pandas.DataFrame
- param max_height:
CCFB gate maximum allowed open height.
- type max_height:
pandas.DataFrame
- param oh4_level:
OH4 surface stage, predicted or historical.
- type oh4_level:
pandas.DataFrame
- param cvp_ts:
CVP pumping rate.
- type cvp_ts:
pandas.DataFrame
- param inside_level0:
Initial CCFB surface stage.
- type inside_level0:
float
- param s1:
Start time.
- type s1:
pd.Timestamp
- param s2:
End time.
- type s2:
pd.Timestamp
- param dt:
Output time step.
- type dt:
pd.Timedelta
- returns:
gate_height (pandas.DataFrame) – Radial gate height time series.
zin (pandas.DataFrame) – Predicted forebay inside water level time series.
- bdschism.ccf_gate_height.get_flux_ts_cfs(s1, s2, flux)[source]
Retrieve SWP, CVP, and SJR flows from a SCHISM flux.th file in cfs.
SJR is sign-adjusted so positive values represent San Joaquin River inflow.
- bdschism.ccf_gate_height.make_priorities(input_tide, stime, etime, save_intermediate=False)[source]
Function that makes the priorities schedule time series based on the predicted tide at San Francisco.
- Parameters:
input_tide (
Series) – Time series of the Predicted tide at SF in LST The time series should be taken from the datastore (water level in m, NAVD88). Headers: datetime,predicted_m,elev_m.stime (
pd.Timestamp) – start time.etime (
pd.Timestamp) – end time.Output (3 irregular time series that contain the schedule for the priority 1, 2 and 3.)
- bdschism.ccf_gate_height.predict_oh4_level(s1, s2, oh4_astro_ts, sffpx_elev_ts, sjr_ts)[source]
Predict total OH4 stage using harmonic tide, SFFPX subtidal, and SJR flow.
- bdschism.ccf_gate_height.process_height(s1, s2, swp_ts, cvp_ts, sjr_ts, oh4_astro_ts, sffpx_elev_ts, save_intermediate=False)[source]
Create a ccfb radial gate height time series file
- Parameters:
s1 (
datetime.datetime) – start time.s2 (
datetime.datetime) – end time.swp_ts (
pandas.dataframe) – swp export time series.cvp_ts (
pandas.dataframe) – cvp export time series.oh4_astro_ts (
pandas.dataframe) – OH4 astronomic tide time series.sffpx_elev_ts (
pandas.dataframe) – sffpx elevation time series.
- Returns:
sim_gate_height (
pandas.DataFrame) – predicted radial gate heightzin_df (
pandas.DataFrame) – predicted ccfb interior surface stage.
- bdschism.ccf_gate_height.radial_gate_flow(zdown, zup, height, n=5, width=None, zsill=None)[source]
compuate ccf radial gate flow in cubic feet/s
- Parameters:
n – number of gate opened
width – width of the each gate (default: 6.096 * M2FT)
zup – upstream water elevation
zsill – elevation of gate sill (default: -4.044 * M2FT)
zdown – downstream water elev
height – gate opening height
- Returns:
gate flow in cfs
- bdschism.ccf_gate_height.remove_continuous_duplicates(df, column_name)[source]
Removes consecutive duplicate values in a specified column of a Pandas DataFrame.
- Parameters:
df (pd.DataFrame) – The input DataFrame.
column_name (str) – The name of the column to check for duplicates.
- Returns:
A new DataFrame with consecutive duplicates removed.
- Return type:
pd.DataFrame
bdschism.channel_depletion module
Convert channel depletion model NetCDF output to source/sink CSVs.
Output flows are in CFS. The CFS-to-CMS conversion is deferred to the
merge_th assembly step via scale_factor in source_sink_integration.yaml.
DSS format is not supported.
- bdschism.channel_depletion.convert_channel_depletion(config_file, set_vars=None)[source]
Load YAML config with
$variablesubstitution and run NetCDF conversion.- Parameters:
config_file (str or Path) – Path to conversion config YAML (e.g.
convert_config_delta.yml).set_vars (dict, optional) – Variable overrides applied during
$variablesubstitution, e.g.{'version': '20260101'}.
- Raises:
ValueError – If required config keys are missing or
modeis not'flow'.
- bdschism.channel_depletion.convert_nc_flow(infile, start_date, output_dir, outfile_prefix, col_prefix, scale_sink_mult=1.0, scale_sink_add=0.0)[source]
Convert channel depletion NetCDF to per-component CSV files (CFS).
Writes individual component files (div, drain, seep) and combined source and sink CSVs. All flow values are in CFS. Sinks are negative.
- Parameters:
infile (str) – Path to NetCDF file containing diversion, drainage, and seepage variables.
start_date (str) – Clip output to timestamps on or after this date (ISO format).
output_dir (str or Path) – Directory for CSV output files. Created if it does not exist.
outfile_prefix (str) – Prefix for output filenames (e.g.
'dcd_20251111').col_prefix (str) – Column name prefix (e.g.
'delta','suisun').scale_sink_mult (float, optional) – Multiplier applied to combined sink (div+seep) in CFS before writing. Default 1.0.
scale_sink_add (float, optional) – Constant (CFS) added to sink after multiplier. Default 0.0.
bdschism.check_nudging_data module
Command line tools for nudging data validation and splicing
- bdschism.check_nudging_data.load_nc_series(nc_file)[source]
- Parameters:
nc_file (str) – Path to NetCDF file.
- Returns:
df (pandas.DataFrame) – DataFrame indexed by datetime with flattened spatial dimensions.
ds (xarray.Dataset) – Original dataset used as template.
- bdschism.check_nudging_data.validate_nudging_files(input_path, min_salt, max_salt, min_temp, max_temp, yaml_file=None, quick=False)[source]
Validate nudging data files for completeness and data quality.
Checks that: - All files between earliest and latest dates exist (daily interval) - No data contains NaN or infinity - Temperature and salinity values are within specified bounds
Supports multiple filename conventions: - hycom_interpolated_hourly_pst20181206.nc - cencoos_hourly_pst20140108.nc - ca_subSFB_fcst_hourly_pst20050119.nc
- Parameters:
input_path (str) – Path to either a directory containing .nc files or a single .nc file.
min_salt (float) – Minimum acceptable salinity value.
max_salt (float) – Maximum acceptable salinity value.
min_temp (float) – Minimum acceptable temperature value.
max_temp (float) – Maximum acceptable temperature value.
yaml_file (str, optional) – Path to YAML file with include/exclude polygon specifications.
quick (bool, optional) – If True, checks all criteria for each variable, then moves to the next variable. Once any criterion fails for a variable, remaining criteria are skipped for that variable (default: False). This identifies bad files quickly without detailed reporting.
- Returns:
bool – True if all validations pass, False otherwise.
dict – Dictionary with validation results and details about any failures.
bdschism.combine_hotstart module
- bdschism.combine_hotstart.combine_hot(run_dir: str = '.', outputs_dir: str = 'outputs', prefix: str = '', latest: bool = False, before: str | Timestamp | None = None, iteration: int | None = None, every: int | None = None, out_dir: str | None = None, link: bool = False, config_log: bool = False, overwrite: bool = False) List[str][source]
High-level API to combine SCHISM hotstart files.
This wraps the native combine_hotstart executable (configured via bdschism settings) and schimpy.hotstart_inventory to map between iterations and datetimes.
- Parameters:
run_dir (str, optional) – SCHISM run directory. Defaults to current directory.
outputs_dir (str, optional) – Directory containing parallel hotstart_000000_*.nc files. Default ‘outputs’. If relative, interpreted relative to run_dir.
prefix (str, optional) – Optional prefix inserted after ‘hotstart.’ in the output filename.
latest (bool, optional) – If True, select the most recent hotstart.
before (str or pandas.Timestamp, optional) – Select the last hotstart on or before this date.
iteration (int, optional) – Combine this specific iteration.
every (int, optional) – Archive every Nth hotstart in time order (10 -> 10th, 20th, …).
out_dir (str, optional) – Archive directory. If relative, interpreted relative to run_dir.
link (bool, optional) – If True, create hotstart.nc in run_dir pointing to the most recently created file using bdschism.settings.create_link.
config_log (bool, optional) – If True, log configuration source when loading settings.
overwrite (bool, optional) – If True, allow overwriting an existing destination file.
- Returns:
Absolute paths of the combined hotstart files that were created.
- Return type:
list of str
bdschism.combine_nc module
- bdschism.combine_nc.combine_nc(input_files, outfile, reset_time=False)[source]
Combines multiple NetCDF files (e.g., out2d_1.nc, out2d_2.nc, etc.) into a single NetCDF file along the time dimension.
- bdschism.combine_nc.combine_uv3d(start_num, end_num, outfile, tmp_out_dir='./outputs.tropic/uv3d', reset_time=False)[source]
- bdschism.combine_nc.compare_dataarray_all_axes(validate_da, check_da, atol=1e-06, rtol=1e-06)[source]
Check two DataArrays match on dims, coords, shape, and values.
bdschism.config_cli module
bdschism.convert_csv_th module
Convert dated CSV time series to SCHISM time-history (.th) format.
Handles auto-detection of headers, optional time clipping, and output in either dated (ISO timestamp) or elapsed-seconds format.
- bdschism.convert_csv_th.convert_csv_th(infile, outfile, dated, reftime=None, start=None, end=None)[source]
Convert a dated CSV to a SCHISM time-history file.
- Parameters:
infile (str or Path) – Input CSV with a datetime index. Comment lines (
#) are preserved in dated output mode.outfile (str or Path) – Output
.thfile path.dated (bool) – If True, write ISO timestamps (
%Y-%m-%dT%H:%M). If False, convert the index to elapsed seconds from reftime.reftime (str or Timestamp, optional) – Reference time for elapsed conversion. Required when dated is False.
start (str or Timestamp, optional) – Clip output to rows on or after this time.
end (str or Timestamp, optional) – Clip output to rows on or before this time.
- Raises:
ValueError – If reftime is not provided when dated is False, or if the detected index is not time-related.
- bdschism.convert_csv_th.detect_header(infile)[source]
Detect whether a CSV has a header row and the number of index columns.
Skips comment lines starting with
#. Identifies a header by finding a row whose first column is not parseable as a timestamp but is followed by a row that is.- Parameters:
infile (str or Path) – Path to input CSV.
- Returns:
has_header (bool) – True if a header row was detected.
index_size (int) – Number of header rows used as column index (0 or 1).
- Raises:
ValueError – If a potential header row has no recognisable index name.
bdschism.convert_struct_data_schism module
Convert processed structure gate products to SCHISM .th input files.
Supported --structure choices:
ccfb_radial: CCFB radial gate product (ndup/height in feet) fromstructures_processed.
smscg_radial_ops: SMSCG radial gate operation coefficients fromstructures_processedops log.
smscg_radial_heights: SMSCG radial heights derived from Wonderware gateposition data in
structures_formatted.
smscg_flash: SMSCG flashboards coefficients from ops log.smscg_boat_lock: SMSCG boat lock coefficients from ops log using theinverse status mapping of
smscg_flash.
bdschism.create_sflux_links module
bdschism.cruise module
- bdschism.cruise.check_read_output10_xyt_available()[source]
Check if read_output10_xyt executable is available in PATH.
Verifies that the SCHISM read_output10_xyt utility is available in the system PATH. This executable is required for extracting model profiles from SCHISM output files.
- Raises:
FileNotFoundError – If read_output10_xyt executable is not found in PATH, with a helpful error message instructing the user how to add it to their environment.
- bdschism.cruise.cruise_plot(data_path, start='2011-03-29', schism_output_path=None, output_stem='salinity_profiles', xmin=20, xmax=104, max_depth=30, use_yearly_format=True, target_stations=None, depth_thresholds=None)[source]
Main work function: Process USGS cruise data and generate comparison plots.
This is the primary work function (as distinguished from CLI wrapper). It orchestrates the complete workflow:
Load and filter USGS cruise observations (yearly or daily format)
For yearly format: apply multi-pass filtering (stations, depth, time)
For each valid date: generate date-specific xyt model extraction request
Extract model salinity profiles from SCHISM output
Generate publication-quality comparison figures (observed vs. model)
- Parameters:
data_path (str) – Path to folder containing cruise data and station metadata.
start (str, optional) – SCHISM model start date (default: 2011-03-29). Used as reference for elapsed time calculations and filtering observations (excludes spinup period).
schism_output_path (str, optional) – Path to SCHISM output folder. If None, defaults to <data_path>/2011outputs.
output_stem (str, optional) – Output file stem for plots (default: ‘salinity_profiles’). PNG and PDF files will be written.
xmin (float, optional) – Distance range limits in km (default: 20-104 km).
xmax (float, optional) – Distance range limits in km (default: 20-104 km).
max_depth (float, optional) – Maximum depth to plot (default: 30 m).
use_yearly_format (bool, optional) – If True, expects yearly CSV files (usgs_cruise_yyyy.csv) with multi-pass filtering. If False, expects daily files (usgs_cruise_yyyymmdd.txt or .csv).
target_stations (list of str, optional) – Station IDs to include. Defaults to [‘2’, ‘3’, …, ‘20’, ‘649’, ‘657’].
depth_thresholds (dict, optional) – Depth thresholds for specific stations (yearly format only). E.g., {‘7’: 9, ‘8’: 9, ‘9’: 9} requires depth > 9 meters. Defaults to {‘7’: 9, ‘8’: 9, ‘9’: 9}.
- Returns:
Generates output figures as PNG and PDF files in data_path.
- Return type:
None
- Raises:
FileNotFoundError – If required files are missing: vgrid.in, read_output_xyt.in, usgs_cruise_stations.csv, cruise data files, or if read_output10_xyt executable is not found in PATH.
ChildProcessError – If read_output10_xyt command fails during model extraction.
Notes
Expected file layout for yearly format:
<data_path>/usgs_cruise_2011.csv (or other years) <data_path>/usgs_cruise_stations.csv <data_path>/2011outputs/vgrid.in <data_path>/2011outputs/read_output_xyt.in <data_path>/2011outputs/out2d_1.nc
For yearly format, a date is included only if ALL target stations have valid observations. Temporary files are cleaned up after plotting.
- bdschism.cruise.cruise_xyt(path, station_data, base_time, outfile)[source]
Generate SCHISM model extraction request file (xyt format) from cruise data.
Creates a request file for SCHISM’s read_output10_xyt utility, specifying which model casts to extract based on cruise observation station locations and times. Each unique station on the cruise is mapped to a model cast request.
- Parameters:
path (str) – Path to cruise observation file with format: Date,Time,Station,Depth,Salinity (with header)
station_data (pd.DataFrame) – Station metadata DataFrame from process_stations(), indexed by station ID. Must contain columns: x, y, name
base_time (datetime.datetime) – Reference time for computing elapsed seconds in model output.
outfile (str) – Output path where xyt request file will be written.
- Returns:
Dictionary mapping cast number (int, 1-indexed) to tuple: (x_coord, y_coord, elapsed_seconds, station_name, station_id)
- Return type:
dict
Notes
The xyt format is used by SCHISM’s read_output10_xyt utility to extract model profiles at specific cast locations and times.
- bdschism.cruise.do_depth_plot(station, cruise_data, surrounding_profiles, ax, xlabel, ylabel, add_legend=False)[source]
- bdschism.cruise.gen_multi_profile_plot(base_date, cruise_records, station_file, output_stem='salinity_profiles', xmin=20, xmax=104, max_depth=30)[source]
Create multi-panel paper figure comparing observed vs. model profiles.
Generates a publication-quality figure with one row per cruise date, comparing observed salinity (left column) with SCHISM model salinity (right column). Handles layout, colorbars, and file saving automatically.
- Parameters:
base_date (datetime.datetime) – SCHISM model start date (for elapsed time calculation).
cruise_records (list of dict) – Each record has keys
time,obs_file,model_file,xyt_file. Each row becomes one date/cruise comparison in the figure.station_file (str) – Path to station metadata CSV file.
output_stem (str, optional) – Output filename stem for saved figures (default: “salinity_profiles”). Figures saved as <stem>.png and <stem>.pdf.
xmin (float, optional) – Distance range limits in km (default 20-104 km).
xmax (float, optional) – Distance range limits in km (default 20-104 km).
max_depth (float, optional) – Maximum depth to display (default 30 m).
- Returns:
Saves figures to disk as PNG and PDF files using _save_figure().
- Return type:
None
- Raises:
ValueError – If cruise_records is empty.
- bdschism.cruise.gen_profile_plot(base_date, cruise_time, survey_file, model_file, station_file, xytfile, ax_obs=None, ax_model=None, is_top=True, xmin=20, xmax=104, max_depth=30)[source]
Generate comparison profile plot of observed vs. model salinity along transect.
Creates a contour plot comparing observed cruise salinity (left) with SCHISM model salinity (right) along a transect for a single cruise date. If axes are provided, adds plots to shared figure; otherwise creates standalone figure and saves as PNG (600 dpi) and PDF.
- Parameters:
base_date (datetime.datetime) – SCHISM model start date (for elapsed time calculation).
cruise_time (datetime.datetime) – Date/time of cruise observations.
survey_file (str) – Path to temporary cruise observation file (single date format).
model_file (str) – Path to model output fort.18 file (date-specific).
station_file (str) – Path to station metadata CSV file.
xytfile (str) – Path to xyt model extraction request file.
ax_obs (matplotlib.axes.Axes, optional) – Axes for observation plot. If None, creates standalone figure.
ax_model (matplotlib.axes.Axes, optional) – Axes for model plot. If None, creates standalone figure.
is_top (bool, optional) – Whether this is the top row (used for label placement).
xmin (float, optional) – Distance range limits in km (default 20-104 km).
xmax (float, optional) – Distance range limits in km (default 20-104 km).
max_depth (float, optional) – Maximum depth to display (default 30 m).
- Returns:
Contour collection from model plot (used for colorbar). Returns None if plot is not standalone.
- Return type:
matplotlib.contourf or None
- bdschism.cruise.gen_station_xyt(base_date, cruise_time, survey_file, station_file, xytfile)[source]
Generate xyt request file from cruise observation data.
Convenience wrapper that loads station data, reads cruise observations, and generates the xyt model extraction request file. This is used to create station-specific model extraction files for SCHISM output post-processing.
- Parameters:
base_date (datetime.datetime) – Reference date for SCHISM model start time (for elapsed time calculation).
cruise_time (datetime.datetime) – Time of cruise observations (used to compute elapsed time from base_date).
survey_file (str) – Path to cruise observation data file.
station_file (str) – Path to station metadata CSV file.
xytfile (str) – Output path for xyt request file.
- Returns:
Generates xytfile as side effect. xytfile contains station locations and times formatted for SCHISM’s read_output10_xyt utility.
- Return type:
None
- bdschism.cruise.longitudinal(cruise_data, station_data, ax, context_label=None, add_labels=False, xlabel=None, xmin=None, xmax=None, max_depth=None, ylabel=True, show_xticklabels=True)[source]
- bdschism.cruise.model_data_for_longitude(cruise_data, station_data, x, z, times, model_data, base_date)[source]
- bdschism.cruise.process_cruise(path)[source]
Load and organize single cruise observation data from file.
Reads cruise data from a text file, organizes observations by station, validates salinity values, and sorts depths in ascending order for each station. This function handles the temporary single-date format created from yearly CSV data.
- Parameters:
path (str) – Path to cruise data file with CSV format: Date,Time,Station,Depth(m),Salinity (with header line)
- Returns:
Dictionary mapping station ID (str) to tuple of: (depth_array, salinity_array, observation_datetime). Both depth and salinity are numpy arrays sorted by depth (ascending).
- Return type:
dict
- Raises:
ValueError – If salinity values cannot be converted to float for a given station. That station is excluded and a warning is printed.
- bdschism.cruise.process_cruise_yearly_csv(path, target_stations=None, depth_threshold_stations=None, model_start_time=None)[source]
Process yearly USGS cruise data from CSV file.
- Parameters:
path (str) – Path to yearly CSV file (e.g., usgs_cruise_2011.csv)
target_stations (list, optional) – List of station IDs to include. If None, all stations are included. Expected format: list of strings like [‘2’, ‘3’, …, ‘649’, ‘657’]
depth_threshold_stations (dict, optional) – Dictionary mapping station IDs to minimum depth threshold. E.g., {‘7’: 9, ‘8’: 9, ‘9’: 9} means stations 7, 8, 9 need depth > 9. If the maximum depth for a station on a given day is below threshold, ALL observations for that station on that day are excluded.
model_start_time (datetime, optional) – Filter out observations made before this time and within 1 month after start. If None, no time filtering applied.
- Returns:
Dictionary of cruise records indexed by date string (YYYY-MM-DD format). Each value is a dict mapping station ID to (depth, salinity, time) tuple.
- Return type:
dict
- bdschism.cruise.process_stations(station_file)[source]
Load and process USGS cruise station metadata.
Reads station information from CSV file and normalizes station IDs by removing trailing “.0” suffixes. Converts distance from meters to kilometers. Station data is indexed by ID for efficient lookup during cruise processing.
- Parameters:
station_file (str) – Path to CSV file containing station metadata. Expected format: id, x, y, dist_km, elev_navd, name, depth_mllw
- Returns:
DataFrame indexed by station ID (str) with columns: x (longitude), y (latitude), dist_km (distance in km), elev_navd, name, depth_mllw. Distance values are converted from meters to kilometers.
- Return type:
pd.DataFrame
- bdschism.cruise.process_xyt(path, casts, base_time)[source]
Load SCHISM model output from fort.18 (xyt format) file.
Parses SCHISM model salinity profiles extracted to fort.18 format, maps results to station IDs using the casts mapping, and organizes data by station with depths sorted in ascending order.
- Parameters:
path (str) – Path to fort.18 model output file containing extracted salinity profiles.
casts (dict) – Dictionary mapping cast number (int) to tuple: (x_coord, y_coord, elapsed_time, name, station_id). Typically generated by cruise_xyt().
base_time (datetime.datetime) – Reference time for converting elapsed seconds in fort.18 to absolute times.
- Returns:
Dictionary mapping station ID (str) to tuple of: (depth_array, salinity_array, observation_time). Depths and salinities are numpy arrays sorted by depth.
- Return type:
dict
- Raises:
ValueError – If cast number in fort.18 is not found in casts mapping.
- bdschism.cruise.validate_out2d_time_variable(out2d_path)[source]
Validate that SCHISM output file contains valid time dimension data.
Checks that the out2d_*.nc file exists and contains a non-empty, non-NaN ‘time’ variable with numeric values. This validation ensures the file is suitable for SCHISM model extraction via read_output10_xyt.
- Parameters:
out2d_path (str) – Path to SCHISM out2d_*.nc output file to validate.
- Raises:
FileNotFoundError – If the specified out2d file does not exist.
ValueError – If time variable is missing, empty, or contains invalid/NaN values.
bdschism.diff_gr3 module
bdschism.gen_elev2d module
Generate elev2D.th for a Bay-Delta SCHSIM model using tides at Point Reyes and Monterey.
2015-06-16: Customized
- class bdschism.gen_elev2d.NetCDFTHWriter(fpath_out, nloc, starttime, dt, slr, hgrid_fpath)[source]
Bases:
THWriter
- bdschism.gen_elev2d.gen_elev2D(hgrid_fpath, outfile, pt_reyes_fpath, monterey_fpath, start, end, slr)[source]
Generate elev2D.th or elev2D.th.nc file for Bay-Delta SCHISM model using Point Reyes and Monterey tide data.
Arguments: hgrid_fpath: Path to hgrid file (e.g. hgrid.gr3) outfile: Path to output file (e.g. elev2D.th or elev2D.th.nc) pt_reyes_fpath: Path to Point Reyes data file(s) or station code (e.g. “/path/to/noaa_pryc1_9415020_elev_*.csv”) monterey_fpath: Path to Monterey data file(s) or station code (e.g. “path/to/noaa_mtyc1_9413450_elev_*.csv”) start: Start time (e.g. “2025-8-27”) end: End time (e.g. “2026-01-04”) slr: Sea level rise increment in meters (e.g. 0.0)
Example usage: > gen_elev2D.py –outfile elev2D.th.nc –hgrid=hgrid.gr3 –stime=2025-8-27 –etime=2026-01-04 –slr 0.0 “/path/to/noaa_pryc1_9415020_elev_*.csv” “path/to/noaa_mtyc1_9413450_elev_*.csv”
bdschism.generate_realtime_elev2d module
- bdschism.generate_realtime_elev2d.stitch_station(df_cur, df_past, df_pred, t_stitch=None)[source]
Stitch the historical water lever with the prediction one
- Parameters:
df_cur (pd.DataFrame) – The current historical data
df_past (pd.DataFrame) – The past historical data
df_pred (pd.DataFrame) – The prediction data
t_transition (datetime, optional) – The time of transition between the historical and prediction data
bdschism.generate_visit_filelist module
- bdschism.generate_visit_filelist.visit_list(output_dir, var, start, end, output, overwrite)[source]
Generate a file containing a list of SCHISM output files to be visualized on VisIt.
- Parameters:
output_dir (str) – Outputs directory containing SCHISM output files.
var (str) – variable name for SCHISM output files (e.g., horizontalVelX).
start (int) – Starting index for the file list.
end (int) – Ending index for the file list.
output (str) – Filename for the list of SCHISM output files.
bdschism.hotstart_date module
bdschism.hotstart_from_hotstart module
Adapted from ZZheng - generate hotstart - transfer from one grid to another
bdschism.hotstart_nudging_data module
bdschism.logging_config module
- class bdschism.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)[source]
Bases:
object- clear_handlers: bool = True
- console: bool = True
- include_pid_in_filename: bool = True
- include_third_party: bool = False
- level: int = 20
- logdir: Path | None = None
- logfile_prefix: str = 'run'
- package_name: str
- propagate: bool = False
- bdschism.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[source]
- bdschism.logging_config.configure_logging_config(cfg: LoggingConfig) Path | None[source]
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.
- bdschism.logging_config.resolve_loglevel(*, debug: bool = False, quiet: bool = False, verbose: int = 0, loglevel: str | None = None) tuple[int, bool][source]
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
bdschism.nc_metadata module
bdschism.ocean_boundary_ops module
bdschism.parse_cu module
Script by Lily Tomkovic to take a net delta consumptive use and parse it into vsource and vsink
- bdschism.parse_cu.adjust_src_sink(src, sink, net_diff, sinkfrac=0.001, debug=False)[source]
Distributes a perturbation to dataframe sc and sink
- Parameters:
src (DataFrame) – DataFrame of positive sources.
sink (DataFrame) – DataFrame of sinks. Must be all of the same sign. If positive, they are assumed to represent the the magnitude of the (latent) sinks. If they are negative, they are the sink values themselves. Return value will match the convention of the input.
net_diff (Series) – Series representing a perturbation to be distributed proportionally over src and sink. Sign convention agrees with that of src. When net_diff is negative, it augments sink. When it is positive it reduces the sink until sinkfrac fraction of the sink is exhausted, after which the remainder augments the source.
sinkfrac (float) – Fraction of sink that can be reduced in order to achieve the perturbation by reducing the sink. Remainder is applied by augmenting src. Has no effect on time steps when net_diff is negative.
debug (bool) – If True, prints out debug information about the input src and sink DataFrames.
- Returns:
src (DataFrame) – DataFrame of adjusted sources, with the same sign convention as the input src.
sink (DataFrame) – DataFrame of adjusted sinks, with the same sign convention as the input sink.
- bdschism.parse_cu.calc_net_calsim(dcd_dss_calsim, start_date=None, end_date=None, dt=<Day>, **kwargs)[source]
Get net consumptive use timeseries from Calsim DSS file.
- Parameters:
dcd_dss_calsim (str|Path) – Path to the Calsim DSS file. Contains DICU_FLOW data.
start_date (pd.Timestamp, optional) – Start date for the timeseries.
end_date (pd.Timestamp, optional) – End date for the timeseries.
dt (float or pd.DateOffset, optional) – Time step in days for interpolation.
kwargs (dict, optional) – Additional keyword arguments to pass to the read_dss function. (unused in this function)
- Returns:
DataFrame with a single column named ‘net’ containing net consumptive use in cfs. The data is read from the DICU_FLOW path in the Calsim DSS file.
- Return type:
pd.DataFrame
- bdschism.parse_cu.calc_net_diff(original_net, adjusted_net, cfs_to_cms=True)[source]
Calculate the difference in net CU between original and adjusted data in cms.
- Parameters:
original_net (pd.DataFrame) – DCD net source and sink data from original timeseries. Used to calculate difference in net CU to apply to SCHISM inputs. Entered as a DataFrame with a single column or Series with units of cfs by default.
adjusted_net (pd.DataFrame) – DCD net source and sink data from adjusted timeseries. Used to calculate difference in net CU from original to apply to SCHISM inputs Entered as a DataFrame with a single column or Series with units of cfs by default.
cfs_to_cms (bool) – Set to True if net data is in cfs and needs to be converted to cms for SCHISM. Only set to False if net data is in cms.
- Returns:
Series of the net difference in CU between original and adjusted data.
- Return type:
pd.Series
- bdschism.parse_cu.calc_net_dsm2(dcd_dss_file, start_date=None, end_date=None, dt=<Day>, exclude_pathname=['//*TOTAL*/////', '//CU/////', '//*DIV*SEEP*/////', '//SUM/////'], **kwargs)[source]
Get net timeseries from DCD DSS file.
- Parameters:
dcd_dss_file (str|Path) – Path to the DCD DSS file. Contains DRAIN-FLOW, SEEP-FLOW, and DIV-FLOW data.
start_date (pd.Timestamp, optional) – Start date for the timeseries.
end_date (pd.Timestamp, optional) – End date for the timeseries.
dt (float or pd.DateOffset, optional) – Time step in days for interpolation.
exclude_pathname (str, optional) – Pathname parts to exclude, ex: ‘//TOTAL*/////’
kwargs (dict, optional) – Additional keyword arguments to pass to the read_dss function. (unused in this function)
- Returns:
Series of net consumptive use in cfs, calculated as source - sink.
- Return type:
pd.Series
- bdschism.parse_cu.calc_net_obs_schism(schism_dir, start_date=None, end_date=None, dt=<Day>, **kwargs)[source]
Use the repository to calculate net SCHISM DCU
- bdschism.parse_cu.calc_net_schism(schism_dir, start_date=None, end_date=None, dt=<Day>, **kwargs)[source]
Get net timeseries from SCHISM th files in cfs.
- Parameters:
schism_dir (str|Path) – SCHISM directory where vsource.th and vsink.th files are found.
start_date (pd.Timestamp, optional) – Start date for the timeseries.
end_date (pd.Timestamp, optional) – End date for the timeseries.
dt (float or pd.DateOffset, optional) – Time step in days for interpolation.
kwargs (dict, optional) – Additional keyword arguments to pass to the SCHISM net calculation functions. For example, if the original data has a specific vsource file, you can pass
vsource_original='vsource_dated.th'and it will be used in the calculation. You must use _original or _perturbed suffixes to distinguish between original and perturbed data.
- Returns:
DataFrame with a single column named ‘net’ containing net consumptive use in cfs. The data is calculated from the vsource and vsink files in the SCHISM directory.
- Return type:
pd.DataFrame
- bdschism.parse_cu.calc_srcsnk_dsm2(dcd_dss_file, start_date=None, end_date=None, dt=<Day>, exclude_pathname=['//*TOTAL*/////', '//CU/////', '//*DIV*SEEP*/////', '//SUM/////'])[source]
Get net source and net sink timeseries from DCD DSS file.
- Parameters:
dcd_dss_file (str|Path) – Path to the DCD DSS file. Contains DRAIN-FLOW, SEEP-FLOW, and DIV-FLOW data.
start_date (pd.Timestamp, optional) – Start date for the timeseries.
end_date (pd.Timestamp, optional) – End date for the timeseries.
dt (float or pd.DateOffset, optional) – Time step in days for interpolation.
exclude_pathname (str, optional) – Pathname parts to exclude, ex: ‘//TOTAL*/////’
- Returns:
src (pd.Series) – Series of net source flow in cfs.
sink (pd.Series) – Series of net sink flow in cfs.
- bdschism.parse_cu.orig_pert_to_schism_dcd(original_type, original_filename, perturbed_type, perturbed_filename, schism_vsource, schism_vsink, out_dir, version, start_date=None, end_date=None, dt=<Day>, **kwargs)[source]
Convert original and perturbed DCD data to SCHISM vsource and vsink inputs.
- Parameters:
original_type (str) – Type of the original DCD data (e.g. ‘dsm2’, ‘calsim’, ‘csv’, ‘schism’).
original_filename (str|Path) – Path to the original DCD data file. If DSS then enter the filename. If SCHISM then enter the directory where vsource.th and vsink.th are found.
perturbed_type (str) – Type of the perturbed DCD data (e.g. ‘dsm2’, ‘calsim’, ‘csv’, ‘schism’).
perturbed_filename (str|Path) – Path to the perturbed DCD data file. If DSS then enter the filename. If SCHISM then enter the directory where vsource.th and vsink.th are found.
schism_vsource (str|Path) – Input SCHISM vsource data, needs to be ‘dated’ and not ‘elapsed’.
schism_vsink (str|Path) – Input SCHISM vsink data, needs to be ‘dated’ and not ‘elapsed’.
out_dir (str|Path) – Output directory to store the altered *.th files.
version (str) – Specifies the tag to put on the output files (e.g. vsource.VERSION.dated.th).
start_date (pd.Timestamp, optional) – Start date for the timeseries. If None, uses the start date from the original data.
end_date (pd.Timestamp, optional) – End date for the timeseries. If None, uses the end date from the original data.
dt (float or pd.DateOffset, optional) – Time step in days for interpolation. Default is 1 day.
**kwargs (dict) – Additional keyword arguments to pass to the SCHISM net calculation functions. For example, if the original data has a specific vsource file, you can pass vsource_original=’vsource_dated.th’ and it will be used in the calculation. You must use _original or _perturbed suffixes to distinguish between original and perturbed data.
- bdschism.parse_cu.orig_pert_to_schism_dcd_yaml(yaml_fn, envvar=None)[source]
Convert original and perturbed DCD data to SCHISM vsource and vsink inputs from yaml input file.
- Parameters:
yaml_fn (str|Path) – Path to the YAML file containing configuration.
envvar (dict or None, optional) – Optional dictionary of environment variables or overrides. If None, no overrides are applied.
- bdschism.parse_cu.read_net_csv(csv_file, start_date=None, end_date=None, dt=<Day>, **kwargs)[source]
Read net timeseries from a CSV file. :param csv_file: Path to the CSV file containing net consumptive use data. :type csv_file: str|Path :param start_date: Start date for the timeseries. :type start_date: pd.Timestamp, optional :param end_date: End date for the timeseries. :type end_date: pd.Timestamp, optional :param dt: Time step in days for interpolation. :type dt: float or pd.DateOffset, optional
- bdschism.parse_cu.sch_dcd_net_diff(net_diff, schism_vsource, schism_vsink, out_dir, version, start_date=None, end_date=None, cfs_to_cms=True)[source]
Convert adjusted DCD data from DataFrame into SCHISM-ready *.th inputs.
- Parameters:
net_diff (pd.DataFrame) – DCD net differences from historical or baseline. Used to apply to SCHISM inputs.
schism_vsource (str|Path) – input SCHISM vsource data, needs to be “dated” and not “elapsed.
schism_vsink (str|Path) – input SCHISM vsink data, needs to be “dated” and not “elapsed.
out_dir (str|Path) – Output directory to store the altered *.th files.
version (str) – Specifies the tag to put on the output files (e.g. vsource.VERSION.dated.th)
start_date (pd.Timestamp, optional) – Start date for the timeseries.
end_date (pd.Timestamp, optional) – End date for the timeseries.
cfs_to_cms (bool, optional) – Set to True if net data is in cfs and needs to be converted to cms for SCHISM. Only set to False if net data is in cms.
- bdschism.parse_cu.strip_dpart(colname)[source]
Remove the 5th part of a DSS path, which is the D part. This is used to strip the D part from the column names in the DCD data. :param colname: The column name in the DSS path format. :type colname: str
- Returns:
The column name with the D part removed.
- Return type:
str
bdschism.plot_input_boundaries module
- bdschism.plot_input_boundaries.get_boundary_data(flux_file='flux.th', vsource_file='vsource.th', vsink_file='vsink.th', elev2d_file='elev2D.th.nc', gate_dir='./', gate_suffix='', time_basis=None, rndays=None, elapsed_unit='s', out_freq='1D', flux_head='/home/runner/work/BayDeltaSCHISM/BayDeltaSCHISM/./data/time_history/flux.th', sink_head='/home/runner/work/BayDeltaSCHISM/BayDeltaSCHISM/./data/channel_depletion/vsink_dated.th', source_head='/home/runner/work/BayDeltaSCHISM/BayDeltaSCHISM/./data/channel_depletion/vsource_dated.th', boundary_list=['tide', 'ccc_rock', 'ccc_old', 'ccc_victoria', 'swp', 'cvp', 'ccfb_gate', 'dcu', 'ndo', 'exports', 'sac', 'american', 'yolo_toedrain', 'yolo', 'east', 'calaveras', 'northbay', 'delta_cross_channel', 'montezuma_radial', 'montezuma_flash', 'montezuma_boat_lock', 'grantline_barrier', 'midr_culvert_l', 'midr_culvert_r', 'midr_weir', 'oldr_head_barrier'], struct_fn='hydraulics.in', obs=False)[source]
Get a DataFrame of boundary data from flux, vsource, vsink, and elev2D.th.nc files.
- bdschism.plot_input_boundaries.get_date_data(gate_name, structures, gate_fn='{gate_name}.th', gate_head='/home/runner/work/BayDeltaSCHISM/BayDeltaSCHISM/./data/time_history/{gate_name}.th', time_basis=None, elapsed_unit='s', out_freq='1D', datetime_idx=None)[source]
- bdschism.plot_input_boundaries.get_observed_data(bds_dir='/home/runner/work/BayDeltaSCHISM/BayDeltaSCHISM', boundary_list=['tide', 'ccc_rock', 'ccc_old', 'ccc_victoria', 'swp', 'cvp', 'ccfb_gate', 'dcu', 'ndo', 'exports', 'sac', 'american', 'yolo_toedrain', 'yolo', 'east', 'calaveras', 'northbay', 'delta_cross_channel', 'montezuma_radial', 'montezuma_flash', 'montezuma_boat_lock', 'grantline_barrier', 'midr_culvert_l', 'midr_culvert_r', 'midr_weir', 'oldr_head_barrier'], period={'begin': '2016-09-01', 'end': '2025-02-01'}, out_freq='1D')[source]
Get observed data from the BDS directory, then get tidal data from noaa download.
- bdschism.plot_input_boundaries.get_observed_tide(period={'begin': '2016-09-01', 'end': '2025-02-01'})[source]
- bdschism.plot_input_boundaries.get_required_files(flux_file, vsource_file, vsink_file, elev2d_file, boundary_list, struct_fn='hydraulics.in', gate_dir='./', gate_suffix='')[source]
Get the required files for boundary data.
- bdschism.plot_input_boundaries.plot_bds_bc(sim_dirs, html_name, obs=False, scenario_names=[], sink_head='/home/runner/work/BayDeltaSCHISM/BayDeltaSCHISM/./data/channel_depletion/vsink_dated.th', source_head='/home/runner/work/BayDeltaSCHISM/BayDeltaSCHISM/./data/channel_depletion/vsink_dated.th', envvar={})[source]
- bdschism.plot_input_boundaries.plot_bds_boundaries(bc_data_list, scenario_names, cols_to_keep=None, write_html=True, html_name='bds_input_boundaries.html', boundary_list=['tide', 'ccc_rock', 'ccc_old', 'ccc_victoria', 'swp', 'cvp', 'ccfb_gate', 'dcu', 'ndo', 'exports', 'sac', 'american', 'yolo_toedrain', 'yolo', 'east', 'calaveras', 'northbay', 'delta_cross_channel', 'montezuma_radial', 'montezuma_flash', 'montezuma_boat_lock', 'grantline_barrier', 'midr_culvert_l', 'midr_culvert_r', 'midr_weir', 'oldr_head_barrier'])[source]
Plot the boundary data from the DataFrame.
bdschism.port_boundary module
Script to convert various data formats (from calsim, csv files) into SCHISM flux, salt and temp time history (.th) files
- bdschism.port_boundary.plot_ported_bc(plot_dict, html_name, sd, ed, sim_dir, out_file_suffix='')[source]
- bdschism.port_boundary.read_csv(file, var, name, dt, p=2.0, interp=True, freq='M')[source]
Reads in a csv file of monthly boundary conditions and interpolates Outputs an interpolated DataFrame of that variable
- bdschism.port_boundary.set_gate_fraction(dts_in, op_var='height', ubound=10, lbound=0, increment='month_fraction')[source]
Adjusts the values of a specified operation variable in a DataFrame to represent fractional gate operations per month.
This function processes a DataFrame containing time-indexed gate operation data (e.g., gate heights), and for each month, it sets a fraction of the time steps to the lower bound (lbound) and the remainder to the upper bound (ubound), based on the initial value of the operation variable for that month. Only rows where the operation variable is not already at the upper or lower bound are modified.
- Parameters:
dts_in (pandas.DataFrame) – The input DataFrame with a DateTimeIndex and an operation variable column.
op_var (str, optional) – The name of the column representing the operation variable to adjust (default is “height”).
ubound (numeric, optional) – The upper bound value for the operation variable (default is 10).
lbound (numeric, optional) – The lower bound value for the operation variable (default is 0).
increment (str, optional) – The increment type for grouping. Default is “month_fraction”. Other supported types: month_fraction - Need to take any Percentage between 0 and 100 and convert them to days of month open month_days - Need to take number of days in a month and operate per days of month
- Returns:
The modified DataFrame with the operation variable adjusted according to the calculated monthly fractions.
- Return type:
pandas.DataFrame
Notes
The function assumes the DataFrame index is a pandas DateTimeIndex.
Only rows where the operation variable is not equal to ubound or lbound are considered for adjustment.
The fraction is determined by the ratio of the first value of the operation variable in the group to ubound.
bdschism.potw module
Convert POTW (Publicly Owned Treatment Works) flow and EC data for SCHISM sources.
Output flow is in CFS (no conversion). The CFS-to-CMS conversion is deferred
to the merge_th assembly step via scale_factor in the integration config.
Salinity output is in PSU.
- bdschism.potw.potw_to_schism(potw_file, output_dir)[source]
Convert POTW CSV to salinity (PSU) and flow (CFS) output files.
Reads a single POTW CSV whose columns are treated as both EC (uS/cm) and flow (CFS) — the same file is used for both derivations, consistent with the
potw_ds_cnra_flow_extendedformat where EC columns are present alongside flow.- Parameters:
potw_file (str or Path) – Path to POTW CSV file. Comments starting with
#are skipped. First column is parsed as a datetime index.output_dir (str or Path) – Directory for output CSVs. Created if it does not exist.
Notes
Output filenames are fixed as
potw_south_delta_salinity.csvandpotw_south_delta_flow.csvwithin output_dir.
bdschism.predict_smscg_tidal_op module
Predict SMSCG tidal open and close hours by linear regression.
The prediction is based on linear regression models that relate tidal gate opening and closing hours to SRV flow, MRZ tidal energy, and the elevation difference between CSE and MRZ.
Users should provide astronomical tidal data as input. If astronomical tidal data are not provided, the prediction will use tidal data from the modeling data repository and may be less accurate.
- bdschism.predict_smscg_tidal_op.load_ts(start, end)[source]
Load time series data from model data repository.
Load mrz, cse elev and srv flow from the delta repository.
Parameters: start (datetime): Start time of the time series data to load. end (datetime): End time of the time series data to load.
- bdschism.predict_smscg_tidal_op.load_ts_from_repo(start, end)[source]
Backward-compatible wrapper for load_ts.
- bdschism.predict_smscg_tidal_op.load_ts_harmonic(repo)[source]
Load predicted time series data from tidal harmonic analysis when gate tidal operations are considered from the specified repository.
Parameters: repo (str): Name of the repository to load harmonic data from.
Returns: cse_elev (pd.Series): Predicted astronomical elev time series data at station cse. mrz_elev (pd.Series): Predicted astronomical elev time series data at station mrz. srv_flow (pd.Series): Predicted astronomical flow time series data at station srv. srv_flow_d1 (pd.Series): Predicted astronomical flow time series data with diurnal component at station srv.
- bdschism.predict_smscg_tidal_op.plot_gate_op_ts(predict_smscg)[source]
Plot predicted gate operation time series.
- bdschism.predict_smscg_tidal_op.predict_gate_op(flow, diff_cse_mrz_elev, mrz_energy, tideh_flow, tideh_mrz, gate_op_period)[source]
Predict gate operation based on index flow, MRZ elevation, and CSE-MRZ elevation difference.
Parameters:
flow (pd.Series): Index flow data, now use SRV ONLY flow diff_cse_mrz_elev (pd.Series): CSE-MRZ elevation difference data. mrz_energy (pd.Series): MRZ energy data. tideh_ndo (pd.Series): Tidal hours at NDO. tideh_mrz (pd.Series): Tidal hours at MRZ. gate_op_period (list): list of Gate tidal operation start and end times, such as [[start_date1, end_date1], [start_date2, end_date2]]
all the input time sereies should have the same length and aligned time index
- bdschism.predict_smscg_tidal_op.smscg_gate(flow_srv, elev_diff_filtered, elev_mrz, flow_srv_d1=None, gate_op_period=None)[source]
Predict SMSCG gate operations based on tidal and flow data.
Parameters: flow_srv (pd.Series): Service flow time series. elev_diff_filtered (pd.Series): Filtered elevation difference between cse and mrz. elev_mrz (pd.Series): MRZ elevation time series.
Returns: list: List of predicted gate open/close times.
bdschism.profile_plot module
- bdschism.profile_plot.profile_plot(x, z, data, ax, context_label=None, add_labels=False, xlabel=None, xmin=None, xmax=None, max_depth=None, add_context_label=True, context_loc='upper right', ylabel=True, show_xticklabels=True)[source]
UnTRIM-like longitudinal profile plot of salinity.
- Parameters:
x (array-like) – Distance, depth, and salinity arrays.
z (array-like) – Distance, depth, and salinity arrays.
data (array-like) – Distance, depth, and salinity arrays.
ax (matplotlib.axes.Axes) – Target axes.
context_label (str, optional) – Text annotation, typically a date or case label.
add_labels (bool, default False) – Add named location labels. This is intentionally respected so multi-row paper figures can label only the top row.
xlabel (str, optional) – X-axis label. Pass this only for the axes where the km marker should appear.
xmin (float, optional) – Bounds in km.
xmax (float, optional) – Bounds in km.
max_depth (int, optional) – Maximum plotted depth.
add_context_label (bool, default True) – Draw context_label when supplied.
context_loc ({"upper right", "upper left"}, default "upper right") – Placement for the context label.
ylabel (bool, default True) – Draw the Depth label.
show_xticklabels (bool, default True) – Show x tick labels.
bdschism.read_dss module
- bdschism.read_dss.check_exclude(pathname, exclude_pathname)[source]
Returns True if pathname matches any of the exclude_pathname patterns. Wildcards (*) in exclude_pathname are supported.
- bdschism.read_dss.read_dss(filename, pathname, dt=<15 * Minutes>, p=2.0, start_date=None, end_date=None, exclude_pathname=None)[source]
Reads in a DSM2 dss file and interpolates Outputs an interpolated DataFrame of that variable
- Parameters:
filename (str|Path) – Path to the DSS file to read
pathname (str|list) – Pathname(s) within the DSS file to read. Needs to be in the format ‘/A_PART/B_PART/C_PART/D_PART/E_PART/F_PART/’ (e.g. ‘//RSAN112/FLOW////’)
bdschism.runtime_hotstart module
bdschism.set_mode module
bdschism.set_nudging module
Set the nudging links for a Bay-Delta SCHSIM model
2025-02-04: Customized
- bdschism.set_nudging.parse_var_map(ctx, param, value)[source]
Parse a string of key=value pairs separated by commas into a dictionary. Expected format: “key1=value1,key2=value2” Used for var_map which feeds the gr3 formats for things like TEM=temperature
- bdschism.set_nudging.set_nudging(suffix: str, workdir='.', var_map={}, param_fn='param.nml')[source]
This is a utility to set up nudging files based on a naming convention common for BayDeltaSCHISM. Assumed this is on Linux or admin-priveleged Windows machine.
- Parameters:
suffix (str) – This is the suffix used when preparing the nudging/gr files. For instance “obshycom” in SAL_nu_obshycom.nc
workdir (str) – Directory where the links and changes are made
var_map (str) – Unexpected mapping in key=value pairs, separated by commas. Ex: –var_map ‘TEM=temperature,SAL=salinity’
param_fn (str) – Which param.nml file will be used to determine module list. Should be the baroclinic param file. Default is param.nml
bdschism.settings module
- bdschism.settings.create_link(source, symlink, config_log=False, abs=False)[source]
Create a link between a source file and a target path based on system-specific link styles.
This function creates a symbolic link, junction, or copies the file, depending on the system settings. The link style is determined dynamically from get_settings(), which specifies the preferred linking method for the operating system.
- Parameters:
source (str) – The path to the source file that will be linked.
symlink (str) – The target path where the link (or copy) will be created.
config_log (bool, optional) – If True, log the configuration source being used.
abs (bool, optional) – If True, use absolute paths for the source and symlink.
- Raises:
ValueError – If the link style retrieved from get_settings() is unsupported.
Notes
If a symbolic link already exists at symlink, it is removed before creating a new one.
On Windows, the function supports creating junction links (mklink), symbolic links, or copying the file instead.
On Unix-based systems, it defaults to using symbolic links.
Examples
Create a symbolic link on Unix-like systems or an appropriate alternative on Windows:
>>> create_link("/path/to/source.txt", "/path/to/symlink.txt")
- bdschism.settings.get_output_from_interpolate_variables(varname, config_log=False)[source]
Get the output filename for the interpolate_variables function.
- Parameters:
varname (str) – The variable name for which to retrieve the output filename (e.g., ‘uv3d’).
config_log (bool, optional) – If True, log the configuration source being used.
- Returns:
The output filename for the interpolate_variables utility.
- Return type:
str
- bdschism.settings.get_settings(config_log: bool = False)[source]
Load and return application settings from a configuration file.
This function retrieves configuration settings using a hierarchy of possible sources: 1. A package-level default configuration file (bds_config.yaml within the package). 2. A project-level configuration file (bds_config.yaml in the current working directory). 3. An environment-specific configuration file, if BDS_CONFIG is set and points to a valid file.
The function uses Dynaconf to load settings, ensuring that the highest-priority configuration (environment variable, project-level, or package default) is used.
- Returns:
A Dynaconf object containing the loaded configuration settings.
- Return type:
Dynaconf
Notes
The package-level configuration file provides default settings.
If a project-level configuration file exists in the current directory, it overrides the package default.
If an environment variable BDS_CONFIG is set and points to a valid file, it takes the highest precedence.
The function logs the configuration source being used.
Examples
Load settings from the highest-priority available configuration file:
>>> settings = get_settings() Using configuration from: /path/to/highest-priority-config.yaml current env development
Access settings:
>>> settings.some_setting 'some_value'
- bdschism.settings.interpolate_variables(config_log=False)[source]
interpolate SCHISM variables from background grid to foreground grid for elevation, tracers, or uv3D
- Parameters:
config_log (bool, optional) – If True, log the configuration source being used.
- Raises:
ValueError – If the link style retrieved from get_settings() is unsupported.
Notes
interpolate_variables8 is the version of interpolate_variables associated with SCHISM 5.11
Examples
Interpolate SCHISM variables on Unix-like systems or an appropriate alternative on Windows:
>>> interpolate_variables()
bdschism.slice_th_nc module
Slice a NetCDF time-history file by date.
Reindexes the time coordinate as elapsed seconds since the requested
start time and updates CF time:units/time:calendar metadata.
Designed for SCHISM *.th.nc boundary-condition files but works with
any CF-compliant NetCDF that has a recognisable time coordinate.
CLI
slice_th_nc --start 2012-02-10 --end 2015-05-12 \
-o elev2D_2012_2015.th.nc elev2D_2000_2025.th.nc
# for files without time:units (e.g. bare SCHISM uv3D.th.nc):
slice_th_nc --reftime 2000-01-01 --start 2012-02-10 --end 2015-05-12 \
-o uv3D_2012_2015.th.nc uv3D_2000_2025.th.nc
- bdschism.slice_th_nc.slice_nc(infile: str, outfile: str, start: str, end: str, *, time_coord: str | None = None, reftime: str | None = None) Tuple[int, str][source]
Slice a NetCDF time-history file to a date range and reindex time.
Reads infile, selects timesteps in
[start, end](inclusive), replaces the time coordinate with elapsed seconds since start, and writes the result to outfile. CFtime:unitsandtime:calendarmetadata are updated accordingly; ahistoryglobal attribute entry is appended.- Parameters:
infile (str) – Path to the input NetCDF file.
outfile (str) – Path for the output NetCDF file.
start (str) – ISO-like start datetime string (e.g.
'2012-02-10'or'2012-02-10T00:00'). Elapsed time in the output is measured from this instant.end (str) – ISO-like end datetime string (inclusive).
time_coord (str, optional) – Explicit name of the time coordinate. When
None(default), the coordinate is detected automatically via_find_time_coord().reftime (str, optional) – Reference epoch for files whose time coordinate carries no CF
unitsattribute (e.g. bare SCHISMuv3D.th.ncfiles). ISO-like string (e.g.'2000-01-01'). Raw time values are assumed to be elapsed seconds from this epoch. When both reftime and aunitsattribute are present, reftime determines the epoch and the unit multiplier is taken fromunitsif parseable, otherwise seconds are assumed. The supplied value is stored as thereftimeglobal attribute in the output file.
- Returns:
status (int) –
0on success,2on any error.message (str) – Human-readable status or error description.
Notes
The output time array contains
float64values representing seconds elapsed since start, matching typical SCHISM*.th.ncconventions.Only a safe subset of encoding attributes is forwarded to the writer to avoid backend incompatibilities.
A datestamped entry is appended to the dataset’s
historyglobal attribute.When reftime is provided it is stored verbatim as the
reftimeglobal attribute of the output file.
bdschism.smscg_log_2_schism_th module
bdschism.source_sink_postprocess module
Delta source/sink postprocessing functions for SCHISM channel depletion workflow.
Covers synthetic source/sink generation, south-delta flow flooring, Paradise Cut salinity propagation, and inferred EC-to-PSU conversion.
All flow values in intermediate CSVs are in CFS. The CFS-to-CMS conversion
is applied when writing final .th files via write_source_sink_th.
- bdschism.source_sink_postprocess.added_src_sink_names(added_src_yaml)[source]
Read MSS added-node names from a source YAML file.
- Parameters:
added_src_yaml (str or Path) – YAML file mapping node names to coordinates (keys become the name list).
- Returns:
Node names as listed in the YAML (source convention).
- Return type:
list of str
- bdschism.source_sink_postprocess.copy_paradise_up(msource_dated_fname, msource_adj_dated_fname, msource_adj_th_fname, metadata=None, msource_adj_dated_th_fname=None, sdate=None, edate=None)[source]
Propagate salinity from Paradise Cut midpoint to its head nodes.
Copies salinity from node 807 to nodes 166, 805, 806 and from node 802 to nodes 162, 163.
- Parameters:
msource_dated_fname (str) – Path to merged source tracer dated CSV (multi-index: variable × location).
msource_adj_dated_fname (str) – Output path for adjusted dated CSV (comma-sep, with metadata header).
msource_adj_th_fname (str) – Output path for adjusted elapsed
.thfile (space-sep, no header).metadata (dict, optional) – Metadata dict passed to
write_ts_csv(units, config path, etc.).msource_adj_dated_th_fname (str or Path, optional) – Output path for dated
.thfile (space-sep, with header, full period).sdate (str or Timestamp, optional) – Start date for elapsed
.thfile. Defaults to first timestamp in CSV.edate (str or Timestamp, optional) – End date for elapsed
.thfile. Defaults to last timestamp in CSV.
- bdschism.source_sink_postprocess.create_mss_minimum_srcsink(fname, var, nominal_cfs, locs, sdate, edate, sink_fraction=None)[source]
Create minimum 3-CFS source/sink exchange flows for added MSS nodes (CFS).
For sink nodes, the flow is modulated by TPS gate state: when TPS gates are closed the full unmodulated flow is applied; otherwise a fractional sink balances the source.
For source nodes, companion salinity and temperature files filled with -9999 are also written alongside fname.
- Parameters:
fname (str or Path) – Output CSV path.
var (str) –
'src'(or'source') for source nodes,'sink'for sink nodes.nominal_cfs (float) – Nominal exchange flow magnitude in CFS (e.g. 3.0).
locs (list of str) – Source location names (will be translated to sink names if var is
'sink').sdate (str or Timestamp) – Start date.
edate (str or Timestamp) – End date.
sink_fraction (float, optional) – Ratio of sink to source for modulated (gate-open) periods. Required when var is
'sink'; ignored otherwise.
- Raises:
ValueError – If sink_fraction is provided for a source variable.
- bdschism.source_sink_postprocess.create_nullzone_sink(outfile, sdate, edate)[source]
Create seasonal null-zone balancing sink CSV (CFS).
Six null-zone sink locations receive a constant 50/6 CFS flow from May through October. Values are negative (sink convention).
- Parameters:
outfile (str or Path) – Output CSV path.
sdate (str or Timestamp) – Start date.
edate (str or Timestamp) – End date.
- bdschism.source_sink_postprocess.floor_source_sink_exchange(vsource_df, vsink_df, sd_nodes_fname=None, tps_th_fname=None, mincfs=3.0, sink_fraction=0.6)[source]
Apply south-delta minimum flow floor and return adjusted CFS DataFrames.
Clips south-delta sources to a minimum value, balances the added source with a fractional sink reduction, then applies special handling for Tom Paine Slough gate closures. All values remain in CFS.
- Parameters:
vsource_df (DataFrame) – Merged source data (CFS, produced by merge_th).
vsink_df (DataFrame) – Merged sink data (CFS, produced by merge_th).
sd_nodes_fname (str or Path, optional) – CSV listing south-delta node IDs. Defaults to the canonical copy in
BayDeltaSCHISM/data/channel_depletion/south_delta_nodes_extran.csv.tps_th_fname (str or Path, optional) – Path to TPS culvert time-history. Defaults to canonical bdschism copy.
mincfs (float, optional) – Minimum source flow in CFS. Default 3.0.
sink_fraction (float, optional) – Fraction of added source applied as sink reduction. Default 0.6.
- Returns:
adj_source (DataFrame) – Adjusted source flows (CFS).
adj_sink (DataFrame) – Adjusted sink flows (CFS).
- bdschism.source_sink_postprocess.inferred_to_psu(infile, outfile)[source]
Convert inferred delta EC CSV to PSU salinity, adding
delta_src_prefix.- Parameters:
infile (str or Path) – Input CSV with EC columns (no prefix; rows are timestamps).
outfile (str or Path) – Output CSV path for PSU salinity.
- bdschism.source_sink_postprocess.tps_masks(ndx, cols='sink', tps_th_fname=None)[source]
Build a boolean mask of Tom Paine Slough gate-closed periods.
- Parameters:
ndx (DatetimeIndex) – Time index to reindex the gate operation record onto.
cols (str, optional) – Column convention for location names:
'sink'or'src'. Default'sink'.tps_th_fname (str or Path, optional) – Path to the TPS culvert time-history file. Defaults to the canonical copy in
BayDeltaSCHISM/data/time_history/tom_paine_sl_culvert.th.
- Returns:
tps_closed (Series of bool) – True when both up and down gates are closed, reindexed to ndx.
tps_locations (list of str) – Location names for TPS nodes 151–160 using cols convention.
- bdschism.source_sink_postprocess.write_source_sink_th(vsource_df, vsink_df, vsource_th_fname, vsink_th_fname, sdate, edate, vsource_dated_th_fname=None, vsink_dated_th_fname=None, metadata=None)[source]
Write CMS source/sink DataFrames as elapsed
.thfiles.Optionally also writes dated
.thfiles (full period, with header) for QC and diffing.- Parameters:
vsource_df (DataFrame) – Adjusted source flows (m^3/s, datetime index).
vsink_df (DataFrame) – Adjusted sink flows (m^3/s, datetime index).
vsource_th_fname (str or Path) – Output path for elapsed source
.thfile (no header).vsink_th_fname (str or Path) – Output path for elapsed sink
.thfile (no header).sdate (str or Timestamp) – Start date (elapsed reference and window start).
edate (str or Timestamp) – End date for output window.
vsource_dated_th_fname (str or Path, optional) – Output path for dated source
.thfile (with header, full period).vsink_dated_th_fname (str or Path, optional) – Output path for dated sink
.thfile (with header, full period).metadata (dict, optional) – Metadata written to the header of dated
.thfiles.
bdschism.source_sink_workflow module
End-to-end workflow for assembling SCHISM source/sink time-history files.
Orchestrates channel depletion NetCDF conversion, POTW and inferred-EC preparation, synthetic source/sink generation, merge_th assembly, south-delta flow flooring, and Paradise Cut salinity propagation.
All intermediate flow CSVs are in CFS. The CFS-to-CMS conversion is applied
in step 7 before writing both dated QC CSVs and elapsed .th files.
The workflow is driven by a single YAML config (ss_workflow.yaml) using
schimpy $variable substitution. Changing version in that file is
typically the only edit needed when a new channel depletion NetCDF arrives.
- bdschism.source_sink_workflow.run_source_sink_workflow(config_file, set_vars=None, force=False)[source]
Run the complete source/sink postprocessing workflow.
Steps
Convert delta channel depletion NetCDF → CFS CSVs.
Convert Suisun channel depletion NetCDF → CFS CSVs.
Convert POTW CSV → flow (CFS) + salinity (PSU).
Convert inferred EC CSV → salinity (PSU).
Generate synthetic source/sink CSVs (skipped if outputs exist and not forced).
Run
merge_thto assemble per-component CFS CSVs into dated merged CSVs.Floor south-delta sources; write adjusted CFS dated CSVs and CMS
.th.Propagate Paradise Cut salinity; write adjusted dated CSV and
.th.
- param config_file:
Path to
ss_workflow.yaml.- type config_file:
str or Path
- param set_vars:
Variable overrides for
$variablesubstitution in all sub-configs, e.g.{'version': '20260101'}.- type set_vars:
dict, optional
- param force:
If True, regenerate synthetic files even if outputs already exist. Default False.
- type force:
bool, optional
bdschism.synthetic_copy module
bdschism.synthetic_sflux module
Create synthetic HRRR forcing files by copying an existing repository and shifting all dates forward by one year.
For each day in [sdate, edate], the script:
Reads: {source_repo}/{YEAR}/hrrr_YYYYMMDD00.nc
Writes: {dest_repo}/{YEAR+1}/hrrr_{YEAR+1}{MM}{DD}00.nc
Leap-year handling
- If the source year is a leap year but the destination year is not:
Feb 29 is skipped.
- If the source year is not a leap year but the destination year is:
Feb 29 is created by copying Feb 28 and shifting the time one day.
The script also:
Shifts the xarray Dataset time coordinate by +1 year (or +1 year +1 day for synthetic Feb 29).
Updates time.attrs[“base_date”] to reflect the new date.
Adds provenance attributes:
“creator” = “CA DWR Delta Modeling Section”
“creation_method” = description of what was copied.
This is intended for creating synthetic “next-year” met forcing when you want to reuse a prior year.
bdschism.three_point_linear_norm module
bdschism.tide module
- bdschism.tide.gen_constituents_tree()[source]
This function generates the constituent trees of Choice of constituents and Rayleigh comparison pairs It returns a list of root nodes for subtide, diurnal, semidiurnal and terdiurnal, and a list of shallow water constituents that have multiple parents. It is implementation from Table 1 to Table 5 in “MANUAL FOR TIDAL HEIGHTS ANALYSIS AND PREDICTION” by M.G.G. Foreman (1996).
- bdschism.tide.get_astro_constituent_names(astro_group, record_length_hours=0)[source]
Recursivly Retrieves the names of all constituents in the astro_group that can be analyazed by the specified record_length_hours.
Args: astro_group: list of root nodes for the main constituent groups (slow, diurnal, semidiurnal, terdiurnal). record_length_hours: the length of the record in hours, used to determine which constituents can be analyzed.
Returns: A sorted list of constituent names that can be analyzed with the given record length.
- bdschism.tide.get_constituents(record_length_hours=0)[source]
Retrieves the names of all constituents in the astro_group and shallow_group that can be analyazed by the specified record_length_hours.
- Parameters:
astro_group – list of root nodes for the main constituent groups (slow, diurnal, semidiurnal, terdiurnal).
shallow_group – list of nodes for shallow water constituents that have multiple parents.
record_length_hours – the length of the record in hours, used to determine which constituents can be analyzed.
Returns: A sorted list of constituent names that can be analyzed with the given record length.
bdschism.uv3d module
- bdschism.uv3d.interpolate_uv3d(param_nml, bg_dir, bg_output_dir, fg_dir, hgrid_bg, hgrid_fg, vgrid_bg, vgrid_fg, interp_template, nday, output, overwrite, bnd_seg=None)[source]
Run interpolate_variables utility to generate uv3d.th.nc.
- Parameters:
param_nml (str or None) – Path to param.nml. If None, defaults to bg_dir/param.nml.
bg_dir (str) – Background simulation directory.
bg_output_dir (str or None) – Output directory inside bg_dir where interpolate_variables is run.
fg_dir (str or None) – Foreground (baroclinic) run directory. Used for hgrid_fg/vgrid_fg links. If None, defaults to bg_dir.
hgrid_bg (str) – Background hgrid filename (relative to bg_dir).
hgrid_fg (str) – Foreground hgrid filename (relative to fg_dir).
vgrid_bg (str) – Background vgrid filename (relative to bg_dir).
vgrid_fg (str) – Foreground vgrid filename (relative to fg_dir).
interp_template (str or None) – Path to interpolate_variables.in template. If None, a minimal file is written based on nday (or rnday from param.nml).
nday (int or None) – Number of days to process when interp_template is None. If None, rnday is read from param_nml.
output (str) – Path where the final uv3d output will be written (moved).
overwrite (bool) – If True, overwrite an existing file in output_dir. If False, fail fast if the file already exists.
bnd_seg (list of int or None) – Used only when interp_template is None. Listing of boundary segments to be interpolated.
- bdschism.uv3d.setup_tmp_dir(bg_output_dir, tmp_bg_output_dir, nfile)[source]
Set up a temporary directory with links to the specific output files for uv3d interpolation.
- bdschism.uv3d.single_uv3d(nfile, param_nml='param.nml', bg_dir='./', bg_output_dir='./outputs', fg_dir='./', hgrid_bg='./hgrid.gr3', hgrid_fg='./hgrid.gr3', vgrid_bg='./vgrid.in.2d', vgrid_fg='./vgrid.in.3d', out_dir='./', overwrite=True, cleanup=True, bnd_seg=None)[source]
Process a single uv3d output file for the specified nfile index.
bdschism.x2_buildpoints module
Extract station xyz from a x2 route UTM file. The resulting station file conforms to SCHISM bp station format. Stations along bay route start from 65km from San Francisco and end at confluence, Station along mzm start from 18km from Marinez end at confluence, Station along Sac starts from confluence and end 25km upstream of sac river, Station along San Joaquin route starts from confluence and end 25km upstream of San Joaquin River. Their depth are defined as relativly to surface. ONLY surface or bottom stations are available, surface station set elevation to 0 and bottom station set elevation to -10000.0. station xyz are output as Bay route, San Joaquin, Sac and MZM in order.
bdschism.x2_time_series module
Create x2 time series from build-point files.
This script reads x2_route.bp as well as the fort.18 resulting from SCHISM read_output9_xyz to extract salinity on X2 stations. It search along x2 stations to find two neiboring stations higher and lower than X2 criteria (bottom or surface). If X2 retreat less than the minimum stations along the transect, the X2 result will be truncated at that point.
usage: –start 2004-04-18 –x2route x2route.bp output: x2 on surface and bottom location time series in csv format, bottom_x2.csv and surface_x2.csv
bdschism.zone_utils module
Created on Fri May 5 09:45:12 2023
@author: qshu