archimedes.codegen

archimedes.codegen(func: Callable | FunctionCache, filename: str, args: Sequence[Any], static_argnums: int | Sequence[int] | None = None, static_argnames: str | Sequence[str] | None = None, return_names: Sequence[str] | None = None, kwargs: dict[str, Any] | None = None, float_type: type = <class 'float'>, int_type: type = <class 'int'>, options: dict[str, Any] | None = None, driver: str | RendererBase | None = None, driver_config: dict[str, str] | None = None, driver_context: dict[str, Any] | None = None) None

Generate C/C++ code from a compiled function.

Creates standalone C or C++ code that implements the computational graph defined by the function. This allows Archimedes models to be deployed on embedded systems, integrated into C/C++ codebases, or compiled to native executables for maximum performance.

Parameters:
  • func (Callable | FunctionCache) – The compiled function to generate code for. If not already a FunctionCache, it will be compiled automatically.

  • filename (str) – The file to write the code to. Must be specified as string is not supported. A header file will also be generated if header=True.

  • args (tuple) – Arguments to the function that specify shapes and dtypes. These can be: - SymbolicArray objects - NumPy arrays with the same shape and dtype as expected inputs - The actual values for static arguments Note: For dynamic arguments, the numeric values are ignored.

  • static_argnums (tuple, optional) – The indices of the static arguments to the function. Will be ignored if func is already a FunctionCache.

  • static_argnames (tuple, optional) – The names of the static arguments to the function. Will be ignored if func is already a FunctionCache.

  • return_names (tuple, optional) – The names of the return values of the function. Ignored if func is already a FunctionCache. If not provided, the function will use default names like y0, y1, etc.

  • kwargs (dict, optional) – Keyword arguments to pass to the function during specialization.

  • float_type (type, default=float) – The C type to use for floating point numbers.

  • int_type (type, default=int) – The C type to use for integers.

  • options (dict, optional) –

    Additional options for code generation. This can include:

    • verbose: If True, include additional comments in the generated code.

    • cpp: If True, generate C++ code instead of C code.

    • main: If True, generate a main function entry point.

    • with_header: If True, also generate a header file with the extension .h.

    • with_mem: If True, generate a simplified C API with memory helpers.

    • indent: The number of spaces to use for indentation in the generated code.

  • driver (str | RendererBase, optional) – Name of the template to use for generating driver code, or a custom implementation of RendererBase. If None, no driver code will be generated.

  • driver_config (dict[str, str], optional) –

    Additional options for rendering the driver template. This might include the following keys:

    • template_path: Path to a custom template file, if not using the default.

    • output_path: Path where the generated code will be written.

    • sample_rate: Sample rate for the loop function in seconds (not used by all templates).

    • input_descriptions: Dictionary mapping input names to descriptions. Used for generating comments in the code.

    • output_descriptions: Dictionary mapping output names to descriptions. Used for generating comments in the code.

  • driver_context (dict, optional) – Additional context for the driver template. This can include additional variables that are used by custom templates. This context is passed directly to the Jinja2 template renderer.

Returns:

The function writes the generated code to the specified file(s).

Return type:

None

Notes

When to use this function: - For deploying models on embedded systems or hardware without Python - For integrating Archimedes algorithms into C/C++ applications - For maximum runtime performance by removing Python interpretation overhead - For creating standalone, portable implementations of your algorithm

This function specializes your computational graph to specific input shapes and types, then uses CasADi’s code generation capabilities to produce C code that implements the same computation. The generated code has no dependencies on Archimedes, CasADi, or Python.

Currently, this function uses CasADi’s code generation directly, so the generated code will contain CASADI_* prefixes and follow CasADi’s conventions.

To store numerical constants in the generated code, either: 1. “Close over” the values in your function definition, or 2. Pass them as hashable static arguments

Driver generation: Optionally, this function can also be used to generate templated “driver” code for different applications. For example, this can be used to create a basic C program that allocates memory and calls the generated function, or to create code for deployment to an embedded system.

Examples

>>> import numpy as np
>>> import archimedes as arc
>>>
>>> # Define a simple function
>>> @arc.compile
... def rotate(x, theta):
...     R = np.array([
...         [np.cos(theta), -np.sin(theta)],
...         [np.sin(theta), np.cos(theta)],
...     ], like=x)
...     return R @ x
>>>
>>> # Create templates with appropriate shapes and dtypes
>>> x_type = np.zeros((2,), dtype=float)
>>> theta_type = np.array(0.0, dtype=float)
>>>
>>> # Generate C code
>>> arc.codegen(rotate, "rotate_function.c", (x_type, theta_type))

The above code will generate ‘rotate_function.c’ and ‘rotate_function.h’ files that implement the rotation function in C.

To use numerical constants, declaring arguments as static will fix the value in the generated code:

>>> @arc.compile(static_argnames=("scale",))
... def scaled_rotation(x, theta, scale=2.0):
...     R = np.array([
...         [np.cos(theta), -np.sin(theta)],
...         [np.sin(theta), np.cos(theta)],
...     ], like=x)
...     return scale * (R @ x)
>>>
>>> arc.codegen(scaled_rotation, "scaled_rotation.c",
...            (x_type, theta_type, 5.0))

See also

compile

Create a compiled function for use with codegen