## Integrating the rTemp Water Temperature Model into GoldSim Using GSPy

This guide demonstrates how to integrate the rTemp water temperature model into GoldSim simulations using the GSPy Python bridge. The integration allows GoldSim to call Python-based thermal physics calculations at each timestep while maintaining control over simulation time and state management.

### Overview of the Integration Architecture

The integration implements a stateless physics engine pattern. GoldSim operates at a daily timestep and manages state variables through Previous Value elements. At each timestep, GoldSim passes current conditions to Python via the GSPy bridge. The Python adapter disaggregates daily meteorological data to hourly values, executes rTemp at hourly resolution for 24 hours, and returns the end-of-day state back to GoldSim.

[SCREENSHOT: Architecture diagram showing GoldSim, GSPy bridge, Python adapter, and rTemp model components]

### Prerequisites

The following software is required:

- GoldSim version 15 or later (64-bit)
- Python 3.11 or 3.14 (64-bit)
- GSPy version 1.8.8
- Python packages: numpy, pandas, scipy, rtemp

Note that GSPy is Windows-only and requires matching Python versions. For Python 3.14, use GSPy_Release_py314.dll. For Python 3.11, use GSPy_Release_py311.dll.

### Installation Steps

#### Step 1: Install Python and Required Packages

Download and install Python 3.14 (64-bit) from python.org. During installation, check the option to add Python to PATH. After installation, open a command prompt and install the required packages:

    py -3.14 -m pip install numpy pandas scipy rtemp

Verify the installation by checking the Python path:

    py -3.14 -c "import sys; print(sys.base_prefix)"

Record this path as it will be needed in the configuration file.

#### Step 2: Download and Configure GSPy

Download GSPy version 1.8.8 from the GitHub releases page at github.com/GoldSim/GSPy/releases. Extract the ZIP file and locate the DLL that matches your Python version. For Python 3.14, use GSPy_Release_py314.dll. Copy this file to your GoldSim project directory and rename it to match your project naming convention (for example, GSPy_314.dll).

#### Step 3: Create the Python Adapter Script

Create a file named rtemp_goldsim_adapter.py in your GoldSim project directory. This script serves as the interface between GSPy and the rTemp model. The script must define a function named process_data that accepts 14 input arguments and returns 3 output values.

[CODE BLOCK: Python adapter script showing process_data function signature and key components]

The adapter performs the following operations:

1. Unpacks input arguments from GoldSim
2. Validates inputs (water depth, latitude, longitude ranges)
3. Checks for dry-bed conditions and bypasses calculation if needed
4. Disaggregates daily min/max meteorological data to hourly values
5. Constructs a pandas DataFrame with datetime stamps
6. Initializes the rTemp model configuration
7. Executes rTemp for 24 hours
8. Extracts final state and diagnostic values
9. Returns results to GoldSim

Set the REFERENCE_DATE variable in the script to match your GoldSim simulation start date. This ensures accurate solar geometry calculations for solar radiation estimates.

#### Step 4: Create the JSON Configuration File

Create a JSON configuration file with the same base name as your DLL. If your DLL is named GSPy_314.dll, create GSPy_314.json. The JSON file must specify the Python path, script path, function name, and define all inputs and outputs.

[CODE BLOCK: JSON configuration showing python_path, script_path, function_name, inputs array, and outputs array]

The python_path must point to your base Python installation, not a virtual environment. Use double backslashes in the path for proper JSON formatting. The inputs and outputs arrays must match the order expected by the Python adapter function.

### GoldSim Model Configuration

#### Creating the External Element

In GoldSim, right-click and select Insert Element, then choose External. Name the element (for example, rTemp_Physics). In the External element properties:

- Set DLL Path to your DLL filename (GSPy_314.dll)
- Set Function Name to GSPy (not process_data)

[SCREENSHOT: External element properties dialog showing DLL and function configuration]

#### Configuring Inputs

Add 14 scalar inputs in the following order:

1. Current_Water_Temp (degrees C)
2. Current_Sediment_Temp (degrees C)
3. Water_Depth (meters)
4. Latitude (degrees, -90 to 90)
5. Longitude (degrees, -180 to 180)
6. Elevation (meters)
7. Timezone (hours from UTC)
8. Air_Temp_Min (degrees C)
9. Air_Temp_Max (degrees C)
10. Dewpoint_Min (degrees C)
11. Dewpoint_Max (degrees C)
12. Wind_Speed_Avg (m/s)
13. Cloud_Cover_Avg (fraction, 0-1)
14. Simulation_Date (elapsed days)

[SCREENSHOT: External element inputs tab showing all 14 inputs configured]

The order is critical. GSPy passes arguments by position, not by name.

#### Configuring Outputs

Add 3 scalar outputs in the following order:

1. New_Water_Temp (degrees C)
2. New_Sediment_Temp (degrees C)
3. Daily_Avg_Net_Flux (W/m²)

[SCREENSHOT: External element outputs tab showing all 3 outputs configured]

#### Creating State Variable Feedback Loops

Water and sediment temperatures must persist between timesteps. Create two Previous Value elements:

Water_Temperature:

- Initial Value: 15.0 (or appropriate initial condition)
- Previous Value: rTemp_Physics.New_Water_Temp

Sediment_Temperature:

- Initial Value: 15.0 (or appropriate initial condition)
- Previous Value: rTemp_Physics.New_Sediment_Temp

Connect these Previous Value elements to the External element inputs:

- rTemp_Physics.Current_Water_Temp = Water_Temperature
- rTemp_Physics.Current_Sediment_Temp = Sediment_Temperature

[SCREENSHOT: GoldSim model showing Previous Value elements connected to External element]

#### Connecting Other Inputs

Connect the remaining inputs to appropriate elements in your model:

- Water_Depth: from your hydraulic calculations
- Latitude, Longitude, Elevation, Timezone: from site parameter elements (typically constants)
- Air_Temp_Min, Air_Temp_Max, Dewpoint_Min, Dewpoint_Max, Wind_Speed_Avg, Cloud_Cover_Avg: from time series or meteorological data elements
- Simulation_Date: connect to ElapsedTime

### Testing the Integration

Start with a short simulation duration (10 days) to verify the integration works correctly. Set your simulation timestep to 1 day. Configure initial conditions and meteorological forcing data. For initial testing, use representative values such as:

- Latitude: 45.0, Longitude: -122.0, Elevation: 100 m, Timezone: 8
- Initial water temperature: 15 C, Initial sediment temperature: 15 C
- Water depth: 1.0 m
- Summer day meteorology: Air temp 15-30 C, Dewpoint 10-15 C, Wind 2 m/s, Cloud cover 0.3

Run the simulation and check the results. Water temperature should follow air temperature trends but with damped fluctuations due to thermal inertia.

[CHART: Time series showing air temperature (blue) and water temperature (red) over simulation period]

### Troubleshooting Common Issues

#### Error: Py_InitializeFromConfig failed

This error indicates the JSON file is pointing to a virtual environment instead of the base Python installation. Verify the python_path in your JSON file points to the base Python directory (for example, C:\Users\YourName\AppData\Local\Programs\Python\Python314), not a .venv directory.

#### Error: Cannot load DLL

Verify the DLL filename matches the JSON filename (both should have the same base name). Confirm you are using the correct DLL version for your Python installation (py314 for Python 3.14, py311 for Python 3.11). Check that Python is 64-bit by running:

    py -3.14 -c "import struct; print(struct.calcsize('P') * 8)"

This should print 64.

#### Error: Error in external function. Return code 1

Check the log file (GSPy_314.log or similar) in your GoldSim project directory. Look for ERROR entries that indicate the specific problem. Common causes include negative water depth values, invalid latitude/longitude ranges, or missing Python packages.

#### Incorrect Solar Radiation Values

Verify the REFERENCE_DATE in rtemp_goldsim_adapter.py matches your GoldSim simulation start date. Solar radiation calculations depend on the calendar date for accurate sun position and day length.

### Performance Considerations

The integration executes at approximately 0.1 seconds per day on typical hardware. An annual simulation (365 days) completes in about 36 seconds. For production runs, set log_level to 0 in the JSON file to minimize logging overhead. For development and debugging, use log_level 2 or 3 for detailed execution information.

### Model Validation

Compare results against standalone rTemp simulations using the same meteorological forcing data. Verify energy balance by examining the Daily_Avg_Net_Flux output. Check that water temperature responds appropriately to meteorological forcing with expected thermal damping. Confirm dry-bed conditions are handled correctly when water depth approaches zero.

[CHART: Comparison of GoldSim-integrated results vs standalone rTemp results]

### Advanced Configuration

The Python adapter script contains several parameters that can be modified:

- DRY_BED_THRESHOLD: Water depth below which calculations are bypassed (default 0.01 m)
- Solar radiation method: Options include Bras, Bird, Iqbal, Ryan
- Longwave radiation method: Options include Brunt, Brutsaert, Swinbank
- Wind function method: Options include Brady-Graves-Geyer and others

These parameters are set in the ModelConfiguration object within the adapter script. Consult the rTemp documentation for details on available methods and their appropriate use cases.

### Conclusion

The GSPy bridge provides a straightforward method for integrating Python-based models into GoldSim. The rTemp integration demonstrates how to handle temporal disaggregation, state management, and error handling in a production environment. The stateless physics engine pattern allows GoldSim to maintain control over simulation time while leveraging specialized Python libraries for complex calculations.

The complete integration files, including the Python adapter script, example JSON configuration, and validation scripts, are available in the rTemp package documentation.