Skip to main content

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
C/C++ and JavaScript is supported but more limited and does not support the model integration capabilities of Python at this time.
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:
  1. Type @ in the code
  2. Select an object from the dropdown
  3. A reference anchor is inserted at that location
The reference resolves to the object when the code executes, allowing you to access its data.

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.
Unit conversion example:
Unit conversions must use compatible units. Attempting to convert incompatable units (such as mass g to length m) will cause an error.

Updating Model Objects

Code can write data back to the model, updating attributes, constraints, resources, tasks, and risks programmatically.

Updating Attributes

Use the update() or update_attribute() function to write attribute values:
Update function signature:
Parameters:
  • object_reference: The @ObjectName reference to update
  • value: The new numeric value
  • unit: The unit string (e.g., “kg”, “m”, “s”) or "" for unitless (default: "")
  • kind: The value type - "number", "integer", "boolean", or "string" (default: "number")
Supported value kinds:
  • "number": Floating-point numbers
  • "integer": Whole numbers
  • "boolean": True/False values
  • "string": Text values

Updating Constraints

Use update_constraint() to update constraint values:
Function signature:

Updating Resources

Use update_resource() to update resource allocations:
Function signature:

Updating Tasks

Use update_task() to update task durations:
Function signature:
Supported time units:
  • milliseconds, ms, msec
  • seconds, s, sec
  • minutes, m, min
  • hours, h, hr
  • days, d, day
  • weeks, w, wk
  • months, mo, mon
  • years, y, yr

Updating Risks

Use update_risk() to update risk assessments with multiple fields:
Function signature:
Available 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: Example usage:
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

File Operations

Monitoring Functions

State Machine Functions

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 using davinci_save_file():
Function signature:
Parameters:
  • file: Data to save (string, bytes, matplotlib figure, dict, list, or file-like object)
  • name: Filename for the saved reference
  • id: Optional identifier (defaults to filename if not provided)
Supported content types:
  • 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
The function creates a Reference object in your model with the saved content.

Loading Files

Load reference files using file.open():
Function signature:
Parameters:
  • path: File path using @ notation to reference objects
  • mode: File mode - 'r' or 'rt' for text, 'rb' for binary (default: 'rb')
  • encoding: Text encoding for text mode (default: 'utf-8')
Returns:
  • 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

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:
  1. Sibling objects (same parent container)
  2. Top-level Model objects
  3. 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:
Relative import levels:
  • . - 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:
This pattern automatically imports the code object behind the scenes and makes its functions available in the global namespace. It’s useful for one-off function calls where you don’t want to add an import statement.

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
For name-based imports:
  1. Siblings: Searches objects with the same parent
  2. Model root: Searches top-level objects in Model
  3. Library root: Searches top-level objects in Library
For relative imports (. 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/)
Code Object 2: stress_analysis (in Model/Calculations/)
Code Object 3: beam_analysis (in Model/Calculations/)
Code Object 4: 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
Use name-based imports when:
  • You want more readable, maintainable code
  • The code object names are unique and stable
  • You’re following Python conventions
Use relative imports when:
  • Organizing related code objects in containers
  • Building reusable module hierarchies
  • You want imports that adapt to container moves
Avoid wildcard imports (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

Use monitor() to record attribute values:
Function signature:
Parameters:
  • name: String identifier for this monitor
  • attribute: Value to record (can be any numeric or string value)
Values are appended to an array each time monitor() is called with the same name.

Retrieving Monitored Data

Use getMonitor() to retrieve recorded values:
Function signature:
Returns:
  • List of monitored values if monitor exists
  • None if 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:
The time_loop() wrapper ensures that:
  • State machine transitions are evaluated at each time step
  • Active state do actions 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:
  1. Select function from dropdown (e.g., calculate_mass())
  2. Click Run
  3. 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
Terminal features:
  • 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:
This code performs a parametric study by varying the applied load, monitoring stress and deflection at each step, and generating comprehensive visualization of the results.

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: Use davinci_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

Properties Fields

boolean
No. Code objects do not currently support object inheritance.
string
Name of the object.
string
Short name of the object.
string
Description of the object.
string
The programming language of the code.
string
The code content.
connection
A list of all Relationships this object has with other model objects.Read more about Relationships