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.analyze_dt.plot_summarized_bad_actors(bad_actors, all_x, all_y, label_top=None)[source]
bdschism.analyze_dt.summarize_elements(ncfile, top_n, min_count)[source]

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_file, export_file, sffpx_elev, plot=False, save_intermediate=False)[source]

Generate the predicted gate height for the Clifton Court Forebay.

Parameters:
  • sdate (str) – Start date in the format “YYYY-MM-DD”.

  • edate (str) – End date in the format “YYYY-MM-DD”.

  • dest (str) – Destination file where the output file will be saved. ex: “ccfb_gate_syn.th”

  • astro_file (str) – Path to the astronomical data file required for processing.

  • export_file (str) – Path to the export file used in 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.draw_down_regression(cvp, qin)[source]
bdschism.ccf_gate_height.export_lookup(x)[source]
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:

datetime.datetime

param s2:

End time.

type s2:

datetime.datetime

param dt:

Output time step.

type dt:

datetime.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.gen_prio_for_varying_exports(input_tide, export_df)[source]
bdschism.ccf_gate_height.get_export_ts(s1, s2, flux)[source]

retrieve swp and cvp pumping rate from a SCHISM flux.th

Parameters:
  • s1 (:py:class:'datetime <datetime.datetime>') – start time.

  • s2 (:py:class:'datetime <datetime.datetime>') – end time.

  • flux (str) – path to the SCHISM flux th file.

Returns:

  • swp_ts (:py:class:’DataFrame <pandas.DataFrame>’) – swp pump rate in cfs.

  • cvp_ts (:py:class:’DataFrame <pandas.DataFrame>’) – cvp pump rate in cfs.

bdschism.ccf_gate_height.get_tidal_hh_lh(sh)[source]
bdschism.ccf_gate_height.get_tidal_ll_hl(sl)[source]
bdschism.ccf_gate_height.make_3_prio(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 (datetime.timedelta) – start time.

  • etime (datetime.timedelta) – 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, astro_tide_file, sffpx_elev)[source]
bdschism.ccf_gate_height.process_height(s1, s2, export, oh4_astro, sffpx_elev)[source]

Create a ccfb radial gate height time series file

Parameters:
  • s1 (datetime.datetime) – start time.

  • s2 (datetime.datetime) – end time.

  • export (str) – path to SCHISM export th file.

  • oh4_astro (str) – path to OH4 astronomic tide file .

Returns:

  • sim_gate_height (pandas.DataFrame) – predicted raidal gate height

  • zin_df (pandas.DataFrame) – predicted ccfb interior surface stage.

bdschism.ccf_gate_height.radial_gate_flow(zdown, zup, height, n=5, width=20.00000064, zsill=-13.267716959999998)[source]

compuate ccf radial gate flow in cubic feet/s

Parameters:
  • n – number of gate opened

  • width – width of the each gate

  • zup – upstream water elevation

  • zill – elevation of gate sill

  • zdown – downstream water elev

  • height – gate opening height

Returns:

gate flow in cfs

bdschism.ccf_gate_height.raidal_gate_flow_ts(zdown_ts, zup_ts, height_ts, s1, s2, dt)[source]
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.ccf_gate_height.save_prio_ts(tsdir, tide_lagged, p1, p2, p3, p4)[source]
bdschism.ccf_gate_height.sffpx_level(sdate, edate, sf_data_repo, margin=datetime.timedelta(days=30))[source]
bdschism.ccf_gate_height.simple_mass_balance(export, zup, zin0, height, dt, vt)[source]
bdschism.ccf_gate_height.tlmax(arr)[source]

return HH(1) or LH (0)

bdschism.ccf_gate_height.tlmin(arr)[source]

return LL(1) or HL(0)

bdschism.diff_gr3 module

bdschism.diff_gr3.diff_congruent_gr3(fname0, fname1, fout)[source]

bdschism.generate_realtime_elev2d module

bdschism.generate_realtime_elev2d.main()[source]
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.hotstart_date module

bdschism.hotstart_date.set_hotstart_date(fn, run_start, restart_time, outprefix, dt)[source]

Change timestamp and date implied by hotstart.

bdschism.hotstart_from_hotstart module

Adapted from ZZheng - generate hotstart - transfer from one grid to another

bdschism.hotstart_from_hotstart.hotstart_newgrid(yaml_fn: str, hotstart_in, hotstart_out, src_dir, trg_dir, modules=None, crs='EPSG:26910', envvar=None)[source]

Transfer hotstart data from one grid to another.

bdschism.hotstart_from_hotstart.str_or_path(value)[source]

Helper function to handle string or Path inputs.

bdschism.hotstart_nudging_data module

bdschism.hotstart_nudging_data.hotstart_nudge_data(sdate, ndays, dest, repo_dir)[source]

bdschism.parse_cu module

bdschism.plot_input_boundaries module

bdschism.port_boundary module

bdschism.profile_plot module

bdschism.profile_plot.get_index_bounds()[source]
bdschism.profile_plot.nearest_neighbor_fill(arr)[source]
bdschism.profile_plot.profile_plot(x, z, data, ax, context_label=None, add_labels=False, xlabel=None, xmin=None, xmax=None, max_depth=None)[source]

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

bdschism.profile_plot.set_index_bounds(min_station, max_station, max_depth)[source]
bdschism.profile_plot.vertical_fill(arr)[source]

bdschism.run_sequence module

bdschism.set_nudging module

Set the nudging links for a Bay-Delta SCHSIM model

2025-02-04: Customized

bdschism.set_nudging.get_nudge_list(fname)[source]
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

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.

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_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.three_point_linear_norm module

class bdschism.three_point_linear_norm.ThreePointLinearNorm(linthresh, vmin=None, vmax=None, clip=False)[source]

Bases: Normalize

autoscale(A)[source]

Set vmin, vmax to min, max of A.

autoscale_None(A)[source]

autoscale only None-valued vmin or vmax

inverse(value)[source]

Maps the normalized value (i.e., index in the colormap) back to image data value.

Parameters:

value – Normalized value.

scaled()[source]

return true if vmin and vmax set

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, write_clinic)[source]

Main function to run interpolate_variables utility.

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_buildpoints.create_arg_parser()[source]

Create an argument parser return: argparse.ArgumentParser

bdschism.x2_buildpoints.main()[source]

Main function

bdschism.x2_buildpoints.main_fixed()[source]
bdschism.x2_buildpoints.x2_route2_bp(x2_route_file, interval, route_id=None, bpout=None, minkm=35)[source]

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.x2_time_series.create_arg_parser()[source]
bdschism.x2_time_series.default_outname(bpname)[source]
bdschism.x2_time_series.find_x2(transect, thresh=2.0, convert_km=0.001, distance_bias=0.0)[source]

Given a series transect, indexed by distance, locate a distance with value is close to thresh

bdschism.x2_time_series.get_start_date_from_param(param_in)[source]
bdschism.x2_time_series.main()[source]
bdschism.x2_time_series.main_hardwire()[source]
bdschism.x2_time_series.process_x2(salt_data_file, route_file, model_extract_date, output_file, param_in=None, model_start_date=None)[source]

Process x2 into a time series

bdschism.zone_utils module

Created on Fri May 5 09:45:12 2023

@author: qshu

bdschism.zone_utils.face_aver(node_depth_average, node_num, face_num, ele_table)[source]
bdschism.zone_utils.face_aver_inst(inst_node_depth_average, node_num, face_num, ele_table)[source]
bdschism.zone_utils.fill_ele_area(face_num, ele_table, node_x, node_y, ele_area)[source]
bdschism.zone_utils.fill_ele_area510(face_num, ele_table, node_x, node_y, ele_area)[source]
bdschism.zone_utils.gen_node_neibor_ele(mesh_node, max_node_in_a_cell, num_ele, num_node)[source]
bdschism.zone_utils.gen_node_wet_dry(node_wet_dry, ele_wet_dry, num_step, num_node, max_ele_at_node, el)[source]
bdschism.zone_utils.quad_area(x1, y1, x2, y2, x3, y3, x4, y4)[source]
bdschism.zone_utils.triangle_area(x1, y1, x2, y2, x3, y3)[source]

Module contents