Sunday, December 29, 2024

SWMM5 Delphi GUI Fsimul.pas Summary

 Below is a high-level summary of Fsimul.pas, the Delphi unit that implements the TSimulationForm in SWMM. This form coordinates the call to the SWMM simulation engine (SWMM5.DLL), displays its progress via a progress bar, and reports the run’s final continuity errors.


1. Purpose

Fsimul.pas defines TSimulationForm, a dialog that:

  • Exports the current SWMM project data into a temporary input file,
  • Opens and runs the SWMM solver (DLL),
  • Displays the run’s percent complete in real-time (progress bar),
  • Ends the run if any errors occur or if the user stops it,
  • Retrieves and displays mass-balance continuity errors (for runoff, flow, and quality),
  • Sets the final run status (successful, warning, error, etc.) returned to the main SWMM application.

2. Key Elements and Behaviors

  1. Notebook Pages:

    • Page 1 (ProgressPage): shows a label, progress bar, “Stop” & “Minimize” buttons.
    • Page 2 (ResultsPage): shows final run status (successful, warnings, or errors) and continuity errors.
  2. Engine Calls:

    • swmm_open(), swmm_start(), swmm_step(), swmm_end(), swmm_close():
      • These are API calls from SWMM5.DLL that parse input, run the simulation step-by-step, retrieve error codes, etc.
  3. Progress Updates:

    • The form calls swmm_step() in a loop, periodically updating:
      • ProgressBar1 with % complete,
      • elapsed days or elapsed hours,
      • Windows application title for minimized state.
    • The user can click “Stop” to terminate the run (setting RunStatus = rsStopped).
  4. Continuity Errors:

    • After swmm_end() completes, the form obtains the final ErrRunoff, ErrFlow, ErrQual errors via swmm_getMassBalErr().
    • These appear on the second “ResultsPage,” along with an icon (info vs. error) and a textual message (e.g., “Run was successful,” “Run was unsuccessful,” etc.).
  5. Run Status:

    • The run status is determined by error codes and checks:
      • rsSuccess, rsWarning, rsError, rsFailed, etc.
      • If results are not generated or the solver encountered a system error, the form updates the final status accordingly (and sets a message in StatusLabel).
  6. User Controls:

    • Stop button sets RunStatus = rsStopped.
    • Minimize button calls Application.Minimize.
    • OK button dismisses the form after final results are displayed.

3. Summary

Fsimul.pas manages the overall process of exporting project data, invoking the SWMM solver DLL, reporting progress, and then presenting final results. Its TSimulationForm is the main interface where users see real-time simulation progress and final mass-balance continuity errors or error messages, enabling them to track and confirm SWMM’s execution within the EPA SWMM application.

SWMM5 Delphi GUI Fresults.pas Summary

 Below is a high-level summary of Fresults.pas, the Delphi unit that implements the TResultsForm in SWMM. This MDI child form displays summary results after a simulation run.


1. Purpose

Fresults.pas defines TResultsForm, an MDI child form that:

  • Retrieves and displays summary information (from SWMM’s report file) on a variety of topics (e.g., subcatchment runoff, node flooding, link flow classification, etc.).
  • Allows the user to view the summary in a grid, sort by different columns, copy the table to the clipboard/file, or print it.

2. Key Elements and Behaviors

  1. Topics and Data Loading:

    • SWMM’s engine produces a text report file. The form, upon refresh, checks for the presence of specific topics (like “Subcatchment Runoff,” “Node Depth,” etc.) in that file.
    • Each valid topic is listed in the TopicsListBox combo box (e.g., Subcatchment Runoff, Node Flooding, etc.).
    • When a topic is chosen, RefreshTopic is called: it calculates row/column counts, sets up multi-line column headers, and then uses Uresults.PopulateGrid to fill TheGrid from the results stored in memory.
  2. Grid Appearance:

    • TheGrid is a TStringGrid showing one row per object (e.g., subcatchment or conduit) and columns with summary metrics (e.g., total inflow, max flow, hours surcharged).
    • The top row of headers in TheGrid can contain multiple lines per column (drawn in TheGridDrawCell with calls to DrawText).
    • Clicking a column header (top row) sorts the table by that column, numeric vs. text sorting determined by ColumnIsText.
  3. Topic-Specific Column Headings:

    • Each topic (e.g. rtRunoff, rtNodeDepth, rtLinkFlow, etc.) has a dedicated set of multi-line column headings built in SetColHeaders, typically parsed from the header lines found in TopicHeaderLines.
  4. Copying Data:

    • A CopyTo method launches a TCopyToForm dialog where format is pinned to text.
    • If a file is specified, it writes the table to that file (via Slist.SaveToFile); otherwise, it copies text to clipboard.
  5. Printing:

    • The Print routine uses SWMM’s custom Printer object. It:
      1. Prints a heading,
      2. Repeats columns chunk by chunk (since some topics have many columns),
      3. Then prints row by row.
  6. Sorting:

    • The user can click a column header to sort rows by that column.
    • The form keeps track of the currently sorted column, and toggles ascending vs descending each click.
  7. Details:

    • The TopicsListBoxClickCheck event changes the displayed topic, reloading TheGrid.
    • The user can also click on the object name in the table (the first column) to locate that object in the main SWMM database and update the browser.

3. Summary

Fresults.pas provides the TResultsForm used to display summary results from the SWMM engine’s .rpt file. It supports multiple summary topics, multi-line column headers, column sorting, copying to the clipboard, and printing. This allows SWMM users to quickly browse, sort, and export the various summary metrics (runoff, infiltration, node inflow, link flow classification, etc.) produced by a SWMM run.

SWMM5 Delphi GUI Fproplot.pas Summary

 Below is a high-level summary of Fproplot.pas, the Delphi unit that implements the TProfilePlotForm in SWMM. This MDI child form displays a profile plot, which is a side-view of water elevations and conduit shapes along a series of connected links/nodes.


1. Purpose

Fproplot.pas defines TProfilePlotForm, an MDI child form that:

  • Renders a longitudinal profile of the drainage system—showing node invert elevations, link inverts/crowns, and simulated water elevations.
  • Can refresh its display (after a re-run), copy its image to files or clipboard, and print or export the plot.

2. Key Elements and Behaviors

  1. Creating and Refreshing the Plot:

    • The CreatePlot method is called with a ReportSelection that includes:
      • List of links forming the profile path.
      • Time period to display (if simulation results exist).
    • The form processes each link and node in the profile, extracting geometry (invert elevations, link lengths, conduit depths) and output data (e.g., node water depth, link water depth if dynamic wave).
    • RefreshPlot:
      • Clears all existing data series.
      • Plots link invert, link crown, node invert, and optionally ground surface.
      • If results exist, it also draws the water surface (HGL) and water-filled interior for each conduit.
  2. Plot Components:

    • Chart1: a TChart displaying the profile line. It contains:
      • LinkInvert (line series for conduit inverts),
      • LinkCrown (line series for conduit crown),
      • NodeInvert (point series for node inverts),
      • GroundLine (line series for node ground elevations),
      • plus dynamic drawing of the water surface.
    • Visual aspects (color, pen style, etc.) are governed by user-settable ProfileOptions and GraphOptions.
  3. Drawing the Water Surface:

    • If in dynamic wave mode, the link’s interior water level is retrieved for each link at the current time step, then a polygon is drawn showing the water-filled portion.
    • The hydraulic grade line (HGL) is drawn from node to node.
  4. Display Options:

    • The user can choose to show or hide the HGL, to auto-scale the vertical axis, or to include ground surfaces.
    • The SetPlotOptions method launches a TProfilePlotOptionsForm to tweak these settings (colors, line thickness, label styles, etc.).
  5. Copying and Printing:

    • CopyTo: sends the plot to the Clipboard or a file in either bitmap or metafile format, via a TCopyToForm dialog.
    • Print: calls SWMM’s shared printing logic (Ugraph.Print) to print or preview.
  6. Data Handling:

    • Gathers link geometry (length, invert offsets) from input data if no run results are available, or from Uoutput’s binary data if run results exist.
    • Gathers node inverts and max depths similarly.
    • When refreshing at a new time period, it updates the water surface polygon/HGL.
  7. User Interaction:

    • Right-clicking on the chart calls SetPlotOptions (the user can change chart style).
    • A Refresh button is shown only if results are not available, to simply re-draw the geometry-only profile.

3. Summary

Fproplot.pas implements the TProfilePlotForm used for generating and refreshing an elevation vs. distance (profile) view along a path of links. It manages conduit shape geometry, node ground/invert elevations, optional water surface fill, hydraulic grade lines, and dynamic wave depths at a selected time step. It also provides user-controlled styling (fonts, colors, line thicknesses), supports copy/print, and collaborates with other SWMM modules (e.g., Uoutput for result data and TProfilePlotOptionsForm for visual options).

SWMM5 Delphi GUI Fproped.pas, Summary

 Below is a high-level summary of Fproped.pas, the Delphi unit in SWMM that defines the Property Editor form (TPropEditForm). This form hosts a TPropEdit component that behaves like an "object inspector," allowing users to edit properties of SWMM data objects in a grid-based interface.


1. Purpose

Fproped.pas implements TPropEditForm, a specialized form that:

  • Displays object properties in a two-column grid (property name vs. property value).
  • Supports editing, validating, and providing help/hints for each property.
  • Manages additional dialogues when a property requires deeper editing (e.g., time series, curves, infiltration parameters, etc.).

2. TPropEditForm: Key Elements and Behaviors

  1. TPropEdit Component:

    • Placed at runtime onto TPropEditForm.
    • Columns:
      • Property (read-only, descriptive name).
      • Value (editable, user input).
    • Tracks each property’s data type, default/edit style (e.g., numeric, combo list, file name, comment, etc.).
    • Has special event handlers for:
      • OnButtonClick: opens supplementary dialogs (time series editor, curve editor, etc.).
      • OnValidate: checks correctness of user input.
      • OnRowSelect: updates hint label describing the selected property.
  2. Form Lifecycle:

    • FormCreate: Instantiates the TPropEdit component, sets styling, event handlers, parent layout, etc.
    • FormDeactivate: Ensures last property edit is validated when user clicks away from the form.
    • FormShow: Makes the form fully visible (especially on first activation).
    • FormClose: Hides the form rather than destroys it.
  3. Editing Specialized Properties:

    • When user clicks the ellipsis button on a property, the ButtonClick event routes to specialized edit dialogs:
      • Time series
      • Rain file name
      • Curve (e.g., Pump curve, Rating curve, Tidal curve)
      • Infiltration
      • Groundwater
      • Snowpack
      • LID usage
      • Initial loadings
      • Node inflows / Pollutant treatment
      • Conduit cross-section
      • Storage curve
      • Label font
      • etc.
  4. Validation:

    • The OnValidate handler calls Uvalidate.ValidateEditor to check if a typed-in property value is valid (numeric range checks, permissible values, etc.).
    • If invalid, displays an error message and reverts focus to the property.
  5. Hints:

    • A small text label (HintLabel) shows context-sensitive help text about the selected property row.
    • RefreshPropertyHint is invoked after property changes or data refreshes.
  6. Navigation:

    • The user can navigate between items in the same object category (e.g., Subcatch #5 to Subcatch #6) via PageUp/PageDown keystrokes.
    • F1 triggers context-sensitive help for the active object type.
  7. Integration:

    • The form is typically hidden unless an object is being edited.
    • After user changes a property, HasChanged in main form is set so that SWMM knows data were modified.
    • Some property edits can invoke deeper sub-dialogs (e.g., infiltration, LID usage, or cross-section shape editors).

3. Summary

Within Fproped.pas, TPropEditForm centralizes property editing for SWMM objects by providing a TPropEdit grid-based property list. Custom logic in ButtonClick and OnValidate extends standard data entry, launching specialized dialogs or validating user input. The form also manages help hints and keyboard navigation (like PgUp/PgDown). Its integrated design ensures any changes are immediately recognized by SWMM and can trigger more advanced configuration dialogs when necessary.

SWMM5 Delphi GUI Fovmap.pas Summary

 Below is a high-level summary of Fovmap.pas, the Delphi unit that defines SWMM’s Overview Map form (TOVMapForm). This form provides an outline view of the entire study area map, with a rectangular highlight showing the map region currently visible on the main MapForm.


1. Purpose

Fovmap.pas implements TOVMapForm, a small, always-available form in EPA SWMM that displays:

  • A miniature (bird’s-eye) view of the entire project map.
  • A focus rectangle representing the bounds of the visible area on the main map (on TMapForm).
  • Dragging this rectangle re-centers the main map’s view.

2. TOVMapForm: Key Functionalities

  1. OVmap (TMap):

    • A dedicated TMap object storing a scaled-down rendering of the main map’s geometry and any backdrop image.
  2. FocusRect (TRect):

    • A rectangle drawn on the overview map indicating which portion is currently seen on TMapForm.
  3. Form Life Cycle:

    • FormCreate: Instantiates OVmap, sets up defaults, and prepares for drawing the map outline.
    • FormDestroy: Frees the OVmap object.
    • FormClose: Hides (rather than frees) the overview map form.
    • FormResize & Rescale: Rescales and redraws the overview map to fit the form’s new dimensions.
  4. Drawing & Refreshing:

    • Redraw: Renders an outline (or backdrop) of the entire project on an internal bitmap.
    • PaintFocusRect: Draws a bold red rectangle to highlight the main map’s current view.
    • ShowMapExtent: Computes and updates the focus rectangle coordinates based on the main map’s zoom and pan settings.
  5. Dragging:

    • The user can click inside the focus rectangle and drag it around to shift the main map’s viewport.
    • FormMouseDown: Begins dragging if the mouse is within FocusRect.
    • FormMouseMove: Dynamically redraws a dashed rectangle as the user drags.
    • FormMouseUp: Repositions the focus rectangle, then re-centers the main map accordingly.
  6. Miscellaneous:

    • NeedsUpdating: A boolean that indicates if changes are pending (e.g., waiting until the form becomes active before redrawing).
    • WMGetMinMaxInfo: Restricts how small the user can resize the overview form.

3. Usage in SWMM

  • Creation: Instantiated when SWMM starts. Stays hidden or visible based on a View menu toggle.
  • Coordination with Main Map:
    • The main MapForm updates OVMapForm whenever project data or zoom changes, calling OVMapForm.Redraw or OVMapForm.ShowMapExtent.
    • If the user drags the focus rectangle in OVMapForm, it calls back to re-pan the main map’s window.
  • Benefits:
    • Quickly locates and navigates large study areas.
    • Makes panning easier: user sees entire layout, and drags focus box to move main map’s window around.

4. Summary

In Fovmap.pas, TOVMapForm provides a scaled-down “overview map” of the entire study area, with a highlighted rectangle to indicate the currently visible portion in the main map form. The user can drag this rectangle to reposition the main view. Internally, OVmap is a TMap object that draws an outline or backdrop image of the complete area, while FocusRect denotes the current zoom/pan region from TMapForm. This overview greatly aids navigation and spatial context in SWMM’s user interface.

SWMM5 Delphi GUI Fmain.pas Summary

 Below is a high-level summary of Fmain.pas, the Delphi unit containing SWMM’s main MDI form (TMainForm). This form manages the program’s user interface, including the main menu, toolbars, status bar, and browser panel.


1. Purpose and Context

Fmain.pas implements TMainForm, the parent (MDI) form in which all other forms (Map, Graphs, Tables, etc.) appear as MDI child windows. The form’s primary responsibilities are:

  • Managing menus and toolbars for file operations, editing, viewing options, simulation runs, and reporting features.
  • Overseeing the data “Browser” panel, which displays the list of object categories and the items within each category.
  • Handling user interactions for creating, opening, saving, and closing project files, plus communicating with other forms that provide more specialized views of the project (map display, results graphs, tables, etc.).
  • Storing user preferences and application settings that are retrieved from or written to an INI file.

2. The TMainForm Class

2.1 Key UI Components

  1. Main Menu

    • File (Open, Save, Export, Print, etc.)
    • Edit (Copy, Select, Find, Group editing, etc.)
    • View (Backdrop, Legends, Pan/Zoom, etc.)
    • Project (Defaults, Summary, Run Simulation, etc.)
    • Report (Status, Summary, Graph, Table, Statistics, etc.)
    • Tools (Map Display Options, Preferences, External Tools, etc.)
    • Window (Cascade, Tile, Close All)
    • Help (Topics, Tutorials, About, etc.)
  2. Toolbars

    • A main toolbar (File commands, copy, find, run, etc.)
    • A status bar with special areas for Auto-Length, Offsets, Flow Units, run status, zoom level, etc.
  3. Browser Panel

    • A multi-tab control with:
      • Data Page: Displays object categories in a TreeView and the items in each category in a ListBox, plus a notes panel.
      • Map Page: Displays map display combo boxes (Subcatch, Node, Link theme), date/time controls, etc.
  4. ProgressBar

    • Used for showing progress (for instance, during simulation runs).
  5. ImageLists

    • Contains bitmaps, icons, and glyphs for toolbar buttons and menus.

2.2 Important Routines & Responsibilities

  1. File Operations

    • OpenFile: Handles reading an existing project file into memory, ensuring current data are saved first.
    • SaveFile: Writes current project data to a specified file, handling read-only files and backup creation.
    • MnuNew, MnuOpen, MnuSave, MnuSaveAs: Standard menu item handlers invoking the main file reading/writing logic.
    • MnuExportMap, MnuExportHotstart, MnuExportStatusRpt: Provide ways to export map images, hotstart state files, or status reports.
  2. MDI Child Management

    • CloseForms: Closes all child forms except the map.
    • RefreshForms: Refreshes data on open child forms after a simulation run.
    • FormExists: Checks if a certain child form is already open.
  3. Browser Panel

    • Contains an ObjectTreeView listing main object categories (Rain Gages, Subcatchments, Nodes, Links, etc.), plus an ItemListBox showing items in the currently selected category.
    • Buttons for creating, deleting, sorting objects, and notes display.
    • Allows the user to select an object category and item, or to create and label new objects.
  4. Simulation Runs

    • RunSimulation: Launches the SWMM engine (via a dialog in Fsimul.pas) and, on completion, updates the run status icon, attempts to read the binary results, and refreshes forms.
  5. Map Display & Navigation

    • Various procedures handle map panning, zooming, alignment of backdrops, legends toggling, etc.
    • MapViewBoxChange updates map display themes for subcatchments, nodes, or links.
  6. Report Generation

    • CreateReport: Called to create time series graphs, tables, profile plots, or scatter plots based on a selection object (TReportSelection).
    • RefreshResults: Reads the summary of results from the output file, updates map display, and refreshes open results windows.
  7. MRU List (Most Recently Used Files)

    • Maintains a short list of last opened project files, which can be quickly accessed from the File menu.
    • MRUDisplay, MRUClick, MRUUpdate manage user selection and updating the list.
  8. Help & Tutorials

    • Integrates with HTMLHelp for context-specific help.
    • Menus for “How Do I?” or “Tutorials” launch SWMM help topics or tutorial help files.
  9. Form Resize & Minimizing

    • On resizing, the main form repositions or resizes the browser panel and map combos.
    • Minimizing and restoring the form updates the drawing style for toolbars if not using the Windows style.

2.3 Event Handling Flow

  • OnCreate

    • Initializes cursors, directories, styles, preferences, MDI environment, and blank project.
    • Optionally opens file specified via command line.
  • OnShow

    • Creates the MapForm.
    • If no command-line file is given, either starts a new project or shows the welcome screen.
  • OnCloseQuery

    • Checks if the user wants to save changes before closing SWMM.
  • OnClose

    • Frees resources, saves preferences, and clears project data.
  • OnKeyDown

    • If user presses Esc, reverts from adding new object to standard selection mode.

3. Summary

In Fmain.pas, TMainForm is the application’s centerpiece, orchestrating all top-level functionality: reading/writing project files, configuring menu and toolbar actions, running simulations, and coordinating the creation and update of MDI child windows (map display, graphs, tables). It houses the “Data Browser” for listing and editing project items, plus map/time controls on the “Map” page of the browser. Ultimately, Fmain.pas stands as the central UI controller in SWMM 5.2, ensuring that user commands and simulation data flow smoothly throughout the application.

SWMM5 Delphi GUI Fraph.pas Summary

 Below is a high-level overview of Fgraph.pas, a Delphi unit from SWMM 5.2 that defines a form (TGraphForm) for displaying simulation results as either a time series plot or a scatter plot.


1. Purpose and Context

SWMM can display simulation results in various plot types. Fgraph.pas implements the TGraphForm (an MDI child form) that renders these plots (time series or scatter plots) using Delphi’s TeeChart library. It relies on routines in Ugraph.pas to handle the details of chart creation, styling, and data retrieval from SWMM’s binary output file.


2. The TGraphForm Class

2.1 Key Fields

  1. Chart1 (TChart):

    • The main TeeChart component.
    • Houses a set of data series used for plotting.
  2. Graph (TReportSelection record):

    • Stores selections (like object/variable, time range, plot type, etc.).
  3. TimeFactor, StartDate, EndDate:

    • Used for time series plots, to manage whether times appear in elapsed hours, days, or actual date/time format.
  4. OptionPage:

    • Determines which tab of a graph options dialog will initially show.
  5. XvarIndex, YvarIndex:

    • Indices in SWMM’s binary output data for the chosen variables (X and Y in a scatter plot).
  6. StartPeriod, EndPeriod, TotalPeriods:

    • Determine which range of simulation time steps to display.

2.2 Main Features

  1. Time Series Plot

    • Each object/variable combination is displayed as a separate series on Chart1.
    • X-axis can be actual dates/times or elapsed time.
    • The user can optionally show observed/calibration data if only one object is being plotted.
  2. Scatter Plot

    • Plots one variable vs. another for a single range of time steps.
    • A single data series is created, containing points of (Xvariable, Yvariable) for each time period.
  3. Creation and Refresh

    • CreateGraph is called once to set up the chart based on selected items:
      • For time series: creates multiple line or area series, one per object.
      • For scatter plot: creates a single point series.
    • RefreshGraph is called to retrieve new data after e.g. a re-run of the simulation.
    • Data are fetched from the SWMM binary output via Uoutput routines (like GetValue).
  4. Graph Options

    • Right-clicking on the chart calls SetGraphOptions, opening a Graph Options dialog (in Ugraph.pas) to change display styles.
    • Standard functionality for copying to clipboard or file, or printing, is available via CopyTo and Print.
  5. Mouse/Keyboard Interactions

    • Pressing Shift + left mouse button zooms in. Right-click triggers graph options.
    • Pressing Esc or close button frees the form.
    • A “lock” button toggles whether the plot auto-refreshes data after a new simulation.

2.3 Key Methods

  1. CreateGraph (Main entry point):

    • Takes a TReportSelection describing what to plot.
    • Decides if it’s a time series or scatter plot.
    • Builds the chart’s data series accordingly.
  2. RefreshGraph:

    • Re-fetches data from the simulation results if not locked.
    • For time series: calls RefreshTimeSeriesPlot.
    • For scatter: calls RefreshScatterPlot.
  3. RefreshTimeSeriesPlot:

    • Clears each data series, then loops over time periods from start to end, calling GetValue for each.
    • Optionally adds calibration data for observed vs. computed comparisons.
  4. RefreshScatterPlot:

    • Clears the single scatter series, again fetching X and Y values over time from the binary output.
  5. SetGraphOptions:

    • Launches a Graph Options dialog, letting the user change colors, grid style, fonts, axis scaling, etc.
  6. CopyTo and Print:

    • Provide ways to save or print the chart.

3. Summary

In Fgraph.pas, the TGraphForm is the specialized form for showing SWMM’s results as a time series or scatter plot. It integrates with SWMM’s output file reading, receives user’s plot selections from a TReportSelection, and displays the resulting chart with help from Ugraph.pas. By calling CreateGraph, RefreshGraph, SetGraphOptions, CopyTo, or Print, the rest of SWMM’s GUI manages how and when a chart is built, updated, exported, or printed.

SWMM5 Delphi GUI Dunithyd.pas Summary

 Below is an overview of Dunithyd.pas, a Delphi unit from SWMM 5.2 that implements a dialog form (TUnitHydForm) for editing the properties of an RDII Unit Hydrograph (UH) group. In SWMM, RDII (Rainfall-Dependent Infiltration/Inflow) can be modeled by defining up to three “short-term,” “medium-term,” and “long-term” unit hydrographs, along with initial abstraction parameters, for each month of the year (plus an “All Months” option). This form lets the user specify all those parameters in a systematic way.


1. Purpose and Context

RDII in SWMM is captured using Unit Hydrographs that describe how rainfall infiltrates and enters the sewer system as infiltration/inflow. Each set of unit hydrographs (short-, medium-, long-term) can vary by month. Additional parameters control initial abstraction—how much rainfall is withheld before generating RDII.

The TUnitHydForm helps the user:

  1. Assign a unique name to the unit hydrograph group,
  2. Specify which rain gage the RDII is associated with,
  3. Provide UH parameters (R,T,K)(R, T, K) for each of the three unit hydrographs, for each month (January, February, etc.), or for “All Months,”
  4. Provide initial abstraction parameters (Dmax,Drec,D0)(D_{max}, D_{rec}, D_0) similarly for each month and each of the three UHs.

Then these RDII definitions can be referenced by nodes that experience infiltration/inflow from that hydrograph group.


2. Main Form: TUnitHydForm

2.1 Key Controls

  1. UHName (TEdit):
    • The user-specified name of the unit hydrograph group.
  2. RGname (TComboBox):
    • The name of the rain gage that drives this RDII. The user picks from among the project’s list of raingages.
  3. PageControl1 with two tabs:
    • TabSheet1: A grid (UHGridEdit) for editing the (R,T,K)(R, T, K) parameters (fraction of rainfall, time to peak, and recession constant) for each of three unit hydrographs (“short-term,” “medium-term,” “long-term”).
    • TabSheet2: A grid (IAGridEdit) for editing the initial abstraction parameters (Dmax,Drec,D0D_{max}, D_{rec}, D_0) for each of the three UHs.
  4. MonthsCombo: A drop-down listing “All Months” plus each month (January ... December). The user can choose which set of monthly parameters to view/edit. Each month has its own set of (R,T,K)(R, T, K) or (Dmax,Drec,D0(D_{max}, D_{rec}, D_0).
  5. OK, Cancel, Help buttons:
    • Finalize changes, discard, or open help topic about RDII hydrographs.

2.2 Internal Data Structures

The form uses:

  • UHParams[0..12, 1..3, 1..3] to store (R,T,K)(R, T, K) for each month (0=All Months, 1=January, ..., 12=December) and each of the three UHs (1=short term, 2=medium term, 3=long term).
  • IAParams[0..12, 1..3, 1..3] to store (Dmax,Drec,D0(D_{max}, D_{rec}, D_0` similarly.

The user sees these in the UHGridEdit.Grid or IAGridEdit.Grid depending on the tab. They pick which month to display from MonthsCombo, and the code copies the arrays to/from the grid for that month.

2.3 Key Methods

  1. FormCreate:

    • Sets up the grids, ensuring 4 rows (one for “Response” label, plus short/medium/long) and 3 columns (R,T,KR, T, K or (Dmax,Drec,D0)(D_{max}, D_{rec}, D_0)).
    • Fills MonthsCombo with “All Months,” “January,” “February,” etc.
  2. SetData(Index, aUnitHyd):

    • Called to load the existing data for a unit hydrograph group:
      1. UHIndex := Index.
      2. UHName.Text with the name from Project.Lists[HYDROGRAPH].Strings[Index].
      3. RGname.Text with the stored raingage name.
      4. Copies each month’s (R,T,K)(R, T, K) and (Dmax,Drec,D0)(D_{max}, D_{rec}, D_0) from aUnitHyd.Params[] / aUnitHyd.InitAbs[] into UHParams[] / IAParams[].
      5. Finds the first month that has any data, sets MonthsCombo.ItemIndex to that month, and displays those data in the two grids.
  3. GetData(S, aUnitHyd):

    • After user presses OK, retrieves the final name UHName.Text into S.
    • Copies the currently displayed month’s data from the grids to UHParams[] and IAParams[].
    • Then writes all months’ data back into aUnitHyd.Params[] and aUnitHyd.InitAbs[].
    • Also sets aUnitHyd.Raingage to RGname.Text.
  4. MonthsComboClick:

    • Saves the currently displayed grid values to UHParams / IAParams for the old month.
    • Switches the displayed month to the newly selected month.
    • Loads that month’s stored values into the grids.
  5. OKBtnClick:

    • If the data passes ValidateData (e.g., no empty name, no duplicate name, a valid raingage name), then ModalResult := mrOK, otherwise an error message appears.

3. Validation Checks

  • UHName must be non-empty, unique among Project.Lists[HYDROGRAPH].
  • Raingage must be non-empty.
  • The numeric fields can be left empty if the user is not using them for that month. Typically, (R,T,K)(R, T, K) or (Dmax,Drec,D0(D_{max}, D_{rec}, D_0) can be 0.0 if not used.

4. Additional UI Behavior

  • The user can define partial data for some months while leaving “All Months” or other months blank. If a month is set to “All Months,” the grids define the baseline parameters used if no monthly override is provided.
  • The grids are small (4 rows, 4 columns). The row 0 is a heading, row 1..3 correspond to the short/medium/long UHs or infiltration sets. The code in SetData / MonthsComboClick copies data to/from arrays, thus letting each month have a separate set of UH/IA parameters.

5. Summary

Dunithyd.pas provides TUnitHydForm, a specialized form in SWMM for editing an RDII unit hydrograph group. It organizes:

  • Name of the hydrograph group,
  • Associated rain gage,
  • (R, T, K) triple for short/medium/long unit hydrographs,
  • Initial abstraction data (Dmax,Drec,D0D_{max}, D_{rec}, D_0),
  • Month-by-month overrides (or “All Months” default).

Once the user finalizes, SWMM stores these parameters in a THydrograph object, enabling infiltration/inflow modeling in the sewer system.

SWMM5 Delphi GUI Dxsect.pas Summary

 Below is an overview of Dxsect.pas, a Delphi unit from SWMM 5.2 that creates a form (TXsectionForm) for editing the cross-sectional geometry of a conduit in SWMM.


1. Purpose and Context

In SWMM, each conduit can have a cross-section shape, such as circular, trapezoidal, rectangular, street, custom, etc. Dxsect.pas implements the user interface allowing one to pick which shape is used and supply the necessary parameters (like height, bottom width, side slopes, etc.). Some shapes rely on external references (like street sections or transects), while others have special dimension lookups or standard sizes (e.g., elliptical or arch shapes).


2. The TXsectionForm Form

2.1 Key Controls and Data Fields

  1. ShapeListView (TListView):

    • Displays all possible shapes (rectangular, trapezoidal, triangular, parabolic, etc.) in an icon list.
    • The user clicks on an icon to select that shape.
  2. NumEdit1, NumEdit2, NumEdit3, NumEdit4 (TNumEdit controls):

    • Up to four numeric parameters describing the geometry of the shape.
    • For example, for a trapezoid shape, these might be:
      1. Bottom width
      2. Left slope
      3. Right slope
      4. (Sometimes blank if not needed).
  3. TsectCombo (TComboBox) and TsectBtn (TBitBtn):

    • Used for shapes that reference external definitions, like "Street" or "Irregular" (Transect-based) or "Custom" (Shape curves).
    • The user picks which named external object (Street or Transect or Shape Curve) they want.
  4. BarrelsEdit and BarrelsUpDown:

    • Number of barrels for the conduit cross-section.
  5. ForceMainNote (TLabel):

    • A special label that appears if the "Force Main" shape is selected, clarifying that one is either entering a Hazen-Williams C-factor or a Darcy-Weisbach roughness, depending on the system.
  6. SidewallsCombo and SidewallsLabel:

    • For rectangular open channels, the user can choose how many sidewalls are removed (0, 1, or 2) from the shape.
  7. SizesCombo:

    • For certain elliptical or arch shapes, the user can pick from a list of standard sizes or choose "Custom."
  8. OK, Cancel, and Help Buttons:

    • Confirm or discard changes, or launch help topic on cross-sections.

2.2 Data Flow

  1. The form is given an existing set of cross-section parameters, such as:
    • shape name
    • four geometry fields
    • number of barrels
    • name of external reference (if used by street, irregular, or custom shapes)
  2. The form highlights the current shape in ShapeListView, sets up the right numeric fields, and optionally displays a combo box for referencing external objects or standard sizes.
  3. The user modifies parameters (like top width, bottom width, side slope, etc.).
  4. On OK, the form checks that the data are valid (no blank references, certain numeric constraints, etc.) and returns them to the main program.

2.3 Special Cases

  • Street shape:
    • TsectCombo references a "Street" object name (the user picks from the list in Project.Lists[STREET]).
  • Irregular shape:
    • TsectCombo references a "Transect" name (the user picks from Project.Lists[TRANSECT]).
  • Custom shape:
    • TsectCombo references a "Shape Curve" name from Project.Lists[SHAPECURVE].
  • Elliptical shapes (horizontal/vertical) and arch shapes:
    • Provide a standard library of sizes in SizesCombo. If "Custom" is chosen, the user can specify dimension fields directly.
    • The code sets dimension fields automatically if a standard size is chosen.
  • Rectangular open shape can remove sidewalls via SidewallsCombo (like an open rectangular channel).
  • Force main shape uses a different friction approach (Hazen-Williams or Darcy-Weisbach) indicated by ForceMainNote.

2.4 Validation

ValidateData checks:

  • Numeric fields must be valid (non-blank if shape requires them).
  • Filled circular shape's filled depth < total depth.
  • If referencing a street or transect or shape curve, the user must provide a valid name (not blank).
  • For elliptical/arch shapes, if "Custom" is used, certain dimension checks apply (like vertical elliptical must be taller than wide, etc.).

2.5 Key Procedures

  • FormCreate: Sets up the shape list, images, label text, and dimension system (US vs. SI).
  • SetData: Called externally to load the given shape & parameters into the form.
  • GetData: Called to return the final shape name & parameters from the form.
  • ShapeListViewSelectItem: Responds to user picking a shape icon, changes the visible numeric fields accordingly, or references an external object.
  • ValidateTextEntry: Ensures each numeric entry is valid or zero if not used.
  • SizesCombo for elliptical or arch shapes:
    • If user picks a standard size, dimension fields are auto-filled and disabled. If "Custom," the user can specify them.

3. Summary

Dxsect.pas provides the main user interface for setting or editing a single conduit’s cross-section geometry in SWMM 5.2. By selecting a shape from a list of icons, entering up to four numeric parameters, optionally referencing external objects (Street, Transect, or Shape Curve), and specifying the number of barrels, the user configures the conduit cross-section that SWMM uses in hydraulic calculations.

SWMM5 Delphi GUI Dwelcome.pas Summary

 Below is an overview of Dwelcome.pas, a Delphi unit from SWMM 5.2 that implements a TWelcomeForm, which is a custom "Welcome" or "Start Page" dialog that can appear when SWMM first launches. This form allows users to quickly access recent projects, sample projects, or documentation resources, and to start new or open existing SWMM files.


1. Purpose and Context

Many applications provide a "Welcome Screen" at startup, presenting options such as:

  • Creating a new project
  • Opening a recent project
  • Accessing sample models
  • Viewing documentation or tutorials

In SWMM, the TWelcomeForm does exactly this. It gathers a variety of resources (recently opened SWMM input files, sample project files) and presents them in a user-friendly interface, letting the user quickly select an option (like opening an existing file, starting a new project, or exploring examples).

Once the user makes a selection, the form returns a code to the main program, indicating what action SWMM should take (e.g., "Load recent file #3," "No action," "Open a sample model," etc.).


2. Main Form: TWelcomeForm

2.1 Visual Components

  1. Panel1 / Panel2: Container panels for layout and styling.
  2. CloseButton (TSpeedButton): A button labeled “Close,” which simply closes the welcome screen with “no action.”
  3. ShowStartPageCB (TCheckBox): If checked, indicates the user wants to see this welcome form every time SWMM starts. Otherwise, once unchecked, SWMM might store a user preference not to show the welcome screen at startup.
  4. GetStartedListView, DevelopListView, SamplesListView, ProjectsListView (all TListView):
    • Each list view contains clickable items with icons, letting the user pick an action (tutorial, user’s guide, create new project, open project, load sample file, or load recent project).
    • For example:
      • GetStartedListView might contain items like “Open the Tutorial” or “View the User’s Guide.”
      • DevelopListView might have “New Project” or “Open Project.”
      • SamplesListView shows sample project entries in the local “Documents\EPA SWMM Projects\Samples” folder, plus an item pointing to an external website with further examples.
      • ProjectsListView displays the list of most recently used (MRU) projects from SWMM’s MRUList.
  5. ClearProjectsLinkLabel (TLinkLabel):
    • A link that clears the "recent projects" list.

2.2 Internal Data

  • The form tracks two main arrays:
    • RecentFileNames[0..7]: the actual file paths for up to 8 MRU items, displayed in ProjectsListView.
    • SampleFileNames[0..6]: the actual file paths for up to 7 sample models, displayed in SamplesListView.

2.3 Key Methods

  1. FormCreate

    • Calls LoadRecentProjects to populate ProjectsListView from MRUList.
    • Calls LoadSampleProjects to populate SamplesListView from known sample files in the user’s Documents folder.
    • Adjusts visibility of "Clear recent projects" link or a label stating "No recent projects."
  2. LoadRecentProjects

    • Reads SWMM’s global MRUList, checks each file for existence, and if found, adds it to ProjectsListView, storing the path in RecentFileNames[...].
    • Hides the list and shows a label if no projects exist.
  3. LoadSampleProjects

    • Defines several example files (like “Detention_Pond_Model.inp”) plus their descriptive captions.
    • Looks in Documents\EPA SWMM Projects\Samples for these files.
    • If found, adds them to SamplesListView, storing the path in SampleFileNames[...].
    • Also adds an item “OpenSwmm.org Examples” that opens a web link if selected.
  4. GetStartedListViewSelectItem / DevelopListViewSelectItem / SamplesListViewSelectItem / ProjectsListViewSelectItem

    • Each ListView’s OnSelectItem event. When a user clicks an item, the form sets its ModalResult to a special integer code (like “saLoadSample” or “saLoadRecent”) or opens a web link for further examples. The main program sees the modal result and decides how to proceed.
  5. ClearProjectsLinkLabelLinkClick

    • Clears the MRUList and the ProjectsListView, updating the UI to reflect no recent projects.
  6. CloseButtonClick

    • Closes the form with “no action” result.

3. Interaction Flow

  1. SWMM starts up and sees the "Show welcome form at startup" preference is true.
  2. TWelcomeForm is shown, listing:
    • GetStarted items (open tutorial, user guide),
    • Samples items (example projects),
    • Develop items (create new project, open existing project),
    • Recent items (list of up to 8 last opened projects).
  3. The user clicks a relevant item, e.g., a recent project. The form sets ModalResult := saLoadRecent, plus sets SelectedFile to the path. Then the form closes.
  4. SWMM sees that result, loads the specified file or performs the indicated action.

4. Summary

Dwelcome.pas provides a “Welcome Screen” that SWMM displays at startup, letting the user quickly open recent or sample projects or navigate to tutorials and user guides. The design includes:

  • ListViews for “Get Started,” “Develop,” “Samples,” and “Recent Projects,” each returning a code that the main application interprets to take an action,
  • A checkbox controlling if this welcome screen should appear on subsequent launches,
  • A link to clear the recent project history.

Thus, it helps new and returning users rapidly get started with SWMM or jump into a recent or sample project.

SWMM5 Delphi GUI Dtseries.pas Summary

 Below is an overview of Dtseries.pas, a Delphi unit from SWMM 5.2 that implements a form (TTimeseriesForm) for defining and editing time series objects within SWMM. A time series in SWMM is a series of (date/time, value) pairs, often used for external inflows, rainfall data, or other model input signals that vary over time.


1. Purpose and Context

In SWMM, a time series can be referenced by nodes, subcatchments, or other elements to provide varying input data (e.g. inflow over time, tidal data, control rules, etc.). The TTimeseriesForm dialog allows the user to:

  1. Specify a unique name for the time series.
  2. Include an optional comment describing its purpose.
  3. Supply the data in two ways:
    • Directly through a table of date/time/value entries,
    • Externally via a file path to a file containing these data.
  4. Optionally preview the time series data on a quick plot to ensure correct ordering and formatting.

Once the user finalizes changes, the time series data are stored in a TTimeseries object in SWMM’s project data structure, enabling it to be used wherever time-varying data are needed in the model.


2. Main Form: TTimeseriesForm

2.1 Key Controls

  1. SeriesName (TEdit):

    • Holds the time series’ name (unique ID in SWMM).
  2. Comment (TEdit):

    • A short, optional description of the series.
  3. GridEdit (TGridEditFrame):

    • Allows direct entry of rows of date, time, value in the StringGrid.
    • Up to 1000 rows (though the Grid is sized for a maximum of 1000).
    • Each row has three columns: date, time, numeric value.
  4. UseFileCheckBox / UseTableCheckBox:

    • Indicate if the user is specifying the time series from:
      • An external file (UseFileCheckBox = True),
      • The table in the grid (UseTableCheckBox = True).
  5. FileNameEdit / FindFileBtn:

    • The file path to an external data file containing the time series, and a browse button to open a file dialog.
  6. BtnView:

    • Launches a quick preview plot of the table-based data in a TPreviewPlotForm.
  7. Buttons:

    • OK: Validates and finalizes data.
    • Cancel: Discards changes.
    • Help: Opens context help about time series.
    • Edit: Opens a comment editor for the time series description.

3. Data Flow

3.1 SetData(Index, S, aSeries)

  • Called to load existing data for a time series:
    1. SeriesIndex := Index (the position in SWMM’s TIMESERIES list).
    2. SeriesName.Text := S (the time series’ name).
    3. Comment.Text := aSeries.Comment.
    4. If aSeries.Filename is non-empty, the user is using an external file.
      • FileNameEdit.Text := aSeries.Filename.
      • UseFileCheckBox.Checked := True.
      • Disables the grid entry (GridEdit.Enabled := False).
    5. Otherwise, it populates GridEdit.Grid from the Dates, Times, and Values lists in aSeries.

3.2 GetData(S, aSeries)

  • Called when the user presses OK to finalize changes:
    1. S := SeriesName.Text to hold the final time series name.
    2. aSeries.Comment := Comment.Text.
    3. If using an external file, store aSeries.Filename. Clear its table-based data lists.
    4. If using a table:
      • Clear aSeries.Filename.
      • Copy each row from GridEdit.Grid into aSeries.Dates, Times, and Values.

3.3 BtnOKClick / ValidateData

  • Checks that:
    1. Time series name is not empty and not a duplicate among Project.Lists[TIMESERIES].
    2. If using a file, that file actually exists.
    3. The user’s date/time entries in the grid are in ascending chronological order (the TimeOrdered check).
    4. The numeric values are valid numbers.

If any check fails, the form does not close and displays an error.

3.4 BtnViewClick (Preview Plot)

  • If the user is using the table-based approach (not an external file), it creates a TPreviewPlotForm, calls PlotTimeSeries(GridEdit.Grid, “Time Series <Name>”, D0), where D0 is the project’s start date.
  • The plot uses the table's date/time to create an X-axis, and the numeric values as Y-axis points.

3.5 UseFileCheckBoxClick / UseTableCheckBoxClick

  • Toggles between external file usage and direct table usage.
  • Disables or enables the relevant controls accordingly.

4. Additional Features

  • Edit button calls a generic comment editor to allow multi-line editing of the time series’ Comment.
  • Name field disallows special characters like ' ', '"', ';', '[' (for the first character).
  • The GridEdit control supports row insertion and numeric input style.

5. Summary

Dtseries.pas provides a user-friendly UI for managing SWMM’s time series objects. Whether referencing a plain text file or manually entering date/time/value rows in a grid, the form ensures:

  1. A valid, unique time series name.
  2. Optionally a comment.
  3. Validated date/time entries in ascending order.
  4. Quick plot preview to confirm correct data ordering.

This data is stored in a TTimeseries object, used throughout SWMM (e.g., for inflows, rainfall, controls, etc.).

SWMM5 Delphi GUI Dtsect.pas Summary

 Below is an overview of Dtsect.pas, a Delphi unit from SWMM 5.2 that provides a form (TTransectForm) for editing the geometry of a natural channel cross-section (a “transect”). In SWMM, a transect is a set of station-elevation data plus related parameters (roughness, bank stations, scale factors) that define how water flows in an irregular open channel.


1. Purpose and Context

A transect in SWMM is typically used to model natural channels or irregular open channels. The TTransectForm lets a user:

  1. Enter a unique name for the transect.
  2. Provide descriptive text (an optional comment).
  3. Specify Manning’s roughness for the left bank, right bank, and channel.
  4. Provide station values for the left and right banks, plus scale factors for horizontal and vertical dimensions.
  5. Input the station-elevation data pairs that define the cross section shape.

Once the user is done, the form stores these parameters into a TTransect object, which SWMM uses to compute flow-area relationships during hydraulic routing.


2. Main Form: TTransectForm

2.1 Key Controls

  1. NameEdit / CommentEdit:

    • The user can set the transect’s ID and an optional comment describing it.
  2. PropEdit1 (TPropEdit):

    • A custom property editor on the right side of the form that displays a list of property labels (e.g., “Roughness,” “Bank Stations,” “Modifiers”) and their values.
    • Specifically, these are arranged in headings and numeric fields for:
      • Left Bank N / Right Bank N / Channel N
      • Left Bank Station / Right Bank Station
      • Station Factor / Elevation Factor / Meander Factor (if any).
  3. GridEdit:

    • A TGridEditFrame that allows the user to enter station-elevation pairs describing the cross-section shape.
    • Each row has columns: row index, station (horizontal coordinate), elevation (vertical coordinate).
    • The user can insert or delete rows. Typically the data must be in ascending order of station.
  4. Buttons:

    • OK: Finalizes changes (closing the form with mrOK) if the data passes validation.
    • Cancel: Closes form, discarding changes.
    • View: Opens a preview plot of the transect using TPreviewPlotForm.
    • Help: Opens context help for transects.
    • Edit: Launches a comment editor for the transect’s textual description.

3. Data Flow

3.1 SetData(I, S, Tsect)

  • Called to populate the form with an existing transect (index I, name S in Project.Lists[TRANSECT]).
  • Copies the transect’s parameters (roughness, bank stations, scale factors) into the PropList string list, displayed by PropEdit1.
  • Copies the station-elevation data from the transect’s Xdata and Ydata lists into the GridEdit.Grid rows.

3.2 GetData(S, Tsect)

  • After the user presses OK, extracts:
    • The new NameEdit.Text into S.
    • The parameters from PropList back into Tsect.Data[].
    • The station-elevation data from GridEdit.Grid into Tsect.Xdata and Tsect.Ydata.
  • Calls Tsect.SetMaxDepth, which recomputes the cross-section’s maximum depth from the input data.
  • If the name changed or the max depth changed, SWMM updates the TRANSECT object and any conduits using that transect.

3.3 Validation

  • ValidateData checks:
    1. Transect name is non-empty.
    2. The name is unique in Project.Lists[TRANSECT].
    3. The main channel roughness is not empty.
    4. The station-elevation data in the grid are valid numeric values and in ascending station order.
  • If any check fails, the form does not close and displays an error message.

3.4 Station-Elevation Grid

  • The user can input up to 1500 points in ascending station order. SWMM uses these points to define the shape of the cross section.
  • The grid has 3 columns: row index (hidden or just numbering?), station, elevation. The first row is a header row, so data starts at row 1.

3.5 View button

  • Creates a TPreviewPlotForm and calls PlotTransectData to show a quick preview of the cross-section shape. The function uses the station, elevation data plus the left and right bank station scale factors to produce a 2D chart.

4. Summary

Dtsect.pas implements the TTransectForm for editing a natural channel cross-section in SWMM. It includes:

  • Text fields for name and comment.
  • A property editor (PropEdit1) to configure roughness values, bank station definitions, and scale factors.
  • A grid (GridEdit) to input the station-elevation pairs describing the channel shape.
  • A View button to preview the cross-section shape in a separate plotting form.
  • Basic validation of user inputs (non-empty name, unique ID, correct station ordering).

The final data is stored into a TTransect object, used by SWMM’s hydraulic engine to compute flow area, top width, etc., in the irregular channel.

SWMM5 Delphi GUI Dtreat.pas Summary

 Below is an overview of Dtreat.pas, a Delphi unit from SWMM 5.2 that implements a dialog form (TTreatmentForm) for editing pollutant treatment expressions at a drainage system node. These expressions determine how pollutants are removed or altered at the node (e.g., the fractional removal 

RR or the outlet concentration CC) based on inflow pollutant levels and flow/process variables.


1. Purpose and Context

In SWMM, you can define treatment expressions at any node (junction, storage, or divider). These specify how pollutants are removed or transformed, such as:

  • A fractional removal RR that depends on flow, HRT (hydraulic residence time), or other pollutant concentrations.
  • An outlet concentration CC that is a function of inflow concentration and other variables.

The TTreatmentForm lets the user directly enter these expressions for each pollutant. SWMM then applies them during the water quality routing stage.


2. Main Form: TTreatmentForm

2.1 Visual Components

  1. Grid (TStringGrid):

    • Two columns: Pollutant (read-only) and Treatment Expression (editable).
    • Rows correspond to each pollutant in the project. For row i+1i+1, Cells[0, i+1] is the pollutant’s name, and Cells[1, i+1] is the user’s expression for that pollutant.
  2. HintMemo:

    • A memo panel that displays usage hints for writing expressions (for instance, showing the allowable process variables, example formulas, etc.).
  3. OKBtn, CancelBtn, HelpBtn:

    • Standard form actions. When the user clicks OK, the form returns with the updated treatment expressions.
  4. Splitter1:

    • Allows resizing between the HintMemo and the Grid.

2.2 Data Flow

  • Each node in SWMM’s Project has a Treatment string list. The user’s expressions are stored with the format "pollutantName=expression" for each pollutant that has a treatment expression.
  • SetData is called to load the existing expressions for each pollutant into the grid.
  • GetData is called to save any updated expressions from the grid back into the node’s Treatment list.

3. Key Methods

3.1 FormCreate

  • Initializes the hint memo with a multi-line string describing how to write treatment expressions (variables, example expressions, etc.).
  • Configures the grid:
    • The top row (row 0) has headers for “Pollutant” and “Treatment Expression.”
    • Additional rows (1..N) are for each pollutant in the project.

3.2 SetData(NodeType, NodeIndex)

  1. Finds the node from Project.GetNode(NodeType, NodeIndex).
  2. Sets the form’s caption to something like "Treatment Editor for Node [ID]".
  3. Fills row i+1i+1 in the grid with the pollutant name and the node’s existing expression for that pollutant, if any (taken from aNode.Treatment.ValueFromIndex[...]).

3.3 GetData(NodeType, NodeIndex)

  • Retrieves the updated expressions from the grid:
    • For each row i+1i+1, if Cells[1,i+1] is non-empty, it forms a string "pollutantName=expression" and adds it to aNode.Treatment. Otherwise, it is ignored.
  • This overwrites the node’s old Treatment list with the new one.

3.4 GridSetEditText

  • Whenever the user edits a cell, HasChanged := True, marking that changes have been made.

3.5 OKBtnClick

  • If the user is done, sets ModalResult := mrOK, letting GetData be called externally to finalize the changes.

3.6 HelpBtnClick

  • Launches a help topic about treatment expressions.

4. Expression Syntax

From the hints, the user can write:

  1. Removal expression: R = <some function>
    • E.g. R = 0.75 * R_TSS means the fractional removal of the pollutant is 0.75 times the removal fraction of TSS.
  2. Concentration expression: C = <some function>
    • E.g. C = BOD * exp(-0.05*HRT) means the outflow BOD concentration is the inflow BOD times an exponential decay based on HRT.
  3. The user can reference:
    • Other pollutant names
    • R_X for the fractional removal of pollutant X
    • Flow variables (FLOW, DEPTH, HRT, DT, AREA)

5. Summary

Dtreat.pas’s TTreatmentForm is a specialized UI for specifying pollutant treatment at a SWMM node:

  • Displaying each pollutant in a row,
  • Allowing an expression for fractional removal or outflow concentration,
  • Storing them in the node’s Treatment list,
  • Used by SWMM’s water quality model to reduce or transform pollutant loads based on the user-defined formula.

SWMM5 Delphi GUI Dtools1.pas Summary

 Below is an overview of Dtools1.pas, a Delphi unit from SWMM 5.2 that provides a TToolOptionsForm dialog for managing add-on tools in SWMM. These custom tools are user-specified external programs or commands that can be launched directly from SWMM’s main menu under “Tools.”


1. Purpose and Context

SWMM allows users to integrate third-party or custom external tools (e.g., text editors, GIS software, or specialized analysis programs) into the interface. The TToolOptionsForm presents a list of these tools, letting the user add, edit, delete, or reorder them. The final list of tools is stored in Utools.ToolList, which SWMM references to populate the Tools menu in the main form.


2. Main Form: TToolOptionsForm

2.1 Visual Components

  1. ToolsListBox: A list displaying the names of the currently configured tools.
  2. AddBtn, DeleteBtn, EditBtn: Buttons for adding a new tool, removing the selected tool, or editing the properties of the selected tool.
  3. MoveUpBtn / MoveDownBtn: TBitButtons that reorder the list by moving the selected tool up or down.
  4. CloseBtn, HelpBtn: Standard close and help actions.

2.2 Internal Logic

  • FormCreate:

    • Populates ToolsListBox.Items from Utools.ToolList.
    • Sets the currently selected item (if any) to index 0.
    • Loads up/down arrow glyphs for the move buttons from the main form’s image list.
    • Calls EnableBtns to adjust button states (Edit, Delete, MoveUp, MoveDown) depending on whether any items exist.
  • EnableBtns:

    • Disables or enables the Edit, Delete, MoveUp, MoveDown buttons if ToolsListBox.Items.Count = 0 or not.
  • AddBtnClick:

    • Creates a TToolPropertiesForm (from Dtools2.pas presumably) to let the user define a new tool.
    • Calls LoadTool(-1) meaning it loads a “new” blank tool.
    • If the dialog returns OK, it calls GetToolName from that form and adds it to ToolsListBox (and presumably Utools.ToolList).
  • DeleteBtnClick:

    • Gets the selected index, calls Utools.DeleteTool(I), and removes the tool from ToolsListBox.
    • Adjusts the selected index and calls EnableBtns.
  • EditBtnClick:

    • Gets the selected index in ToolsListBox.
    • Creates a TToolPropertiesForm, calls LoadTool(I) to load that tool’s properties, and if the user saves changes, updates that entry in ToolsListBox to the new name returned by GetToolName.
  • MoveUpBtnClick / MoveDownBtnClick:

    • Exchanges tools in Utools.ToolList via Utools.ExchangeTools(I, I-1) or Utools.ExchangeTools(I, I+1).
    • Refreshes ToolsListBox from the updated Utools.ToolList and sets the selected item to the new position.
  • HelpBtnClick:

    • Displays a help topic (HELP_CONTEXT, 213160).

3. Relationship to Other Units

  • Utools:

    • Maintains the global ToolList of external tools, each presumably with fields for name, command line, optional arguments, etc.
    • Exposes methods like DeleteTool(I) or ExchangeTools(I, J) to manipulate the list.
  • DTools2:

    • Contains TToolPropertiesForm, the dialog for defining or editing a single tool’s properties (name, command path, arguments, etc.).
  • Fmain:

    • The main form that references the tools in ToolList to populate the “Tools” menu dynamically.

4. Summary

Dtools1.pas is a straightforward form providing a user-friendly interface to manage additional external tools in SWMM. Each tool is represented by a name (and presumably a command line). The form supports:

  • Addition of a new tool (launching a separate form to gather the tool’s properties).
  • Deletion of an existing tool.
  • Editing the properties of a selected tool.
  • Reordering the list of tools (up/down).

Ultimately, this helps build the Tools menu in SWMM’s main form, so that the user can quickly launch external tools from within SWMM.

SWMM5 Delphi GUI Dtimeplot.pas Summary

 Below is an overview of Dtimeplot.pas, a Delphi unit from SWMM 5.2 that provides the TTimePlotForm dialog for setting up time series plots of simulation results. Users can specify multiple data series, each representing a particular object-variable combination (e.g., flow in a link, water depth at a node, runoff from a subcatchment, etc.), along with additional options like date range and axis settings. When the user is done, SWMM will generate the requested time series plot using the specified configurations.


1. Purpose and Context

In SWMM, a time series plot displays how a certain parameter (flow, depth, pollutant concentration, rainfall, etc.) evolves over time. The TTimePlotForm allows users to select:

  • Which objects (subcatchments, nodes, links, or the entire system).
  • Which variables (e.g., water depth, flow, pollutant).
  • **Whether to use elapsed or actual date/time on the X-axis.
  • The time window (start and end date/time).
  • Number of data series (up to six) in one combined plot, each assigned to either the left or right Y-axis.

When the user hits OK, the form sets up a TReportSelection structure that describes the items to plot, then calls MainForm.CreateReport(ReportSelection) to produce the time series plot.


2. Main Form: TTimePlotForm

2.1 Pages and Controls

  1. PageControl1 with two TabSheet pages:

    • TabSheet1 ("Data Series Selection"): Lists the data series to be plotted. The user can add or delete series, or move them up or down (changing the order in the plot's legend).
    • TabSheet2 ("Edit Data Series"): A page to specify which object is being plotted, which variable, and other details like axis assignment and legend label.
  2. Buttons:

    • Add (BtnAdd): Creates a new data series and switches to TabSheet2 to define it.
    • Edit (BtnEdit): Edits the currently selected series in TabSheet2.
    • Delete: Removes the currently selected series.
    • MoveUp / MoveDown: Reorders the data series in the list.
    • Accept: On TabSheet2, updates the series with the user’s input.
    • OK: Closes the form, finalizing the ReportSelection.
    • Cancel: Closes the form without changes.
    • Help: Brings up context help.
  3. SeriesListBox:

    • Lists each data series in textual form, typically: "[object type] [object ID] [variable name]".
  4. Object Type (ObjTypeCombo), Object Name (ObjNameEdit), Variable (VariableCombo):

    • The user chooses subcatchment/node/link/system and a variable.
    • If “System” is chosen, no object name is needed.
    • ObjNameEdit can be filled automatically from the currently selected object in SWMM’s data browser, via SetObject() or AddSelectedObject().
  5. Time range:

    • StartDateCombo1 / EndDateCombo1: The user picks which date/time indices from the simulation to start and stop the plot.
    • ElapsedTimeBtn or DateTimeBtn: Chooses whether to label the X-axis in elapsed hours or actual date/time.
  6. LeftAxisBtn / RightAxisBtn:

    • Decides if the series is assigned to the left or right Y-axis.
  7. LegendLabelEdit:

    • The user’s custom label for the data series in the plot’s legend (optional).

3. Data Structures

3.1 TReportSelection

  • A SWMM structure that describes how to build a plot or table. For time-series plots:
    1. ReportType := TIMESERIESPLOT.
    2. StartDateIndex, EndDateIndex: the user’s chosen date/time period.
    3. DateTimeDisplay: if True uses date/time on X-axis, otherwise uses elapsed time.
    4. Items: a list of data series descriptions (strings).
    5. ItemCount: how many data series.
    6. VariableCount: same as ItemCount for time series.
    7. Each data series is in ReportItems[], containing object type, object name, variable index, axis assignment, and an optional legend label.

3.2 The Relationship to SWMM’s Data

  • ObjTypeCombo.ItemIndex corresponds to SUBCATCHMENTS=0, NODES=1, LINKS=2, SYS=3.
  • For subcatchments, node or link variables, the Variable is adjusted by offset indices (SUBCATCHOUTVAR1, NODEOUTVAR1, LINKOUTVAR1, or SYSOUTVAR1) in the final step (OkBtnClick).
  • The user picks the date/time combos from MainForm.DateListBox.

4. Workflow

  1. Setup: Called to initialize the time range combos (StartDateCombo1, EndDateCombo1) and to set the check for elapsed vs. date/time axis.
  2. Add: Switches from TabSheet1 to TabSheet2, clearing the details for a new data series, optionally pulling in the user’s currently selected SWMM object from the data browser (AddSelectedObject).
  3. Edit: The user picks an existing series in SeriesListBox, the form loads its details into TabSheet2 for editing.
  4. Accept: The user finalizes the new or edited series data (object type, name, variable, axis, legend text). This updates SeriesListBox with a textual description, and updates an internal ReportSelection.ReportItems[SeriesIndex].
  5. OK: The user finalizes the entire plot. The form sets ReportType = TIMESERIESPLOT, date/time indices, DateTimeDisplay, ItemCount, and calls MainForm.CreateReport(ReportSelection).

5. Validation

  • If the user picks a non-system object type but the specified object name doesn’t exist in the project, an error message is shown (“There is no such object in your project.”).
  • The user can only have up to 6 data series.
  • The date/time combos must have StartDateIndex <= EndDateIndex.

6. Summary

Dtimeplot.pas provides TTimePlotForm, a specialized interface for building multi-series time series plots in SWMM. It allows the user to specify multiple object-variable pairs, their date/time coverage, and how they appear in the final plot (axis assignment, legend label, etc.). This ensures a flexible, user-friendly approach to visualizing simulation results over time.

SWMM5 Delphi GUI Dsummary.pas Summary

 Below is an overview of Dsummary.pas, a Delphi unit from SWMM 5.2 that implements a dialog form (TProjectSummaryForm) for summarizing the number of various object types in the current SWMM project. This summary is displayed in a TStringGrid on the form.


1. Purpose and Context

SWMM models contain many different object types:

  • Raingages, Subcatchments, Aquifers, Snowpacks, Hydrographs
  • Node objects (Junctions, Outfalls, Dividers, Storage Units)
  • Link objects (Conduits, Pumps, Orifices, Weirs, Outlets)
  • Controls, Pollutants, Land Uses
  • Special inflows (Time Series, Dry Weather, Groundwater, RDII)
  • LID Controls
  • Treatment Units

The TProjectSummaryForm displays a count of each of these object types currently in the project. It also reveals which infiltration model is used, and what flow units / routing method are selected. This is a quick, top-level summary for the entire project.


2. Main Form: TProjectSummaryForm

2.1 Primary Controls

  1. StringGrid1: The grid where the summary is displayed. Each row corresponds to a particular type of SWMM object or property. The first column of the grid holds a text label, and the second column holds the corresponding count or value.

  2. Constants: The form references a string array S containing 26 items, each one describing an object type or model option (e.g., "Raingages", "Subcatchments", "Routing Model", "Dry Weather Inflows", etc.).

  3. Internal Counters:

    • TSFcount: The number of time series inflow nodes
    • DWFcount: The number of dry weather inflow nodes
    • GWFcount: The number of groundwater inflow nodes
    • IIFcount: The number of RDII inflow nodes
    • TUcount: The number of treatment nodes
    • LIDcount: The number of LID controls across all subcatchments

3. Data Flow

3.1 FormCreate

  • The code sets RowCount in StringGrid1 to the number of summary rows (26 in the S array).
  • Populates the first column (Cells[0,I]) with the text from the S array.
  • For object categories that exist in Project.Lists[...] (like raingages, subcatchments, etc.), it writes Cells[1,X] with the count from Project.Lists[X].Count.
  • For infiltration model name and flow units or routing method, it uses data from Project.Options.Data[...].
  • Calls GetInflowsCount() to fill counters for time series inflows, DWF, RDII, etc.

3.2 GetInflowsCount

  • Loops through subcatchments to find:
    • Subcatchments with groundwater defined (GWFcount).
    • Summation of LID usage across subcatchments (LIDcount).
  • Loops through node types (junctions, storage units, etc.) to see if a node has:
    • Direct external inflow (TSFcount),
    • Dry weather inflow (DWFcount),
    • RDII inflow (IIFcount),
    • Treatment definitions (TUcount).
  • Calls UpdateNodePropertyCount(N: TNode) for each node to update these counters.

3.3 UpdateNodePropertyCount

  • If N.DXInflow.Count > 0, increments TSFcount.
  • If N.DWInflow.Count > 0, increments DWFcount.
  • If N.IIInflow.Count > 0, increments IIFcount.
  • If N.Treatment.Count > 0, increments TUcount.

3.4 Display in StringGrid1

After these counters are computed, the form writes them to the cells:

Cells[1,20] := IntToStr(TSFcount);   // Time Series Inflows
Cells[1,21] := IntToStr(DWFcount);   // Dry Weather Inflows
Cells[1,22] := IntToStr(GWFcount);   // Groundwater Inflows
Cells[1,23] := IntToStr(IIFcount);   // RDII Inflows
Cells[1,24] := IntToStr(LIDcount);   // LID Controls
Cells[1,25] := IntToStr(TUcount);    // Treatment Units

4. Additional UI Behavior

  • The form’s OnKeyDown closes the form when Esc is pressed.
  • It’s read-only: user can’t edit these counts, just observe them.

5. Summary

Dsummary.pas provides TProjectSummaryForm, a small read-only dialog listing how many of each object type the SWMM project contains, plus some global model settings (flow units, infiltration model, etc.). This helps the user get a quick “inventory” of the model’s objects. It also calculates the number of special inflow or LID usage conditions that exist, ensuring the user is aware of all inflow sources and controls in the model.

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...