Sunday, December 29, 2024

SWMM5 transect.c Summary

 The transect.c file in SWMM 5 handles the geometry of irregular cross-section transects used in hydraulic modeling. It defines functions to process the geometry, create and validate transects, and compute related flow characteristics based on user-supplied parameters. These functions are especially crucial when modeling streets, channels, or other conveyances with irregular or custom shapes.

Key Components of transect.c:

  1. Transect Creation and Deletion:

    • transect_create(): Allocates memory for multiple transects and initializes the necessary variables.
    • transect_delete(): Frees the memory associated with all transects when they are no longer needed.
  2. Reading and Parsing Parameters:

    • transect_readParams(): Reads and processes parameters for each transect from input data, including Manning's roughness coefficients and station elevation data.
    • addStation(): Adds a new station (point along the transect) to the transect with its corresponding elevation and location.
  3. Geometry Calculation:

    • createTables(): Creates tables of geometry for each transect, including the calculation of cross-sectional areas, widths, and wetted perimeters for various depths.
    • getGeometry(): Calculates and updates the geometry of a transect at a given depth.
    • getSliceGeom(): Computes the geometry (width, area, and wetted perimeter) of a transect slice between two stations.
    • getFlow(): Uses Manning's equation to calculate the flow for each transect section.
  4. Manning's n and Section Factor:

    • setManning(): Assigns Manning's roughness values to the left, right, and channel sections of a transect.
    • setMaxSectionFactor(): Determines the maximum section factor for a transect, which is important for flow calculations.
  5. Street Transects:

    • transect_createStreetTransect(): Creates a transect for a street cross-section, considering both the street’s geometry and the associated runoff characteristics. This function models a street as either a half or full section with potential backing, curb, gutter, and other features.

Purpose of transect.c:

  • Geometry Representation: The primary function of transect.c is to represent the geometry of the drainage system, particularly for irregularly shaped cross-sections (e.g., streets, trapezoidal channels). It calculates the area, wetted perimeter, and flow characteristics at different depths to accurately simulate water flow.

  • Manning’s Equation: The file applies Manning’s equation to calculate flow through cross-sections with different roughness values, adjusting for the geometry of the shape.

  • Street Modeling: The file includes special handling for street cross-sections, modeling them as either half or full streets with various geometries (curb, gutter, backing, etc.), and calculates their respective flow and hydraulic characteristics.

  • Hydraulic Calculations: By creating and validating transects, transect.c ensures that accurate hydraulic calculations are made, considering the channel’s geometry and roughness values, which directly impact flow routing in SWMM simulations.

Overall, transect.c is an essential part of the SWMM 5 engine for modeling and simulating runoff and water flow through channels, streets, and other irregularly shaped hydraulic structures.

SWMM5 toposort.c Summary

 The toposort.c file in SWMM 5 is responsible for topologically sorting the conveyance network links to ensure proper routing of water flow in the drainage system. It utilizes topological sorting techniques to arrange nodes and links such that all the downstream nodes appear after their respective upstream nodes in the sorted order. This is important for accurate simulation of water flow and for detecting any loops in the network.

Key Components of toposort.c:

  1. Adjacency List Creation:

    • createAdjList(): Creates an adjacency list for the nodes, listing the outgoing links for each node. This adjacency list helps identify the direction of flow in the network.
    • adjustAdjList(): Adjusts the adjacency list to handle special cases like DIVIDER nodes. For instance, links that involve diversions are re-ordered in the adjacency list.
  2. Topological Sorting:

    • topoSort(): This function performs the topological sort of the drainage network's links. It processes nodes and links in such a way that all links are ordered from upstream to downstream, ensuring that no link leads to a cyclic dependency.
    • toposort_sortLinks(): This function calls createAdjList() to create an adjacency list, then sorts the links using topological sorting methods.
  3. Cycle Detection:

    • findCycles(): This function checks for loops or cycles in the network, where flow might get trapped in a cycle and prevent proper simulation. It uses the spanning tree of the network to identify such cycles and handle them accordingly.
    • findSpanningTree(): This function finds a spanning tree starting from a node and traces through the network, identifying and marking links as part of the spanning tree.
    • evalLoop(): This function evaluates whether a set of links forms a cycle or not. If a cycle is detected, it is reported.
  4. Cycle Detection in Dummy Links:

    • checkDummyLinks(): This function checks for nodes that have both incoming and outgoing dummy links. Dummy links are placeholders for certain types of flow, and having both incoming and outgoing dummy links could lead to ambiguous sorting.

Purpose of toposort.c:

  • Topological Sorting: Ensures that the nodes and links are processed in the correct order during simulation. It is critical that upstream nodes and their links are processed before downstream nodes to simulate accurate water flow.

  • Cycle Detection: Prevents the simulation from proceeding if there are any loops in the system, as loops in the flow network would result in incorrect calculations.

  • Handling Special Nodes: Specifically handles DIVIDER nodes and dummy links to make sure the routing works correctly even in complex networks with special conditions.

Overall, toposort.c is crucial for setting up the routing of water flow in the SWMM simulation, ensuring that all nodes and links are ordered correctly for accurate simulation results.

SWMM5 text.h Summary

 The text.h file in SWMM 5 defines a variety of constants, text strings, and keywords that are used throughout the program. It is primarily responsible for managing the textual output of the simulation, including error messages, warnings, and reporting options. The file also organizes keywords for different sections of input files, such as rainfall data, infiltration methods, and flow routing methods.

Key Components in text.h:

  1. Text Formatting Constants:

    • Constants like FMT01, FMT03, FMT04, etc., define various formatted strings used throughout the program. These are used for displaying messages, formatting outputs, and structuring report headings.
  2. Error and Warning Messages:

    • The file defines numerous warning and error messages, such as WARN01 for warnings related to wet weather time steps and WARN02 for node depth warnings. These warnings and errors are displayed when specific conditions in the simulation are met.
    • Example:
      • WARN01: "WARNING 01: wet weather time step reduced to recording interval for Rain Gage."
      • WARN02: "WARNING 02: maximum depth increased for Node."
  3. Analysis Option Keywords:

    • These keywords define various simulation options that can be specified in the input file. For example, options for flow units (w_FLOW_UNITS), infiltration methods (w_HORTON), and routing models (w_KW).
    • These keywords are used to control different aspects of the simulation, such as the routing model, the time step intervals, or the type of infiltration model.
  4. Flow Units and Methods:

    • Defines various flow unit types, such as w_CFS (cubic feet per second), w_MGD (million gallons per day), w_LPS (liters per second), and routing methods like w_KW (kinematic wave) and w_DW (dynamic wave).
  5. Surcharge Methods and Infiltration Models:

    • Keywords for different methods of surcharge (w_EXTRAN and w_SLOT) and infiltration methods (w_HORTON, w_GREEN_AMPT, etc.).
  6. Pollutant Buildup and Washoff Functions:

    • Defines various methods for pollutant buildup and washoff, including exponential (w_EXP), saturation (w_SAT), and external (w_EXT) methods.
  7. Reporting and Output Options:

    • Keywords like w_REPORT, w_DISABLED, w_INPUT, w_CONTINUITY, and w_FLOWSTATS are used to specify which data should be included in the simulation report.
  8. Time Series and Table Keywords:

    • Keywords for defining and reading time series data (w_FILE, w_TIMESERIES), as well as specifying tables for use in the simulation (e.g., curves for rating flow vs. depth).
  9. Control Rules:

    • Keywords like w_RULE, w_IF, w_AND, w_OR, and w_THEN define the structure of control rules that can be applied during the simulation, for example, to control pumps or gates.
  10. Storage Node Shapes:

  • Defines different types of storage node shapes such as w_CYLINDRICAL, w_CONICAL, and w_PARABOLOID, which are used to define the geometry of storage tanks or reservoirs.

Summary:

The text.h file plays a vital role in SWMM 5 by defining the text strings, keywords, and error/warning messages used across the program. It organizes and structures important simulation options, input data types, and reporting criteria, allowing users to specify various aspects of the simulation through text-based input files. This structure also ensures consistency and simplifies modifications to the input/output mechanisms of the SWMM simulation.

SWMM5 table.c Summary

 The table.c file in SWMM 5 handles the manipulation and management of Curve and Time Series objects, which are essential for defining relationships between variables (e.g., rainfall rates, runoff, pollutant loads). It provides functions for reading, writing, and processing data for curves (used to define relationships between variables) and time series (used for time-based data such as rainfall, temperature, etc.). This file is key for processing input data, interpolating values, and performing lookups in the context of the SWMM simulation.

Key Functions in table.c:

  1. table_interpolate:

    • This function performs linear interpolation between two data points (x1, y1) and (x2, y2) to estimate the value (y) corresponding to an x value that lies between x1 and x2.
  2. table_readCurve:

    • Reads a curve table from input data. This function handles the definition of curves used for mapping variables to one another, such as flow vs. depth or other relationships.
  3. table_readTimeseries:

    • Reads time series data from input and stores it in a TTable object. This is used for time-varying data like rainfall, temperature, and other time-dependent parameters.
  4. table_addEntry:

    • Adds an entry (x, y) to a table. This is used to store data points in both curves and time series tables.
  5. table_deleteEntries:

    • Deletes all entries in a table. This is useful for cleaning up memory when a table is no longer needed.
  6. table_init:

    • Initializes the properties of a TTable structure, setting default values for curve and time series tables.
  7. table_validate:

    • Ensures that the data in a table is valid, checking that the x-values are in ascending order. If not, it returns an error.
  8. table_getFirstEntry & table_getNextEntry:

    • These functions allow you to retrieve the first and subsequent entries (x, y) from a table. They are used for processing tables and performing lookups.
  9. table_lookup:

    • Looks up the y-value corresponding to an x-value in a curve or time series table. It returns the interpolated value if necessary.
  10. table_getMaxY:

    • Retrieves the maximum y-value from the initial part of the table, useful for determining the extent of a table.
  11. table_getStorageVolume & table_getStorageDepth:

    • These functions are used in SWMM for tables that define storage curves, particularly for stormwater detention or retention basins.
  12. table_tseriesInit:

    • Initializes a time series table, setting the first and last date/time entries, and preparing it for interpolation and lookups.
  13. table_tseriesLookup:

    • Looks up a y-value corresponding to a given x (date/time) value in a time series table. Supports interpolation and extrapolation.
  14. table_getNextFileEntry:

    • Retrieves the next data entry (x, y) from an external file, which is essential for reading time series or curve data from files.
  15. table_parseFileLine:

    • Parses a line from a time series or curve file, extracting the x (date/time) and y (value) pairs for storage in the table.

Table Structure and Use in SWMM:

  • Curve Tables: These are used to define relationships between two variables, like flow vs. depth or other physical properties.
  • Time Series Tables: These store time-varying data, such as rainfall, temperature, and other temporal input data for simulations.

Functions for Interpolation and Lookup:

  • Interpolation: Functions like table_interpolate and table_lookup are used to estimate values between known data points in the table, allowing the model to handle time-varying inputs like rainfall.
  • Extrapolation: Functions like table_tseriesLookup handle extrapolation when time series data is outside the existing table range.

Use of External Files:

  • Some tables are loaded from external files (e.g., time series data for rainfall). The functions handle file reading and parsing, as seen in table_getNextFileEntry and table_parseFileLine.

Validation:

  • The table_validate function ensures the integrity of table data, ensuring that x-values in the table are ordered correctly, which is important for interpolation and lookups.

Summary:

The table.c file in SWMM 5 is crucial for managing and processing curve and time series data. It enables interpolation, extrapolation, and lookup of values from these data structures, which are used throughout the SWMM simulation for various physical processes like runoff, routing, and water quality. The file also handles input parsing, validation, and memory management for tables, making it a core component of the SWMM computational engine.

SWMM5 swmm5.c Summary

 The swmm5.c file is the core computational engine for the U.S. Environmental Protection Agency's Storm Water Management Model (SWMM). This file coordinates the flow of calculations throughout the simulation, calling other modules for tasks like runoff analysis, routing, and water quality computations. It handles input and output files, manages global state variables, processes each simulation step, and interacts with exception handling if errors arise.

Key Functions in swmm5.c

  1. swmm_run:

    • This is the entry point for running the simulation. It takes input, report, and output file names as arguments, opens the project, and calls the necessary functions to execute the simulation and save the results.
  2. swmm_open:

    • This function opens a project by reading the input data and initializing necessary structures. It processes the input file, performs initial validation, and prepares for simulation.
  3. swmm_start:

    • Starts the simulation by initializing all components (e.g., rainfall, routing, statistics) and setting up the necessary conditions. It also handles simulation setup like writing options and warnings.
  4. swmm_step:

    • Advances the simulation by one routing time step. It handles the calculation of runoff, routing, and water quality for the current time step and updates the elapsed time.
  5. swmm_stride:

    • Advances the simulation by a fixed number of seconds. This function is useful for simulations where time steps need to be manually specified or adjusted.
  6. execRouting:

    • This function is responsible for routing water and pollutants through the drainage system, which includes computing runoff and performing necessary flow routing.
  7. saveResults:

    • Saves the results of the simulation to the output file, either as averages or raw values, depending on the user’s configuration.
  8. swmm_end:

    • Ends the simulation by performing necessary cleanup tasks, including closing output files, reporting results, and releasing resources.
  9. swmm_report:

    • Generates a report of the simulation results.
  10. swmm_getMassBalErr:

    • Retrieves the mass balance errors (e.g., runoff, flow, and quality errors) of the simulation.
  11. swmm_getVersion:

    • Returns the version number of the SWMM engine.
  12. swmm_getError:

    • Retrieves the error message and code of the last exception that occurred during the simulation.
  13. swmm_getWarnings:

    • Retrieves the number of warning messages that were issued during the simulation.

Exception Handling:

  • The file also includes support for exception handling through the EXH macro. This handles errors like memory access violations, floating-point errors, and other exceptions that may occur during simulation.
  • The xfilter function handles filtering and reporting of these exceptions, making sure the user is informed if any critical errors occur.

Simulation Flow:

  1. Input Reading: The swmm_open function opens the input files and reads the project data.
  2. Initialization: The swmm_start function initializes the simulation parameters and sets up the various computational models (e.g., rainfall, routing, quality).
  3. Simulation Steps: The simulation progresses step-by-step, with each step handled by swmm_step, which computes the required water flow and quality for that step.
  4. Reporting: The results are either written immediately or stored for later use, depending on the user's settings.
  5. Simulation Termination: Once the simulation is complete, swmm_end cleans up the resources and generates the final reports.

API Functions:

  • swmm_run: Runs the entire simulation based on input and output file paths.
  • swmm_getVersion: Retrieves the version number of the SWMM engine.
  • swmm_getError: Retrieves any error messages during the simulation.
  • swmm_getWarnings: Retrieves warnings issued during the simulation.
  • swmm_report: Writes the results to the report file.

Error Handling:

  • SWMM uses a global ErrorCode variable to track errors. If an error occurs, the simulation stops, and the error message is written to the report.
  • Warnings are tracked separately in the Warnings variable, and users can retrieve them using the swmm_getWarnings function.

File Management:

  • swmm_open and swmm_close handle the opening and closing of project files. This includes input files (e.g., project definition, data files) and output files (e.g., report, result files).

Report Generation:

  • swmm_report generates a summary of the simulation, including runoff statistics, flow routing, and water quality results. This is useful for reviewing simulation performance and results.

Summary:

The swmm5.c file plays a central role in controlling the simulation process for the EPA's SWMM model. It coordinates input reading, simulation execution, and output generation while handling exceptions and ensuring that the simulation runs smoothly. The modular design allows for flexible simulation of hydrological processes and easy integration of new features or updates.

SWMM5 surfqual.c Summary

 The surfqual.c module in SWMM5 is responsible for handling the quality of runoff in subcatchments. This includes calculating the buildup of pollutants on the surface, their washoff due to rainfall, and the treatment of runoff using Low Impact Development (LID) practices. The module also deals with the loading of pollutants from surface runoff and provides the necessary functions to calculate and update the water quality throughout the simulation.

Key Concepts and Functions

  1. Pollutant Buildup:

    • Pollutants accumulate on the surface of subcatchments due to various land uses.
    • The module uses land use functions to calculate the buildup of pollutants over time.
    • surfqual_getBuildup calculates the pollutant buildup on the surface based on the land use and the subcatchment’s characteristics.
  2. Ponded Water and Wet Deposition:

    • Wet deposition and runon (water flowing from upstream subcatchments) contribute to the pollutant load in the ponded water.
    • findPondedLoads updates the concentration of pollutants in ponded water and contributes to the overall mass balance for pollutants.
    • surfqual_sweepBuildup accounts for the reduction in pollutant buildup through street sweeping.
  3. Pollutant Washoff:

    • Pollutant washoff occurs due to runoff, and this module computes how much of the accumulated pollutants are washed off during rainfall or snowmelt events.
    • surfqual_getWashoff calculates the washoff of pollutants due to the runoff generated by a subcatchment.
  4. LID Treatment:

    • LID practices like rain gardens or permeable pavements treat runoff by removing pollutants.
    • findLidLoads calculates the pollutant load reductions due to LID treatment and accounts for the runoff generated from these areas.
  5. Key Functions:

    • surfqual_initState initializes the pollutant buildup and quality state for a subcatchment.
    • surfqual_getBuildup adds to the pollutant buildup on the surface of a subcatchment.
    • surfqual_sweepBuildup reduces the buildup due to street sweeping.
    • surfqual_getWashoff calculates the washoff of pollutants due to runoff.
    • findWashoffLoads computes the washoff loads for each land use and adds them to the subcatchment's total runoff loads.
  6. Pollutant Load Mass Balance:

    • This module contributes to the mass balance for pollutants, updating the total mass of pollutants in the system and tracking them over time.
    • OutflowLoad holds the mass of pollutants in runoff leaving the subcatchment.

Core Variables:

  • OutflowLoad[]: An array used to track the mass load of pollutants in the runoff flowing out of the subcatchment.
  • Vevap: The volume of water evaporated from the subcatchment.
  • Vinfil: The volume of water infiltrated into the soil or groundwater.
  • Voutflow: The volume of water that flows out of the subcatchment as runoff.

Core Functions:

  • surfqual_initState: Initializes the pollutant state variables for the subcatchment (e.g., old and new pollutant concentrations).
  • surfqual_getBuildup: Calculates and adds to the pollutant buildup on the subcatchment’s surface.
  • surfqual_sweepBuildup: Reduces pollutant buildup over the subcatchment when street sweeping occurs.
  • surfqual_getWashoff: Computes the pollutant washoff from the subcatchment during rainfall or snowmelt events.
  • findWashoffLoads: Calculates the pollutant washoff based on the pollutant buildup and land use functions.
  • findLidLoads: Calculates the contribution of pollutants from LID areas (such as rain gardens or permeable pavements) and updates the overall mass balance.

Example Use Case:

Consider a stormwater management model that includes both urban and residential areas. The surfqual.c module would be used to calculate how much pollution accumulates on the surface due to runoff from streets, parking lots, and lawns (land use). During a rainstorm, pollutants are washed off these surfaces and carried into the drainage system. If LID practices are in place (e.g., permeable pavements), the module would account for the pollutants removed by these systems. The module would also keep track of the volume of water evaporated, infiltrated, and the overall pollutant load leaving the subcatchment.

Summary:

The surfqual.c module is crucial for managing water quality in SWMM5. It calculates the accumulation and removal of pollutants on the surface, accounting for various processes such as washoff, evaporation, infiltration, and LID treatment. The module provides functions to handle pollutant buildup, mass balance updates, and runoff water quality, which are critical for simulating stormwater behavior in urban environments.

SWMM5 subcatch.c Summary

 The subcatch.c module in SWMM5 is responsible for calculating runoff from subcatchments. A subcatchment is a geographical area from which runoff is generated, and this module handles the runoff from both impervious and pervious areas, including their interactions with Low Impact Development (LID) features and groundwater.

Key Concepts and Functions

  1. Runoff Calculation:

    • Subcatchment Area: Each subcatchment is divided into impervious and pervious areas, with runoff and infiltration computed for each.
    • Runon: Water flowing from upstream areas into the subcatchment. This flow is distributed over the non-LID portion of the subcatchment unless the LID occupies the entire subcatchment.
    • LID Interactions: The module supports LID features like rain gardens or permeable pavements, which treat runoff before it enters the drainage system.
    • Snowmelt: The module also includes the ability to calculate snowmelt if snow is present.
  2. Core Variables:

    • Runoff: Calculated based on rainfall, snowmelt, and the subcatchment’s characteristics.
    • Evaporation (Vevap) and Infiltration (Vinfil): Subcatchments also have evaporation and infiltration losses, which are calculated over each time step.
    • LID Drainage: LID units capture and treat some of the runoff. These are tracked separately in variables like VlidIn (inflow to LID), VlidOut (surface outflow), VlidDrain (drain outflow), and VlidReturn (return flow to the pervious area).
  3. Key Functions:

    • subcatch_readParams: Reads parameters from the input file for each subcatchment (e.g., area, impervious fraction, slope).
    • subcatch_getRunoff: Computes the total runoff for a subcatchment during a given time step. This includes runoff from impervious and pervious areas, as well as contributions from LID systems.
    • subcatch_getRunon: Distributes the runoff from upstream subcatchments to the subcatchment.
    • subcatch_addRunonFlow: Adds the runoff flow from upstream areas to the subcatchment’s inflow.
    • subcatch_getNetPrecip: Calculates the total precipitation (rainfall + snowmelt) for the subcatchment.
    • subcatch_getStorage: Returns the total volume of stored water (including ponded water and LID storage).
    • subcatch_setOldState: Updates the old state of a subcatchment, storing the previous time step’s runoff and snow depth.
  4. Water Balance:

    • Each subcatchment maintains a water balance involving runoff, infiltration, evaporation, and snowmelt. These values are updated over each time step.
  5. Infiltration and Groundwater:

    • Infiltration: The module calculates the infiltration into the soil based on the characteristics of the subcatchment and its surface conditions.
    • Groundwater: If groundwater is present in the subcatchment, the module calculates inflows and outflows from the groundwater system (e.g., infiltration from the surface, lateral flow to the node).

Water Balance Components:

  1. Inflow: Includes precipitation, snowmelt, runon from upstream subcatchments, and ponded water.
  2. Losses: Includes evaporation and infiltration into the soil or groundwater.
  3. Outflow: Includes surface runoff leaving the subcatchment, either through drainage or outflow to the subcatchment’s outlet.

Integration with Other Modules:

  • LID and Groundwater: This module integrates with the lid.c and gwater.c modules to account for the impact of Low Impact Development (LID) features and groundwater on runoff and infiltration.
  • Pollutant Buildup and Washoff: This module works with surfqual.c to calculate pollutant buildup and washoff from the subcatchment.

Summary of Key Functions and Methods:

  • subcatch_readParams: Reads and assigns the input parameters for each subcatchment (e.g., rain gage, outlet, area, impervious fraction).
  • subcatch_getRunoff: Calculates the runoff for a subcatchment during a time step based on input precipitation and subcatchment characteristics.
  • subcatch_getRunon: Computes the runoff flowing into the subcatchment from upstream areas.
  • subcatch_addRunonFlow: Adds runoff from upstream subcatchments to the current subcatchment’s inflow.
  • subcatch_getStorage: Calculates the volume of stored water in the subcatchment’s surface (ponded water).
  • subcatch_getResults: Computes the weighted average of runoff, snow depth, and water quality for the subcatchment.
  • subcatch_setOldState: Updates the previous state of the subcatchment’s runoff and snow depth.

Example Use Case:

A stormwater management model for a city might use this module to simulate the runoff generated by different land surfaces, including streets, parks, and buildings. Each subcatchment is modeled based on its area, impervious fraction, and slope. The module calculates the volume of water running off each subcatchment, including the impact of rainfall, snowmelt, and runoff from upstream areas. It also accounts for the effects of LID practices (like rain gardens) and infiltration into the groundwater. The final output can include runoff volumes, flow rates, and water quality at the subcatchment outlets.

In conclusion, the subcatch.c module is central to modeling runoff from subcatchments in SWMM5. It computes runoff, loss rates, and pollutant washoff, while also interacting with other modules like LID and groundwater to create a comprehensive model of stormwater behavior.

SWMM5 street.c Summary

 Overview of street.c module

The street.c module in SWMM5 provides functions to handle the creation, deletion, and parameter reading of street cross-section objects used in hydrologic modeling. This module supports the representation of streets in the drainage network, including their geometry, slope, and roughness, which are important for modeling runoff in urban environments.

Key Functions

  1. street_create:

    • Purpose: Creates a collection of Street objects in memory, initializing them for use in the model.
    • Input: nStreets — number of street objects to create.
    • Output: Returns an error code (0 if successful).
    • Details: Allocates memory for the street objects and initializes them.
  2. street_delete:

    • Purpose: Deletes the collection of Street objects created in the model.
    • Output: Frees allocated memory for the street objects.
  3. street_readParams:

    • Purpose: Reads the parameters for a street cross-section from an input file.
    • Input: tok[] — tokenized input string; ntoks — number of tokens.
    • Output: Returns an error code.
    • Details: Parses the input data and assigns the corresponding values to the Street object, including parameters such as roadway crown, curb height, cross slope, roughness, and street backing. If any required parameters are missing or incorrect, the function returns an error.
  4. street_getExtentFilled:

    • Purpose: Calculates the degree to which a street is filled with water based on the link depth and cross-section area.
    • Input: link — the index of the link representing the street.
    • Output: Returns the degree of fill as a ratio (0 to 1).
    • Details: If the routing model is dynamic wave (DW), the function uses the maximum depth at the link's nodes. Otherwise, it computes the fill level based on the cross-section area of the conduit.

Data Structure (TStreet)

The module relies on the TStreet data structure to represent a street’s geometry. The fields within this structure include:

  • width: Roadway width.
  • curbHeight: Height of the curb.
  • slope: Cross slope of the roadway.
  • roughness: Manning's roughness coefficient for the road surface.
  • gutterDepression: Gutter depression height.
  • gutterWidth: Width of the gutter.
  • sides: Number of sides of the street (1 or 2).
  • backWidth: Width of the street backing.
  • backSlope: Slope of the street backing.
  • backRoughness: Roughness coefficient for the street backing.

Core Logic

  1. Street Geometry and Parameters:

    • The street geometry is defined by parameters such as crown height, gutter width, slope, and roughness. These are used to calculate runoff and flow characteristics in urban settings where streets are a critical part of the drainage network.
  2. Street Cross-Section Calculation:

    • The module supports street cross-sections for both paved and unpaved streets. The Transect function, which is invoked by street_readParams, calculates the geometric properties of the street cross-section based on the input parameters.
  3. Street Fill Calculation:

    • The function street_getExtentFilled computes the degree to which a street is filled with water. This is useful for modeling stormwater runoff and determining how much water is captured by the street versus flowing through the drainage system.

Application

The street.c module is important for accurately modeling stormwater runoff in urban environments, where streets often serve as significant conduits for runoff. By specifying detailed parameters for streets, such as slopes and roughness coefficients, SWMM 5 can more accurately simulate how stormwater flows over streets and interacts with other parts of the drainage system.

Example Use Case:

For a city planning scenario, you might have a collection of streets, each with different cross-sections. By configuring the street geometry, such as curb heights and gutter slopes, you can simulate how these streets handle runoff during a rainstorm. This allows you to estimate flooding, identify areas that require stormwater improvements, and ensure that the drainage system is designed to handle expected flow rates.

Summary

The street.c module enables SWMM5 to handle complex urban street geometry in the context of stormwater modeling. It allows for precise configuration of street parameters, such as crown height, slope, roughness, and drainage capacity, ensuring that streets are modeled accurately in runoff and flooding simulations.

SWMM5 statsrpt.c Summary

 The **statsrpt.c** module in SWMM 5 handles the reporting of summary statistics for the simulation. It generates detailed tables summarizing various aspects of the simulation, including runoff, groundwater, flow, and storage volumes, and it reports these statistics in a format suitable for analysis.


### Key Concepts and Functions in **statsrpt.c**:


#### 1. **Key Reporting Functions**:

   - **`statsrpt_writeReport`**: This is the main function that generates and writes the simulation's summary statistics. It calls various other helper functions to report different aspects of the simulation, such as subcatchment runoff, groundwater data, node depths, and link flows.

   

   - **`writeSubcatchRunoff`**: Reports runoff statistics for each subcatchment, including total precipitation, runoff, infiltration, evaporation, and the maximum runoff rate.

   

   - **`writeGroundwater`**: Writes the groundwater summary, including infiltration, evaporation, lateral flow, deep flow, and the maximum flow for groundwater processes in the subcatchments.

   

   - **`writeSubcatchLoads`**: Reports pollutant loads for each subcatchment, including pollutant buildup, wash-off, and total pollutant loads for each subcatchment.

   

   - **`writeNodeDepths`**: Reports depth statistics for nodes, including average and maximum depth, surcharging, and flooding information.

   

   - **`writeNodeFlows`**: Reports inflow statistics for nodes, including maximum lateral inflow, total inflow, and the volume of water in the node.

   

   - **`writeNodeSurcharge`**: Reports surcharging statistics for nodes, specifically for those experiencing surcharges in dynamic wave flow routing.

   

   - **`writeNodeFlooding`**: Reports flooding statistics, including the total time spent flooding and the volume of water flooded.

   

   - **`writeStorageVolumes`**: Reports storage volume statistics for storage nodes, including average and maximum volumes, and flow through storage units.

   

   - **`writeOutfallLoads`**: Reports the total loads (pollutants) at outfall nodes, including flow, volume, and pollutant mass.

   

   - **`writeLinkFlows`**: Reports flow statistics for links, including maximum flow, velocity, and depth.

   

   - **`writeFlowClass`**: Reports the flow classification for each conduit, showing the fraction of time each flow classification occurred (e.g., subcritical, supercritical, normal, etc.).

   

   - **`writeLinkSurcharge`**: Reports the surcharge statistics for conduits, showing the time periods during which each conduit was surcharged.


#### 2. **Table Formatting**:

   The report tables are well-structured to show the following types of information:

   - **Subcatchment Runoff Summary**: Includes details such as the total precipitation, runoff, evaporation, infiltration, and impervious/pervious runoff for each subcatchment.

   - **Groundwater Summary**: Includes infiltration, evaporation, lateral flow, deep flow, and the maximum flow for groundwater in each subcatchment.

   - **Node Depth Summary**: Includes average and maximum depths for nodes, surcharging and flooding occurrences, and the time of maximum depth.

   - **Node Inflow Summary**: Reports inflows to nodes, including maximum lateral inflow and total inflow.

   - **Storage Volume Summary**: Summarizes storage unit volumes, including average and maximum volumes, and the time the storage was full or surcharged.

   - **Outfall Loading Summary**: Reports pollutant loads at outfalls, including flow, volume, and pollutant mass.

   - **Link Flow Summary**: Provides details on link flows, including maximum flow, velocity, and the time the link was surcharged.

   - **Link Surcharge Summary**: Shows surcharging statistics for links, including the time spent in surcharge conditions.


#### 3. **Units and Formatting**:

   - The module ensures the correct units are applied to all values (e.g., inches, feet, cfs, etc.), and it provides a consistent format for reporting.

   - For pollutants, the units used for reporting can vary, and the module ensures that values are formatted correctly based on the unit system (US or SI) and the type of pollutant.

   - The flow values are reported in either scientific notation or standard format, depending on the size of the value.


#### 4. **Important Statistics**:

   - **Subcatchment Statistics**: These include various water balance components (precipitation, runoff, infiltration, etc.) and pollutant loads.

   - **Groundwater Statistics**: These include lateral flow, infiltration, evaporation, and deep flow in groundwater systems.

   - **Node Statistics**: These include depths, inflows, overflows, and flooding information for nodes.

   - **Link Statistics**: These include flow rates, velocities, and surcharge times for links.


#### 5. **Output Format**:

   - The report is generated in a structured, tabular format that makes it easy to interpret the results for each component of the system (e.g., subcatchments, nodes, links, etc.).

   - The module uses functions like `fprintf` to format and print the results to the report file in a consistent manner, making it easier for users to understand the results.


### Summary:

The **statsrpt.c** module plays a critical role in generating summary reports for a SWMM 5 simulation. It handles the reporting of a wide range of statistics related to runoff, groundwater, flow, storage, and water quality, presenting these statistics in a clear, structured format. This functionality is essential for understanding the behavior of the drainage system and for validating the simulation results against expected or observed data.

SWMM5 stats.c Summary

 The stats.c module in the SWMM 5 source code is responsible for managing and updating the statistical data collected during a simulation. It tracks various metrics related to the flow, volume, and quality of water as it moves through the drainage system. The module collects and reports data for nodes, links, subcatchments, and other system components.

Key Concepts and Functions in stats.c:

1. Global Variables:

  • SubcatchStats, NodeStats, LinkStats, StorageStats, OutfallStats, PumpStats: These variables store statistics for subcatchments, nodes, links, storage units, outfalls, and pumps, respectively.
  • MaxStats Arrays: These arrays (e.g., MaxMassBalErrs, MaxCourantCrit) store the maximum values for various system statistics, such as mass balance errors and Courant stability criteria, during the simulation.
  • SysOutfallFlow: This variable tracks the total outfall flow for the simulation.

2. Key Functions:

  • stats_open: Initializes the statistical system by allocating memory for various statistics structures and setting initial values.
  • stats_close: Closes the statistics system and frees allocated memory.
  • stats_report: Reports the collected simulation statistics, including flow routing accuracy, node/link flow statistics, and time step statistics.
  • stats_updateSubcatchStats: Updates the statistics for a specific subcatchment, including rainfall, runoff, infiltration, and pollutant load.
  • stats_updateNodeStats: Updates the statistics for a specific node, including water depth, flooding, surcharging, and lateral flow.
  • stats_updateLinkStats: Updates the statistics for a specific link, including flow, velocity, and surcharge time.
  • stats_findMaxStats: Finds and updates the maximum values for mass balance errors, Courant stability, and other critical metrics.
  • stats_updateMaxStats: Updates the maximum value statistics for a specific node or link.
  • stats_updateTimeStepStats: Updates the time step statistics, including the average, minimum, and maximum time steps.
  • stats_updateCriticalTimeCount: Updates the count of times a node or link was critical in terms of the time step.
  • stats_updateConvergenceStats: Updates the statistics related to convergence (non-convergence count) for nodes.

3. Statistical Reporting:

  • Flow Statistics: The module tracks various flow statistics, such as inflow, outflow, flooding, surcharging, and overflow, for nodes and links.
  • Quality Statistics: For water quality constituents, the module tracks pollutant buildup, washoff, and mass balance for nodes and links.
  • Time Step Statistics: Time step statistics, including the minimum, maximum, and average time steps, are reported for the simulation.
  • Routing Accuracy: The module tracks routing accuracy, including the flow routing error (mass balance error) and Courant stability criteria.
  • Convergence and Non-Convergence: The module tracks the number of non-converging nodes and links during the simulation, which is essential for diagnosing numerical stability issues.

4. Key Statistical Metrics:

  • Mass Balance Errors: Tracks the discrepancy between inflow and outflow at nodes and links to ensure conservation of mass.
  • Courant Stability: Measures the stability of the simulation based on the Courant criterion, which is important for numerical simulations using dynamic wave routing.
  • Flow Turns: Tracks the number of times the flow direction changes at a node or link during the simulation.
  • Max Flow and Depth: Tracks the maximum flow and depth at nodes and links, which are critical for system design and analysis.

Summary:

The stats.c module is essential for collecting, updating, and reporting various statistics during a SWMM 5 simulation. It tracks both hydrologic and hydraulic metrics, such as flow rates, water depths, pollutant loads, and convergence criteria. This module provides valuable insights into the system's performance and stability during the simulation and is crucial for understanding the behavior of the drainage system, especially in complex simulations involving multiple time steps and events.

SWMM5 snow.c Summary

 The snow.c module in the SWMM 5 source code is responsible for modeling snow accumulation, snowmelt, and snow removal processes in the hydrological model. This module simulates the impact of snow on the runoff from subcatchments, including the accumulation of snow, the melting of snow due to precipitation and temperature, and the potential for snow removal from streets or other impervious surfaces.

Key Concepts and Functions in snow.c:

1. Snowmelt Parameters and Data Structures:

  • Snow Keywords: These are identifiers used in the input data to refer to different types of snow surfaces (plowable, impervious, and pervious).
  • TSnowpack: This structure represents the snowpack on a subcatchment, which includes the amount of snow (in depth) on different surfaces, the cold content (temperature-related energy storage), and the snow's free water content (meltwater).
  • TSnowmelt: This structure holds parameters related to snowmelt, including melt coefficients, temperature base for melting, and other characteristics that affect snowmelt and snow accumulation.

2. Key Functions:

  • snow_readMeltParams: This function reads snowmelt parameters from input data, including values like the melt coefficient, snow depth, and fraction of plowable impervious area.
  • snow_createSnowpack: This function initializes a snowpack object for a subcatchment and assigns it a set of snowmelt parameters.
  • snow_initSnowpack: This function initializes the state of the snowpack for a subcatchment, including assigning snow depth and free water content to different sub-areas (e.g., plowable, impervious, and pervious surfaces).
  • snow_plowSnow: This function simulates snow plowing operations on the subcatchment, moving snow between sub-areas (e.g., from plowable to impervious or pervious surfaces).
  • snow_getSnowMelt: This function computes the snowmelt rate based on precipitation (rainfall and snowfall), temperature, and other snow-related factors.
  • snow_getSnowCover: This function computes the total volume of snow cover on the subcatchment.
  • snow_setMeltCoeffs: This function sets the melt coefficients based on the current temperature or snow season of the year.

3. Snowmelt Calculation Process:

  • Snow Accumulation: Snowfall is added to the snowpack. The snow depth on different surfaces (plowable, impervious, and pervious) is updated based on the snowfall.
  • Snowmelt: Snowmelt is calculated based on precipitation and temperature. If it is raining, the melt rate is calculated using a rainfall-based melt model. If the temperature exceeds a certain threshold, the snowpack melts using a degree-day method. The meltwater is routed through the snowpack, and the cold content is updated accordingly.
  • Snow Removal: Snow removal is simulated for plowable impervious areas. The snow removed is routed to other surfaces or subcatchments, and the snow depth is reduced.
  • Cold Content and Temperature: The cold content (a measure of how much energy is required to melt the snow) is updated based on the temperature and the snow's previous state.

Summary of Key Concepts:

  • Snowmelt: The process of snow turning into water as it melts due to temperature and precipitation. The rate of snowmelt is determined by the temperature and the snowmelt coefficients.
  • Snowpack: The accumulation of snow and its characteristics, such as depth, free water content, and cold content.
  • Subcatchment Snow Coverage: Different subcatchments may have snow on various surfaces, such as impervious or pervious areas, which influence the snowmelt process.
  • Snow Removal: A process that removes snow from plowable impervious areas and transfers it to other areas or subcatchments.

Summary:

The snow.c module is an essential component of SWMM5 that simulates the interaction between snow, rainfall, and runoff. By modeling snow accumulation and melt, this module helps account for seasonal changes in runoff behavior due to snow cover. It includes a variety of parameters and functions to simulate snow accumulation, snowmelt, and snow removal, and it integrates this process into the overall hydrological modeling of subcatchments. The snowpack state (depth, cold content, and free water) is updated dynamically throughout the simulation based on precipitation and temperature conditions.

SWMM5 shape.c Summary

 The shape.c module in the EPA SWMM5 source code is responsible for handling custom cross-sectional shapes used in conduit (link) modeling. Specifically, it is used to compute geometric properties of custom user-defined shapes for the flow paths in the drainage system. These properties are crucial for flow routing and are used in the calculation of flow rates, velocities, and hydraulic radii.

Key Functions in the shape.c Module:

  1. shape_validate:

    • This function validates and computes the necessary geometric properties of a custom cross-section shape. It checks if the shape is valid and then computes the shape's geometry using the supplied width vs. height curve.
  2. computeShapeTables:

    • This function generates the tables of geometric properties for a custom cross-section shape. It computes the area, perimeter, and hydraulic radius for each height interval in the shape’s curve and stores them in the respective geometry tables.
  3. normalizeShapeTables:

    • After computing the tables, this function normalizes them to the full height of the cross-section. This is done by dividing the values by the total area and hydraulic radius, ensuring consistency and correct scaling.
  4. getSmax:

    • This function calculates the maximum section factor (a value related to the hydraulic efficiency of the shape) for the custom cross-section. It also calculates the maximum area for the shape.
  5. getNextInterval:

    • This function handles the transitions between height intervals in the custom shape curve and calculates the width of the shape at different heights using linear interpolation.
  6. getWidth:

    • This function interpolates the width of the custom cross-section at a given height based on the width vs. height curve provided by the user.
  7. getArea:

    • This function calculates the area of the trapezoidal section formed by two points in the width vs. height curve. It is used for calculating the area of the cross-section at different height intervals.
  8. getPerim:

    • This function computes the perimeter (wetted perimeter) of the cross-section for the given height interval. This is important for calculating the flow and hydraulic radius.

Workflow:

  1. Validate and Compute Geometry:

    • The first step in using this module is to validate and compute the geometric properties of the custom shape using the shape_validate function. This involves reading the shape's width vs. height curve and using it to calculate the area, perimeter, and hydraulic radius at various intervals of height.
  2. Normalize Geometry Tables:

    • Once the tables are computed, they are normalized to the full height of the cross-section (using normalizeShapeTables) to ensure that all values are relative to the maximum dimensions of the shape.
  3. Hydraulic Calculations:

    • The computed geometric properties (area, perimeter, hydraulic radius, etc.) are then used in hydraulic calculations to determine flow rates and other hydraulic characteristics for the conduits in the drainage network.
  4. Custom Cross-Section Support:

    • The module supports custom cross-sections defined by the user. These custom shapes are important for modeling irregular or non-standard conduits in the drainage system.

Summary of Key Concepts:

  • Shape Curve: A user-defined table that describes the width of the cross-section at various heights. This is essential for calculating the flow area and wetted perimeter, which in turn affect flow and velocity calculations.
  • Hydraulic Radius: This is the ratio of the cross-sectional area of flow to the wetted perimeter. It is used in the Manning’s equation for flow calculation.
  • Section Factor: A dimensionless number that characterizes the efficiency of the cross-section in conveying flow. It is calculated from the area and hydraulic radius.

Summary:

The shape.c module is an important part of SWMM5’s flexibility, allowing for custom user-defined conduit shapes. It computes the geometric properties of these custom shapes, which are then used in flow calculations. The module supports irregular conduit shapes that are not easily modeled using standard circular or trapezoidal shapes.

SWMM5 rain.c Summary

 The rain.c file in SWMM5 handles the import and storage of external rainfall data into the SWMM rainfall interface format. It supports various formats for reading data, processes the rainfall records, and integrates them into the SWMM model for use in simulation.

Key Functions and Features of rain.c:

1. rain_open():

  • This function opens the binary rainfall interface file for reading or writing, depending on the mode (SCRATCH_FILE, USE_FILE, or SAVE_FILE).
  • If needed, it creates a new rainfall interface file and writes the header information, including the rain gage details.

2. rain_close():

  • This function closes the rainfall interface file and the RDII processor if they are open.

3. createRainFile():

  • This function writes rainfall data from all rain gage files into a single SWMM rainfall interface file. It ensures that the gage data is correctly added to the file and includes appropriate header information.

4. rainFileConflict():

  • This function checks if there are conflicts in the station ID across multiple gages, ensuring that each gage has a unique station ID.

5. addGageToRainFile():

  • This function reads the rainfall data from a specified rain gage file and writes it to the rain interface file. It also handles different formats, including NWS, AES, and CMC formats.

6. initRainFile():

  • This function initializes the rainfall interface file for reading. It verifies that the file is correctly formatted and retrieves the gage data.

7. findGageInFile():

  • This function looks for a specific rain gage's station ID in the rainfall interface file and retrieves its data.

8. findFileFormat():

  • This function determines the format of the rainfall data file, supporting formats like NWS_TAPE, NWS_SPACE_DELIMITED, NWS_COMMA_DELIMITED, and others.

9. readFile():

  • This function reads the rainfall records from the gage's data file and writes them to the SWMM rainfall interface file, based on the file format.

10. readNWSLine():

  • This function reads a single line of rainfall data from NWS-style data files (including space-delimited, comma-delimited, and online formats), parses the values, and writes them to the interface file.

11. saveAccumRainfall():

  • This function saves accumulated rainfall data by evenly distributing the total rainfall over the accumulation period and writing it to the rainfall interface file.

12. saveRainfall():

  • This function writes the current rainfall value to the SWMM rainfall interface file, including the date and time of the reading.

13. setCondition():

  • This function sets the condition code based on flags in the rainfall data, such as indicating missing or deleted periods.

14. initRainFile():

  • This function initializes the rainfall interface file for reading, ensuring that the file format is correct and that the rainfall data can be properly read.

Summary of Key Concepts:

  • Rainfall Data Formats: The file supports multiple rainfall data formats, including NWS tape, space-delimited, comma-delimited, AES, CMC, and standard SWMM formats. It identifies the format and processes the data accordingly.

  • Data Parsing and Writing: The functions read and parse the rainfall data, ensuring that it is correctly formatted and written into the SWMM rainfall interface file. The data includes station IDs, rainfall depths, and timestamps.

  • Rainfall Processing: The file handles the conversion of rainfall values, accumulation of rainfall over time, and the inclusion of rainfall values with proper timestamps in the SWMM binary rainfall file.

  • Error Handling: The functions ensure that errors in data formatting, conflicts between station IDs, and other issues are handled gracefully, with appropriate error messages being reported.

Overall, the rain.c file is crucial for handling external rainfall data in various formats, converting it into a format suitable for SWMM, and integrating it into the simulation model. It plays a vital role in importing and processing rainfall data from various sources, ensuring that the data can be used for hydrologic and hydraulic modeling within SWMM.

SWMM5 rdii.c Summary

 The rdii.c file in SWMM5 is responsible for managing the Rainfall Dependent Infiltration/Inflow (RDII) process. RDII is crucial in representing how rainfall infiltrates and flows into a sewer system, contributing to overflows and treatment demands. This file handles the storage, calculation, and management of RDII inflows for simulation and reporting within the SWMM model.

Key Functions and Features:

1. rdii_readRdiiInflow():

  • Reads RDII inflow data for a specific node from input data, associates it with a unit hydrograph, and assigns the associated area for the RDII calculation.

2. rdii_initUnitHyd():

  • Initializes the unit hydrograph parameters for RDII processing, including rainfall parameters for each month.

3. rdii_readUnitHydParams():

  • Reads parameters of unit hydrographs, which define the relationship between rainfall events and inflows into the system.

4. rdii_openRdii():

  • Opens and prepares the RDII interface file, initializing the RDII inflow processing system, reading any existing RDII inflow data, and creating new files if necessary.

5. rdii_closeRdii():

  • Closes the RDII interface file and releases any memory allocated for RDII processing.

6. rdii_getNumRdiiFlows():

  • Retrieves the number of RDII flows for a specific time period based on the current date.

7. rdii_getRdiiFlow():

  • Retrieves the RDII flow for a specific node, returning the flow value along with the node index.

8. rdii_getRainInterval():

  • Retrieves the time interval for rainfall data that corresponds to a unit hydrograph (UH) group.

9. getUnitHydConvol():

  • Performs the convolution of a unit hydrograph with past rainfall data to calculate the RDII flow at a given time based on previous rainfall.

10. saveRdiiFlows():

  • Saves the current RDII inflow data to the RDII interface file.

11. closeRdiiProcessor():

  • Finalizes RDII processing by writing statistics and freeing memory allocated during the RDII process.

12. rdii_deleteRdiiInflow():

  • Deletes the RDII inflow object associated with a specific node, freeing the allocated memory.

13. applyIA():

  • Applies initial abstraction (IA) to rainfall data for unit hydrographs, adjusting rainfall for any pre-set abstraction before using it in RDII calculations.

14. updateDryPeriod():

  • Updates the dry period for a unit hydrograph, tracking the time since the last non-zero rainfall.

15. getUnitHydRdii():

  • Computes the RDII generated by past rainfall for each unit hydrograph (UH) group.

16. getUnitHydOrd():

  • Returns the ordinate (flow value) of a unit hydrograph at a given time.

17. getNodeRdii():

  • Retrieves the RDII flow for each node that has RDII inflow data, storing it in the system for further processing.

18. rdii_createRdiiFile():

  • Creates and initializes a new RDII interface file, which will store RDII inflow data and relevant metadata for future simulations.

19. getMaxPeriods():

  • Determines the maximum number of past periods of rainfall data to store for unit hydrographs.

Key Concepts and Components:

  • Unit Hydrographs (UH): The RDII inflow for a node is modeled using unit hydrographs. These hydrographs define the relationship between rainfall events and the flow that enters the system, based on previous rainfall.

  • RDII Processing: The RDII processing works by calculating RDII inflows based on the convolution of past rainfall data with predefined unit hydrographs. This is done on a time-step basis (e.g., hourly or every 15 minutes) based on the rainfall and unit hydrograph parameters.

  • Inflow and Outflow: RDII inflows are generated based on rainfall that enters a sewer system, and they can contribute to overflows or system loading. The file tracks how much RDII is generated at each node and contributes to the overall system flow.

  • Interface File: The RDII inflow data is saved to an interface file (binary or text), which is used by SWMM for modeling and reporting purposes. The interface file contains information about the RDII time step, flow rates, and node-specific RDII data.

Overall Functionality:

The rdii.c file integrates RDII inflows into the SWMM model, using unit hydrographs to represent the relationship between rainfall and sewer inflow. It manages the creation, reading, and writing of RDII data files, processes rainfall events for RDII calculations, and ensures that all RDII data is accurately tracked and saved for use in simulations.

SWMM5 report.c Summary

 The report.c file in SWMM5 handles the generation of reports for simulations. It includes functions for reporting errors, warnings, and results for various aspects of a simulation, including subcatchments, nodes, links, runoff, groundwater, and more.

Key Features and Functions:

1. Report Options and Flags:

  • The report_readOptions() function reads and sets reporting options (such as whether to report results for subcatchments, nodes, and links).
  • The RptFlags structure controls which categories of results are reported (e.g., RptFlags.nodes, RptFlags.links).

2. Writing Results:

  • report_writeLine(): Writes a line of text to the report file.
  • report_writeSysTime(): Logs the starting and ending times of the simulation.
  • report_writeLogo(): Writes a logo header at the beginning of the report.
  • report_writeTitle(): Writes the project title to the report.
  • report_writeOptions(): Logs the analysis options used in the simulation.
  • report_writeRainStats(): Reports statistics related to rainfall data.
  • report_writeRunoffError(): Reports runoff quantity continuity errors if any.
  • report_writeNodeResults(): Logs results for selected nodes.
  • report_writeLinkResults(): Logs results for selected links.

3. Error and Warning Reporting:

  • report_writeErrorMsg(): Writes error messages to the report file based on error codes.
  • report_writeWarningMsg(): Writes warning messages, such as issues with data input or inconsistencies.
  • report_writeInputErrorMsg(): Reports input errors, including the specific line where the error occurred.

4. Continuity Error Reporting:

  • report_writeRunoffError(): Reports errors in the runoff continuity.
  • report_writeLoadingError(): Reports errors in the pollutant loading continuity.
  • report_writeQualError(): Reports errors in water quality routing continuity.
  • report_writeFlowError(): Reports errors in flow routing continuity.

5. Detailed Element Reporting:

  • report_writeMaxStats(): Reports the nodes and links with the highest mass balance errors or the most frequent Courant time step issues.
  • report_writeNonconvergedStats(): Reports nodes that failed to converge most frequently.
  • report_writeTimeStepStats(): Reports statistics about the routing time steps, including the number of iterations and whether the system was in steady state.
  • report_RouteStepFreq(): Writes a grouped frequency table for routing time steps.

6. Detailed Reporting of Simulation Results:

  • report_writeSubcatchments(): Reports results for subcatchments, including runoff, evaporation, infiltration, and quality metrics.
  • report_writeNodeResults(): Reports results for nodes, including flow, overflow, depth, and head.
  • report_writeLinkResults(): Reports results for links, including flow, velocity, depth, and capacity.

7. Control Actions:

  • report_writeControlActionsHeading(): Starts the section for control actions taken.
  • report_writeControlAction(): Logs a control action taken, including the link affected and the rule that triggered the action.

Key Features for Report Generation:

  1. Time Series Reporting:

    • The report includes time-series data for various simulation aspects, such as rainfall, runoff, and quality concentrations. This is done for selected subcatchments, nodes, and links.
  2. Error Handling and Logging:

    • Error messages and warnings related to the simulation process are captured and included in the report, helping users identify issues in their input data or the simulation process.
  3. Continuity Errors:

    • The system tracks continuity errors for runoff, pollutant loadings, and water quality. These errors are reported if they exceed certain thresholds, allowing users to detect discrepancies in the simulation.
  4. Control and Flow Management:

    • The report includes information about control actions (e.g., adjustments made to control nodes or links) and the frequency of flow instability in the system (e.g., flow reversals or non-convergence).
  5. Flexible Reporting:

    • Users can choose which aspects of the simulation to report on (subcatchments, nodes, links) and can control the level of detail in the report.

Overall Functionality:

The report.c file is integral to generating detailed reports for SWMM simulations. It allows users to customize the output, track simulation errors, and analyze various results related to runoff, groundwater, water quality, and control actions. The report helps users understand the performance of the model and troubleshoot any issues in their simulation setup.

SWMM5 Roadmap.txt Summary

 The SWMM 5 (Storm Water Management Model) source code is organized into several C modules, each responsible for different aspects of the simulation. The engine is designed to be compiled into a Dynamic Link Library (DLL) or shared object library depending on the platform (Windows, Linux, or macOS). A main.c file is provided to build an executable that interacts with the engine, running the simulation based on input files.

Here's a breakdown of the SWMM 5 engine source code and its modules:

Header Files

These files define constants, data structures, function prototypes, and global variables used throughout the source code:

  1. enums.h: Contains enumerated constants (e.g., unit types, simulation options).
  2. objects.h: Defines the main classes of objects used in SWMM (e.g., nodes, links, subcatchments).
  3. consts.h: Defines numerical constants used in calculations.
  4. text.h: Contains text strings used throughout the code (e.g., error messages).
  5. macros.h: Defines macros used in the code.
  6. globals.h: Declares global variables used in multiple modules.
  7. funcs.h: Contains function prototypes for functions that can be called across various modules.

Core Computational Modules

These modules handle the core of the SWMM 5 simulation engine:

  • swmm5.c: Supervisory control functions for the program, such as initializing the simulation, setting up objects, and managing the overall simulation flow.
  • project.c: Handles the creation, destruction, and management of all project data, including looking up objects by their ID names and setting default values.
  • input.c: Reads input data from the project files, setting up the model objects with the data.
  • runoff.c: Performs runoff calculations for subcatchments, including both quantity and quality of runoff.
  • routing.c: Routes runoff and external inflows through the drainage system network of nodes and links.
  • massbal.c: Performs mass balance calculations for runoff and routing.
  • stats.c: Collects simulation statistics such as flow rates, water depths, and number of solution iterations.
  • statsrpt.c: Writes summary simulation results to a status report.
  • output.c: Manages the reading and writing of runoff and routing results to/from a binary output file.
  • report.c: Prepares a status report and writes detailed results for subcatchments, nodes, and links based on user preferences.

Hydrology and Flow Modules

These modules are used to compute the hydrologic and hydraulic processes in the simulation:

  • rain.c: Places data from external rainfall files into a unified rainfall interface file.
  • gage.c: Provides rainfall data to the model from an external source, either from an interface file or a time series.
  • climate.c: Provides climate data (temperature, evaporation, wind speed) to the simulation.
  • snow.c: Computes snow accumulation, snow removal, and snowmelt for subcatchments.
  • infil.c: Handles infiltration calculations for subcatchments.
  • gwater.c: Computes groundwater fluxes and updates groundwater depths in the simulation.
  • subcatch.c: Computes rainfall runoff, pollutant buildup and washoff, and street sweeping for each subcatchment.
  • landuse.c: Evaluates pollutant buildup and washoff based on land use for subcatchments.
  • lid.c: Evaluates the performance of Low Impact Development (LID) practices in the model.
  • lidproc.c: Computes the performance of individual LID units.

Flow and Quality Routing Modules

These modules are used to route flows and water quality constituents through the drainage network:

  • flowrout.c: Controls the top-level flow routing process in the drainage system.
  • inflow.c: Provides direct time series inflows and recurring dry weather inflows to the drainage system at each time step.
  • rdii.c: Computes Rainfall Dependent Infiltration/Inflow (RDII) at selected nodes in the drainage network.
  • inlet.c: Calculates flow captured by street inlet drains and diverts it to sewer nodes.
  • kinwave.c: Implements kinematic wave flow routing for the system.
  • dynwave.c: Performs dynamic wave flow routing at each time step.
  • dwflow.c: Solves the dynamic wave continuity and momentum equations for conduits.
  • controls.c: Implements rule-based control actions for pumps and regulators during the simulation.
  • qualrout.c: Routes water quality constituents through the drainage system.
  • treatmnt.c: Computes pollutant removal at specific nodes where treatment functions have been assigned.
  • node.c: Contains functions to compute the properties and behaviors of drainage system nodes (junctions, flow dividers, storage units, outfalls).
  • link.c: Contains functions to compute the properties and behaviors of links (conduits, pumps, orifices, weirs, and outlets).
  • forcmain.c: Computes friction losses in force mains using the Hazen-Williams or Darcy-Weisbach equations.
  • culvert.c: Computes flow reductions in culverts due to inlet control.

Utility Modules

These modules provide various support functions for SWMM 5:

  • datetime.c: Functions for manipulating and formatting dates and times.
  • error.c: Error reporting functions.
  • findroot.c: Root-finding functions for solving equations.
  • hash.c: Implements hash tables for fast object retrieval by ID.
  • hotstart.c: Manages hot start files for resuming simulations from a saved state.
  • iface.c: Functions for reading from and writing to routing interface files.
  • keywords.c: Defines lists of keywords that appear in SWMM input files.
  • mathexpr.c: Functions for parsing and evaluating mathematical expressions.
  • mempool.c: Manages a memory pool used for storing object IDs.
  • odesolve.c: Implements the fifth-order Runge-Kutta method for solving ordinary differential equations (ODEs).
  • shape.c: Computes geometric properties for closed conduits with user-defined shapes.
  • street.c: Reads the geometric properties of street cross-sections.
  • table.c: Provides functions for accessing lookup tables (e.g., curves, time series).
  • toposort.c: Implements topological sorting for links in a drainage network to detect closed loops.
  • transect.c: Creates geometric tables for irregular-shaped cross-section transects.
  • xsect.c: Computes geometric properties for conduit cross-sections.

Compilation and Execution

The SWMM 5 engine is compiled into a shared object or DLL that can be used by external applications. A main.c file is provided to create an executable version of SWMM that performs the simulation based on input files, executes the necessary calculations, and outputs the results.

Conclusion

The SWMM 5 engine source code is modular, with each module performing specific tasks related to hydrologic and hydraulic modeling, flow routing, water quality simulation, and more. The system is designed to be flexible and extensible, with options for handling complex systems involving rainfall runoff, pollutant transport, and various flow control mechanisms.

SWMM5 roadway.c Summary

 The roadway.c module in the EPA SWMM5 code is specifically designed to compute flow overtopping a roadway using the FHWA HDS-5 methodology. It calculates flow over a ROADWAY_WEIR object typically used in scenarios involving a culvert crossing where the conduit is placed at zero offset and the roadway weir has an offset equal to the height of the roadway.

Here’s a breakdown of the functions in this module:

Constants and Parameters:

  1. Discharge Coefficients:
    • These coefficients are used to compute the flow rate based on the water depth over the roadway weir. There are two sets:
      • Low Head: For (head / road width) <= 0.15
      • High Head: For (head / road width) > 0.15
  2. Submergence Factors:
    • These factors adjust the discharge coefficients based on the submergence (depth of water over the roadway weir). Different factors are provided for paved and gravel road surfaces.

Functions:

  1. roadway_getInflow:
    • Purpose: Computes the flow across a roadway weir based on upstream and downstream water levels, the road width, and the type of road surface.
    • It calculates the discharge (q) using the formula for weir flow: q=cD×length×h1.5q = cD \times \text{length} \times h^{1.5}
    • It adjusts the discharge coefficient based on the water depth over the road (hWr) and the road surface type (paved or gravel). It also calculates the derivative of flow (dqdh) for further computations.
  2. getCd:
    • Purpose: Returns the appropriate discharge coefficient (cD) based on the water depth (hWr), the difference in water elevation between the upstream and downstream sides of the road, the road width, and the road surface type (paved or gravel).
    • The function checks if the head-to-road width ratio (hWr / roadWidth) is low or high, and selects the appropriate coefficient tables accordingly.
  3. getY:
    • Purpose: Interpolates the value of a coefficient (cD or kT) based on the provided x value and a given lookup table (table). The function searches through the table for the appropriate value using linear interpolation between two points.

Key Concepts:

  • Discharge Coefficients: These are critical in determining the flow rate over a roadway. They depend on the height of water (head) over the roadway and the road width.
  • Submergence Factor: A factor that adjusts the discharge coefficient based on how submerged the roadway is.
  • Flow Calculation: The flow is calculated based on the relationship between the head over the roadway and the road width. If the head-to-width ratio is small (low head), a different formula is used compared to when the ratio is large (high head).

Summary:

This module calculates the flow overtopping a roadway during rainfall or other events using the FHWA HDS-5 methodology, and integrates those calculations into the SWMM 5 model to analyze the hydrological behavior of roadways within the drainage network. The calculation depends on the water depth, road width, and road surface type, and includes adjustments for submergence and flow conditions.

SWMM5 routing.c Summary

The routing.c module in the EPA SWMM5 code handles the core process of routing runoff and external inflows through the drainage system network of nodes and links. This module integrates various routing functions and control mechanisms for simulating the movement and transformation of water (and pollutants) through the system.

Key Functions in the routing.c Module:

  1. routing_open:

    • Initializes the routing system by opening necessary files, initializing the flow and quality routing systems, and sorting the drainage network links. It also sets up control rule evaluations and initializes the routing events.
  2. routing_getRoutingStep:

    • Calculates and returns the time step to be used for flow routing. This function considers whether events are active, routing models, and the control rule evaluation times.
  3. routing_execute:

    • The main function that executes the routing process during each time step. It manages flow routing, control actions, and updates mass balance totals for inflows and outflows. It also handles water quality routing if applicable.
  4. evaluateControlRules:

    • This function checks if any control rules (such as pump or regulator control) are triggered during the current time step. It evaluates the control rules based on the current time and adjusts settings for links if necessary.
  5. addSystemInflows:

    • Adds the various inflows (including external, dry weather, wet weather, groundwater, RDII, LID drainage, etc.) to the system, updating the lateral flows at nodes.
  6. removeSystemOutflows:

    • Removes outflows from the system, including those from storage nodes, conduits, and any other outgoing flows from the system.
  7. addWetWeatherInflows, addGroundwaterInflows, addRdiiInflows, etc.:

    • Functions responsible for adding specific types of inflows to the system, including wet weather runoff, groundwater contributions, RDII flows, and more. These functions update the inflows at the nodes based on the current time step.
  8. routeFlow:

    • This function performs the actual flow routing through the drainage system. It computes the flow through each link and updates the flow conditions for nodes accordingly.
  9. sortEvents:

    • Sorts the events in chronological order, ensuring that the simulation respects the sequence of user-defined events. This is crucial for simulations that involve dynamic events or control rules that depend on timing.

Core Concepts and Workflow:

  • Flow Routing: The process of computing the flow of water through the drainage system based on the hydraulic properties of links (pipes, conduits, etc.) and the water levels at the nodes (junctions, outfalls, etc.). This process uses either a kinematic wave (KW) model or a dynamic wave (DW) model.

  • Control Rules: SWMM includes the ability to model control structures (like pumps or regulators) which can change the flow in the system based on predefined rules. The evaluateControlRules function manages these controls during the simulation.

  • Water Quality Routing: The module also supports the transport of pollutants along with the flow, updating the quality at each node and link as the water moves through the system. This is handled by the qualrout_execute function.

  • Event Handling: The simulation may involve different events (e.g., control actions, or specific inflow changes) that are triggered at specific times. The event handling system, including the sortEvents function, ensures that these events are processed in the correct order.

Summary:

The routing.c module in SWMM5 is a central component for simulating the movement of water and pollutants through the drainage system. It performs complex hydraulic and hydrologic calculations, including routing flow, evaluating control actions, and updating water quality conditions across nodes and links in the system. The module integrates various data sources like inflows (wet, dry, groundwater), external data, and control rules to simulate realistic behavior of stormwater and wastewater systems.

InfoSWMM: A 2030 AI-Assisted Study Guide

  InfoSWMM: A 2030 AI-Assisted Study Guide delete   InfoSWMM: A 2030 AI-Assisted Study Guide A comprehensive study guide for someone in 2030...