---
url: /dyad/stable/manual/advanced/custom_analysis.md
---

# Write a custom analysis {#advanced-custom-analysis}

In Dyad, an analysis is a runnable query that can be performed on a model to produce a solution object that is used to build various visualizations to display to the user information about the model. The Dyad Analysis Interface is the Julia-level interface for calling analysis queries and interacting with the solution object.

## High-Level Definition {#High-Level-Definition}

All analyses are defined in terms of extending other analyses. At the lowest level we have the special `Analysis` type in Dyad which is extended by all analyses defined by julia packages. We call these analyses "base analyses". When a user writes an analysis for a specific context, they will extend one of the base analyses. This new analysis is named "derived analysis" and it can reference one or more models and it has its own parameters besides the parameters inherited from the base analysis.

## Creating analyses in Dyad {#Creating-analyses-in-Dyad}

1. A base analysis is specified in a .dyad files. as a `partial analysis`.  The implementation in Julia must match the name of the defined analysis, i.e. `partial analysis TransientAnalysis` corresponds to the `TransientAnalysisSpec` with its associated `TransientAnalysisSolution` type.

2. To define a derived analysis, the user would write Dyad code that extends one of the base analysis types.

3. The Dyad kernel will codegen julia code specific to that derived analysis.

4. To run an analysis, a user can either call the derived analysis constructor `<DerivedAnalysisName>Spec` and then `run_analysis`.

5. `run_analysis(spec::AbstractAnalysisSpec)` returns an `AbstractAnalysisSolution`.

6. One can know what the available artifacts from an `AbstractAnalysisSolution` are by running the command `AnalysisSolutionMetadata(::AbstractAnalysisSolution)`. This

metadata is designed to be a serializable object which can be stored by Dyad Builder to allow for querying the available visualizations in absence of the `AbstractAnalysisSolution`.

1. For artifacts, such as a standard plot or the generation of a standard data table, `artifacts(::AbstractAnalysisSolution, name::Symbol)` is called using the name of the artifact.

2. Each `AbstractAnalysisSolution` can also be imbued with a "customizable visualization". For the customizable visualization, more customization options are given to the user / Dyad Builder provider, such as the front end allowing the user to choose colors, fonts, etc. For this visualization, the provider

gives a `AbstractCustomizableVisualizationSpec` from which `customizable_visualization(::AbstractAnalysisSolution, ::AbstractCustomizableVisualizationSpec)` should return a visualization of the "standard form" which satisfies the given spec. If the analysis does not have customizable visualizations, then this method does not need to be implemented and the default fallback of `missing` will be used.

## Creating analyses in julia only {#Creating-analyses-in-julia-only}

If one wants to use the DyadInterface interface without using the Dyad codegen, then they would only interact with base analyses. In this case it is recommended to have control over the MTK model creation too. The dyad kernel generates functions that can build the ready-to-use `System` for a particular model, but they also add a caching layer which is to be used by the `<DerivedAnalysisName>Spec` constructors. If you are using the base analysis interface, then you should create the model from scratch and not use the cached version.

In this case the steps would be:

1. Create a base analysis spec by first defining an abstract type `AbstractCustomAnalysisSpec <: AbstractAnalysisSpec` and then a `CustomAnalysisSpec <: AbstractCustomAnalysisSpec`.

2. Create a `CustomAnalysisSolution <: AbstractAnalysisSolution` that is a fully serializable struct (via [`DyadInterface.serialize_solution`](/manual/advanced/custom_analysis#DyadInterface.serialize_solution)).

3. Define `DyadInterface.run_analysis(spec::CustomAnalysisSpec)` that returns a `CustomAnalysisSolution`.

4. Define `DyadInterface.AnalysisSolutionMetadata(::CustomAnalysisSolution)` such that it returns the available artifacts that your analysis defines.

5. Define `DyadInterface.artifacts(res::CustomAnalysisSolution, name::Symbol)` which returns the requested artifact from your result based on the `name` that is passed.

6. Define `DyadInterface.customizable_visualization(sol::CustomAnalysisSolution, ::AbstractCustomizableVisualizationSpec)` for vizualizations that take user input.

### Parameter Overrides {#Parameter-Overrides}

Custom analyses that build on top of a base analysis (such as `TransientAnalysisSpec` or `SteadyStateAnalysisSpec`) need to handle **parameter overrides**. Rather than modifying the model directly, parameter adjustments are passed as a `Dict{SymbolicT, SymbolicT}` via the `overrides` field of the base spec. The overrides dict maps model parameters (as symbolic variables) to their new values.

For example, a derived analysis that overrides a model parameter `α` would construct the overrides like this:

```julia
using ModelingToolkit: SymbolicT

function DyadInterface.run_analysis(spec::MyDerivedTransientSpec)
    no_namespace_model = ModelingToolkit.toggle_namespacing(spec.model, false)
    overrides = Dict{SymbolicT, SymbolicT}()
    push!(overrides, no_namespace_model.α => spec.α1)
    base_spec = TransientAnalysisSpec(;
        name = spec.name, alg = spec.alg,
        overrides,
        start = spec.start, stop = spec.stop,
        model = spec.model,
        # ... other fields
    )
    run_analysis(base_spec)
end
```

If your custom analysis extends `AbstractAnalysisSpec` directly (i.e., it defines its own problem setup rather than delegating to a base spec), the `overrides` should be passed to the `ODEProblem` or `SteadyStateProblem` constructor:

```julia
prob = ODEProblem{true, FullSpecialize}(simplified_model, overrides, tspan; fully_determined = true)
```

## Creating analyses graphically {#Creating-analyses-graphically}

When interacting with a Dyad library graphically, a user cannot create a new "base" (`partial`) analysis.  However, they can and should create new derived analyses (that `extend` the available `partial` analyses).

The user can potentially add new analysis parameters if they want to override model parameters. For example if a model associated to the analysis has a parameter `p` with a default value of 1, the user can override it at the analysis level (without chanigng the original model) by creating an analysis parameter `p` that will be identically mapped to the model parameter `p` by the Dyad codegen. In this way we can generate JSON files that specify values for `p` and change its value without re-running the codegen. Only if the structure of the analysis changes (like adding new analysis parameters) we will need to re-run the codegen.

## Abstract Interface Definitions {#Abstract-Interface-Definitions}

```julia
AbstractAnalysisSpec
```

The abstract type for all analysis specifications that maps to Dyad analyses. The subtypes of this type will use [`run_analysis`](/manual/advanced/custom_analysis#DyadInterface.run_analysis) to perfom analyses. The result of an analysis is always a subtype of [`AbstractAnalysisSolution`](/manual/advanced/custom_analysis#DyadInterface.AbstractAnalysisSolution).

The argument to `run_analysis` is a base analysis specification defined on the Julia side as a `struct` that subtypes [`AbstractAnalysisSpec`](/manual/advanced/custom_analysis#DyadInterface.AbstractAnalysisSpec) and referenced on the Dyad side via a `partial analysis` that extends `Analysis`. Base analysis specifications can be built either manually via their constructors or by derived analysis specifications that are created by the codegen. To manually build a base analysis specification like the [`TransientAnalysisSpec`](@ref), one can use

```julia
model = MyModel() # build an MTK model
spec = TransientAnalysisSpec(;
    model, name = :MyModelTransient, abstol = 1e-6, reltol = 1e-3, stop = 10.0)
```

For more details, check out [the julia workflow for the Transient Analysis](@ref%20julia_transient_workflow).

The difference between a base analysis and a derived one is that a base analysis does not impose defaults for all of its fields, but the values need to be provided upon construction. A derived analysis will have default values for all its parameters and it will build the appropriate base analysis. Since base analyses and derived ones share behaviours, it is recommended to define an abstract type togheter with the base type. As an example, one can write a `show` method for the abstract type that corresponds to the analysis and that would then also provide a `show` method that will work for the derived analysis specifications that will be defined by the codegen.

**Dispatching on the abstract type or on the base type**

The base spec and the derived specs differ in **how they store the overrides** of model parameters. The base spec keeps them in its `overrides::Dict{SymbolicT, SymbolicT}` field, mapping model quantities to values. A derived spec stores them inline, as one struct field per analysis parameter (`α1::Float64 = 1.0` for a Dyad `parameter α1::Real = 1`), and has no `overrides` field at all; the `run_analysis` method the codegen emits for it translates those fields into the `overrides` dict of a base spec and delegates to it.

The rule for choosing the signature of a method follows from this:

* Dispatch on the **abstract type** (`AbstractCustomAnalysisSpec`) for behaviour that is shared by the base spec and every derived spec, i.e. that only touches fields both have. `show`, `get_alg` or `nameof` are of this kind: `alg` and `name` are fields of both.

* Dispatch on the **base type** (`CustomAnalysisSpec`) for anything that reads or writes `overrides`, or otherwise depends on the concrete layout of the base spec. [`setup_analysis`](@ref) and [`structural_spec_fields`](@ref) are of this kind.

Defining a method that reads `overrides` on the abstract type makes it applicable to derived specs that do not have that field, and calling it on one fails with a `FieldError` instead of falling back to the generic method. This matters for tools that operate on analysis specs generically: DyadOrchestrator, for example, discovers spec types by subtype and calls `setup_analysis` on them, and relies on the `setup_analysis(::AbstractAnalysisSpec)` fallback (which returns the spec unchanged) to tell a spec that builds no setup from one that does.

Suppose we want to build an analysis named `CustomAnalysis`. In this case we would have the following:

```julia
abstract type AbstractCustomAnalysisSpec <: AbstractAnalysisSpec end

@kwdef struct CustomAnalysisSpec{M, T} <: AbstractCustomAnalysisSpec
    name::Symbol
    model::M
    analysis_parameter::T
end
```

which define the base analysis and if we have a particular model, `ModelA`, a custom analysis created by the codegen would be something like

```julia
@kwdef mutable struct ModelACustomAnalysisSpec <: AbstractCustomAnalysisSpec
    name::Symbol = :ModelACustomAnalysis
    analysis_parameter::Float64 = 1.0
    model::Union{Nothing, System} = ModelA(; name)
end
```

and one would use this in the following way:

```julia
spec = ModelACustomAnalysisSpec()
run_analysis(spec)
```

The derived analysis specification is used to fully represent a concrete analysis declaratively and it can be mapped to a JSON file which can be used by Dyad Builder to interact in an efficient manner with the analysis by avoiding codegen on non-structural analysis modifications. For more details see the [the JSON workflow for the Transient Analysis](@ref%20json_transient_workflow).

The corresponding Dyad code would be

```julia
partial analysis CustomAnalysis
  extends Analysis
  parameter analysis_parameter::Real

  model::Empty = Empty()
end
```

for the base analysis, which should be placed in a `.dyad` file inside a `YourPackage/dyad` folder, and

```julia
analysis ModelACustomAnalysis
  extends CustomAnalysis(analysis_parameter=1.0)
  model = ModelA()
end
```

for the derived analysis that an user would write. The `model` parameter is separate from other parameters of the analysis because one can also override model parameters inside an analysis:

```julia
analysis ModelACustomAnalysis
  extends CustomAnalysis(analysis_parameter=1.0)
  parameter model_parameter1::Real = 1
  model = ModelA(model_parameter=model_parameter1)
end
```

Note that the analysis parameter `model_parameter1` is mapped to the model parameter `model_parameter`, so the parameters in the analysis are not restricted to the names inside the model. For more details see the [the Dyad workflow for the Transient Analysis](@ref%20dyad_transient_workflow).

For a complete implementation, see the `TransientAnalysis`.

Whether a spec type can be run as-is is exposed by the [`is_runnable`](@ref) trait, which the codegen sets to `false` for the specs it emits for `partial` analyses.

Note that currently for an analysis to be recognized, the `.dyad` file that defines it must be inside of a component library.

```julia
AbstractAnalysisSolution
```

The abstract type and interface on the Julia result from running an analysis.

**interface**

All `AbstractAnalysisSolution`s must implement this interface:

* `AnalysisSolutionMetadata(::AbstractAnalysisSolution)` returns a serializable description of the visualizations that can be constructed from the solution object.

* `artifacts(::AbstractAnalysisSolution, name::Symbol)` returns the artifacts of name `name`. The allowed `artifact`s are defined by the `AnalysisArtifactMetadata` provided by `get_metadata`.

* `customizable_visualization(::AbstractAnalysisSolution, ::AbstractVisualizationSpec)` returns a visualization object. For example, for a `PlotlyVisualizationSpec`, this would return a Plots.jl plot built by the Plotly backend.

* `serialize_solution(serializable_solution::AbstractAnalysisSolution)` and `deserialize_solution(serialized_solution)::AbstractAnalysisSolution`, where the visualizations from the deserialized version should be the same as the version that is never serialized.

```julia
AbstractStandardVisualizationSpec
```

An AbstractCustomizableVisualizationSpec is a visualization spec for a "customizable visualization". Each `AbstractAnalysisSolution` is imbued with a customizable visualization which Dyad Builder has more plotting controls on, and this type is the specification of those plot controls on the standrad plot.

### Reusable interface utilities {#Reusable-interface-utilities}

When creating new analyses, it can be useful to be able to reuse the translation of certain parts of the spec.

```julia
ODEProblemConfig(spec::AbstractAnalysisSpec)
```

Translate ODEProblem specific analysis specification attributes to their julia native counterparts.

**Compatible specs need the following fields:**

```julia
- `alg`
- `start`
- `stop`
- `abstol`
- `reltol`
```

**The following optional fields are also supported:**

```julia
- `overrides`
- `saveat`
- `dtmax`
- `dt`
- `tstops`
- `verbose`
- `log_file`
```

**The fields that one can use from this struct are:**

```julia
- `alg`: the ODE integrator to use. The spec's `alg` field should be an [`ODEAlg`](@ref) variant.
- `op`: the override pairs from `overrides` in the spec, as a `Dict{SymbolicT, SymbolicT}`.
- `tspan`: the timespan of the problem (obtained from `start` & `stop` in the spec).
- `saveat`: the `saveat` keyword to be passed when solving. User-set values are
  canonicalized to a `Vector{Float64}` (a scalar spec value is expanded to the
  `start:dt:stop` grid); unset or `0` means default saving and is passed as `()`.
  Optional in the spec, defaults to `()`.
- `abstol`: the `abstol` keyword to be passed when solving.
- `reltol`: the `reltol` keyword to be passed when solving.
- `dtmax`: the `dtmax` keyword to be passed when solving. Optional in the spec, defaults to `spec.stop - spec.start`.
  It bounds how large an *adaptive* step may grow, so the fixed time step algorithms ignore it
  (setting both warns).
- `dt`: the `dt` keyword to be passed when solving, or `nothing` to let the integrator pick
  the step size (which is what `dt = 0` in the spec means). Required to be positive for the
  fixed time step algorithms, see [`is_fixed_step`](@ref).
- `adaptive`: `false` for the fixed time step algorithms, `nothing` to leave the
  algorithm's own adaptivity in place. Use [`ode_solve_kwargs`](@ref) to turn `dt` and
  `adaptive` into solver keyword arguments, so that `nothing` means "do not pass it".
- `tstops`: time points the integrator must step through exactly. Optional in the spec, defaults to `Float64[]`.
- `verbose`: the verbosity level for the solver.
- `log_file`: path to a log file for solver output.
- `specialization`: the `SciMLBase` specialization marker type to use as the second type
  parameter of the problem constructor, translated from the spec's `specialization` field
  (a [`SpecializationLevel`](@ref) variant). Specs without that field fall back to
  `SciMLBase.AutoSpecialize`; see [`get_specialization`](@ref).
```

Another reusable part is getting a structurally simplified model out of an analysis spec. This can be useful over just calling `mtkcompile` in your own analysis because it also handles adding additional passes.

```julia
get_simplified_model(spec::AbstractAnalysisSpec)
```

This function takes in a AbstractAnalysisSpec and returns a structurally simplified model. If the model is already simplified in the spec it just returns that. If the spec has additional passes (only `automatic_discontinuity_detection` for now) for `mtkcompile`, they are applied.

The spec needs to contain the model in `.model`. For `automatic_discontinuity_detection`, a boolean field with the same name must be present.

## Interface Metadata Queries {#Interface-Metadata-Queries}

```julia
ArtifactMetadata
```

Metadata describing an available artifacts for a given AbstractAnalysisSolution.

**Fields**

* `name::Symbol`: The name of the artifact. This is meant to be a unique symbol identifer which is then used in the `artifacts` function in order to choose this plot.

* `type::ArtifactType`: The type of the artifact.

* `title::String`: The title of the artifact. This is meant to be the display name in Dyad Builder for the user to select the artifact.

* `description::String`: The description of the artifact. This is meant to be a more detailed description that will be shown to Dyad Builder user if they ask for more information about the artifact.

```julia
AnalysisSolutionMetadata(sol::AbstractAnalysisSolution)
```

A serializable description of the visualizations that are allowed from a given `AbstractAnalysisSolution`.

**Fields**

* `artifacts`::Vector{ArtifactMetadata}\`: a description of the artifacts allowed for the given analysis solution

* `allowed_symbols::Vector{Symbol}`: the symbols which are allowed to be chosen in the customizable visualization. Note that this is not actually stored in the struct, it's computed on the fly.

* `symbol_groups::Dict{Symbol, Vector{Symbol}}`: a dictionary mapping symbol categories. Analysis implementations can decide how to split the `allowed_symbols` in relevant groups.

**Constructors**

* `AnalysisSolutionMetadata(::Vector{ArtifactMetadata}, ::Dict{Symbol, Vector{Symbol})` can be used if the analysis groups the available symbols.

* `AnalysisSolutionMetadata(::Vector{ArtifactMetadata}, ::Vector{Symbol})` can be used for analyses that do not have symbol groups. This will create a `:all` group for all symbols.

```julia
rebuild_sol(sol::AbstractAnalysisSolution)
```

\[EXPERIMENTAL]: Rebuild the fields of a serialized [`AbstractAnalysisSolution`](/manual/advanced/custom_analysis#DyadInterface.AbstractAnalysisSolution) such that it can be used for plotting. Currently it is assumend that [`run_analysis`](/manual/advanced/custom_analysis#DyadInterface.run_analysis) is stripping the solution such that the resulting `AbstractAnalysisSolution` is easily serializable.

## Customizable Visualizations {#Customizable-Visualizations}

```julia
Attribute
```

**Plotting options special cased in Dyad Builder.**

```julia
PlotlyVisualizationSpec <: AbstractCustomizableVisualizationSpec
```

The plot controls for a standard Plotly plot.

**Fields**

* `symbols::Vector{Symbol}`: The symbols specifying the parts of the solution to plot. This should be a subset of the `allowed_symbols` from the `AnalysisSolutionMetadata`.

* `plots_attributes`: The plotting attributes changing items like color, font size, etc. for the standard visualization. These attributes are required to match the Plots.jl standard attributes and it is designed to be a valid structure for splatting into a plot call, i.e. `plot(something; plots_attributes...)` should generate the correct plot with respect to the given attributes.

```julia
customizable_visualization(::AbstractAnalysisSolution, ::PlotlyVisualizationSpec)
```

Generates the standard visualization of a given `AbstractAnalysisSolution`. This standard visualization should respect the formatting decisions as specified by `PlotlyVisualizationSpec` and the return should be a Plots.jl-generated plot generated by the Plotly backend.

If the analysis does not have customizable visualization, it should return `missing`, which is also the default fallback method.

## Artifacts {#Artifacts}

```julia
artifacts(sol::AbstractAnalysisSolution)
```

Return the names of the artifacts supported by the given analysis solution based on the [`AnalysisSolutionMetadata`](/manual/advanced/custom_analysis#DyadInterface.AnalysisSolutionMetadata).

```julia
artifacts(sol::AbstractAnalysisSolution, name::Symbol)
```

Generates the artifact with the given `name` for a given `AbstractAnalysisSolution`. The `name` must be one of the allowed names in the `artifacts(sol)`. The result of this function should match the corresponding `ArtifactType` declared in the [`AnalysisSolutionMetadata`](/manual/advanced/custom_analysis#DyadInterface.AnalysisSolutionMetadata).

```julia
ArtifactType
```

The set of allowed artifact types for an `AbstractAnalysisSolution`.

```julia
ArtifactType.PlotlyPlot
```

A plot generated by Plots.jl with the Plotly backend to be displayed in Dyad Builder with a few modifications.

```julia
ArtifactType.DataFrame
```

A DataFrames.jl DataFrame table of results to be displayed in Dyad Builder in an interactive table.

```julia
ArtifactType.Download
```

A blob that is meant to be downloaded on demand by the user. This blob should be a standard serializable object that the user knows how to deal with, such as an FMU or JLD2 file.

## Running analyses {#Running-analyses}

```julia
run_analysis(spec::AbstractAnalysisSpec)::AbstractAnalysisSolution
```

Runs the analysis corresponding to the specification. The return type should always be a subtype of [`AbstractAnalysisSolution`](/manual/advanced/custom_analysis#DyadInterface.AbstractAnalysisSolution) and be something serializable.

**Positional Arguments**

* `spec`: `AbstractAnalysisSpec` object.

```julia
run_analysis(spec::AbstractAnalysisSpec, modifications)
```

Build the analysis setup for `spec` with [`setup_analysis`](@ref), apply the `modifications` (see [`update_parameters`](@ref)) and run the resulting setup. This works for any spec that supports `setup_analysis`, including derived analysis specs.

```julia
run_analysis(setup::AbstractAnalysisSetup)::AbstractAnalysisSolution
```

Run an analysis from a setup built by [`setup_analysis`](@ref), skipping model simplification and problem construction.

```julia
run_analysis(setup::AbstractAnalysisSetup, modifications)
```

Run the analysis from a copy of `setup` with the `modifications` applied via [`update_parameters`](@ref); `setup` itself is left untouched.

## Serialization {#Serialization}

The results of [`run_analysis`](/manual/advanced/custom_analysis#DyadInterface.run_analysis) are serialized and can be deserialized to inspect earlier runs. The analysis author can customize this step if needed.

```julia
serialize_solution(filename::AbstractString, serializable_solution::AbstractAnalysisSolution)
```

Generates a serialized artifact for long term storage and saves it at the filename location. The default implementation accepts any julia type that is serializable via the Serialization package. This function can be overridden if the analysis implementer wants to serialize using a different method.

```julia
deserialize_solution(filename::AbstractString)::AbstractAnalysisSolution
```

Regenerates the original solution that was serialized using serialize_solution from an artifact located at the filename path. The default implementation will regenerate any solution the was serialized via the Serialization package. This function can be overridden if the analysis implementer wants to deserialize using a different method.
