Sunday, December 29, 2024

SWMM5 runoff.c Summary

 The runoff.c module in the EPA SWMM5 source code handles the runoff analysis by calculating the runoff from rainfall, simulating snowmelt, and handling water quality aspects like pollutant buildup, washoff, and wet weather inflows. This module is crucial for managing the hydrological processes and surface runoff in the SWMM5 simulation.

Key Functions in the runoff.c Module:

  1. runoff_open:

    • Initializes the runoff analysis system, including the ODE solver and memory for pollutant runoff loads. It also checks for the appropriate runoff interface file mode (use or save file) and initializes it.
  2. runoff_close:

    • Frees memory and closes any interface files used to store runoff results. It also writes the total number of time steps to the runoff file.
  3. runoff_execute:

    • Main function for executing the runoff analysis during the simulation. It calculates runoff, pollutant loads, snowmelt, and processes the results by updating the subcatchment states.
  4. runoff_getTimeStep:

    • Determines the appropriate time step for the runoff analysis based on the current simulation date, rainfall, and other conditions like evaporation.
  5. runoff_initFile:

    • Initializes the runoff interface file for saving results. This includes writing the necessary headers like the number of subcatchments and pollutants.
  6. runoff_readFromFile:

    • Reads runoff results from an interface file. This is useful when resuming a simulation that uses previously saved runoff data.
  7. runoff_saveToFile:

    • Saves the current runoff results to an interface file, including runoff flow rates and pollutant loads.
  8. runoff_getOutfallRunon:

    • Determines the runoff that is routed from outfall nodes to subcatchments as runon. This simulates the transfer of water from outfalls into receiving subcatchments.
  9. runoff_getRunoff:

    • Computes the total runoff (in cubic feet per second) generated by each subcatchment during the time step.
  10. runoff_getOutfallRunon:

    • Handles the routing of runoff from outfall nodes to corresponding subcatchments as runon, accounting for the flow and pollutant load transfer.
  11. runoff_saveToFile:

    • Saves runoff results (both flow and pollutant loads) to the runoff interface file.
  12. runoff_readFromFile:

    • Reads runoff results from an interface file for the current time step.

Key Concepts in the Module:

  • Runoff Time Step: The module calculates runoff in discrete time steps, which are determined based on the current simulation conditions (e.g., whether it's raining or dry).

  • Evaporation, Infiltration, and Snowmelt: The module also accounts for water lost to evaporation and infiltration, as well as snowmelt runoff, if applicable.

  • Pollutant Buildup and Washoff: The module computes the buildup of pollutants on surfaces and how much of it is washed off during runoff events, taking into account the effects of street sweeping and land use types.

  • LID (Low Impact Development): This module integrates LID features, such as permeable pavements or bioretention, in subcatchments to handle runoff more sustainably.

  • Interface File: The module reads and writes runoff results to an interface file that stores runoff volumes, pollutant loads, and other related data.

Workflow:

  1. Initialization: The module first initializes the runoff system by allocating memory, checking file modes, and setting up necessary components like the ODE solver.

  2. Runoff Calculation: During each time step, the module calculates runoff based on the precipitation, snowmelt, evaporation, infiltration, and pollutant washoff. The results are updated in the subcatchments.

  3. Reading and Writing Data: The module reads data from previous runoff simulations if available, and writes the results of the current simulation to the interface file.

  4. Outfall Runon: The module handles runoff from outfall nodes, routing it to receiving subcatchments and adding it to their respective runon.

  5. Final Reporting: After the simulation, the module outputs the runoff data, including pollutant loads and runoff volumes, to the designated file.

Summary:

The runoff.c module is a core component of the SWMM5 engine. It performs essential hydrological computations related to surface runoff, snowmelt, and water quality in urban drainage systems. It integrates various factors, including rainfall, snowmelt, evaporation, and infiltration, to simulate runoff accurately. The module also accounts for Low Impact Development (LID) practices and tracks pollutants as they are washed off surfaces. It supports both reading from and writing to interface files for saving and resuming simulations.

SWMM5 treatmnt.c Summary

 The treatmnt.c file in SWMM5 deals with the treatment of pollutants in nodes and links within the model. It contains functions to define, evaluate, and apply pollutant treatment functions based on the node inflows, concentrations, and other system properties.

Key Functions and Features of treatmnt.c:

1. treatmnt_open():

  • This function allocates memory for pollutant removals by treatment at each node. It initializes the R (removal) and Cin (inflow concentration) arrays to store pollutant removals and inflow concentrations for each pollutant.

2. treatmnt_close():

  • This function frees the memory allocated for the pollutant removal and inflow concentration arrays.

3. treatmnt_readExpression():

  • This function reads a treatment expression from the input file. The expression defines how pollutants are treated in the system (e.g., removal percentage or effluent concentration).
  • It creates a treatment object for the node and assigns the treatment expression to the corresponding pollutant.

4. treatmnt_delete():

  • This function deletes the treatment objects for each pollutant at a node. It frees the memory for the treatment equations.

5. treatmnt_setInflow():

  • This function calculates the inflow concentrations at a node based on the mass flow rates of pollutants. It sets the inflow concentrations (Cin) based on the inflow rate (qIn) and the pollutant mass flow rates.

6. treatmnt_treat():

  • This function updates the pollutant concentrations at a node after treatment. It applies the removal or effluent concentration treatment equation to each pollutant based on the treatment type.
  • The treatment is based on a removal percentage or concentration and may involve first-order decay if no treatment function is provided.

7. createTreatment():

  • This function creates a treatment object for each pollutant at a node if it does not already exist. It allocates memory for the treatment objects.

8. getVariableIndex():

  • This function finds the index of a process variable or pollutant. It checks if the string corresponds to a process variable or a pollutant concentration and returns the appropriate index.

9. getVariableValue():

  • This function returns the value of a process variable or pollutant concentration. It retrieves the value of the process variable (like flow or depth) or the pollutant concentration at the node being evaluated.

10. getRemoval():

  • This function computes the removal of a specific pollutant based on the treatment equation. It applies the removal function to the inflow concentration or to the current concentration in the node, depending on the treatment type.

Summary of Key Concepts:

  • Pollutant Treatment: The file handles the treatment of pollutants at each node by applying treatment equations that either remove a portion of the pollutant or set an effluent concentration.
  • Treatment Types: There are two main treatment types:
    • Removal: The pollutant concentration is reduced by a specified percentage.
    • Effluent Concentration: The pollutant concentration is set to a specified value, and the removal is calculated based on the original concentration.
  • Mass Balance: The treatment calculations ensure that the mass of pollutants is conserved in the system. The removal of pollutants is tracked in the mass balance and is based on inflow rates and concentrations.
  • Cyclic Treatment: The system checks for cyclic dependencies between pollutants. If a treatment function depends on another pollutant's concentration, the system avoids infinite recursion.

Overall, the treatmnt.c file is crucial for modeling how pollutants are treated in the SWMM5 system, including how treatments are applied to the inflow, the reaction processes within nodes, and the tracking of pollutant mass through the system.

SWMM5 qualrout.c Summary

 The qualrout.c file in SWMM5 handles the water quality routing calculations within the model. It contains functions that update the concentration of pollutants in the water as it moves through the drainage system. The routing is performed for nodes, links, and storage units, and it accounts for various processes like evaporation, seepage, and pollutant decay.

Key Functions and Features of qualrout.c:

1. qualrout_init():

  • This function initializes the water quality concentrations in all nodes and links. Initially, each pollutant concentration is set to zero, except for wet nodes and links where the initial concentration is assigned based on the predefined concentration values in the model (e.g., Pollut[p].initConcen).

2. qualrout_execute():

  • This is the main function that routes water quality through the drainage system during each time step. It works by first calculating the mass flow of pollutants through links, then finding the quality of water at each node and link.
  • It calls functions like findLinkMassFlow() to calculate how pollutants move through links, and findNodeQual() and findLinkQual() to update the concentrations in nodes and links.

3. getMixedQual():

  • This function calculates the concentration of a pollutant in a completely mixed reactor (such as a node or link) by considering the inflow concentration and the existing concentration within the node or link. The new concentration is computed using mass balance, and it ensures that the concentration does not exceed the maximum of the two inflows (original or new).

4. findLinkMassFlow():

  • This function calculates the mass flow of pollutants through a link and updates the total mass of pollutants in the downstream node. It accounts for the flow through the link, considering both the current and past concentrations of pollutants.

5. findNodeQual():

  • For nodes with no storage volume, this function simply calculates the new quality concentration based on the mass inflow and outflow. If there is no inflow, the concentration is maintained from the previous time step, and if the node is dry, the concentration is set to zero.

6. findLinkQual():

  • This function updates the concentration of pollutants in links based on the upstream node's quality and the link's flow conditions. For conduits, it computes pollutant concentrations by considering evaporation, seepage, and reaction losses, and applies first-order decay if needed. It adjusts the concentrations based on the inflow, outflow, and volume of the link.

7. findSFLinkQual():

  • This is a special function used for steady flow routing. It adjusts the quality of pollutants in a link by applying pollutant decay and considering the effects of evaporation and seepage.

8. findStorageQual():

  • For nodes with storage volume (e.g., storage nodes), this function computes the pollutant concentrations by considering evaporation, seepage losses, and inflows. It applies first-order decay to the pollutant concentrations, mixes the inflows with the existing concentrations, and ensures that the concentration is set to zero if the volume is too small or if there is no inflow.

9. updateHRT():

  • This function calculates the hydraulic residence time (HRT), which is the average time that water remains in a storage node. It is updated based on the volume and inflow rate at the node. The HRT is important for pollutant treatment calculations and for determining how long pollutants stay in a storage area.

10. getReactedQual():

  • This function computes the effect of first-order decay on the pollutant concentration over a given time step. The concentration is reduced according to the decay rate (kDecay), and the loss of pollutant mass due to the reaction is added to the mass balance.

Summary of Key Concepts:

  • Pollutant Decay: Pollutants are subject to first-order decay, where their concentration decreases over time at a rate determined by kDecay.
  • Mass Flow: Pollutants move with the flow of water through links and nodes, and their mass is tracked in the system to ensure that the water quality is accurately routed.
  • Evaporation and Seepage: Water quality is adjusted for evaporation (which increases concentration) and seepage (which removes pollutants).
  • Mixed Qualities: At each node or link, the quality of water is determined by mixing the inflows and applying losses due to decay, evaporation, and seepage.
  • Hydraulic Residence Time (HRT): The amount of time that water spends in a node or link, which affects how much pollutant is removed due to decay.

Overall, this file is crucial for maintaining accurate water quality routing in the SWMM5 model, ensuring that pollutants are properly tracked and accounted for as they move through the stormwater system.

SWMM5 project.c Summary

 The project.c file is a key component of the SWMM5 (Storm Water Management Model) project management system. It handles the initialization, validation, and memory management of the project's data objects, such as subcatchments, nodes, links, pollutants, and more. The file provides functionality for opening and closing a project, reading input data, allocating memory for project objects, and validating data. It also manages hash tables for efficiently identifying objects by their ID names and handles the cleanup of memory when the project is closed.

Key Features of the Code:

1. Project Initialization:

  • project_open(): Initializes a new SWMM project by setting default values, opening the required files, and initializing data structures.
  • project_readInput(): Reads the input data for the project from the input file, including the number of objects and their properties.
  • project_validate(): Validates the input data to ensure correctness, including checking for valid curves, time series, subcatchments, nodes, links, and other project components.
  • project_init(): Initializes the internal state of all objects, including subcatchments, nodes, links, and more.

2. Memory Management:

  • createObjects(): Allocates memory for all project objects (e.g., subcatchments, nodes, links) based on the number of objects defined in the input file.
  • deleteObjects(): Frees the memory allocated for all project objects, including land use factors, groundwater, and other components.
  • createHashTables(): Allocates memory for hash tables used to store object IDs for quick lookup.
  • deleteHashTables(): Frees the memory used for hash tables and cleans up memory pools.

3. Object Management:

  • project_addObject(): Adds an object to a hash table, ensuring that no duplicate object IDs are added.
  • project_findObject(): Finds an object by its ID using the hash table for efficient lookup.
  • project_findID(): Finds the address where an object's ID string is stored in memory.
  • project_createMatrix(): Allocates memory for a matrix of doubles, used for storing various project-related data.
  • project_freeMatrix(): Frees the memory allocated for a matrix of doubles.

4. Data Validation and Defaults:

  • setDefaults(): Sets default values for various project settings, including units, flow routing methods, time steps, and more.
  • project_validate(): Ensures that the data in the project file is valid, including checking curves, time series, and other components.
  • project_readOption(): Reads specific project options from input data, such as simulation start and end dates, time steps, and flow units.

5. File Management:

  • openFiles(): Opens the input and output files for reading and writing the project's data.
  • deleteFiles(): Frees the memory used by the file structures once the project is closed.

6. Infiltration, LID, and Water Quality:

  • infil_create(): Allocates memory for infiltration-related data.
  • lid_create(): Allocates memory for Low Impact Development (LID) objects.
  • lid_delete(): Frees memory used by LID objects.
  • infil_delete(): Frees memory used by infiltration-related data.
  • gwater_create(): Allocates memory for groundwater-related data.
  • gwater_delete(): Frees memory used by groundwater-related data.

Workflow:

  1. Opening a Project:

    • The project is opened by reading the project files (input, report, and output) and initializing the required data structures, including hash tables and object arrays.
  2. Reading Input Data:

    • The input file is parsed to extract project data, such as subcatchments, nodes, links, and other elements. This data is validated to ensure it conforms to the expected structure.
  3. Object Initialization:

    • Objects such as subcatchments, nodes, and links are initialized based on the parsed input data. Memory is allocated for each object, and their properties are set to default values where necessary.
  4. Validating Data:

    • The input data is validated to check for consistency, including ensuring that all objects are properly defined, time steps are valid, and parameters are within acceptable ranges.
  5. Running the Simulation:

    • Once the project is initialized and validated, the simulation can run, utilizing the data stored in the project objects. Various computational methods are applied based on the project configuration (e.g., flow routing, water quality, infiltration, etc.).
  6. Closing the Project:

    • When the simulation is complete, the project is closed, and memory used by project objects is freed.

Summary:

The project.c file is essential for managing the project's data in SWMM5. It provides functionality for reading input data, validating it, initializing objects, and managing memory. The file also handles the opening and closing of the project's files and the creation and deletion of various project-related objects, such as subcatchments, nodes, and links. By managing these operations, the file ensures that the project runs smoothly and that the necessary data is available for simulation and output generation.

SWMM5 output.c Summary

The output.c file in SWMM5 (Storm Water Management Model) is responsible for managing binary output file operations related to system simulation results, including subcatchments, nodes, links, and pollutants. It handles the writing and reading of simulation data to and from a binary file, as well as the storage of various results (e.g., flow, depth, volume, and pollutant concentrations). The file supports large datasets, including the ability to handle the storage of results over multiple time periods.

Key Features of the Code:

1. File Operations:

  • File Management:
    • output_openOutFile(): Opens the binary output file for saving simulation results.
    • output_saveID(): Saves the ID of an object (subcatchment, node, link, or pollutant) to the binary output file.
    • output_saveResults(): Writes computed results for the current report time to the binary file.
    • output_end(): Writes closing records to the binary file, including positions of saved data and the final results.
    • output_checkFileSize(): (Deprecated) Checks if the file size is too large for 32-bit systems to handle.
    • output_saveAvgResults(): Saves the averaged results (e.g., average flow) for nodes and links at the end of a reporting period.

2. Data Structures and Variables:

  • TAvgResults: Structure used to store averaged results for nodes and links.
  • SysResults[MAX_SYS_RESULTS]: Stores system-wide variables such as total rainfall, evaporation, runoff, and system storage.
  • SubcatchResults, NodeResults, LinkResults: Arrays to store results for subcatchments, nodes, and links, respectively.
  • AvgNodeResults, AvgLinkResults: Arrays to store average results for nodes and links over the reporting period.

3. Averaging Results:

  • output_openAvgResults(): Allocates memory for storing average results for nodes and links.
  • output_closeAvgResults(): Frees memory used for storing average results.
  • output_initAvgResults(): Initializes average results to zero for nodes and links.
  • output_updateAvgResults(): Updates the average results for nodes and links after each simulation step.
  • output_saveAvgResults(): Saves the average results to the binary file.

4. Subcatchment, Node, and Link Results:

  • Subcatchment Results: Includes variables like rainfall, snow depth, evaporation, infiltration, runoff, and groundwater flow.
  • Node Results: Includes variables like depth, head, volume, lateral inflow, and overflow.
  • Link Results: Includes variables like flow, depth, velocity, volume, capacity, and pollutant concentrations.

5. System-Wide Results:

  • SysResults[SYS_*]: Stores various system-wide variables such as total rainfall, evaporation, infiltration, runoff, and storage.
  • output_saveSubcatchResults(): Saves computed subcatchment results to the binary output file.
  • output_saveNodeResults(): Saves computed node results to the binary output file.
  • output_saveLinkResults(): Saves computed link results to the binary output file.

6. Time Management:

  • output_readDateTime(): Reads the date and time for a specific reporting period from the binary output file.
  • output_readSubcatchResults(): Reads subcatchment results for a specific time period.
  • output_readNodeResults(): Reads node results for a specific time period.
  • output_readLinkResults(): Reads link results for a specific time period.

7. Large File Support:

  • The code includes provisions for handling large files by using 64-bit file offsets (F_OFF) and conditional compilation for Windows and non-Windows platforms to handle large files.

Workflow:

  1. File Initialization:

    • The output file is opened, and basic project data is written to the binary file, including subcatchment, node, link, and pollutant data.
    • The file is structured to store the ID names of objects, followed by their results for each reporting period.
  2. Saving Results:

    • The results for each subcatchment, node, and link are saved to the binary file. This includes both instantaneous results (e.g., flow, depth, volume) and averaged results (e.g., average flow over the reporting period).
  3. Averaging Results:

    • At the end of each reporting period, the average results for nodes and links are calculated and saved to the binary file. This allows for reporting of the average conditions over a given period.
  4. System-Wide Results:

    • System-wide results, such as total rainfall, total runoff, and total storage, are computed and stored in the SysResults array. These results are saved to the binary file after each reporting period.
  5. Memory Management:

    • Memory for storing results is dynamically allocated and freed as needed. This includes memory for average results and individual object results.

Summary:

The output.c file is responsible for managing the output of SWMM5 simulations, specifically for saving and reading results in a binary format. It handles the calculation and storage of results for subcatchments, nodes, links, and pollutants over time. The file includes features for averaging results over reporting periods, supporting large files, and efficiently managing memory for storing simulation data. The integration of these features allows SWMM5 to generate detailed, time-step based output for various hydrological and water quality parameters.

SWMM5 odesolve.c and odesolve.h Summary

 The odesolve.c and odesolve.h files in SWMM5 (Storm Water Management Model) implement an ODE (Ordinary Differential Equation) solver using the Runge-Kutta-Cash-Karp method. This method is a fifth-order integration technique with adaptive step size control. The solver is designed to compute the values of system states (e.g., flow, pollutant concentrations) over time in dynamic simulations of hydrological processes.

Key Features:

1. Runge-Kutta-Cash-Karp Method:

  • RKCK Method is used for solving systems of ODEs. It is a high-accuracy method with adaptive step size control, adjusting the step size to maintain the desired precision.
  • It uses intermediate steps to calculate the final result at each time step, improving accuracy.
  • This method is used in many applications that require solving time-dependent systems with complex interactions, such as hydrological modeling in SWMM5.

2. Adaptive Step Size Control:

  • The step size is adjusted dynamically based on the estimated error at each step. If the error exceeds a threshold, the step size is reduced, and if the error is small, the step size is increased.
  • This feature ensures efficient computation and allows for high accuracy without unnecessarily small steps.

3. Main Functions in odesolve.c:

  • odesolve_open(int n): Initializes the system, allocating memory for the arrays that hold state variables, derivatives, error estimates, and scaling factors for the ODE solver.
  • odesolve_close(): Frees the memory used by the ODE solver after the integration is complete.
  • odesolve_integrate(): The primary function that performs the integration of the system of ODEs from an initial state (ystart[]) to a final time point (x2). It uses the rkqs() function for adaptive step size control.
  • rkqs(): Performs the Runge-Kutta integration step and adjusts the step size to meet the desired accuracy. It also monitors the error in the integration process and reduces the step size if necessary.
  • rkck(): Implements the Runge-Kutta-Cash-Karp method for the integration. It computes the new state values at each time step, using intermediate values and coefficients.

4. Auxiliary Functions:

  • rkqs(): This function handles the integration step. It computes the new state values using the RKCK method and adjusts the step size based on the error. If the error is too large, the function reduces the step size and tries again.
  • rkck(): Performs the integration step using intermediate values calculated from the system's state variables and their derivatives. This function uses the Runge-Kutta coefficients to compute the next state values accurately.
  • derivs(): A user-supplied function that computes the derivatives of the system's state variables (the right-hand side of the ODE system).

5. Error Control and Step Size Adjustment:

  • The solver uses an error control mechanism to monitor the accuracy of the integration at each step. The error is estimated based on the difference between two different approximations, and if the error exceeds the allowed tolerance (eps), the step size is reduced.
  • The step size is adapted based on the error and the local truncation error to balance between accuracy and efficiency.

6. Function Definitions:

  • odesolve_open(): Allocates memory for state variables, scaling factors, error estimates, and intermediate results used in the integration process.
  • odesolve_close(): Frees the memory allocated by the solver.
  • odesolve_integrate(): Main function to integrate the system of ODEs, using the RKCK method with adaptive step size control.
  • rkqs(): Performs one step of integration and adjusts the step size based on the error.
  • rkck(): Performs the Runge-Kutta-Cash-Karp step, calculating intermediate values and updating state variables.

Integration Flow:

  1. Initialization:

    • The solver is initialized by allocating memory for the necessary variables (state variables, derivatives, error estimates, etc.).
    • The initial state (ystart[]) is set based on the starting conditions of the system.
  2. Integration Process:

    • The odesolve_integrate() function is called to integrate the system from the initial time (x1) to the final time (x2).
    • rkqs() and rkck() perform the integration, adjusting the step size as needed and monitoring the error to maintain accuracy.
  3. Error Monitoring:

    • The errmax value is computed at each step to monitor the local truncation error. If the error exceeds the specified tolerance, the step size is reduced, and the integration is repeated with the new step size.
  4. Completion:

    • Once the final time point is reached, the values of the state variables are stored in ystart[], and the memory used by the solver is freed.

Summary:

The odesolve.c file provides a robust and efficient method for solving systems of ODEs using the Runge-Kutta-Cash-Karp method with adaptive step size control. This is essential for dynamic simulations in SWMM5, where the state variables evolve over time based on complex hydrological processes. The adaptive step size ensures efficient computation while maintaining the required accuracy for the simulation, making it a critical component in modeling the behavior of stormwater systems over time.

Saturday, December 28, 2024

SWMM5 objects.h Summary

 The objects.h file in SWMM5 (Storm Water Management Model) contains definitions for data structures that represent various objects in the model, including nodes, links, subcatchments, pollutants, inflows, and other system components. These structures allow the model to manage and simulate different aspects of stormwater management, such as rainfall, runoff, groundwater, treatment processes, and flow routing.

Key Data Structures:

1. File Information (TFile):

  • Represents a file used by the system, including its name, mode (open, closed, scratch), and the current state (opened or closed).

2. Curve and Time Series (TTable, TTableEntry):

  • TTableEntry: Represents a data point in a curve or time series.
  • TTable: Represents a curve or time series, including its ID, type, and a linked list of entries (data points).

3. Rain Gage (TGage):

  • Represents a rain gauge, including its data source (time series or file), rainfall type, units, and related statistics (e.g., snow factor, rainfall accumulation).

4. Temperature (TTemp):

  • Represents temperature-related data, including data source, time series, temperature, vapor pressure, and psychrometric constants.

5. Wind Speed (TWind):

  • Represents monthly average wind speeds, either from a time series or monthly data.

6. Snow (TSnow):

  • Represents snowmelt data, including the snow temperature threshold, snow catch deficiency correction, and snowmelt coefficients.

7. Evaporation (TEvap):

  • Represents evaporation data, including evaporation rate, pan coefficients, and recovery patterns.

8. Adjustments (TAdjust):

  • Represents monthly adjustments to temperature, evaporation, rainfall, and hydrological conductivity.

9. Event (TEvent):

  • Represents an event's start and end date.

10. Aquifer (TAquifer):

  • Represents groundwater aquifer data, including properties like porosity, conductivity, evaporation fractions, and initial conditions for the water table and moisture content.

11. Groundwater Statistics (TGWaterStats):

  • Represents statistical data for groundwater, including infiltration, evaporation, lateral flow, and storage statistics.

12. Groundwater (TGroundwater):

  • Represents groundwater flow parameters, including surface water outflow coefficients, groundwater flow parameters, and initial conditions for moisture content and water table height.

13. Snowmelt (TSnowmelt):

  • Represents parameters for the snowmelt process, including snowmelt coefficients, snow depth, and surface types (impervious, pervious).

14. Snowpack (TSnowpack):

  • Represents the state of the snowpack, including snow depth, free water content, and snowmelt indices.

15. Subcatchment (TSubcatch):

  • Represents a subcatchment in the model, including properties like area, impervious fraction, slope, rainfall, evaporation, infiltration, and water quality (pollutant concentrations). The subcatchment also contains information about LID areas and groundwater flow equations.

16. Time Pattern (TPattern):

  • Represents time series patterns used for various parameters, including rainfall, evaporation, or inflow data.

17. External Inflow (TExtInflow):

  • Represents an external inflow (e.g., pollutant or flow) into the system, including data on concentration or mass and the time series or pattern associated with the inflow.

18. Dry Weather Flow Inflow (TDwfInflow):

  • Represents dry weather flow data, including average values and time patterns.

19. Unit Hydrograph Inflow (TRdiiInflow):

  • Represents an inflow based on a unit hydrograph, including the area of the sewershed and the unit hydrograph index.

20. Unit Hydrograph Group (TUnitHyd):

  • Represents a group of unit hydrographs, including data like initial abstraction, time base, and peak time for each month.

21. Treatment (TTreatment):

  • Represents a treatment process applied to a node or link, including a mathematical expression for removal or concentration.

22. Node (TNode):

  • Represents a node in the conveyance system, which can be a junction, outfall, storage, or divider. This structure includes properties such as elevation, depth, volume, inflows, outflows, and water quality states.

23. Outfall (TOutfall):

  • Represents an outfall node, including properties like type (fixed, tidal, timeseries, etc.), stage, and routing to subcatchments.

24. Storage (TStorage):

  • Represents a storage unit (e.g., a detention pond or reservoir), including properties like evaporation, surface area, shape, and exfiltration.

25. Flow Divider (TDivider):

  • Represents a divider node, which splits flow between two or more links based on a set of conditions (e.g., weir flow, cutoff, overflow, or tabular relationships).

26. Link (TLink):

  • Represents a link in the conveyance system, such as a pipe, culvert, or conduit. It includes properties like flow, depth, cross-sectional area, and flow direction.

27. Conduit (TConduit):

  • Represents a conduit link in the system, including properties like length, roughness, capacity, and flow rates.

28. Pump (TPump):

  • Represents a pump in the system, including properties like type, curve, and settings for controlling flow.

29. Orifice (TOrifice):

  • Represents an orifice in the system, including properties like discharge coefficients and control settings.

30. Weir (TWeir):

  • Represents a weir in the system, including properties like discharge coefficients, end contractions, and flow control settings.

31. Outlet (TOutlet):

  • Represents an outlet device, including properties like discharge coefficients and rating curves.

32. Pollutant (TPollut):

  • Represents a pollutant in the system, including properties like units, mass conversion factors, and concentration levels for various flow types (e.g., dry weather, runoff, groundwater).

33. Buildup (TBuildup):

  • Represents a function for pollutant buildup on a surface, including a normalizer and function type for calculating buildup rates.

34. Washoff (TWashoff):

  • Represents a function for pollutant washoff from a surface, including coefficients and exponents for the washoff process.

35. Landuse (TLanduse):

  • Represents a land use type, including properties like street sweeping intervals, buildup functions for pollutants, and washoff functions.

36. Reporting Flags (TRptFlags):

  • Represents the flags used to control which results are reported (e.g., node results, flow statistics, continuity errors, etc.).

37. Runoff Totals (TRunoffTotals):

  • Represents the cumulative runoff totals, including values for rainfall, runoff, evaporation, infiltration, and storage.

38. Loading Totals (TLoadingTotals):

  • Represents the cumulative loading totals for pollutants, including buildup, deposition, sweeping, BMP removal, runoff, and final load.

39. Groundwater Totals (TGwaterTotals):

  • Represents the cumulative groundwater totals, including values for infiltration, evaporation, lateral flow, and deep percolation.

40. Routing Totals (TRoutingTotals):

  • Represents the cumulative routing totals for flow and water quality, including inflows, outflows, losses, and reactions.

41. Time Step Statistics (TTimeStepStats):

  • Represents the statistics for the time step in the simulation, including the minimum, maximum, and average time steps, as well as the number of trials.

42. Rainfall Statistics (TRainStats):

  • Represents the statistics for rainfall data, including the number of periods with rainfall, missing data, and malfunctioning gauges.

43. Subcatchment Statistics (TSubcatchStats):

  • Represents the statistics for subcatchments, including values for precipitation, runoff, infiltration, and impervious/pervious runoff.

44. Node Statistics (TNodeStats):

  • Represents the statistics for nodes, including values for depth, flooding, surcharging, inflow, overflow, and water quality.

45. Storage Statistics (TStorageStats):

  • Represents the statistics for storage units, including values for volume, evaporation, exfiltration, and maximum flow.

46. Outfall Statistics (TOutfallStats):

  • Represents the statistics for outfall nodes, including average flow, maximum flow, and pollutant load totals.

47. Pump Statistics (TPumpStats):

  • Represents the statistics for pumps, including flow, energy consumption, and start-ups.

48. Link Statistics (TLinkStats):

  • Represents the statistics for links, including flow, velocity, depth, flooding, and time spent in different flow conditions.

49. Maximum Value Statistics (TMaxStats):

  • Represents the maximum values for nodes or links, including the maximum value and the corresponding object index.

50. Report Field Info (TRptField):

  • Represents the configuration for reporting variables, including the name, units, and precision of the reported value.

Summary:

The objects.h file defines a wide range of data structures used to represent the various objects in the SWMM5 system, such as nodes, links, subcatchments, pollutants, and other system components. These structures allow for efficient simulation of stormwater management systems, handling aspects like runoff, groundwater flow, pollutant transport, and water quality. The file also defines cumulative statistics, reporting configurations, and error handling mechanisms to ensure accurate results during the simulation.

SWMM5 node.c Summary

 The node.c file in SWMM5 (Storm Water Management Model) handles the functions related to the nodes in the conveyance system. Nodes represent junctions, outfalls, storage units, and dividers in the drainage system. This file defines how these nodes behave, how their properties are initialized, how water flows through them, and how they interact with other parts of the model. The file also manages the mass balance of water, including inflows, outflows, evaporation, and infiltration for each node.

Key Features of the Code:

1. Node Types and Properties:

  • Junction: A node where multiple links (pipes, conduits, etc.) meet.
  • Outfall: A discharge point where water flows out of the system, either at a fixed stage, tidal, time series, or free outfall.
  • Storage: A node that stores water, such as a detention pond or a reservoir.
  • Divider: A node that splits flow into two or more links based on specific conditions (like weir flow or cutoff flow).

2. Functions for Node Handling:

  • node_readParams(): Reads the parameters for a specific node (junction, outfall, storage, or divider) from an input line and assigns values to the corresponding node properties.
  • node_setParams(): Sets the properties of a node, including its type, invert elevation, depth, and volume.
  • node_validate(): Validates the properties of a node, ensuring that depths, volumes, and other parameters are within acceptable ranges.
  • node_initState(): Initializes the state variables of a node, such as its depth, volume, and water quality levels at the start of the simulation.
  • node_setOldHydState(): Updates the old hydraulic state values of a node at the end of a time step.
  • node_setOldQualState(): Updates the old water quality state values of a node at the end of a time step.
  • node_initFlows(): Initializes the inflows, outflows, and overflow at a node at the start of each time step.

3. Node-Specific Methods:

  • Junction:
    • For junction nodes, the method assigns values for maximum depth, initial depth, surcharge depth, and ponded area.
  • Outfall:
    • Outfall nodes can have different types: FIXED, TIDAL, TIMESERIES, and FREE. The method reads parameters based on the outfall type and handles different flow conditions accordingly.
  • Storage:
    • Storage nodes represent detention areas or reservoirs. These nodes store water up to a certain depth and volume. The depth is calculated based on the volume of stored water, and the method also handles exfiltration losses.
  • Divider:
    • Divider nodes control the distribution of flow between different links. The method handles different types of dividers like CUTOFF, OVERFLOW, WEIR, and TABULAR.

4. Water Flow and Volume Calculations:

  • node_getDepth(): Computes the depth of water in a node based on its volume.
  • node_getVolume(): Computes the volume of water in a node based on its depth.
  • node_getSurfArea(): Computes the surface area of water in a node based on its depth.
  • node_getOutflow(): Computes the flow out of a node, either through a connected link or as discharge at an outfall.
  • node_getMaxOutflow(): Computes the maximum outflow from a node, considering storage and overflow.
  • node_getSystemOutflow(): Computes the total outflow from a node, including overflow and routing to other parts of the system.
  • node_getLosses(): Computes the losses from a node, including evaporation and infiltration.

5. Hydraulic and Water Quality State Management:

  • The code keeps track of both hydraulic (water depth and volume) and water quality (pollutant concentrations) states for each node. This is crucial for maintaining the system's mass balance and ensuring the proper routing of water and pollutants through the system.

6. Outfall and Storage Node Handling:

  • Outfall Nodes:
    • Different types of outfalls are handled, each with a different discharge behavior. For example, a TIDAL outfall uses a tidal curve to determine the stage (water level), while a TIMESERIES outfall uses a time series of stage data.
    • The water depth at the outfall node is computed based on the outfall stage, critical depth, and normal flow depth.
  • Storage Nodes:
    • Storage nodes can have various shapes, such as cylindrical, conical, or pyramidal. The depth and volume of water in the storage node are calculated based on the shape and the water level.

7. Error Handling and Warnings:

  • The code includes error checks for invalid node properties, such as negative volumes or depths that exceed the maximum allowable values.
  • Warnings are generated if the node's depth is increased to accommodate a conduit crown or if the volume curve for a storage node produces negative volumes.

Summary:

The node.c file defines the behavior of different types of nodes in the SWMM5 model, including junctions, outfalls, storage nodes, and dividers. It handles the initialization, validation, and update of node properties and computes key hydraulic and water quality parameters such as depth, volume, inflows, outflows, and losses. The file also includes error handling and warnings to ensure the consistency and accuracy of the model's behavior, making it a crucial component of the SWMM5 system for modeling stormwater runoff and drainage systems.

SWMM5 mempool.c Summary

 The mempool.c file implements a simple, fast memory allocation system using memory pools. It defines functions for managing memory blocks, pooling, and efficient allocation and deallocation of memory. This system is designed to minimize the overhead of frequent memory allocations by pre-allocating large memory blocks and managing them internally.

Key Components:

Memory Pool Management:

  • AllocInit(): Initializes a new memory pool by creating a block and setting up a root pointer that tracks the pool's state.
  • AllocSetPool(): Changes the current memory pool. This allows for managing multiple pools in the system.
  • AllocReset(): Resets the current pool by moving the pointer back to the start of the first block. This enables the reuse of the memory without deallocating it.
  • AllocFreePool(): Frees all memory used by the current pool, including all blocks within the pool.
  • Alloc(): Allocates memory from the current pool. It ensures that memory is aligned to a 4-byte boundary and automatically handles moving to a new block when the current one is exhausted.

Helper Structures:

  • alloc_hdr_t: Represents a header for each block of memory in the pool. It keeps track of the block's start, the next free memory location, and the block's end.
  • alloc_root_t: Represents the root of the current memory pool, which includes a pointer to the first block and the current block being used for allocation.

Functions:

  1. AllocHdr():

    • A helper function that allocates a new header and a memory block of size ALLOC_BLOCK_SIZE (defined as 64000 bytes). It initializes the block's memory pointers and returns the header for further use.
  2. AllocInit():

    • Initializes a new memory pool by allocating an alloc_root_t structure and the first block. The pool is set as the current pool, and it returns a pointer to the pool.
  3. Alloc():

    • Allocates a specified amount of memory from the current pool. It checks if the current block has enough free memory. If not, it allocates a new block. It also aligns memory to a 4-byte boundary and manages memory efficiently.
  4. AllocSetPool():

    • Changes the current memory pool by updating the root pointer to a new pool. It returns the previous pool for potential future use.
  5. AllocReset():

    • Resets the current pool by setting the free memory pointer back to the start of the first block. This allows reusing the memory pool without actually freeing the memory.
  6. AllocFreePool():

    • Frees all memory used by the current pool, including the memory blocks and the root structure itself.

Memory Block Allocation:

The pool system allows memory to be allocated in large blocks (64000 bytes in this case). When a block is exhausted, a new block is created, and the pointer is moved to the new block. This reduces the overhead associated with frequent calls to malloc and free.

Allocation Flow:

  • When memory is requested, the system checks the current block for available space. If the block is full, it allocates a new block and continues.
  • The system uses block headers (alloc_hdr_t) to manage each block of memory and track the current free pointer (free), which points to the next available location in the block.
  • The memory is aligned to a 4-byte boundary to ensure that it is suitable for typical machine architectures.

Memory Management Efficiency:

This memory pool system improves performance by reducing the overhead of repeatedly allocating and freeing small chunks of memory. Instead, it pre-allocates large blocks of memory and manages them internally.

Summary:

The mempool.c file is a simple and efficient memory management system designed to handle large memory allocations within the SWMM5 project. It uses a pooling mechanism to reduce allocation overhead, efficiently managing memory by allocating large blocks and dividing them as needed. This system helps improve performance in environments where frequent memory allocations and deallocations occur.

SWMM5 mathexpr.c Summary

 The mathexpr.c file is responsible for evaluating symbolic mathematical expressions within the SWMM5 (Storm Water Management Model). The module parses and computes expressions that consist of numbers, variable names, mathematical functions, and arithmetic operators. The expressions are evaluated using a binary tree structure, and the results are computed through a stack-based evaluation mechanism.

Key Features:

Operand Codes:

  • Operands: The file uses specific operand codes for operations like addition, subtraction, multiplication, division, and exponentiation. It also includes predefined functions such as cos, sin, tan, sqrt, etc.
  • Example Operand Codes:
    • 1 = (
    • 2 = )
    • 3 = +
    • 7 = Number
    • 8 = User-defined variable
    • 10 to 27 = Math functions like cos, sin, sqrt, log10, step, etc.
    • 31 = Exponentiation (^)

Core Data Structures:

  • ExprTree: Represents a node in a binary tree structure for the mathematical expression. Each node holds an operator code (opcode), the variable index (ivar), or a numerical value (fvalue). The tree has left and right pointers for its subtrees.

  • MathExpr: A linked list structure that represents the final postfix expression for evaluation.

Main Components and Functions:

  1. mathexpr_create():

    • This is the main function that takes a mathematical expression in string form (formula) and a function to retrieve variable values (getVar).
    • It uses a recursive function (getTree()) to parse the expression into a tree structure and then converts the tree into a postfix linked list (MathExpr) through traverseTree().
  2. getTree():

    • This function recursively builds an expression tree from the string input. It processes operands, operators, functions, and variables.
    • It handles parenthesis and operator precedence by creating a tree structure where the operators become the internal nodes, and the operands (variables and numbers) become the leaves.
  3. mathexpr_eval():

    • This function evaluates the mathematical expression represented by the linked list (MathExpr).
    • It uses a stack (ExprStack) to evaluate the expression. For each operation (e.g., addition, multiplication), it pops values from the stack, performs the operation, and pushes the result back onto the stack.
  4. getToken():

    • Extracts a token (a variable or number) from the input expression string.
  5. getMathFunc():

    • Identifies mathematical functions like cos, sin, sqrt, etc., from the current token.
  6. getOperand():

    • Identifies basic operands such as operators (+, -, *, /, etc.), parentheses ((, )), and numbers.
  7. Mathematical Functions:

    • The module supports a wide range of mathematical functions like cos, sin, log, sqrt, exp, and many others. These functions are handled using specific operand codes (e.g., cos is handled by opcode 10).
  8. getVariable():

    • Looks up a variable by name and returns its value index (if defined).
  9. newNode():

    • Allocates memory for a new tree node used to build the expression tree.
  10. deleteTree():

    • Frees the memory used by the expression tree after evaluation is complete.

Evaluation Logic:

  • The evaluation logic follows the "postfix" or Reverse Polish Notation (RPN) approach. This allows for the evaluation of expressions without needing parentheses to dictate precedence.
  • The expression is first parsed into a binary tree, then traversed into a linked list in postfix order. Finally, the linked list is evaluated using a stack-based approach where operands are pushed to the stack and operators pop operands from the stack to perform the operations.

Example Workflow:

  1. Expression Input:

    • A mathematical expression like 3 + sin(x) * 2.
  2. Parsing the Expression:

    • The getTree() function builds an expression tree with operands (3, x, 2) and operators (+, *, sin).
  3. Postfix Conversion:

    • The expression tree is then converted into a linked list in postfix notation, e.g., 3 2 x sin * +.
  4. Evaluation:

    • The mathexpr_eval() function evaluates the postfix expression using a stack.
  5. Result:

    • The result is computed by performing the operations in the correct order, yielding the final result.

Mathematical Functions Supported:

  • Trigonometric: cos, sin, tan, cot, asin, acos, atan, acot, sinh, cosh, tanh, coth
  • Other: abs, sgn, sqrt, log, exp, log10, step (for conditional expression), and ^ (exponentiation).

Error Handling:

  • The code includes error checking for invalid operators, mismatched parentheses, and undefined variables. If an error occurs, the system will set the Err flag, preventing further processing and indicating the error.

Summary:

This module provides a powerful way to evaluate complex mathematical expressions in SWMM5. It supports a wide range of mathematical functions and operations, including trigonometric, logarithmic, and arithmetic functions. The expression parsing and evaluation are handled efficiently using a binary tree for parsing and a stack for evaluation, making it suitable for the dynamic nature of SWMM5’s simulation environment.

SWMM5 massbal.c Summary

 The massbal.c file is responsible for handling mass balance calculations in the SWMM5 (Storm Water Management Model) system. It ensures that water, pollutants, and groundwater mass are properly tracked and conserved throughout the system. The file provides functions for initializing, updating, and reporting mass balances for various components, such as runoff, groundwater, flow routing, and water quality (WQ).

Key Features of the Code:

Constants:

  • MAX_RUNOFF_BALANCE_ERR: The maximum allowed error in runoff mass balance (set to 10%).
  • MAX_FLOW_BALANCE_ERR: The maximum allowed error in flow mass balance (set to 10%).

Shared Variables:

  • RunoffTotals: Tracks total values for surface runoff (rainfall, evaporation, infiltration, runoff, etc.).
  • LoadingTotals: Tracks pollutant mass balance totals (washoff, deposition, infiltration, etc.).
  • GwaterTotals: Tracks groundwater mass balance totals (infiltration, evaporation, percolation, etc.).
  • FlowTotals: Tracks total flow mass balance totals (inflows, outflows, flooding, storage, etc.).
  • StepFlowTotals: Stores flow totals for the current time step.
  • StepQualTotals: Stores water quality totals for the current time step.
  • NodeInflow and NodeOutflow: Store the total inflows and outflows for each node.
  • TotalArea: The total drainage area for the system.

Exportable Variables:

  • NodeInflow and NodeOutflow: Store the inflows and outflows for each node in the system.
  • TotalArea: Represents the total drainage area in square feet.

Key Functions:

  1. massbal_open():

    • Initializes the mass balance system by setting up the global totals for water, pollutants, and flow for the system. It allocates memory for arrays that track water quality totals, inflows, and outflows, and initializes continuity errors.
  2. massbal_close():

    • Frees the memory allocated by the mass balance system.
  3. massbal_report():

    • Reports mass balance results for the system. It calculates and reports errors in runoff, groundwater, and flow routing mass balances.
  4. massbal_getBuildup():

    • Computes the total buildup of pollutants in the system by summing up the contributions from various subcatchments.
  5. massbal_updateRunoffTotals():

    • Updates the runoff totals (e.g., rainfall, infiltration, runoff) after each time step.
  6. massbal_updateGwaterTotals():

    • Updates groundwater totals, tracking values like infiltration, evaporation, percolation, and groundwater outflow.
  7. massbal_updateRoutingTotals():

    • Updates routing totals for flow and water quality over the current time step. It tracks the inflows, outflows, and losses for both flow and pollutants.
  8. massbal_addInflowFlow() and massbal_addOutflowFlow():

    • Adds inflow and outflow flow values for routing totals, respectively.
  9. massbal_addInflowQual() and massbal_addOutflowQual():

    • Adds inflow and outflow pollutant mass values for routing totals.
  10. massbal_addReactedMass():

    • Adds the mass of pollutants that have reacted during the current time step.
  11. massbal_getStorage():

    • Computes the total system storage, summing up the volumes in both nodes and links.
  12. massbal_getStoredMass():

    • Computes the total mass of pollutants stored in the system, accounting for both nodes and links.
  13. massbal_getRunoffError():

    • Calculates the mass balance error for runoff, comparing the inflows and outflows in the system.
  14. massbal_getLoadingError():

    • Calculates the mass balance error for pollutant loadings, comparing the total buildup and removal of pollutants.
  15. massbal_getGwaterError():

    • Computes the mass balance error for groundwater, comparing the total inflows and outflows in the groundwater system.
  16. massbal_getFlowError():

    • Computes the flow routing mass balance error, comparing the total inflows and outflows of the flow system.
  17. massbal_getQualError():

    • Computes the water quality routing mass balance error, comparing the inflows and outflows of pollutants.
  18. massbal_getStepFlowError():

    • Computes the flow error for the current time step, comparing the inflows and outflows of the system.

Mass Balance for Runoff, Pollutants, and Groundwater:

  • The system tracks water and pollutant movements through the network of subcatchments, nodes, and links. Each component (e.g., runoff, pollutants, groundwater) has its own set of continuity totals that are updated as the simulation progresses.
  • Runoff: Tracks rainfall, infiltration, evaporation, and runoff flows.
  • Water Quality (WQ): Tracks pollutant buildup, deposition, infiltration, and runoff.
  • Groundwater: Tracks infiltration into groundwater, evaporation from groundwater, and percolation into deeper layers.

Error Handling:

  • The code checks for mass balance errors in various components (runoff, pollutants, groundwater, flow routing) and ensures that the system conserves mass throughout the simulation. Any errors in the mass balance are flagged and reported.

Reporting:

  • At the end of the simulation or during the process, the massbal_report() function generates a report detailing the mass balance errors for runoff, pollutants, groundwater, and flow routing. This is crucial for assessing the accuracy and performance of the model.

Summary:

The massbal.c file is a critical component for mass balance calculations in SWMM5. It ensures that water, pollutants, and groundwater are properly tracked and conserved throughout the simulation. The system handles both the mass balance updates during each time step and the final reporting of any errors in the conservation of mass. By keeping track of inflows, outflows, and changes in storage, the code ensures that the system behaves in a physically realistic manner and helps identify any inconsistencies or errors in the model's performance.

SWMM5 macros.h Summary

 The macros.h file defines several commonly used macros in the SWMM5 project to simplify and optimize code. These macros are used for error checking, memory management, mathematical operations, and function calls. Here's a breakdown of each section:

Key Macros:

Memory Management:

  1. MEMCHECK(x):

    • Checks whether a pointer x is NULL. If x is NULL, it returns 101, otherwise 0. This is useful for checking if memory allocation was successful.
  2. FREE(x):

    • Frees a pointer x if it is not NULL, and sets it to NULL afterward. This is a safe way to deallocate memory.

Mathematical Operations:

  1. ABS(x):

    • Computes the absolute value of x. If x is negative, it returns -x; otherwise, it returns x.
  2. MIN(x, y):

    • Returns the minimum of x and y.
  3. MAX(x, y):

    • Returns the maximum of x and y.
  4. MOD(x, y):

    • Computes the modulus of x by y (i.e., x % y).
  5. LOG10(x):

    • Computes the base-10 logarithm of x. It checks if x is greater than 0.0 before applying log10(), otherwise, it returns x unchanged. This ensures that the logarithm is only calculated for positive values.
  6. SQR(x):

    • Computes the square of x (i.e., x * x).
  7. SGN(x):

    • Returns the sign of x: -1 for negative x, 1 for positive x, and 0 for x equal to 0.
  8. SIGN(x, y):

    • Returns the absolute value of x if y is non-negative, or the negative absolute value of x if y is negative. This macro is useful for computing values that depend on the sign of a second variable.
  9. UCHAR(x):

    • Converts a lowercase character x to uppercase if it's a letter between a and z. If x is not a lowercase letter, it returns x unchanged.
  10. ARRAY_LENGTH(x):

    • Computes the length of an array x by dividing the total size of the array by the size of its first element. This is useful for determining the number of elements in a statically allocated array.

Error Checking:

  1. CALL(x):
    • Executes the function or expression x, but only if ErrorCode is not positive (i.e., ErrorCode is 0 or a negative value). If ErrorCode is positive, it prevents the execution of x. This is useful for error handling, ensuring that subsequent operations are only performed if no errors have occurred.

Summary:

The macros.h file defines a set of utility macros for handling memory, mathematical operations, and error checking. These macros help improve code readability, reduce redundancy, and ensure safe memory management and error handling throughout the SWMM5 project.

SWMM5 lidproc.c Summary

 The lidproc.c file is responsible for computing the hydrological performance of LID (Low Impact Development) units in a given time step in the EPA SWMM5 (Storm Water Management Model) framework. It models the water movement through various layers in LID systems (e.g., surface, pavement, soil, storage, and underdrain) and calculates flux rates for each layer based on input parameters such as rainfall, runoff, infiltration, and evaporation.

Key Features of the Code:

Constants:

  1. STOPTOL: The tolerance for integration error, which defines how accurate the model must be.
  2. MINFLOW: The cutoff for dry conditions, below which the flow is considered negligible.

Enumerations:

  1. LidLayerTypes: Defines the layers in an LID unit:

    • SURF: Surface layer
    • SOIL: Soil layer
    • STOR: Storage layer
    • PAVE: Pavement layer
    • DRAIN: Underdrain system
  2. LidRptVars: Represents different variables that can be reported for LID units, such as surface inflow, total evaporation, surface infiltration, etc.

Imported Variables:

  • HasWetLids: A flag indicating whether any LID units are wet, used in the model to determine if runoff treatment is active.

Local Variables:

These variables track the current state of moisture levels, flux rates, and water volumes in each layer of an LID unit (surface, pavement, soil, storage, etc.). The variables also handle calculations for fluxes like evaporation, infiltration, runoff, and drain flow.

Key Functions:

  1. lidproc_initWaterBalance():

    • Initializes the water balance components for an LID unit (inflow, evaporation, infiltration, surface flow, drain flow, and initial storage volume).
  2. lidproc_getOutflow():

    • This is the core function that computes the outflow from a specific LID unit. It uses the moisture levels in each layer to calculate fluxes for evaporation, infiltration, storage, and runoff. It integrates the changes over time and returns the surface runoff from the LID unit.
  3. modpuls_solve():

    • Solves the system of equations for LID units using the Modified Puls method, which is an iterative process to solve the differential equations governing the water flow in each layer of the LID unit.
  4. getSurfaceOutflowRate(), getSurfaceOverflowRate(), getPavementPermRate():

    • These functions compute the surface outflow, surface overflow, and pavement permeability, respectively, based on the conditions of the LID unit at the given time.
  5. Flux Rate Functions:

    • Functions like biocellFluxRates(), greenRoofFluxRates(), pavementFluxRates(), etc., are used to compute the flux rates for different types of LID processes (e.g., bio-retention cells, green roofs, porous pavement, etc.). These functions take the current moisture levels as input and compute how water moves through the system, including infiltration, evaporation, and runoff.
  6. getStorageExfilRate() and getStorageDrainRate():

    • These functions compute the exfiltration rate from the storage layer and the flow rate through the underdrain system, respectively. These are critical for LID systems with storage and drainage components.
  7. updateWaterBalance():

    • This function updates the mass balance for the LID unit, adding the contributions of inflow, evaporation, infiltration, and outflow to the unit's water balance.
  8. getEvapRates():

    • Computes the evaporation rates from each layer (surface, pavement, soil, storage) of the LID unit, considering factors like the available water and pervious fraction of the surface.
  9. Special LID Functions:

    • roofFluxRates(), barrelFluxRates(), and other similar functions compute the specific flux rates for different LID types like rooftop disconnection and rain barrels.

Key Concepts:

  • Moisture Level and Flux Calculation: The model computes the moisture levels in each layer (surface, soil, pavement, storage) and calculates the fluxes (infiltration, evaporation, runoff) based on these levels. The fluxes are then used to update the water balance of the LID unit.
  • Surface, Soil, and Storage Layers: Each layer of the LID unit behaves differently. For example, the surface layer allows for surface runoff, the soil layer permits infiltration, and the storage layer manages excess water.
  • Puls Method for Integration: The code uses the Modified Puls method to solve the system of differential equations governing the LID’s performance over time.

Water Balance and Simulation:

The lidproc_getOutflow() function integrates the flow through each layer of the LID unit, updating the water balance at each time step. It accounts for:

  • Surface Inflow: Runoff and rainfall that enter the LID unit.
  • Surface Evaporation: Water lost from the surface layer.
  • Surface Infiltration: Water that moves from the surface layer into the soil or storage.
  • Storage Evaporation and Exfiltration: Evaporation and water loss from the storage layer.
  • Underdrain Flow: Water that drains from the storage layer via the underdrain system.

Reporting:

  • The lidproc_saveResults() function writes the results to a report file, including detailed information about the flux rates, volumes, and water balance of each LID unit. It tracks whether the LID is dry or wet and adjusts the reporting accordingly.

Summary:

This module is central to the performance analysis of LID systems in SWMM5. It calculates how each LID unit handles stormwater over time, considering all aspects of water flow, storage, infiltration, and evaporation. The integration of these processes through the Modified Puls method provides a detailed and accurate representation of LID performance in managing runoff and water quality.

SWMM5 lid.c Summary

 The lid.c file handles the core operations for managing and simulating Low Impact Development (LID) practices in SWMM5 (Storm Water Management Model). It processes the input data for different LID processes (like bio-retention cells, green roofs, rain gardens, etc.), calculates the water balance for each LID unit, and manages their state during the simulation. Here’s an overview of the functionality provided by this code:

Key Data Structures:

  1. LidList: A linked list holding individual LID units in a group.
  2. LidGroup: A collection of LID units deployed in a specific subcatchment, tracking the total pervious area, flow to pervious area, and the drain flows.
  3. LidProc: A structure containing the design parameters for a specific type of LID process (e.g., bio-retention cell, porous pavement, etc.). Each LID process has various layers (surface, pavement, soil, storage, etc.) with associated properties.
  4. LidUnit: A specific instance of a LID process applied to a subcatchment. It contains parameters such as the number of units, their area, initial saturation, and flow parameters for runoff, drain flow, and evaporation.

Major Functions:

  1. lid_create():

    • Initializes arrays for LID processes (LidProcs) and LID groups (LidGroups).
    • Allocates memory for LID processes and groups based on the user-defined input.
  2. lid_delete():

    • Deallocates memory for LID processes and groups, including the free-up of resources like report files.
  3. lid_readProcParams():

    • Reads LID process parameters from an input file, allowing different types of LID systems to be configured (e.g., bio-retention cells, green roofs).
    • It can read various LID layers such as surface, pavement, soil, storage, and drainage mat parameters.
  4. lid_readGroupParams():

    • Reads the parameters for a specific LID unit, such as the number of units, their area, initial saturation, and how much runoff from impervious and pervious areas is treated.
  5. lid_getRunoff():

    • Computes runoff and drain flows from LID units in a subcatchment during a time step. The function calculates how much runoff is treated by the LID, including surface runoff, drain flow, evaporation, and infiltration.
  6. lid_addDrainRunon() and lid_addDrainInflow():

    • These functions manage the routing of LID drain flows to other subcatchments or conveyance systems, ensuring that the drainage flows are properly accounted for in the model.
  7. lid_writeSummary():

    • Writes a summary report of the LID processes and their performance for each subcatchment. The summary includes details such as the number of units, their area, and the percentage of impervious and pervious runoff treated.
  8. lid_writeWaterBalance():

    • Writes detailed water balance information for each LID unit, including inflow, evaporation, infiltration, surface runoff, drain flow, and the change in storage over the simulation period.
  9. validateLidProc() and validateLidGroup():

    • Validates the parameters for individual LID processes and groups. This ensures that all necessary layers are defined and that parameters like permeability, thickness, and porosity are within acceptable ranges.
  10. evalLidUnit():

    • Evaluates the performance of an individual LID unit during a time step. It calculates the outflow from the LID unit, considering various processes like evaporation, infiltration, and drainage.

Water Balance:

Each LID unit has a water balance that tracks:

  • Inflow: Water entering the LID unit from rainfall and runoff.
  • Evaporation: Water lost through evaporation.
  • Infiltration: Water that infiltrates into the soil or storage layer.
  • Surface Runoff: Water that exits the LID unit as surface runoff.
  • Drain Flow: Water that exits the LID unit via the underdrain system.
  • Storage: Water stored in the LID unit, which can be later evaporated or infiltrated.

Key Features:

  • LID Units: Multiple LID units can be deployed in a subcatchment. Each LID unit is configured based on its type (e.g., bio-retention cell, rain garden).
  • Pollutant Removal: The code supports pollutant removal through LID processes, with pollutant removal rates defined for the underdrain system.
  • Infiltration: Different infiltration methods are supported, including the Green-Ampt method for vegetative swales.
  • Reporting: Detailed performance and water balance reports can be generated for each LID unit, providing insights into their effectiveness in managing runoff.

Error Handling:

The code includes robust error handling for reading input data (e.g., checking that all required layers and parameters are defined) and for validating LID configurations. If any issues are detected, appropriate error messages are logged.

Summary:

This module is an essential part of the SWMM5 LID modeling functionality, allowing users to simulate the performance of LID systems for stormwater management. It computes how well different LID types treat runoff, manage water, and reduce pollution, providing valuable data for urban drainage design and sustainability planning.

SWMM5 lid.h Summary

 The lid.h file provides the public interface for the LID (Low Impact Development) functions used in the EPA SWMM5 (Storm Water Management Model). It defines the data structures and function prototypes related to the modeling and simulation of LID units and processes. The file also includes necessary enumerations and constants for managing different types of LID processes and handling water balance calculations.

Key Components of the Header File:

Enumerations:

  1. LidTypes: Defines the different types of LID processes that can be modeled, such as:

    • BIO_CELL: Bio-retention cell
    • RAIN_GARDEN: Rain garden
    • GREEN_ROOF: Green roof
    • INFIL_TRENCH: Infiltration trench
    • POROUS_PAVEMENT: Porous pavement
    • RAIN_BARREL: Rain barrel
    • VEG_SWALE: Vegetative swale
    • ROOF_DISCON: Roof disconnection
  2. TimePeriod: Specifies two time periods for drain flow calculations:

    • PREVIOUS: The previous time period
    • CURRENT: The current time period

Data Structures:

  1. LID Layer Structures: These structures define the various layers of an LID unit, including surface, pavement, soil, storage, underdrain, and drainage mat layers. Each layer has specific parameters such as thickness, void fraction, permeability, and roughness.

    • TSurfaceLayer: Surface layer parameters (e.g., depression storage, roughness, and slope).
    • TPavementLayer: Pavement layer parameters (e.g., void fraction, permeability, and clogging).
    • TSoilLayer: Soil layer parameters (e.g., porosity, field capacity, and saturated hydraulic conductivity).
    • TStorageLayer: Storage layer parameters (e.g., void fraction, saturated hydraulic conductivity, and clogging factor).
    • TDrainLayer: Underdrain system parameters (e.g., flow coefficients, head levels, and delay).
    • TDrainMatLayer: Drainage mat layer parameters for green roofs (e.g., thickness, void fraction, and roughness).
  2. LID Process (TLidProc): This structure represents the generic LID process design for a unit of area, including all the layers and properties associated with the specific LID type.

    • Contains parameters for surface, pavement, soil, storage, drain, and drainage mat layers.
    • Includes pollutant removal data (drainRmvl) for underdrain systems.
  3. Water Balance (TWaterBalance): This structure holds water balance statistics for a specific LID unit, such as inflow, evaporation, infiltration, runoff, drain flow, and storage volumes.

  4. LID Unit (TLidUnit): This structure represents a specific LID unit applied in a subcatchment, containing details such as:

    • The number of replicate units and their area.
    • Flow rates and water balances.
    • Detailed reporting information (TLidRptFile).
  5. LID Report File (TLidRptFile): This structure is used for managing the report file related to a specific LID unit, including the file pointer, dry period tracking, and results.

Function Prototypes:

  1. LID Creation and Deletion:

    • lid_create(int lidCount, int subcatchCount): Initializes the LID processes and groups based on the number of LID processes and subcatchments.
    • lid_delete(void): Deallocates memory for LID processes and groups.
  2. LID Parameter Handling:

    • lid_readProcParams(char* tok[], int ntoks): Reads LID process parameters from input data.
    • lid_readGroupParams(char* tok[], int ntoks): Reads parameters for specific LID units placed in subcatchments.
  3. Water Balance and Performance Calculation:

    • lid_validate(void): Validates LID parameters.
    • lid_initState(void): Initializes the state of LID units.
    • lid_getRunoff(int subcatch, double tStep): Computes runoff and drain flows from LID units in a subcatchment.
    • lid_writeSummary(void): Writes a summary of LID performance to a report file.
    • lid_writeWaterBalance(void): Writes detailed water balance results to a report file.
  4. Pollutant and Drainage Handling:

    • lid_addDrainLoads(int subcatch, double c[], double tStep): Adds pollutant loads from LID drains to system mass balance totals.
    • lid_addDrainRunon(int subcatch): Adds drain flow contributions to subcatchments.
    • lid_addDrainInflow(int subcatch, double f): Adds drain flow to conveyance system nodes.
  5. LID Unit and Process Evaluation:

    • lidproc_initWaterBalance(TLidUnit *lidUnit, double initVol): Initializes the water balance for an LID unit.
    • lidproc_getOutflow(TLidUnit* lidUnit, TLidProc* lidProc, double inflow, double evap, double infil, double maxInfil, double tStep, double* lidEvap, double* lidInfil, double* lidDrain): Computes the outflow (runoff, drainage, etc.) for a specific LID unit.
    • lidproc_saveResults(TLidUnit* lidUnit, double ucfRainfall, double ucfRainDepth): Saves the results for a specific LID unit.

Purpose:

The lid.h file defines the essential data structures and function prototypes needed to model and simulate LID practices within the SWMM5 framework. The functions cover the initialization, parameter reading, water balance calculation, and reporting for various types of LID units, such as rain gardens, green roofs, and porous pavements. This interface is crucial for performing stormwater management simulations using LID strategies to manage runoff, improve water quality, and support sustainable urban drainage 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...