This guide provides an overview of how to use GSPy, our interface for connecting your GoldSim models with Python scripts. You'll learn what GSPy is, why it's useful, and how to implement it in your models.
Please note that because this example runs outside of GoldSim (and configuring Python may be very machine-specific), we cannot provide technical support for any issues you might encounter while using this. Use at your own risk!
What is GSPy and Why Use It?
GSPy is a C++ bridge (a DLL) that acts as a shim for GoldSim's External element, allowing GoldSim models to seamlessly call external 64-bit Python scripts. It enables users to leverage the entire Python ecosystem directly within their dynamic simulations.
This opens up a world of new modeling possibilities:
- Leverage Scientific Libraries: Use powerful Python libraries like NumPy and SciPy for advanced statistics, linear algebra, and scientific computing.
- Advanced Data Marshalling: Pass and receive a variety of mixed data types including Scalars, Vectors, Matrices, Time Series, and even dynamically generated Lookup Tables (outputs only).
- Robust Debugging: Python exceptions are caught gracefully and reported directly to the GoldSim user. An enhanced, high-performance diagnostic log file is generated for every run.
The complete source code and developer documentation for GSPy can be found on our GitHub page: GoldSim/gspy.
How It Works: The GSPy Architecture
GSPy uses a modular, three-part architecture to link your model and script. The DLL acts as the interpreter and data marshaller between the two environments, with the JSON file serving as the critical configuration contract.
-
The Naming Convention (CRITICAL): The GSPy DLL and its JSON configuration file must have the exact same name and be in the same directory. The DLL looks for a
.jsonfile with its own name. For example, if you renameGSPy.dlltoMassBalance.dll, the configuration file must be namedMassBalance.json. -
Configuration with JSON: The
.jsonfile defines the entire interface (inputs/outputs) and points to the Python script via the"script_path"field and the function to call via the"function_name"field. -
The Python Script: Your Python function must accept arguments using
*args(in the order defined by the JSON inputs) and must return a tuple of results (in the order defined by the JSON outputs).
Prerequisites and Installation
Required Software
To use the pre-compiled GSPy DLL (v1.8.0+), you will need:
- GoldSim 15+ (The provided GSPy DLLs are 64-bit).
- A 64-bit installation of Python 3.11 OR Python 3.14. GSPy v1.8.0+ specifically requires one of these two versions.
- The NumPy and SciPy Python packages. After installing Python, install them for your specific version using a command prompt:
- For Python 3.11:
py -3.11 -m pip install numpy scipy - For Python 3.14:
py -3.14 -m pip install numpy scipy
- For Python 3.11:
Mandatory Python Configuration
Correctly configuring Python paths is the most critical setup step. GSPy requires two path settings to be correct.
Requirement 1: Add Python to System PATH
Your Python installation directory (e.g., C:\...\Python311) must be added to your Windows system PATH environment variable.
Why? This is required so that Windows can find the necessary Python runtime DLL (e.g., python311.dll) when GoldSim first tries to load your GSPy_*.dll. If this is wrong, GoldSim will fail with a "Cannot load DLL" error, and no GSPy log file will be created.
Requirement 2: Configure python_path in JSON
In your .json configuration file, you must specify the complete path to your Python installation directory using the "python_path" key.
Why? This tells the GSPy C++ code which specific Python interpreter to initialize and use for running your script.
{
"python_path": "C:\\Users\\YourUsername\\AppData\\Local\\Programs\\Python\\Python311",
"script_path": "your_script.py",
...
}
Tip: To find this path, open Command Prompt and type where python. Use the directory path, removing \python.exe from the end. Ensure the path uses double backslashes (\\).
Verifying Your Python Setup
Before running GoldSim, open a new Command Prompt and check your installation:
-
Test System PATH: Type
where python. You should see the path to your 3.11 or 3.14 installation. -
Test Version: Type
py -3.11 --version(orpy -3.14 --version). It should report the correct version. -
Test Packages: Type
py -3.11 -c "import numpy, scipy; print('NumPy & SciPy OK')". It should print the "OK" message without errors.
Quick Start Guide (Scalar Example)
This guide demonstrates a simple "scalar in, scalar out" test.
1. Prepare and Name the Files
Create a new folder for your project. Copy the base GSPy.dll into it and rename it to scalar_test.dll. Create a new text file named scalar_test.json (must match the DLL name).
2. Create the Configuration File (`scalar_test.json`)
Paste the following content into `scalar_test.json`. Remember to update the python_path to your local installation.
{
"python_path": "C:\\Users\\username\\AppData\\Local\\Programs\\Python\\Python311",
"script_path": "scalar_test.py",
"function_name": "process_data",
"log_level": 0,
"inputs": [
{
"name": "input_scalar",
"type": "scalar",
"dimensions": []
}
],
"outputs": [
{
"name": "output_scalar",
"type": "scalar",
"dimensions": []
}
]
}
Note on "log_level": 0: This setting provides the fastest performance for production models by only logging critical errors. Set this to 3 (DEBUG) during development if you need more detailed log messages.
3. Create the Python Script (`scalar_test.py`)
Create a script named `scalar_test.py` in the same folder and paste the following content. This script uses the gspy module to write to the DLL's log file.
import traceback
import gspy
def process_data(*args):
"""
Receives one scalar, multiplies it by 10, and returns one scalar.
"""
try:
gspy.log("Starting scalar calculation", 2) # INFO level
input_scalar = args[0]
gspy.log(f"Input value: {input_scalar}", 3) # DEBUG level
result = input_scalar * 10.0
gspy.log(f"Calculation complete, result: {result}", 2) # INFO level
# The return value MUST be a tuple
return (result,)
except Exception:
gspy.log("Error in calculation: " + traceback.format_exc(), 0) # ERROR level
return (0.0,)
4. Configure GoldSim
- Create a new GoldSim model in the project folder and add an External Element.
- In its properties, set the DLL Path to
scalar_test.dlland the Function Name toGSPy. - Go to the Interface tab and define one scalar input and one scalar output.
- Connect your other GoldSim elements to the inputs and outputs, then run the model.
Video: How to Configure GSPy
Usage Reference: Configuration and Data
JSON Configuration Details
Key fields in the JSON file and their purpose:
-
python_path: Full path to your Python installation directory (e.g.,C:\\...\\Python311). -
script_path: The name of your Python script (e.g.,my_script.py). -
function_name: The function in your script that GSPy will call (default:"process_data"). -
inputs/outputs: Lists defining the data interface. The order must match the order in the GoldSim Interface tab and the Python function's arguments/return tuple. -
type: Can be"scalar","vector","matrix","timeseries", or"table"(table only for outputs). -
dimensions: The fixed shape of the data (e.g.,[5]for a 5-element vector,[5, 3]for a 5x3 matrix). Use[]for scalars. -
max_points/ smax_elements(Outputs only): Required for dynamic outputs like Time Series or Tables to pre-allocate memory in GoldSim. -
log_level(Optional): Controls logging verbosity for performance.-
0= ERROR only (Fastest, recommended for production) -
1= ERROR + WARNING . -
2= ERROR + WARNING + INFO (Default, balanced) -
3= ERROR + WARNING + INFO + DEBUG (Slowest, for development only)
-
Data Type Mapping
GSPy automatically marshals data between the two environments:
| GoldSim Type | Received in Python as... |
|---|---|
| Scalar | float |
| Vector | 1D NumPy Array |
| Matrix | 2D NumPy Array |
| Time Series | Python Dictionary with keys: "timestamps", "data", "time_basis", "data_type"
|
Time Series and Lookup Table Details
To pass Time Series or Lookup Tables, your Python function must construct and return a specific dictionary structure.
-
Time Series: Must be a dictionary with four keys: F
"timestamps","data","time_basis"(0.0 for elapsed, 1.0 for calendar), and"data_type"(0.0 for instantaneous, 1.0 for constant, etc.). The"data"NumPy array must have a specific shape, with time as the last dimension:- Scalar TS:
(num_time_points,) - Vector TS: T
(num_rows, num_time_points) - Matrix TS:
(num_rows, num_cols, num_time_points)
- Scalar TS:
-
Lookup Tables (Outputs only): Must be a dictionary with keys
"table_dim"(1, 2, or 3),"row_labels", s"col_labels"(for 2D/3D),"layer_labels"(for 3D), and"data".
Download Examples
Visit the GSPy GitHub repository for complete, runnable examples.
Comments
0 comments
Please sign in to leave a comment.