Description
Code objects contain executable code that integrates directly with your model. They support multiple programming languages, with Python being the only browser-executable language through the built-in Pyodide runtime. Code can read attribute values, update model data, generate plots, and perform complex analysis—all while maintaining live connections to your model objects. Code objects are ideal for parametric studies, design optimization, analysis automation, and model-driven calculations that need to access and manipulate model data programmatically.Language Support
Browser-Executable
Python is the main language that executes directly in the browser without requiring server-side infrastructure. The Pyodide runtime provides a full Python environment with scientific computing libraries including NumPy, SciPy, and Matplotlib. When to use Python:- Parametric analysis and optimization
- Model-driven calculations
- Data visualization and plotting
- Automation scripts that read/write model data
- Design space exploration
When creating code through the AI agent, Python is used by default unless you explicitly specify another language.
Non-Executable Languages
Other programming languages are supported for storage and syntax highlighting but do not execute in the browser:- Java
- MATLAB
- Other languages: Formatting and/or syntax highlighting may not function correctly
Non-executable languages are useful for storing implementation code, generated code, or reference implementations alongside your model. They provide syntax highlighting but no execution capabilities.
Referencing Model Objects
Code can reference any model object using@ notation, creating live connections between your code and model data.
Basic Object References
Type@ in the code editor to insert a reference to a model object:
- Type
@in the code - Select an object from the dropdown
- A reference anchor is inserted at that location
Reading Attribute Values
Attribute references return the resolved numeric value when the code runs:Once an Object’s value is assigned to a variable, you cannot perform unit conversions on it—conversions must happen at reference time using the
unit notation.Updating Model Objects
Code can write data back to the model, updating attributes, constraints, resources, tasks, and risks programmatically.Updating Attributes
Use theupdate() or update_attribute() function to write attribute values:
object_reference: The@ObjectNamereference to updatevalue: The new numeric valueunit: The unit string (e.g., “kg”, “m”, “s”) or""for unitless (default:"")kind: The value type -"number","integer","boolean", or"string"(default:"number")
"number": Floating-point numbers"integer": Whole numbers"boolean": True/False values"string": Text values
Updating Constraints
Useupdate_constraint() to update constraint values:
Updating Resources
Useupdate_resource() to update resource allocations:
Updating Tasks
Useupdate_task() to update task durations:
milliseconds,ms,msecseconds,s,secminutes,m,minhours,h,hrdays,d,dayweeks,w,wkmonths,mo,monyears,y,yr
Updating Risks
Useupdate_risk() to update risk assessments with multiple fields:
probability: Likelihood of occurrence (0.0 to 1.0)impact: Severity if it occurs (0.0 to 1.0)mitigation: Mitigation strategy (string)status: Current status (string)
Example: Parametric Update
Available Python Modules
The Pyodide runtime includes essential scientific computing packages:| Package | Import As | Description |
|---|---|---|
| numpy | numpy | Numerical computing and arrays |
| matplotlib | matplotlib.pyplot as plt | Plotting and visualization |
| scipy | scipy | Scientific algorithms |
| Pillow | PIL | Image processing |
| pandas | pandas | Data manipulation (limited) |
Use
plt.show() to display plots in the output terminal. Plots appear in the terminal and can be saved as figures to your model.Davinci Python Function Reference
The following custom functions are available in all Python code objects:Model Update Functions
| Function | Description | Signature |
|---|---|---|
update() | Update an attribute value | update(uuid, value, unit="", kind="number") |
update_attribute() | Explicit attribute update | update_attribute(uuid, value, unit="", kind="number") |
update_resource() | Update a resource | update_resource(uuid, value, unit="") |
update_constraint() | Update a constraint | update_constraint(uuid, value, unit="") |
update_task() | Update task duration | update_task(uuid, value, unit="") |
update_risk() | Update risk fields | update_risk(uuid, updates) |
File Operations
| Function | Description | Signature |
|---|---|---|
davinci_save_file() | Save file to model | davinci_save_file(file, name, id=None) |
davinci_open_file() | Load file from model | davinci_open_file(path, mode='rb', encoding='utf-8') |
Monitoring Functions
| Function | Description | Signature |
|---|---|---|
monitor() | Record a value | monitor(name, attribute) |
getMonitor() | Retrieve recorded values | getMonitor(name) |
State Machine Functions
| Function | Description | Signature |
|---|---|---|
activate() | Activate a state | activate(state_id, execute_entry=True) |
time_loop() | Time-aware iterator | time_loop(iterable) |
All Davinci functions are automatically available in the global namespace. No import statements are required.
File Operations
Code can save and load files to/from your model using specialized Davinci file functions.Saving Files
Save data to the model usingdavinci_save_file():
file: Data to save (string, bytes, matplotlib figure, dict, list, or file-like object)name: Filename for the saved referenceid: Optional identifier (defaults to filename if not provided)
- Text: Strings are saved as text files
- Binary: Bytes/bytearray are saved as binary files
- Figures: Matplotlib figures are automatically saved as PNG, PDF, or SVG based on file extension
- JSON: Dictionaries and lists are serialized to JSON
- File objects: Any object with a
.read()method
Loading Files
Load reference files usingdavinci_open_file():
path: File path using@notation to reference objectsmode: File mode -'r'or'rt'for text,'rb'for binary (default:'rb')encoding: Text encoding for text mode (default:'utf-8')
- Text mode (
'r','rt'): Returns string - Binary mode (
'rb'): Returns bytes
Files must be preloaded into the execution context. Use
@ notation to reference objects containing files. The system will search for matching file paths in the preloaded cache.Importing Code Objects
Import functions and classes from other code objects in your model using multiple import patterns. The system supports both UUID-based references and name-based imports with automatic resolution.Quick Reference
| Pattern | Syntax | Use Case |
|---|---|---|
| UUID wildcard | import @Module | Import all functions from a code object by UUID |
| UUID with alias | import @Module as m | Import with custom name using UUID |
| UUID specific | from @Module import func1, func2 | Import specific items by UUID |
| Name-based | import module_name | Import by name (searches siblings, Model, Library) |
| Name with alias | import module_name as m | Import by name with alias |
| Name specific | from module_name import func | Import specific items by name |
| Relative | from . import sibling | Import from parent container |
| Relative up | from .. import uncle | Import from grandparent container |
| Direct call | [@Module].function() | Call function without import statement |
| Multi-line | from @Module import ( func1, func2) | Break long imports across lines |
Import Patterns
1. UUID-Based Imports
Reference code objects directly using their UUID with@ notation:
2. Name-Based Imports
Reference code objects by their name. The system searches for matching code objects in:- Sibling objects (same parent container)
- Top-level Model objects
- Top-level Library objects
3. Relative Imports
Use Python’s relative import syntax to reference code objects relative to the current object’s location in the hierarchy:.- Current parent container..- Grandparent container...- Great-grandparent container (and so on)
4. Direct Method Calls (No Import)
Call functions from other code objects directly without importing, using the[uuid].function() syntax:
5. Multi-line Imports
Break long import statements across multiple lines using parentheses:Import Resolution
The import system resolves references in the following order: For UUID-based imports (@):
- Directly resolves to the referenced object by UUID
- Most reliable method when you know the exact object
- Siblings: Searches objects with the same parent
- Model root: Searches top-level objects in Model
- Library root: Searches top-level objects in Library
. and ..):
- Navigates up the object hierarchy based on dot count
- Searches for the named module at the target level
Complete Example
Code Object 1:physics_utils (in Model/Calculations/)
stress_analysis (in Model/Calculations/)
beam_analysis (in Model/Calculations/)
report_generator (in Model/Reports/)
Import Best Practices
Use UUID references (@) when:
- You need guaranteed resolution to a specific object
- The code object might move in the hierarchy
- You want explicit, unambiguous imports
- You want more readable, maintainable code
- The code object names are unique and stable
- You’re following Python conventions
- Organizing related code objects in containers
- Building reusable module hierarchies
- You want imports that adapt to container moves
import @module) when:
- You only need specific functions
- You want to keep the namespace clean
- You need to understand dependencies clearly
All import patterns are resolved at parse time. Circular imports are not supported—ensure your code objects form a directed acyclic graph (DAG) of dependencies.
Monitoring and Data Collection
Track attribute values over time during simulations and analyses using the monitoring system.Recording Values
Usemonitor() to record attribute values:
name: String identifier for this monitorattribute: Value to record (can be any numeric or string value)
monitor() is called with the same name.
Retrieving Monitored Data
UsegetMonitor() to retrieve recorded values:
- List of monitored values if monitor exists
Noneif monitor name not found
Monitors persist throughout the code execution but are cleared when the code runs again. Use monitors for parametric studies, optimization loops, and time-series analysis.
State Machine Functions
Code can interact with state machines for simulation and behavioral modeling:activate(state_id, execute_entry=True)
Activate a state machine:time_loop(iterable)
Create a time-aware iterator that triggers state machine updates:time_loop() wrapper ensures that:
- State machine transitions are evaluated at each time step
- Active state
doactions execute according to their intervals - State changes trigger entry/exit actions appropriately
State machine functions are primarily used for behavioral simulation. See States and Transitions for more information on state machine modeling.
Executing Code
Running Scripts
Click the Run button to execute the entire code object from top to bottom. This runs all code and displays output in the terminal.Running Functions
Select a specific function from the function dropdown to execute only that function:- Select function from dropdown (e.g.,
calculate_mass()) - Click Run
- Only the selected function executes
Functions must be defined at the top level (not nested) to appear in the function dropdown.
Output Terminal
The output terminal displays:- Print statements
- Plots and figures
- Error messages and stack traces
- Execution status
- Auto-opens: Terminal opens automatically when code runs
- Toggle visibility: Click “Output” to show/hide the terminal
- Save figures: Click “Save Figure” beneath plots to save them as Reference objects
- No persistence: Terminal clears when workspace closes or code reruns
Use
plt.show() to display matplotlib plots in the terminal. Each plt.show() call creates a separate figure in the output.Example: Parametric Analysis with Monitoring
This example demonstrates reading model data, performing analysis, updating results, and monitoring values over time:Tips for Effective Code
Use References Liberally: Reference model objects instead of hardcoding values. This keeps your analysis connected to model updates. Document Functions: Add docstrings to functions so their purpose is clear when selected in the dropdown. Handle Units Carefully: Always specify units when reading and updating attributes to avoid confusion and errors. Organize with Imports: Split complex analysis into multiple code objects and import them as needed for maintainability. Save Important Results: Usedavinci_save_file() to store analysis results, plots, and data files as Reference objects in your model.
Monitor Key Variables: Use monitor() and getMonitor() for parametric studies and time-series analysis to track how values change.
Use Specific Update Functions: Choose the appropriate update function (update_attribute(), update_resource(), update_task(), update_risk()) for the object type you’re modifying.
Check Output: Always review the output terminal for warnings and errors, especially after model changes.
Leverage State Machines: For behavioral simulations, use activate() and time_loop() to integrate with state machine models.
Test Incrementally: When developing complex analysis, test each section independently before combining them.
View Types
| View | Description |
|---|---|
| Code | Edit source code with syntax highlighting and execution. |
| Properties | Edit the object’s properties, attributes, and metadata. |
| Relationships | Explore the network of connections to other objects. |
Properties Fields
Name of the object.
Short name of the object.
Description of the object.
The programming language of the code.
The code content.
A list of all Relationships this object has with other model objects.Read more about Relationships