Sunday, December 29, 2024

SWMM5 Delphi GUI Dsubland.pas Summary

 Below is an overview of Dsubland.pas, a Delphi unit from SWMM 5.2 that implements a SubLandUsesForm dialog. This dialog is used to edit how land uses are distributed within a subcatchment. In SWMM, a subcatchment can be allocated among different land uses (e.g., residential, commercial, industrial) that have distinct buildup/washoff parameters for pollutants. The TSubLandUsesForm allows the user to specify what percentage of the subcatchment’s area each land use occupies.


1. Purpose and Context

SWMM can model nonpoint source pollutant buildup/washoff using land use objects. Each Subcatchment can contain a mix of multiple land uses (for instance, 30% residential, 70% commercial). The TSubLandUsesForm helps the user assign these percentages:

  • The user sees a list of land uses (one per row).
  • For each land use, the user enters the percent of subcatchment area occupied by that land use.

These allocations can sum to 100%. During simulation, pollutant buildup/washoff rates are scaled by these percentages.


2. Main Form: TSubLandUsesForm

2.1 Visual Components

  1. PropEdit1 (TPropEdit):
    • A custom property editor placed on Panel1.
    • The editor has two columns:
      • Property (the land use name)
      • Value (the percent of subcatchment area).
  2. PropList (TStringList):
    • Holds the values (the percentages) for each land use row.
  3. OKBtn, CancelBtn, HelpBtn:
    • Standard form action buttons at the bottom.

2.2 Data Organization

  • LanduseCount / PropCount: the number of land uses in the project.
  • Each row in PropEdit1 corresponds to one land use.
  • The name (land use) is shown in the first column, the user’s input (percentage) in the second column.
  • The string list PropList holds these percentage values in the same order the land uses appear in Project.Lists[LANDUSE].

3. Key Methods and Events

3.1 FormCreate

  1. Sets up the PropEdit1 with column headings (“Land Use,” “% of Area”).
  2. Allocates an array of TPropRecord (PropRecd) to match the number of land uses in the project.
  3. For each land use name in Project.Lists[LANDUSE], it sets:
    • PropRecd[i].Name to the land use name,
    • PropRecd[i].Style := esEdit,
    • PropRecd[i].Mask := emPosNumber (ensuring only numeric input for the percent).

3.2 SetData(LandUses)

  • Called externally to load an existing distribution of land use areas for a subcatchment.
  • Each entry in the LandUses string list has the format: landuseName=percentValue.
  • For each land use in the entire project, it checks if it appears in LandUses. If it does, the matching percentage is appended to PropList; if not, it appends an empty string (“”).

3.3 GetData(LandUses, Count)

  • After the user presses OK, the form calls GetData to store the final distribution:
    1. Clears LandUses.
    2. Walks through each row in PropList.
    3. Converts the string to a float (P).
    4. If P > 0, it adds landuseName=P to the LandUses list, increments Count.
  • This results in a list of land uses with nonzero percent allocations.

3.4 OKBtnClick

  • The user’s final step.
  • Calls:
    1. PropEdit1.IsValid (ensuring no invalid numeric inputs).
    2. ValidateInput:
      • Sums all percentages. If they exceed 101%, shows an error (“Percentages exceed 100%.“).
      • If OK, ModalResult := mrOK.

3.5 ValidateInput

  • Gathers each line in PropList, parses it as a float, sums the values.
  • If the sum > 101, returns an error. (The 101% threshold accounts for rounding error in user input.)

4. Usage Example

  1. A subcatchment has land uses: Residential, Commercial, Open Space.
  2. The user calls SetData(LandUses) where LandUses might have lines like Residential=25 and Commercial=50 for the existing configuration.
  3. The form displays three rows in PropEdit1: “Residential,” “Commercial,” “Open Space.” The first two have “25,” “50” and the third is blank.
  4. The user changes values—maybe sets “Residential=30,” “Commercial=50,” “Open Space=20.” The sum is 100%.
  5. On OK, GetData(LandUses, Count) returns these final lines, and Count=3.

5. Summary

Dsubland.pas provides a simple TSubLandUsesForm dialog to let users specify or edit percentage allocations of land uses within a subcatchment:

  • The form displays all land uses in the model (one row each),
  • The user enters a percentage for each relevant land use,
  • The form ensures the sum does not exceed 101%,
  • The final data are stored in a string list for the subcatchment’s land uses.

This helps SWMM track which portion of the subcatchment belongs to which land use categories, crucial for pollutant buildup/washoff modeling.

SWMM5 Delphi GUI Dstreet.pas Summary

 Below is an overview of Dstreet.pas, a Delphi unit from SWMM 5.2 that provides a TStreetEditorForm dialog. This dialog is used to define or edit the street cross-section geometry for a Street object in SWMM.


1. Purpose and Context

Certain model implementations of SWMM include the concept of a Street object—essentially, a cross-section that describes how street flow is conveyed along curbs or gutters. The TStreetEditorForm allows the user to:

  1. Provide geometric parameters (e.g., curb height, gutter slope, street width).
  2. Specify whether there is 1 side or 2 sides to the street section for flow accumulation.
  3. Accept a name (unique ID) for the street cross-section.

Once the user finalizes this data and presses OK, the form transfers the updated parameters back into the TStreet object for use during flow routing computations in SWMM.


2. Main Form: TStreetEditorForm

2.1 Key Fields and Controls

  1. NameEdit:

    • A TNumEdit control for the Street object’s name. Must be non-empty and not duplicate an existing street name in the project.
  2. NumEdit0..NumEdit9:

    • Numeric fields where each parameter is stored, e.g.:
      • NumEdit0: Possibly the roadway cross slope.
      • NumEdit1: Maybe curb height, or some other dimension.
      • And so forth up through NumEdit9.
    • Each is a TNumEdit ensuring numeric input.
  3. RadioButton1 / RadioButton2:

    • Indicate if the street cross-section has 1 side or 2 sides for flow.
  4. OkBtn / CancelBtn / HelpBtn:

    • Standard form actions.
  5. Image1:

    • A visual icon associated with the form (from an image list).

2.2 Data in SWMM

A TStreet object might have a Data[] array with indices up to MAXSTREETPROPS. Each Data[J] corresponds to a particular street geometry parameter, such as:

  • STREET_SLOPE
  • STREET_CURB_HEIGHT
  • STREET_GUTTER_SLOPE
  • STREET_WIDTH
  • Possibly up to 10 parameters total, stored in NumEdit0..NumEdit9.
  • STREET_SIDES indicating if 1 or 2 sides are present (RadioButton1 or RadioButton2).

When the user is done editing:

  • The code updates aStreet.Data[STREET_SIDES] to "1" if one side, or "2" if both sides.
  • Other numeric fields are read from NumEditX.Text.

2.3 Key Methods and Events

  1. FormCreate

    • Sets up the form, applying units (feet or meters) to labels and loading an icon into Image1.
  2. SetData(I, S, aStreet)

    • Called to load the street’s data into the form:
      • StreetIndex = I (the index in the project’s STREET list).
      • NameEdit.Text = S (the street’s name).
      • Each NumEditX is set to the corresponding aStreet.Data[X].
      • RadioButton1 checked if aStreet.Data[STREET_SIDES] = '1' otherwise RadioButton2.
  3. GetData(S, aStreet)

    • Retrieves user input from NameEdit and the numeric edits, storing them in the aStreet.Data[] array.
    • Sets S to the street’s name, and updates the side count in STREET_SIDES.
  4. Button1Click (OKBtn)

    • Validates:
      • Street name is non-empty and unique.
      • All required numeric fields are present and nonzero.
    • If valid, ModalResult := mrOK, otherwise an error message is shown.
  5. NameEditKeyPress

    • Prevents the user from beginning the name with '[ ' (ensuring it doesn’t conflict with SWMM input format sections).
  6. Modified Flag

    • Set to true whenever user changes something (like NameEditChange).
    • Helps SWMM track unsaved changes.
  7. FormKeyDown

    • Launches help if F1 is pressed.
  8. Button3Click (HelpBtn)

    • Invokes SWMM’s context help for street cross-section editing.

3. Data Flow

  1. SetData is called, the form loads the existing TStreet.Data[] properties (like slope, width, etc.) into NumEditX fields, sets name in NameEdit.
  2. The user modifies the fields and chooses either OK or Cancel.
  3. OKBtnClick checks for valid name, duplicates, and numeric fields.
  4. If valid, GetData writes back into the TStreet object (Street.Data[X]), including if it has 1 or 2 sides.
  5. The form closes with mrOK.

4. Summary

Dstreet.pas provides a specialized form (TStreetEditorForm) that ensures each Street cross-section has the correct geometry (width, curb/gutter dimensions, slope, etc.) and is named uniquely. By collecting numeric inputs in NumEditX fields and toggling a one- vs. two-sided design, the user can properly define how water flows in the street segment. The code handles basic validation (non-empty name, no duplicates, numeric parameters not zero). The result is used by SWMM in advanced street flow modeling or gutter flow calculations.

SWMM5 Delphi GUI Dstorage.pas, Summary

 Below is an overview of Dstorage.pas, a Delphi unit from SWMM 5.2 that provides a StorageForm dialog for specifying the geometry of a storage unit node in SWMM. Storage units can have their surface area defined in different ways (functional, tabular, or shapes like cylindrical, conical, paraboloid, or pyramidal). These shapes control how surface area and volume vary with depth in the node.


1. Purpose and Context

In SWMM, storage units are nodes that hold water with a known area-depth or volume-depth relationship. The TStorageForm allows the user to choose one of several geometry options and provide parameters—either as simple numeric coefficients (functional shapes), direct tabular data (storage curves), or shape-based parameters. Once the user finishes, the data are stored back into the node’s Data[] array for use in hydraulic simulations.


2. Main Form: TStorageForm

2.1 Visual Components

  1. ListView1: A list of possible storage shapes:
    • 0: Elliptical or Circular Cylinder (Cylindrical)
    • 1: Truncated Elliptical Cone (Conical)
    • 2: Elliptical Paraboloid (Parabolic)
    • 3: Rectangular Pyramid/Box (Pyramidal)
    • 4: Functional (defined by a functional relationship)
    • 5: Tabular (defined by a named curve)
  2. CardPanel1 with separate Card pages for each geometry approach:
    • ShapeCard: For the first four items (cylindrical, conical, etc.), three numeric parameters (ParamEdit1..3) plus descriptions/labels.
    • FunctionalCard: For a functional shape (FuncEdit1..3).
    • TabularCard: Has a combo box (ComboBox1) to pick a storage curve from the project.
    • VolumeCard: A page for Area/Volume display at a given depth (DepthNumEdit).
  3. CalcLinkLabel (e.g., “Show Volume Calculator” or “Show Shape Selection”): Toggling between the shape parameters view and an interactive “calculator” view for area/volume at a user-specified depth.
  4. EditBitBtn: Launches the time series/curve editor to modify the chosen storage curve.
  5. OkBtn, CancelBtn, HelpBtn: Standard dialog actions.

2.2 Data Storage

SWMM uses string arrays (like Data[]) to store a node’s storage parameters:

  • Data[STORAGE_GEOMETRY_INDEX] : string indicating geometry type (CYLINDRICAL, CONICAL, PARABOLIC, PYRAMIDAL, FUNCTIONAL, TABULAR).
  • Data[STORAGE_COEFF0_INDEX], [STORAGE_COEFF1_INDEX], [STORAGE_COEFF2_INDEX]: numeric parameters describing the shape.
  • Data[STORAGE_ATABLE_INDEX]: name of a storage curve (if shape is TABULAR).

When the user chooses a shape and inputs parameters, these are eventually written back into Data[].


3. Workflow

3.1 SetData(Data[])

  • Called to populate the form’s controls with existing storage parameters from Data[].
  • If Data[STORAGE_GEOMETRY_INDEX] = 'FUNCTIONAL', the form’s ListView1 is set to index 4, and FuncEdit1..3 are loaded.
  • If Data[STORAGE_GEOMETRY_INDEX] = 'TABULAR', the form’s ListView1 is set to index 5, and ComboBox1 is set to the storage curve name.
  • Otherwise, the form picks the correct shape index (0..3) and loads the numeric parameters (ParamEdit1..3).

3.2 GetData(Data[])

  • After user hits OK, the form gathers user inputs back into the Data[] array.
  • If the shape is Functional (ListView1.ItemIndex=4), sets Data[STORAGE_GEOMETRY_INDEX] = 'FUNCTIONAL' and the 3 coefficients.
  • If Tabular (=5), sets geometry to 'TABULAR' and Data[STORAGE_ATABLE_INDEX] to the chosen curve name.
  • Otherwise, picks 'CYLINDRICAL', 'CONICAL', 'PARABOLIC', or 'PYRAMIDAL' depending on item index 0..3, and places the numeric parameters into STORAGE_COEFF0..2_INDEX.

3.3 OkBtnClick

  • If the shape is Tabular and the user hasn’t selected a curve, an error is raised. Otherwise, the form’s ModalResult is set to mrOK.

3.4 CalcLinkLabel / VolumeCard

  • The user can click the link “Show Volume Calculator” to see how area and volume vary with depth for the chosen shape. This triggers the code to:
    1. Fill placeholders if any required fields are blank.
    2. Temporarily store the shape parameters in local variables (A0, A1, A2, etc.).
    3. Switch to the VolumeCard page.
    4. The user can then type a depth in DepthNumEdit and see the resulting area/volume.
  • If the user clicks the link again, the form switches back to the original shape card.

3.5 Volume/Area Calculation Logic

  • For a shape-based geometry (cylindrical, conical, etc.), it uses formulas for area AA and volume VV as a function of depth:
    • E.g., Cylinder: A=Ï€×L×W4A = \pi \times \frac{L \times W}{4}, V=A×DV = A \times D, etc.
    • E.g., Conical: area = Ï€LW/4+D()\pi L W/4 + D(\dots), volume = \dots.
  • For a Functional shape, area is A=a0+a1×Da2A = a_0 + a_1 \times D^{a_2}.
  • For a Tabular shape, the code retrieves a user-defined curve and does a piecewise linear interpolation to find area and integrates it for volume up to the given depth.

4. Summaries of Key Methods

  • FormCreate: Prepares the UI, sets default labels for US or SI units, loads shapes into ListView1, etc.
  • ListView1SelectItem: Switches the visible card (ShapeCard, FunctionalCard, TabularCard, etc.) based on the selected shape.
  • CalcLinkLabelLinkClick: Toggles between shape-parameter editing and volume display mode.
  • DepthNumEditChange: Whenever the user modifies the depth in the calculator, updates the displayed area/volume.
  • SetData: Loads from Data[] to the form.
  • GetData: Writes from the form to Data[].
  • OkBtnClick: Final validation; if something is missing for a tabular shape (no curve name), it rejects.

5. Summary

Dstorage.pas provides a flexible UI for storage unit geometry in SWMM. It supports:

  1. Shape-based (cylindrical, conical, parabolic, pyramidal),
  2. Functional (user-supplied equation for area vs. depth),
  3. Tabular (area-depth data from a named curve).

Users can preview the area/volume at any depth, ensuring correct geometry data for subsequent hydraulic modeling.

SWMM5 Delphi GUI Dstats.pas Summary

 Below is an overview of Dstats.pas, a Delphi unit from SWMM 5.2 that provides a stay-on-top form (TStatsSelectForm) for selecting statistical analyses of time series results at a particular location (e.g., a specific node, link, subcatchment, or the entire system). The resulting selections are collected into a TStatsSelection record (from Ustats.pas) and used by SWMM to generate a statistical report (in Fstats.pas).


1. Purpose and Context

SWMM can generate long-term statistical analyses (for example, annual or seasonal frequency stats) of a parameter like node flooding, link flow, or pollutant concentration. This form allows the user to specify:

  1. Which object to analyze (subcatchment, node, link, or entire system).
  2. Which variable (e.g., runoff, flow, depth, pollutant, etc.).
  3. Which analysis type (e.g., peak, mean, total, duration, etc.).
  4. Which time period (continuous vs. event-based)
  5. Additional parameters for event definition (e.g., minimum flow, volume, or time between events).

All these choices are summarized into a TStatsSelection structure. The user then clicks OK, and SWMM launches the TStatsReportForm (defined in Fstats.pas) to produce the final report.


2. Main Form: TStatsSelectForm

2.1 Key Controls

  1. ObjectTypeCombo (TComboBox): Chooses the object category—Subcatchments, Nodes, Links, or System.
  2. ObjectIDEdit: The ID (name) of the specific subcatch, node, or link to analyze. If System is chosen, no ID is needed.
  3. VariableCombo: Lists available output variables for the chosen object category (flow, infiltration, water depth, pollutant concentration, etc.).
  4. TimePeriodCombo: Selects between continuous stats (entire simulation) or event-based stats (identified by a min. event gap).
  5. StatsTypeCombo: Picks the type of statistic—Mean, Peak, Total, Duration, Inter-event time, or for water quality—Mean Concen, Total Load, etc.
  6. MinValueEdit, MinVolEdit, MinDeltaEdit: Numeric fields used if event-based analysis is chosen, specifying minimal thresholds (minimum value, minimum volume, and minimum inter-event time) that define an “event.”
  7. ObjectIDBtn: Fills ObjectIDEdit with the currently selected item from the data browser (if consistent with the chosen category).
  8. OK, Cancel, Help: Standard actions.

2.2 Internal Variables

  • StatsTypeIndex: Distinguishes which set of stats is available (basic vs. flow vs. quality).
  • TStatsSelection fields (filled upon OK):
    • ObjectType (subcatch, node, link, system)
    • ObjectID (string)
    • Variable (index of the chosen variable)
    • TimePeriod (continuous or event-based)
    • StatsType (e.g. stMean, stPeak, stTotal, etc.)
    • MinEventDelta / MinEventValue / MinEventVolume (numeric thresholds)

3. Workflow

3.1 FormCreate / FormShow

  • ObjectTypeCombo is set to whichever object category the user is currently viewing in the data browser, if any (subcatchment, node, or link).
  • VariableCombo is then populated with the relevant list of variables, e.g., if subcatchments are chosen, the combo includes subcatchment variables from MainForm.SubcatchViewBox.Items.
  • The form also sets default combos for time period, event-based threshold fields, etc.

3.2 ObjectTypeComboClick

  • When the user picks “Subcatchments,” “Nodes,” or “Links,” the code populates VariableCombo with the correct variable list. If “System,” a separate list of system-level variables is used.
  • If an object is currently selected in the data browser, that object’s ID is loaded into ObjectIDEdit.

3.3 VariableComboClick

  • Chooses the valid StatsTypeCombo items (mean, peak, total, etc.) for the selected variable. For instance, if a pollutant variable is chosen, “Mean Concen,” “Total Load,” etc., become valid.

3.4 TimePeriodComboClick

  • If event-based analysis is chosen, certain numeric fields (MinDeltaEdit) become enabled or disabled.

3.5 OKBtnClick

  1. Calls GetStatsSelection(Stats) to fill a local TStatsSelection.
  2. If valid (e.g., if an object is selected, date/time checks are valid, etc.), it hides the form and creates a TStatsReportForm.
  3. The TStatsReportForm.CreateReport(Stats) is called to generate the statistical analysis result.

3.6 GetStatsSelection

  • Gathers ObjectType, ObjectID, Variable, and StatsType.
  • Reads numeric threshold fields for event-based analysis.
  • If ObjectType <> SYS, checks ObjectIDEdit.Text is not blank and references a valid object.
  • Sets booleans like IsQualParam or IsRainParam in the TStatsSelection record based on the chosen variable.

3.7 Validation

  • If the user fails to specify an object (except for “System”), an error message appears (“No object was selected”).
  • If PlotParameter is out of range, or if date/time are reversed (not relevant here, but might be handled similarly).
  • Then if all good, the form calls the final steps to build the stats report.

4. Additional Points

  • The form references Ustats for the TStatsSelection structure.
  • The user can specify a minimum infiltration or minimum event volume to define “events.” Only durations that exceed these thresholds are considered for event-based stats (like “Inter-Event Time” or “Duration”).

5. Summary

Dstats.pas provides a self-contained UI form to define a statistical analysis request for SWMM. By letting the user pick an object type, variable, analysis method, and time range mode (continuous vs. event-based), it compiles a TStatsSelection that’s used by the statistical report engine. This is how SWMM offers specialized statistics (peak flows, total loads, durations above thresholds, etc.) over simulation results for individual or system-level variables.

SWMM5 Delphi GUI Dsnow.pas Summary

 Below is an overview of Dsnow.pas, a Delphi unit from SWMM 5.2 that defines a form (TSnowpackForm) for defining or editing a Snowpack object’s properties in SWMM. A Snowpack object models how snow and ice accumulate, melt, and are removed from subcatchment surfaces (plowable, impervious, or pervious areas).


1. Purpose and Context

In SWMM’s snowmelt routine, each subcatchment can reference a Snowpack object that specifies:

  • Melt coefficients (minimum and maximum)
  • Base temperature
  • Free water capacity
  • Initial snow/ice depth
  • Parameters for different land surface types (plowable, impervious, pervious)
  • Snow removal or “plowing” parameters.

TSnowpackForm presents these options via a two-page TPageControl:

  1. First Page (TabSheet1) includes a TGridEditFrame (PackGrid) containing separate columns for plowable, impervious, and pervious parameters.
  2. Second Page (TabSheet2) handles snow removal options.

Once the user inputs or edits values, the form validates them (ensuring no negative or invalid ranges) and, upon OK, stores them back to the TSnowpack object in SWMM.


2. Main Form: TSnowpackForm

2.1 Visual Components

  1. NameEdit: A text box for the Snowpack’s unique name (no duplicates, not empty).
  2. PackGrid (TGridEditFrame):
    • A grid with columns for each sub-area type (plowable, impervious, pervious) and rows for parameters such as Melt Coefficients, Base Temp, Free Water Fraction, etc.
    • Each cell is text-based, storing numeric values.
  3. FracPlowableEdit: Fraction of the impervious area that is “plowable.”
  4. NumEdit1..NumEdit6: Numeric fields for snow removal parameters, like removal depth, removal fractions, etc.
  5. SubcatchNameEdit: Name of the subcatchment that will receive plowed snow.
  6. PageControl1 with TabSheet1 (Snowpack properties) and TabSheet2 (Snow removal).

3. Data Structures: TSnowpack

A TSnowpack object has fields:

  • Data[i][j]: a 2D array (3 columns for plowable/impervious/pervious, and 7 rows for parameters, typically something like:
    1. Min Melt Coeff
    2. Max Melt Coeff
    3. Base Temperature
    4. Fraction Free Water
    5. Initial Snow Depth
    6. Initial Free Water
    7. Depth at 100% Cover
  • FracPlowable: fraction of impervious area that can be plowed
  • Plowing[i]: an array for 1..6 representing snow removal parameters (including the subcatchment name in index 7)

4. Workflow

4.1 SetData(Index, SP)

  1. NameEdit.Text = Snowpack name from Project.Lists[SNOWPACK].Strings[Index]
  2. PackGrid.Grid is populated with SP.Data[...] values across 7 rows * 3 columns (for each land surface type).
  3. The “plowable fraction” (FracPlowableEdit.Text) and the plowing parameters (NumEdit1..NumEdit6, plus SubcatchNameEdit) are set from SP.Plowing[...].

4.2 GetData(S, SP)

  • After OK is pressed, the form retrieves:
    • S := Trim(NameEdit.Text) as the Snowpack name.
    • For each cell in PackGrid.Grid, SP.Data[i][j] gets that cell’s numeric string.
    • SP.FracPlowable, SP.Plowing[1..7] from the relevant fields on TabSheet2.

4.3 Validation (in ValidateInput)

  1. Snowpack Name not empty or duplicated.
  2. Non-negative numeric parameters for melt coefficients, base temperature, etc.
  3. Min. melt coeff <= Max. melt coeff.
  4. Free water fraction <= 1.0.
  5. FracPlowableEdit is in [0..1].
  6. If snow removal depth > 0, ensure a subcatchment name is provided.
  7. Sum of removal fractions does not exceed 1.0.

If any check fails, a message is shown, the user is re-focused on the offending control, and OK is canceled.


5. Event Handlers

  • NameEditChange / PackGridSelectCell / PackGridDrawCell:
    • Keep track of changes, ensure the plowable column doesn’t allow an input in “Depth at 100% Cover.”
  • OKBtnClick: Runs ValidateInput; if everything is correct, closes with ModalResult := mrOK.
  • HelpBtnClick: Brings up context help, which changes depending on which TabSheet is active.

6. Summary

Dsnow.pas provides a form to manage the parameters for a Snowpack object in SWMM. By splitting parameters across plowable/impervious/pervious areas and providing a second tab for snow removal rules, it ensures that each Snowpack can be fully defined, validated, and stored. After confirming, the updated Snowpack is available in the model for snowmelt-related computations.

SWMM5 Delphi GUI Dreport.pas Summary

 Below is an overview of Dreport.pas, a Delphi unit from SWMM 5.2 that defines a dialog (TReportSelectForm) for specifying the contents of various types of tabular or graphical reports. These include:

  1. Time Series Plot
  2. Scatter Plot
  3. Table by Variable
  4. Table by Object

Once the user makes selections (e.g., which objects, which variables, and date ranges), the form gathers this information into a TReportSelection record and calls MainForm.CreateReport(...) to generate the actual report or plot.


1. Purpose and Context

In SWMM, the user can create several kinds of reports/plots:

  • Time Series Plot: multiple objects vs. time.
  • Scatter Plot: one variable on X-axis and another on Y-axis, for selected objects/dates.
  • Table by Variable: a time series table (one variable for multiple objects).
  • Table by Object: multiple variables for a single object.

TReportSelectForm is a stay-on-top form that prompts the user to choose:

  • Object types (subcatchments, nodes, links, system).
  • Which objects specifically (selected from the map or browser).
  • Which variables to include.
  • Which date/time range (start, end, possibly in elapsed or absolute time).
  • Additional details (time axis style, maximum number of items, etc.).

Once user clicks OK, the form’s code packages all these choices into a TReportSelection structure. The main UI (MainForm) uses CreateReport(ReportSelection) to actually build or display the requested table or plot.


2. Main Form: TReportSelectForm

2.1 Notable Controls and Tabs

  1. Notebook1
    • A multi-page control. Depending on ReportTypeChoice, a specific page is shown:
      • Page 0: Time Series or Table-type selection (objects + variables).
      • Page 1: Scatter plot selection (X-axis, Y-axis).
  2. CategoryCombo (or XCategoryCombo/YCategoryCombo for scatter)
    • Chooses the object class: subcatchments, nodes, links, or system.
  3. VariableListBox
    • A check list box for variables. The user can select one or multiple.
  4. ItemsListBox
    • A list box for the specific objects chosen. For instance, if it’s a time series plot, the user can pick multiple nodes or links.
  5. Date Ranges
    • StartDateCombo1/2, EndDateCombo1/2: combo boxes listing simulation date/time steps.
    • For time series or scatter plots, user picks a start and end date index.
  6. Add / Delete / MoveUp / MoveDown
    • Manage which objects appear in ItemsListBox.
  7. XObjectEdit/YObjectEdit
    • For scatter plots, store the single X or Y object ID.
  8. XVariableCombo/YVariableCombo
    • For scatter plots, which variable on X or Y axis.

3. Process Flow

3.1 SetReportType(aReportType)

  • Configures the form for a given report type:
    • TIMESERIESPLOT, SCATTERPLOT, TABLEBYVARIABLE, or TABLEBYOBJECT.
  • The form’s Notebook1.PageIndex is set accordingly.
  • Sets MaxObjects (the maximum number of objects the user can select).
  • For tables/plots dealing with subcatchments/nodes/links, populates the relevant combos with their available variables.
  • If the user is picking from system-level variables, the code also includes the “System” category.

3.2 CategoryComboClick / XCategoryComboClick / YCategoryComboClick

  • When the user picks “Subcatchments,” “Nodes,” “Links,” or “System,” these routines fill the associated variable combos:
    • For subcatchments, fill from MainForm.SubcatchViewBox.Items (skipping the “(None)” item).
    • For nodes, from MainForm.NodeViewBox.Items.
    • For links, from MainForm.LinkViewBox.Items.
    • For system, from SysViewNames[].
  • For time-series or table by variable, it also updates the ItemsListBox if the user is currently viewing a subcatch/node/link in the SWMM data browser.

3.3 AddToItemList

  • When the user presses Add, the code retrieves the currently selected object in SWMM (CurrentList/CurrentItem) and appends its ID to ItemsListBox.

3.4 VariableListBoxClick

  • In “Table by Variable” or “Time Series Plot,” we allow multiple variables if we’re dealing with system or “table by object,” otherwise only one.
  • If multi-variable is not allowed, clicking one variable unchecks others.

3.5 BtnOKClick

  1. Checks constraints:
    • Must have at least one variable selected (if needed).
    • Must have valid date range (StartDate <= EndDate).
    • Must not exceed MaxObjects.
  2. If a scatter plot, ensures the user has valid Xobject, Yobject.
  3. If valid, calls CreateReport to build a TReportSelection record with all the info, and calls MainForm.CreateReport(ReportSelection).

3.6 CreateReport

  • Gathers user selections:
    • ReportType: determined by ReportTypeChoice.
    • ObjectType: subcatchments, nodes, links, or system.
    • StartDateIndex / EndDateIndex: from combos.
    • Items: from ItemsListBox (or if scatter, from XobjectEdit + YobjectEdit).
    • VariableCount / Variables[]: from VariableListBox or XVariableCombo / YVariableCombo.
    • Whether we use elapsed time or actual date/time.
  • Then it calls MainForm.CreateReport(ReportSelection) to produce the final table or chart.

4. Special Cases

  1. System objects: The user can’t select multiple system “objects”—there’s only one system. Thus, ItemsListBox is hidden or disabled.
  2. Table by Object: The user picks only one object in ItemsListBox, but can pick multiple variables in VariableListBox.

5. Summary

Dreport.pas is the “front end” to SWMM’s tabular and plot reports. By collecting user choices about objects, variables, and date ranges, it forms a consistent approach for:

  • Time series graphs (multiple objects, single or multiple variables).
  • Scatter plots (two distinct objects/variables).
  • Tabular reports (by variable or by object).

Finally, it invokes MainForm.CreateReport(ReportSelection) to generate the actual result. This design ensures consistent input validation and user flow across SWMM’s various reporting tools.

SWMM5 Delphi GUI Dquery.pas Summary

 Below is an overview of Dquery.pas, a Delphi unit from SWMM 5.2 that provides a stay-on-top form (TQueryForm) for performing a Map Query. A Map Query in SWMM allows users to highlight particular objects (subcatchments, nodes, or links) on the map that meet certain criteria (for example, nodes with flooding > 0, or subcatchments with a certain runoff depth, etc.). Additionally, it supports special queries for nodes having inflows and subcatchments with LID controls.


1. Purpose and Context

In SWMM’s user interface, a Map Query helps the user quickly find and highlight which elements of the network satisfy a specified condition—such as “subcatchment infiltration rate is above X,” or “node has an RDII inflow assigned,” or “link flow is below Y.”

The TQueryForm allows the user to define:

  1. Which type of element is being queried (subcatchment, node, link, LID subcatchment, or inflow node).
  2. For subcatchments/nodes/links, which variable to compare.
  3. The relation (e.g., “above,” “below,” or “equals”) to use in the comparison.
  4. A comparison value if needed.

Once the user performs the query, objects matching the condition are highlighted on the map, and the rest are grayed out. A readout at the bottom shows how many objects matched.


2. Main Form: TQueryForm

2.1 Key Controls

  1. ComboBox1: Selects which category to query (“Subcatchments,” “Nodes,” “Links,” “LID Subcatchments,” or “Inflow Nodes”).
  2. ComboBox2: If subcatchments/nodes/links are chosen, lists the specific view variables relevant to that object type (e.g., “Area,” “Runoff,” “Depth,” “Flooding,” etc.). If “LID Subcatchments” is chosen, lists different LID types (e.g., “Biocell,” “Rain Barrel,” etc.). If “Inflow Nodes” is chosen, lists different inflow types (Direct Inflow, DWF, RDII, Groundwater).
  3. ComboBox3: The comparison operator (above, below, equals). Only used if subcatchments/nodes/links are chosen.
  4. Edit1: The numeric or text value for the query comparison.
  5. Button1 (labeled Go or an icon): Executes the query.
  6. Panel1: Displays how many objects matched the query.
  7. The form is stay-on-top, ensuring it remains accessible while working with the map.

2.2 Internal Data / Global Variables

  • QueryFlag: A boolean indicating if a map query is currently active.
  • QueryRelation: The chosen relation (above, below, equals).
  • QueryValue: The numeric value typed in Edit1 for the comparison.
  • CurrentSubcatchVar, CurrentNodeVar, CurrentLinkVar: Indicate which variable is currently used to color subcatchments, nodes, or links on the map, respectively.
  • OldSubcatchVar, OldNodeVar, OldLinkVar: The previously displayed map variable (before the query).
  • OldShowSubcatchs, OldShowNodes, OldShowLinks: Whether subcatchments, nodes, or links were visible prior to the query.

3. Workflow

3.1 FormShow

  1. Backs up the current map display settings (OldSubcatchVar, etc.).
  2. Disables the main form’s subcatch/node/link view combos (so user can’t change the displayed variable while the query is active).
  3. Calls ComboBox1Change to re-populate the second combo box with the correct list of variables for the chosen object type.

3.2 ComboBox1Change / UpdateVariables

  • If user picks “Subcatchments,” the form loads subcatchment variables (rainfall, infiltration, etc.) from MainForm.SubcatchViewBox.Items.
  • If “Nodes,” it loads node variables from MainForm.NodeViewBox.Items.
  • If “Links,” it loads link variables from MainForm.LinkViewBox.Items.
  • If “LID Subcatchments,” it loads a list of LID types.
  • If “Inflow Nodes,” it loads inflow types (“Direct,” “DWF,” “RDII,” “GW”).

3.3 Button1Click (the “Go” button)

  • Checks if user’s Edit1 is valid if a numeric comparison is needed (subcatch/node/link).
  • If valid, sets QueryFlag := True; saves the user’s chosen comparison operator (QueryRelation) and numeric value (QueryValue).
  • Disables the main form’s view combos.
  • Depending on which object type was chosen (ComboBox1.ItemIndex):
    • If 0 = Subcatchments: sets CurrentSubcatchVar to the chosen subcatchment variable, calls Uoutput.SetSubcatchColors, etc.
    • If 1 = Nodes: sets CurrentNodeVar, calls Uoutput.SetNodeColors.
    • If 2 = Links: sets CurrentLinkVar, calls Uoutput.SetLinkColors.
    • If 3 = LID Subcatchments: calls SetLIDSubcatchColors to highlight subcatchments that have LID, possibly filtering by type.
    • If 4 = Inflow Nodes: calls SetInflowNodeColors to highlight nodes that have certain inflow types.
  • Calls UpdateQueryCaption to display how many objects matched the query.
  • Redraws the map and updates legends.

3.4 SetInflowNodeColors

  • Clears all node color indices.
  • If the user chose “Direct Inflow,” it sets ColorIndex = 1 for nodes that have direct external inflow.
  • If “DWF,” does so for nodes with Dry Weather Flow.
  • If “RDII,” for nodes with RDII inflow.
  • If “GW,” for subcatchments that have groundwater flow assigned to a node, colors that node.

3.5 SetLIDSubcatchColors

  • Clears all subcatchment color indices.
  • Sets CurrentSubcatchVar := LID_USAGE.
  • If user picks “Any LIDs,” any subcatchment with an LID gets ColorIndex=1.
  • Otherwise checks if it has the chosen LID type (like “Rain Garden”).
  • Objects with ColorIndex=1 are considered “matched.”

3.6 UpdateQueryCaption

  • Counts how many objects (subcatchments, nodes, or links) have ColorIndex>0.
  • Displays “N items found” in Panel1.

3.7 FormClose

  • If QueryFlag=True, resets the map to its old display variables (OldSubcatchVar, etc.).
  • Re-enables the main form’s subcatch/node/link combos.
  • Clears the query.

4. Summary

Dquery.pas defines a small, always-on-top form that queries subcatchments, nodes, or links for a condition and highlights those objects on the map. By:

  • Letting the user pick object type and variable or picking “LID subcatchments” / “inflow nodes” queries,
  • Selecting a comparison operator (above, below, equal),
  • Entering a numeric threshold (if needed),

the form then updates the map’s color coding so that only those objects meeting the condition appear highlighted. This interactive Map Query feature helps modelers quickly identify and visualize network elements that match specific criteria (e.g., nodes with flooding, subcatchments with certain infiltration, or elements with certain special properties like LIDs or inflows).

SWMM5 Delphi GUI Dproselect.pas Summary

 Below is an overview of Dproselect.pas, a Delphi unit from SWMM 5.2 that provides a profile selection dialog (TProfileSelectForm). This dialog lets users build or retrieve a profile plot path for SWMM—i.e., a series of links (and intermediate nodes) that define a longitudinal section of the drainage network. Once defined, this path can be used to create a profile plot that shows water levels over time or design geometry for those links.


1. Purpose and Context

In SWMM, a profile is a path of links (and nodes) through the network. The user may want to see a cross-sectional water level profile along that path under certain hydraulic conditions. TProfileSelectForm helps:

  1. Manually build a list of links for a profile (adding links one-by-one).
  2. Automatically find a path between two specified nodes (using a minimum-links path).
  3. Load a previously saved profile from the project.
  4. Save the newly defined profile path (giving it a name) for future use.
  5. Finally, OK triggers the creation of the actual profile plot, handled by SWMM’s plotting routine.

2. Main Form: TProfileSelectForm

2.1 Key Controls

  1. StartNodeEdit / EndNodeEdit (TEdit): Name of the first/last node in the profile.
  2. StartNodeBtn / EndNodeBtn:
    • Buttons that set StartNodeEdit or EndNodeEdit to whatever node is currently selected in SWMM’s data browser.
  3. LinksListBox: Lists all the link IDs the user has placed in the profile path, in order.
  4. FindPathBtn: Finds a minimal-link path from StartNode to EndNode (if one exists) automatically.
  5. UseProfileBtn: Opens another form to pick from a saved profile in the project, which is then loaded into LinksListBox.
  6. SaveProfileBtn: Saves the current LinksListBox to the project’s ProfileNames and ProfileLinks lists, under a user-entered name.
  7. OK / Cancel: Confirms or cancels.
  8. ProfileLinksBox: A group box around the LinksListBox; its caption can display either “Links in Profile” or the profile’s name if one is loaded/saved.

3. SWMM Data Interactions

  • Project.ProfileNames: A TStringList storing names of saved profiles.
  • Project.ProfileLinks: A parallel TStringList storing the link sequences (each line being a newline-separated list of link IDs) for each profile in ProfileNames.
  • For each new profile, the user supplies a name that is appended to ProfileNames and the path (link IDs) is appended to ProfileLinks.

4. Event Handlers and Key Routines

4.1 FormCreate

  • Positions the form near the main form’s client area, sets up glyphs for the buttons, and enables/disables certain controls based on if there are any existing saved profiles.

4.2 StartEndNodeBtnClick

  • Transfers the currently selected node from SWMM’s data model to the StartNodeEdit or EndNodeEdit.

4.3 BtnAddLinkClick

  • Adds the currently selected link in SWMM’s data model to LinksListBox at the current index + 1, effectively inserting it right after the user’s currently highlighted link in the list.

4.4 FindPathBtnClick

  1. Reads StartNodeEdit/EndNodeEdit, ensures those nodes exist.
  2. Builds adjacency lists (via CreateAdjLists) so each node references all links to its neighbors.
  3. Calls GetMinPath to find a minimal link path between the two nodes.
  4. Stores the resulting link path in LinksListBox.

4.5 GetMinPath(StartNode, EndNode, NodeStack, LinkStack)

  • Uses a BFS-like approach with TQueue/TStack to find a path with the fewest links from StartNode to EndNode.
  • Marks and updates each node’s “PathLen.” If the end node can’t be reached, returns empty.
  • If found, unwinds the path from EndNode backward to StartNode and populates LinkStack.

4.6 SaveProfileBtnClick

  1. Prompts the user for a name (via InputBox).
  2. Checks if that name is already in Project.ProfileNames; if so, error.
  3. Otherwise, appends the name to ProfileNames, and the link IDs from LinksListBox to ProfileLinks (as one multi-line string).
  4. Sets Uglobals.HasChanged := True.

4.7 UseProfileBtnClick

  • Opens TProfileSelectionForm (Dprofile.pas), letting the user pick from the existing saved profiles.
  • On success, loads that profile’s link list into LinksListBox.

4.8 BtnOKClick

  1. Checks if at least one link is in the list.
  2. Calls CheckProfile to ensure each consecutive link is physically connected to the next.
  3. If valid, calls CreatePlot which sets up TReportSelection and requests SWMM to create a profile plot.
  4. Closes the form.

4.9 CheckProfile

  • For each consecutive pair of links in LinksListBox, ensures they share a node. Also checks if the link actually exists in the project.
  • If any mismatch, returns the index of the invalid link. If all good, returns -1.

4.10 CreatePlot

  • Builds a TReportSelection record specifying a PROFILEPLOT type with the link IDs from LinksListBox.
  • Calls MainForm.CreateReport(ReportSelection), generating the actual profile plot in SWMM.

5. Summary

Dproselect.pas provides a user-friendly “Stay-on-top” form, enabling:

  1. Manual or automatic path building for a SWMM profile plot.
  2. Saving the path under a name for re-use.
  3. Checking and ensuring the path is physically contiguous.
  4. Ultimately creating a profile plot in SWMM after the user hits OK.

This tool is essential for custom or ad-hoc path creation, allowing the user to quickly define or re-use a sequence of links and visualize water level profiles across that selection.

SWMM5 Delphi GUI Dproplot.pas Summary

 Below is an overview of Dproplot.pas, a Delphi unit from SWMM 5.2 that provides a dialog form (TProfilePlotOptionsForm) for editing display options of a profile plot. In SWMM, profile plots show how water levels vary along a series of nodes/links; this form lets the user customize colors, fonts, axis scaling, and other aspects of the plot’s appearance.


1. Purpose and Context

A profile plot in SWMM typically shows the elevation of conduit inverts, water surface profiles, and possibly ground elevation along a chosen path of nodes. The TProfilePlotOptionsForm dialog allows the user to:

  1. Adjust chart and background colors (e.g., water color, conduit color).
  2. Control labeling options, fonts, and line thickness.
  3. Override or enable automatic y-axis scaling.
  4. Decide whether to include the Hydraulic Grade Line (HGL), ground surface, etc.
  5. Edit the main chart title, horizontal axis title, and vertical axis title.

When OK is pressed, these choices are saved back to SWMM’s data structures, which in turn update the actual profile plot in the main UI.


2. Main Form: TProfilePlotOptionsForm

2.1 Visual Components

  1. PageControl1 with multiple TabSheets:
    • TabSheet1: Colors (background, panel, conduit, water).
    • TabSheet2: Chart titles (main, horizontal axis, vertical axis) and grid line toggles.
    • TabSheet3 / TabSheet4: Labeling options, arrow length, axis scaling controls, etc.
    • TabSheet5: Additional check boxes (e.g., show ground, line width, etc.).
  2. ColorBox1..ColorBox4: TColorBoxes for picking colors.
  3. MainTitleEdit / HorizAxisEdit / VertAxisEdit: Edits for the user to type text for chart titles.
  4. FontDialog: A standard Delphi font dialog for picking fonts.
  5. Check Boxes:
    • AutoScaleCheckBox: if checked, SWMM calculates Y-axis min/max automatically.
    • LabelsOnAxisBox, LabelsOnPlotBox: whether node labels appear along the axis or on the plot.
    • CheckBox1: toggles including the HGL line.
    • CheckBox3: toggles drawing the ground line.
    • And others controlling grid lines, default usage, etc.
  6. Spin Controls (TUpDnEditBox / TNumEdit):
    • LabelSizeSpin: size of labels for node names.
    • ArrowLengthSpin: length of arrow from node label to node.
    • YminEdit, YmaxEdit, YincEdit: user-specified vertical axis minimum, maximum, and increment.

2.2 Associated Data Structures

  • TGraphOptions: Contains general plotting options (e.g., fonts, colors, whether grid lines show).
  • TProfileOptions: Contains profile-specific settings:
    • E.g., ConduitColor, WaterColor, LineWidth, LabelsOnAxis, etc.

2.3 Key Routines

  1. LoadOptions(...)

    • Called externally to populate the form’s controls from the existing graph/profile options, and main/axis titles.
    • Fills text fields (MainTitleEdit, etc.) with the current chart title.
    • Sets color pickers (ColorBox) from the TGraphOptions.PanelColor, .BackColor, etc.
    • Checks or unchecks boxes (LabelsOnAxisBox, etc.) based on TProfileOptions fields.
    • If the user previously specified a custom or default color, ColorBox1 might be set to 'Default' (meaning a special “use style default” color).
  2. UnloadOptions(...)

    • Reads user’s changes back out of the form into the passed TGraphOptions / TProfileOptions.
    • Takes color from ColorBox# and writes them to ConduitColor, WaterColor, etc.
    • Reads MainTitleEdit.Font to set TitleFontName, TitleFontSize, etc.
    • Whether the user toggled CheckBox1 to exclude HGL.
    • Whether auto-scaling is on, etc.
  3. SetLeftAxisScaling(Ymax, theChart)

    • Called to fill YminEdit, YmaxEdit, YincEdit with the chart’s current min, max, and increment, plus provides a label showing the chart’s actual min and the user-supplied Ymax.
  4. GetLeftAxisScaling(theChart)

    • Reverse of above: reads YminEdit, YmaxEdit, YincEdit, and updates theChart.LeftAxis.Minimum, .Maximum, .Increment if the user is not in auto-scale mode.
  5. MainTitleFontLabelClick / AxisFontLabelClick

    • Invokes FontDialog to let the user pick a new font for the main title or for the axes. After the user chooses, updates the form’s text fields’ Font property.
  6. AutoScaleCheckBoxClick

    • If auto-scale is checked, the user’s numeric entries for Y-min, Y-max, and Y-inc are disabled.

3. Workflow

  1. FormCreate: Minimal setup. Possibly sets the default color in ColorBox1 to 'Default' if the SWMM style theme demands it.
  2. LoadOptions: The caller passes in the existing chart/plot settings. The form updates all controls to reflect those settings, e.g. colors, fonts, checkboxes, axis labels.
  3. The user modifies any of the form’s controls (titles, colors, checkboxes).
  4. When the user presses OK, UnloadOptions is called, storing the new settings back into the appropriate structures:
    • GraphOptions: for general chart styles (background, fonts).
    • ProfileOptions: for profile-specific options (conduit color, water color, label arrow length, etc.).
    • The user can also override the vertical scale by unchecking AutoScale and entering custom Y-min, Y-max, Y-inc.
  5. The main SWMM code then redraws or reconfigures the profile chart using these new settings.

4. Summary

Dproplot.pas is a specialized form for setting the profile plot’s appearance in SWMM. It handles:

  • Chart layout (colors, fonts, grid lines)
  • Profile-specific items (water color, conduit color, label style, show/hide HGL or ground line)
  • Y-axis scaling (auto or user-defined)
  • Title and axis text

By centralizing these adjustments, SWMM provides a user-friendly way for engineers/scientists to tailor profile plots to their preferences, improving clarity and presentation in results.

SWMM5 Delphi GUI Dproject.pas Summary

 Below is an overview of Dproject.pas, a Delphi unit from SWMM 5.2 that provides a form (TProjectForm) for viewing the project’s input file content in a structured way. Specifically, the form displays all sections of the SWMM input data (e.g., 

TITLETITLE, RAINGAGESRAINGAGES, SUBCATCHMENTSSUBCATCHMENTS, etc.) in a list box, and shows the lines belonging to the currently selected section in a string grid.


1. Purpose and Context

In SWMM, a project is typically stored as a text-based .inp file with various sections. Each section (TITLETITLE, OPTIONSOPTIONS, SUBCATCHMENTSSUBCATCHMENTS, etc.) contains parameters describing parts of the model. The TProjectForm in Dproject.pas:

  1. Exports the project’s data to a text representation (using Uexport.ExportProject).
  2. Organizes these text lines by section.
  3. Lets the user browse each section’s lines in a read-only format:
    • A ListBox for picking the section name.
    • A StringGrid that displays the lines for that section.

This is mostly a convenience or debugging feature—showing the user exactly how SWMM’s data is structured internally.


2. Main Form: TProjectForm

2.1 Components

  1. ListBox1: On the left side, listing the names of the input file sections (e.g., “[TITLE]”, “[OPTIONS]”, “[RAINGAGES]”, etc.).
  2. StringGrid1: On the right side, showing the lines of whichever section is selected in ListBox1.
  3. Panel1 / Panel2 / Panel3: Layout panels.
  4. Splitter1: A vertical splitter between the section list (ListBox1) and the lines (StringGrid1).
  5. Edit1: An invisible text box used to measure or set consistent row heights, ensuring correct DPI scaling.

2.2 Internal Variables

  • S (TStringList): A temporary string list that holds the entire exported text of the project.
  • Section (integer): The currently selected section index in ListBox1.

3. Data Flow

3.1 FormCreate

  • Creates S := TStringList.Create, to store the entire .inp file text.
  • Sets StringGrid1.DefaultRowHeight and ListBox1.ItemHeight to match Edit1.Height (ensuring consistent text layout across DPI settings).
  • Positions the form to fill the same area as MainForm.ClientHandle.

3.2 FormShow

  • Calls Uexport.ExportProject(S, Uglobals.ProjectDir), which writes a textual representation of the entire SWMM project into string list S.
  • Iterates over S to find lines that begin with [, i.e. the section headers, and adds them to ListBox1.Items.
  • Initializes Section := -1.
  • Selects the first item in ListBox1 and triggers ListBox1Click.

3.3 ListBox1Click

  • When a user picks a section from ListBox1, we find that section’s header line in S by matching S[J].
  • Then, from that line onward, we collect lines until hitting another section header ([).
  • We skip lines that are blank or have only ;; (comment lines for a project header).
  • The resulting lines are placed in StringGrid1, each line in a separate row.

3.4 RefreshGrid

  • Clears the grid.
  • Finds the selected section’s text lines.
  • Resizes StringGrid1.RowCount accordingly.
  • Fills each row (Cells[0, row]) with one line from the input.

3.5 Closing and Freed Resources

  • On FormClose, S.Free is called to release the memory used by the string list.

4. UI Behavior

  1. StringGrid is read-only. The user can’t edit lines—this is purely a view.
  2. Panel1Resize sets StringGrid1.DefaultColWidth := Panel1.Width, ensuring the single column spans the full panel width.
  3. StringGrid1DrawCell: By default, if a TStringGrid row is selected while it does not have focus, it might draw the selection with highlight color. This handler overrides that, drawing the line with a standard background color if the grid is not the active control, so it doesn’t show a highlight selection.

5. Summary

Dproject.pas implements a form that:

  • Exports the entire SWMM project to a textual .inp format.
  • Lists each input section in a left-side ListBox.
  • Shows each line of that section in a right-side StringGrid.

This allows users to inspect the complete project data as it would appear in the input file, all within SWMM’s interface, without manually opening the .inp file in an external text editor. By presenting a per-section view, the user can easily jump to different parts of the input structure.

SWMM5 Delphi GUI Dprofile.pas Summary

 Below is an overview of Dprofile.pas, a Delphi unit from SWMM 5.2 that provides a form (TProfileSelectionForm) for selecting and managing saved profile plots in a SWMM project. A “profile” in SWMM typically refers to a longitudinal section (i.e., a series of connected nodes and links) that the user wants to plot over time.


1. Purpose and Context

In SWMM, you can create profile plots showing how water level (hydraulic grade line) changes along a series of nodes and links. The application allows you to save these node/link sequences under a name (a “Profile Name”) for easy re-use.

The TProfileSelectionForm dialog is where users:

  1. See a list of previously saved profile names.
  2. Can rename an existing profile.
  3. Can remove a profile from the project.
  4. Finally, can select one profile to work with, returning that selection to the calling code.

2. Main Form: TProfileSelectionForm

2.1 Components

  1. ProfilesListBox: A TListBox that lists the names of all saved profiles in the project.
  2. RenameBtn: Lets the user rename the selected profile.
  3. RemoveBtn: Removes the selected profile from the list.
  4. OKBtn / CancelBtn: Confirm or dismiss the selection.
  5. A hidden TmpProfiles (TStringList) that stores the actual link sequences for each profile, paralleling the names in ProfilesListBox.Items.

2.2 Key Variables

  • HasChanged (boolean): Tracks whether any changes (rename or remove) have been made.
  • SelectedProfile (integer): The index of the profile that the user ultimately selected (or -1 if none).

2.3 Interaction with SWMM’s Project Data

  • Project.ProfileNames: A TStringList in SWMM’s Uproject global data structure that stores the user-friendly names of each profile.
  • Project.ProfileLinks: Another TStringList that stores the link sequences (one line per profile) in parallel with Project.ProfileNames.

When this form is opened, it:

  1. Copies Project.ProfileNames into ProfilesListBox.Items.
  2. Copies Project.ProfileLinks into TmpProfiles.

When the user clicks OK:

  1. The form writes any updated ProfilesListBox.Items back into Project.ProfileNames.
  2. Writes the updated TmpProfiles back into Project.ProfileLinks.
  3. Sets SelectedProfile = ProfilesListBox.ItemIndex.
  4. If anything changed (HasChanged), sets Uglobals.HasChanged := True; so the project knows it’s modified.

3. Workflow

  1. FormCreate: Initializes TmpProfiles as a new TStringList and sets HasChanged := False.
  2. FormShow:
    • Copies Project.ProfileNames into ProfilesListBox.Items.
    • Copies Project.ProfileLinks into TmpProfiles.
    • Ensures the list box has item 0 selected (if available).
  3. Renaming a Profile:
    • The user selects a profile in ProfilesListBox.
    • Clicking RenameBtn prompts the user for a new name (InputBox).
    • If the new name is unique (or the same as the old name), the profile name is updated in ProfilesListBox.Items.
    • Sets HasChanged := True.
  4. Removing a Profile:
    • The user selects a profile in ProfilesListBox.
    • Clicking RemoveBtn deletes it from both ProfilesListBox and TmpProfiles (keeping the indices aligned).
    • Adjusts ItemIndex to a valid index, if any remain.
    • Sets HasChanged := True.
  5. OKBtnClick:
    • Copies the edited ProfilesListBox.Items back into Project.ProfileNames.
    • Copies TmpProfiles back into Project.ProfileLinks.
    • SelectedProfile := ProfilesListBox.ItemIndex.
    • If HasChanged, sets Uglobals.HasChanged := True.
    • Closes with ModalResult := mrOK.

4. Summary

Dprofile.pas manages the ProfileSelectionForm where users can manage multiple saved profile views in SWMM. This dialog:

  • Displays existing profiles in a list.
  • Allows rename or remove of a profile.
  • Finally returns the selected profile index to the caller.
  • Updates SWMM’s global data (Project.ProfileNames, Project.ProfileLinks) accordingly, so that the project’s set of saved profiles is kept in sync with the user’s changes.

By offering straightforward name-based management, TProfileSelectionForm ensures users can easily re-use or modify the “profile” node sequences for repeated hydraulic profile plots in SWMM.

SWMM5 Delphi GUI Dprevplot.pas Summary

 Below is an overview of Dprevplot.pas, a Delphi unit from SWMM 5.2 that provides a dialog form (TPreviewPlotForm) for displaying a quick preview plot of data contained in other editors—namely the Curve editor, Time Series editor, or Transect editor. The form also supports showing cross-sectional geometry for storage units or custom shapes.


1. Purpose and Context

When the user clicks the View button in various SWMM dialogs (e.g., the Transect, Curve, or Time Series editors), SWMM needs a quick way to visualize the data (stations and elevations for transects, X-Y pairs for curves, time-value pairs for time series, etc.). TPreviewPlotForm serves this purpose:

  1. It holds a TChart (named Chart1) with 4 data series:
    • Series1: A line series (top line of an entire transect).
    • Series2: A line series (top line of just the main channel portion).
    • Series3: A line series (plots generic X-Y data for curves/time series).
    • Series4: An area series (used to “fill in” the bottom of a transect cross-section).
  2. The form can display these Series differently depending on whether it’s showing a transect cross-section, a standard X-Y curve, a time series, or a special cross-section shape.

2. Main Form: TPreviewPlotForm

2.1 Components

  • Chart1: A TChart that hosts line/area series.
  • Series1, Series2, Series3, Series4:
    • Series1 / Series2: line series used for transect top lines.
    • Series3: line series for curves, time series, or single-series X-Y plots.
    • Series4: area series for filled-in portion of a transect.
  • Buttons:
    • CopyBtn: Copy the chart image to clipboard.
    • PrintBtn: Print the chart.
    • CloseBtn: Closes the preview form.
  • Panel arrangement: Panel1 holds the chart, BtnPanel holds the buttons.

2.2 Key Routines

  1. PlotCurveData(DataGrid, Title, UseStairs, SwitchXY)

    • Reads X-Y pairs from DataGrid and places them into Series3.
    • If UseStairs = True, uses a step-plot style.
    • If SwitchXY = True, the grid’s X & Y columns are swapped.
    • Adds a chart title and axis labels from the grid’s header row.
  2. PlotTimeSeries(DataGrid, Title, D0)

    • Interprets columns (0: date, 1: time, 2: value) from DataGrid.
    • Converts date+time to “elapsed hours” from a reference date/time D0.
    • Adds those points to Series3 and sets Chart1.BottomAxis.Title.Caption to “Elapsed Time (hours).”
  3. PlotTransectData(DataGrid, Xleft, Xright, Xfactor, Yfactor, Title, Units)

    • Used for cross-section data.
    • DataGrid rows contain station (column 1) and elevation (column 2).
    • Series4 draws an area of the entire transect (filling from lowest station to highest).
    • Series1 draws the top line across the entire width.
    • If Xleft / Xright exist, Series2 highlights the portion of the transect that is the “main channel.”
    • Xfactor, Yfactor can rescale the station or elevation values.
  4. PlotStorageXsect(DataGrid, Title)

    • Interprets column 1 as depth, column 2 as cross-sectional area.
    • Draws a symmetrical shape about the center line, as if it’s a storage tank cross-section (radius derived from A/Ï€\sqrt{A/\pi}).
    • Creates left half (negative X) and right half (positive X) about the Y-axis.
  5. PlotShapeXsect(DataGrid, Title)

    • Interprets column 1 as depth, column 2 as width ratio.
    • Plots a custom cross-section shape symmetrically about the Y-axis (like half the shape to the left, half to the right).
    • Potentially ensures a 1:1 aspect ratio by adjusting the axis scale.
  6. CopyBtnClick: calls Ugraph.CopyTo(Chart1), copying the chart image to the clipboard.

  7. PrintBtnClick: calls Ugraph.Print(Chart1, MainForm.thePrinter, Xprinter.dPrinter) to open a print dialog.

2.3 Additional Utility Methods

  • SetBottomAxisScale: If the maximum X in a plot is less than 10, tries to auto-scale the axis with finer increments.
  • StripReturns(S): Removes carriage returns (#13) from a string (used for axis titles that might contain line breaks).

3. Typical Usage

  • When the user opens a “Transect Editor” or “Curve Editor,” they might see a View button. Clicking it collects data from a TStringGrid and calls one of the Plot...() methods in TPreviewPlotForm (e.g. PlotTransectData or PlotCurveData).
  • The form then appears with the chart automatically scaled, a relevant caption, X/Y axis labels, and possibly a filled area or multiple lines.
  • The user can Copy the chart image, Print it, or Close the form.

4. Summary

Dprevplot.pas enables SWMM’s “preview plot” functionality for various editors, giving a simple, uniform way to visualize table-based data (transect cross-sections, curves, time series, etc.). With minimal user input, it sets up and displays a TChart with up to four different series (line or area) for a clear, on-demand preview:

  1. Series1 / Series2: lines for transect outlines (full cross-section vs. main channel).
  2. Series3: a generic line series for curves or time series.
  3. Series4: an area fill for the bottom or banks of a transect.

The user can then copy or print the displayed chart before closing the preview.

SWMM5 Delphi GUI Dprefers.pas Summary

 Below is an overview of Dprefers.pas, a Delphi unit from SWMM 5.2 that provides a dialog (TPreferencesForm) for setting various program preferences in the SWMM user interface. These preferences include:

  • General UI behaviors (e.g., blinking map highlighters, confirming deletions, auto backups).
  • Decimal precision for displayed subcatchment, node, and link results.
  • Whether to display a start page on launch, how to handle auto-saving, and more.
  • The application’s visual Style (Delphi VCL theme).

1. Purpose and Context

SWMM allows users to customize various preferences that affect the user interface and certain behaviors not directly related to model computations. The TPreferencesForm is a tabbed dialog that aggregates all these settings, letting the user adjust them in one place. Upon confirmation, these settings are saved to SWMM’s global variables and persist between sessions (e.g., stored in an .ini file or registry).


2. Main Form: TPreferencesForm

2.1 Tabs

TPageControl organizes the preferences into two tabs:

  • TabSheet1: General UI settings
    • Blinking map highlighter, map flyovers, confirm on delete, automatic backup, tab-delimited project file, reporting time in elapsed format, auto-save results, showing the startup/welcome screen, clearing the recent projects list, etc.
  • TabSheet2: Decimal precision / output display
    • Allows the user to set how many decimals are shown for each subcatchment, node, and link output variable.

2.2 Controls

  1. Check Boxes (CheckBox1..CheckBox9) for general preferences like blinking map highlighter, confirm deletions, etc.
  2. Combo Boxes for default variable selection (e.g., NodeVarBox, LinkVarBox, SubcatchVarBox) and a numeric spin edit (TUpDnEditBox) that determines the decimal precision of each variable.
  3. StylesCombo: A drop-down listing available VCL Styles (TStyleManager.StyleNames), letting the user pick a different UI theme.
  4. Buttons: OK, Cancel, Help.

3. Internal Data Management

Within TPreferencesForm, there are arrays storing the decimal digits to be displayed for each set of variables:

  • SubcatchDigits[]: For subcatchment view variables (SUBCATCHOUTVAR1..SUBCATCHVIEWS).
  • NodeDigits[]: For node variables (NODEOUTVAR1..NODEVIEWS).
  • LinkDigits[]: For link variables (LINKOUTVAR1..LINKVIEWS).

When the user changes the spin edit for, say, a subcatchment variable, it updates SubcatchDigits[SubcatchVarBox.ItemIndex]. After hitting OK, these arrays get written back into SWMM’s global data structures:

  • SubcatchUnits[i].Digits := SubcatchDigits[...]
  • NodeUnits[i].Digits := NodeDigits[...]
  • LinkUnits[i].Digits := LinkDigits[...]

4. Event Flow

4.1 FormCreate

  • Initializes the check box captions from PrefersList[] (like “Blinking Map Highlighter,” “Flyover Map Labeling,” etc.).
  • Sets each check box according to the existing global preference variables (Uglobals.Blinking, Uglobals.FlyOvers, etc.).
  • Populates StylesCombo with all available VCL styles. Selects the current style’s name.
  • Fills the subcatch/node/link combo boxes (SubcatchVarBox, etc.) with the names of their output variables and copies the current decimal precision into local arrays (SubcatchDigits[], etc.).

4.2 (User Interaction)

  • The user toggles check boxes for UI behavior.
  • Chooses a subcatchment/node/link variable from the combo box and changes the spin edit to define the decimal places.
  • Possibly picks a different theme from StylesCombo.

4.3 OKBtnClick

  • Calls SetPreferences, which updates Uglobals variables:

    • Uglobals.Blinking := CheckBox1.Checked;
    • Uglobals.FlyOvers := CheckBox2.Checked;
    • … etc.
  • If the user checks “Clear Recent Project List” (CheckBox9), it clears Uglobals.MRUList.

  • Writes new decimal digits for each output variable’s display.

  • Returns mrOK.

4.4 RetrieveStyleName

  • Returns StylesCombo.Text so the main code can apply the chosen VCL style (e.g., TStyleManager.SetStyle(...)).

5. Summary

Dprefers.pas provides a straightforward way for SWMM users to customize how the software behaves and displays data, including:

  • UI behaviors (blinking highlighter, confirm on delete, etc.).
  • Project file formats (tab-delimited or normal).
  • Decimal precision for each subcatchment/node/link result variable.
  • The application’s VCL theme.

By saving these preferences to SWMM’s global variables, the user’s choices persist across sessions, ensuring a consistent, personalized experience.

SWMM5 Delphi GUI Dpollut.pas Summary

 Below is an overview of Dpollut.pas, a Delphi unit from SWMM 5.2 that provides a dialog (TPollutantForm) to create or edit the properties of a pollutant. A pollutant object in SWMM contains several parameters defining its concentration in various inflow streams, its first-order decay rate, and more.


1. Purpose and Context

In SWMM, pollutants represent chemical or biological constituents transported in runoff and sanitary flows. The TPollutantForm allows the user to edit:

  1. Pollutant Name and Units
  2. Concentrations in rainfall, groundwater, infiltration/inflow (I&I), dry weather flow, and the initial system concentration
  3. Decay Coefficient for a first-order decay process
  4. Whether buildup occurs only during snowfall
  5. Co-pollutant relationships (where pollutant concentration can be derived as a fraction of another pollutant’s concentration)

These properties are then used by SWMM’s water quality analysis routines.


2. Main Form: TPollutantForm

2.1 Visual Components

  1. Property Editor (TPropEdit, referenced as PropEdit1):

    • Displays each pollutant parameter in a name/value grid.
    • Allows the user to edit numeric or text values.
    • Provides events for validation (OnValidate) and hint messages (OnRowSelect).
  2. Panels and Buttons:

    • OK, Cancel, Help at the bottom.
    • A HintLabel in Panel3 that shows context-sensitive help when the user highlights a property row in the property editor.

2.2 Pollutant Properties and Hints

PollutProps (an array of TPropRecord) enumerates each pollutant property’s editing style, input mask, default text, etc.:

  1. Name (string, no spaces)
  2. Units (combo list: mg/L, µg/L, #/L, etc.)
  3. Rain Concen.
  4. GW Concen. (groundwater)
  5. I&I Concen.
  6. DWF Concen. (dry weather flow)
  7. Init. Concen. (initial system concentration)
  8. Decay Coeff.
  9. Snow Only (combo: NO/YES)
  10. Co-Pollutant
  11. Co-Fraction (fraction relating current pollutant to co-pollutant’s runoff concentration)

These are matched with a set of hints (PollutHint[]) explaining each property, displayed in HintLabel upon row selection.


3. Data Flow

3.1 SetData(Index, Pollut: TPollutant)

  • Called by the main application to load data from an existing pollutant (or a new one) into the form:
    1. PollutIndex records which item of Project.Lists[POLLUTANT] we’re editing (or -1 if new).
    2. If Index < 0, uses DefaultProps as the property values.
    3. Otherwise:
      • Property 0 is the pollutant’s name from Project.Lists[POLLUTANT].Strings[Index].
      • Properties 1..10 come from Pollut.Data[].
    4. Copies these values into PropList, which the PropEdit1 control will display.

3.2 FormShow

  • Calls PropEdit1.SetProps(PollutProps, PropList), linking the TPropRecord definitions to the string list of values.
  • Calls PropEdit1.Edit to enter interactive editing mode in the property grid.

3.3 User Edits

  • The user modifies each property in the property editor.
  • If the user changes rows, OnRowSelect -> ShowPropertyHint updates HintLabel.Caption.
  • OnValidate -> ValidateEntry ensures certain fields are not left blank (e.g., concentration fields).

3.4 OKBtnClick and Validation

  1. OKBtnClick triggers:
    • PropEdit1.IsValid: ensures each property passes OnValidate.
    • ValidateName: ensures the pollutant name is not blank or duplicated in Project.Lists[POLLUTANT].
    • If any check fails, the form remains open and displays an error message.
  2. If all checks pass, the form sets ModalResult := mrOK.

3.5 GetData(var S: String; Pollut: TPollutant)

  • Called after OK, storing the user’s final entries:
    1. S := PropList[0] for the pollutant’s name.
    2. For properties 1..10, Pollut.Data[k-1] := PropList[k].
  • The main calling code then uses the new name (S) and updated Pollut.Data[] to overwrite the old pollutant object in Project.Lists[POLLUTANT].

4. Validation Methods

  • ValidateEntry (OnValidate): For properties #2..#6, ensures the field cannot be empty. Displays an error message if blank.
  • ValidateName: Checks that PropList[0] (the name) is neither empty nor duplicated among existing pollutants.

5. Summary

Dpollut.pas defines a user-friendly form for editing pollutant properties in SWMM. By combining a property editor grid with validation logic, it ensures every pollutant has a unique name, valid numeric concentrations, optional co-pollutant relationships, and correct decay and “snow only” settings. Once the user confirms, these changes are transferred back into the SWMM project’s pollutant database for use in water quality modeling.

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