vipr.plugins.api package

Subpackages

Submodules

vipr.plugins.api.controllers module

UI Controller for result retrieval endpoints.

This controller provides API endpoints for retrieving stored UI results.

class vipr.plugins.api.controllers.StoredResultResponse(*, result_id: str, status: str, data: T, retrieved_at: str)

Bases: BaseModel, Generic[T]

Generic response wrapper for stored UI results

data: T
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

result_id: str
retrieved_at: str
status: str
class vipr.plugins.api.controllers.StoredResultResponse(*, result_id: str, status: str, data: T, retrieved_at: str)

Bases: BaseModel, Generic[T]

Generic response wrapper for stored UI results

data: T
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

result_id: str
retrieved_at: str
status: str
class vipr.plugins.api.controllers.UIController(*args: Any, **kw: Any)

Bases: ArgparseController

Controller for UI-related endpoints including result storage.

class Meta

Bases: object

label = 'ui'
stacked_on = 'base'
stacked_type = 'nested'
cleanup_storage()

Cleanup old UI results and config files.

get_result()

Retrieve stored UI result by ID (UUID or human-readable).

get_result_config()

Get configuration file for a specific result.

get_result_status()

Check UI result status.

get_storage_info()

Get UI storage information and statistics.

list_results()

List all stored UI results with metadata.

vipr.plugins.api.controllers.UIResultResponse

alias of StoredResultResponse[UIData]

vipr.plugins.api.controllers.cleanup_old_config_files(max_age_hours: int = 24) int

Clean up old config YAML files from the config directory.

Parameters:

max_age_hours – Maximum age in hours before deletion (default: 24)

Returns:

Number of files deleted

vipr.plugins.api.data_collector module

DataCollector for VIPR Framework with integrated result storage control and builder interfaces.

This module provides a UI Plugin implementation that collects, structures and transmits data from the backend to frontend UI components, and manages result storage with UUIDs. Features separate builder interfaces for consistent table and diagram manipulation.

class vipr.plugins.api.data_collector.DataCollector(app=None, item_index: int | None = None, parent_data: UIData | None = None, transient_plot_data: dict | None = None, transient_plot_scripts: dict | None = None, transient_diagram_scripts: dict | None = None)

Bases: object

UI Plugin that collects and structures data for frontend visualization and manages result storage with UUIDs.

This class follows a builder pattern for collecting different types of UI data (tables, logs, diagrams) and provides methods to structure and return this data.

Each Cement app instance gets its own DataCollector instance via app.extend(‘datacollector’, DataCollector()).

add_global_log(message: str, level: LogLevel = LogLevel.INFO) None

Add a log entry that applies to the entire batch.

create_item_collector(item_index: int) DataCollector

Create a DataCollector for a specific item (generic batch processing).

The child shares the parent’s transient dicts so that set_plot_data() and set_plot_script() calls on the child are visible when the parent’s save_result() runs the script exporter.

Parameters:

item_index – Index of the item to create collector for

Returns:

DataCollector instance configured for the specific item

diagram(id: str, title: str | None = None) DiagramBuilder

Get diagram builder for this DataCollector instance.

enable_result_storage() str

Enable result storage for the current operation.

Returns:

Generated UUID for this result

image(id: str, title: str | None = None) ImageBuilder

Get image builder for this DataCollector instance.

log(message: str, level: LogLevel = LogLevel.INFO) None

Add log entry to this DataCollector instance.

RECOMMENDED APPROACH: Use self.app.log.info/warning/error/etc instead!

The VIPRLogHandler automatically forwards all Cement logging calls (self.app.log.*) to DataCollector for frontend display. This provides: - Standard Cement logging (console/files) - Automatic frontend timeline integration - No code changes required

Example (RECOMMENDED):

self.app.log.info(“Processing started”) self.app.log.warning(“Warning message”) self.app.log.error(“Error occurred”)

This method is mainly for: - Code without app context access - Programmatic log generation - Special use cases requiring direct DataCollector access

Parameters:
  • message (str) – The log message

  • level (LogLevel) – Log level enum (LogLevel.INFO, LogLevel.ERROR, etc.)

Example

app.datacollector.log(“Processing started”, LogLevel.INFO) app.datacollector.log(“Error occurred”, LogLevel.ERROR)

return_gui_data() dict[str, Any]

Return all UI data for this DataCollector instance.

save_result(result_id: str, data: Any | None = None) None

Save result data for this DataCollector instance. Also extracts and saves images, tables, diagrams, plot scripts and config file as separate files for easy viewing and reproducibility.

Call order:
  1. Script export — reads live UIData + transient buffers (BEFORE serialisation)

  2. Clear transient — prevent leakage into pickle

  3. Serialise — model_dump()

  4. Save pickle — data.pkl

  5. Other exporters — work on serialised dict (unchanged behaviour)

set_batch_metadata(**metadata) None

Set batch-level metadata.

store_current_result(data: Any | None = None) str | None

Store current result.

table(id: str, title: str | None = None) TableBuilder

Get table builder for this DataCollector instance.

class vipr.plugins.api.data_collector.DiagramBuilder(data_collector: DataCollector, id: str, title: str | None = None)

Bases: object

Interface for diagram manipulation.

add_series(x: str, y: str, error_bars: str | None = None, label: str | None = None) DiagramBuilder

Add a series.

get() Diagram

Get the diagram.

set_data(name: str, values: Any) DiagramBuilder

Set data field.

set_metadata(**kwargs) DiagramBuilder

Set metadata.

set_plot_script(script, data_format: str = 'auto') DiagramBuilder

Register a Tier-2 standalone plot script for this diagram.

The callable is resolved immediately via inspect.getsourcefile() and stored in _transient_diagram_scripts (which survives until after generate_diagram_scripts runs in save_result step 6). The Tier-1 auto-generated template is suppressed.

Parameters:
  • script – Callable (recommended), Path, or str path to the script file.

  • data_format – ‘csv’, ‘npz’, or ‘auto’ (default).

Returns:

self (for chaining)

skip_script_generation() DiagramBuilder

Suppress Tier-1 auto-generation for this diagram entirely.

Use this for diagrams whose data is designed for the interactive frontend (Plotly) and for which a standalone matplotlib script would be misleading.

Returns:

self (for chaining)

class vipr.plugins.api.data_collector.ImageBuilder(data_collector: DataCollector, id: str, title: str | None = None)

Bases: object

Interface for image manipulation.

get() Image

Get the image.

set_from_bytes(data: bytes, format: str) ImageBuilder

Set image data from bytes.

Parameters:
  • data – Raw image data as bytes

  • format – Image format (‘png’, ‘svg’, ‘jpg’)

Returns:

Self for chaining

set_from_file(path: str) ImageBuilder

Set image data from file.

Parameters:

path – Path to image file

Returns:

Self for chaining

set_from_matplotlib(fig, format: str = 'png', dpi: int = 150, **kwargs) ImageBuilder

Set image data from matplotlib figure.

Parameters:
  • fig – matplotlib figure object

  • format – Image format (‘png’, ‘svg’, ‘jpg’)

  • dpi – Resolution for raster formats

  • **kwargs – Additional arguments passed to fig.savefig()

Returns:

Self for chaining

set_metadata(**kwargs) ImageBuilder

Set metadata.

set_plot_data(**arrays) ImageBuilder

Store plot data in DataCollector’s transient buffer.

Data is NOT serialised into data.pkl — it is only used by the script exporter (before serialisation) and then discarded.

The key in the shared dict is "{item_index}:{image_id}" in batch mode, or "0:{image_id}" for single-item runs. This prevents data from different batch items with the same image ID from overwriting each other.

Parameters:

**arrays – Named arrays / lists, e.g. x=np.array(…), y=[…]

Returns:

Self for chaining

set_plot_script(script, data_format: str = 'auto') ImageBuilder

Associate a standalone plot script with this image.

The script is copied to results/<uuid>/scripts/ when save_result() is called, together with the data provided via set_plot_data().

The script reference is stored transiently — it never reaches data.pkl and does not pollute image.metadata.

Parameters:
  • script

    A callable (e.g. the make_plot function imported from the standalone script module) — preferred, gives IDE navigation and compile-time safety:

    from vipr_reflectometry.reflectorch.plot_scripts.reflectivity_plot import make_plot
    .set_plot_script(make_plot, data_format='csv')
    

    Alternatively accepts a pathlib.Path or str pointing to the .py file directly.

  • data_format – ‘csv’, ‘npz’, or ‘auto’ (auto-detected from arrays)

Returns:

Self for chaining

class vipr.plugins.api.data_collector.TableBuilder(data_collector: DataCollector, id: str, title: str | None = None)

Bases: object

Interface for table manipulation.

add_column(name: str, values: list[Any]) TableBuilder

Add a column.

add_row(**row_data) TableBuilder

Add a row.

get() Table

Get the table.

vipr.plugins.api.decorator module

Type-safe API decorator for marking controller methods as API endpoints.

This decorator eliminates string-based mappings between CLI commands and HTTP endpoints while preserving Cement plugin initialization through controlled execution flow.

vipr.plugins.api.decorator.api(path: str, method: str = 'POST', request: type[BaseModel] | str | type | None = None, response: Any | None = None, tags: list[str] | None = None, operation_id: str | None = None, summary: str | None = None, description: str | None = None, transform_result: Callable[[Any], Any] | None = None)

Type-safe decorator to mark controller methods as API endpoints.

This decorator provides a hybrid approach where decorators define the mapping but runner.run_controller() handles execution with proper plugin initialization.

Parameters:
  • path – HTTP endpoint path (e.g., “/inference/run”)

  • method – HTTP method (“GET”, “POST”, “PUT”, “DELETE”)

  • request – Pydantic model CLASS for request validation (not string!)

  • response – Pydantic model CLASS for response validation

  • tags – OpenAPI tags for endpoint grouping

  • description – Endpoint description (defaults to docstring)

  • transform_result – Optional function to transform CLI output for HTTP response

Returns:

Decorated function with _api_meta attribute containing endpoint metadata

Example

@api(“/inference/run”, “POST”,

request=VIPRInference, response=dict, tags=[“inference”], transform_result=lambda r: serialize_numpy_data(r[“ui_data”]))

@ex(help=’Predict reflectivity parameters’) def predict(self):

# Method called via runner.run_controller() - plugins initialized # Config data available in self.app.config return self.app.inference.run()

vipr.plugins.api.models module

Enhanced Pydantic models with builder functionality for the API plugin.

This module defines the core data models used throughout the API plugin, providing type safety, validation, and builder methods for UI data collection. It also contains the core configuration models for VIPR inference.

vipr.plugins.api.models.ChiSquaredStats

alias of GoodnessOfFitStats

class vipr.plugins.api.models.Diagram(*, id: str, title: str | None = None, data: dict[str, ~typing.Any] = <factory>, series: list[~vipr.plugins.api.models.SeriesDefinition] = <factory>, metadata: ~vipr.plugins.api.models.DiagramMetadata | None = None)

Bases: BaseModel

Diagram with builder methods.

add_series(x: str, y: str, error_bars: str | None = None, label: str | None = None) Diagram

Add a series to the diagram.

classmethod convert_numpy(v)

Auto-convert numpy arrays.

data: dict[str, Any]
property display_title: str

Return title if provided, otherwise use id as title.

id: str
metadata: DiagramMetadata | None
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

series: list[SeriesDefinition]
set_data(name: str, values: Any) Diagram

Set data field (add or update).

set_metadata(**kwargs) Diagram

Set or update metadata.

title: str | None
class vipr.plugins.api.models.DiagramMetadata(*, x_label: str | None = None, y_label: str | None = None, x_scale: ScaleType | None = None, y_scale: ScaleType | None = None, title: str | None = None, chi_squared: GoodnessOfFitStats | None = None, **extra_data: Any)

Bases: BaseModel

Diagram metadata with support for custom fields.

chi_squared: GoodnessOfFitStats | None
model_config: ClassVar[ConfigDict] = {'extra': 'allow'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

title: str | None
x_label: str | None
x_scale: ScaleType | None
y_label: str | None
y_scale: ScaleType | None
class vipr.plugins.api.models.GoodnessOfFitStats(*, chi_squared_predicted: float | None = None, chi_squared_polished: float | None = None, reduced_chi_squared_predicted: float | None = None, reduced_chi_squared_polished: float | None = None, rss_predicted: float | None = None, rss_polished: float | None = None, mse_predicted: float | None = None, mse_polished: float | None = None, rmse_predicted: float | None = None, rmse_polished: float | None = None, mae_predicted: float | None = None, mae_polished: float | None = None, mape_predicted: float | None = None, mape_polished: float | None = None)

Bases: BaseModel

Comprehensive goodness-of-fit statistics.

chi_squared_polished: float | None
chi_squared_predicted: float | None
mae_polished: float | None
mae_predicted: float | None
mape_polished: float | None
mape_predicted: float | None
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

mse_polished: float | None
mse_predicted: float | None
reduced_chi_squared_polished: float | None
reduced_chi_squared_predicted: float | None
rmse_polished: float | None
rmse_predicted: float | None
rss_polished: float | None
rss_predicted: float | None
class vipr.plugins.api.models.Image(*, id: str, title: str | None = None, data: str = '', format: str = 'png', metadata: dict[str, ~typing.Any] | None = <factory>)

Bases: BaseModel

Image with metadata for UI display.

data: str
property display_title: str

Return title if provided, otherwise use id as title.

format: str
id: str
metadata: dict[str, Any] | None
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

title: str | None
class vipr.plugins.api.models.ItemData(*, item_index: int, tables: list[~vipr.plugins.api.models.Table] = <factory>, diagrams: list[~vipr.plugins.api.models.Diagram] = <factory>, images: list[~vipr.plugins.api.models.Image] = <factory>)

Bases: BaseModel

Visualization data for one spectrum.

diagrams: list[Diagram]
find_diagram(title: str) Diagram | None

Find diagram by title.

find_diagram_by_id(id: str) Diagram | None

Find diagram by ID.

find_image(title: str) Image | None

Find image by title.

find_image_by_id(id: str) Image | None

Find image by ID.

find_table(title: str) Table | None

Find table by title.

find_table_by_id(id: str) Table | None

Find table by ID.

images: list[Image]
item_index: int
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

tables: list[Table]
class vipr.plugins.api.models.LogEntry(*, message: str, timestamp: datetime, level: str = 'info')

Bases: BaseModel

Log entry with metadata.

level: str
message: str
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

timestamp: datetime
class vipr.plugins.api.models.LogLevel(value)

Bases: str, Enum

Standard Python logging levels compatible with Cement framework.

CRITICAL = 'critical'
DEBUG = 'debug'
ERROR = 'error'
INFO = 'info'
WARNING = 'warning'
class vipr.plugins.api.models.ScaleType(value)

Bases: str, Enum

Enumeration of available scale types for diagram axes.

LINEAR = 'linear'
LN = 'ln'
LOG = 'log'
LOG10 = 'log10'
class vipr.plugins.api.models.SeriesDefinition(*, x: str, y: str, error_bars: str | None = None, label: str | None = None)

Bases: BaseModel

Data series definition.

error_bars: str | None
label: str | None
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

x: str
y: str
class vipr.plugins.api.models.Table(*, id: str, title: str | None = None, data: list[dict[str, ~typing.Any]] = <factory>)

Bases: BaseModel

Table with builder methods.

add_column(name: str, values: list[Any]) Table

Add or update a column.

add_row(**row_data) Table

Add a row to the table.

data: list[dict[str, Any]]
property display_title: str

Return title if provided, otherwise use id as title.

get_column(name: str) list[Any]

Get all values from a column.

id: str
model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

title: str | None
class vipr.plugins.api.models.UIData(*, items: list[~vipr.plugins.api.models.ItemData] = <factory>, global_logs: list[~vipr.plugins.api.models.LogEntry] = <factory>, batch_metadata: dict[str, ~typing.Any] = <factory>)

Bases: BaseModel

Multi-spectrum UI data - always list format even for single spectrum.

batch_metadata: dict[str, Any]
property batch_size: int

Number of spectra in this result.

property diagrams: list[Diagram]

all diagrams from first spectrum.

Type:

Legacy compatibility

find_diagram(title: str) Diagram | None

Legacy compatibility: find diagram in first spectrum.

find_diagram_by_id(id: str) Diagram | None

Legacy compatibility: find diagram by ID in first spectrum.

find_image(title: str) Image | None

Legacy compatibility: find image in first spectrum.

find_image_by_id(id: str) Image | None

Legacy compatibility: find image by ID in first spectrum.

find_table(title: str) Table | None

Legacy compatibility: find table in first spectrum.

find_table_by_id(id: str) Table | None

Legacy compatibility: find table by ID in first spectrum.

global_logs: list[LogEntry]
property images: list[Image]

all images from first spectrum.

Type:

Legacy compatibility

property is_single_spectrum: bool

Whether this is a single spectrum result.

items: list[ItemData]
property logs: list[LogEntry]

combine global logs and first spectrum logs.

Type:

Legacy compatibility

model_config: ClassVar[ConfigDict] = {}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

property tables: list[Table]

all tables from first spectrum.

Type:

Legacy compatibility

vipr.plugins.api.result_storage module

Result Storage Module for API Plugin - UUID-based result storage.

This module provides storage and retrieval of API results using UUIDs. Results are stored as pickle files in a temporary directory.

class vipr.plugins.api.result_storage.ResultStorage(result_dir: str | None = None)

Bases: object

UI-specific result storage using pickle files and result identifiers. Supports both UUIDs and human-readable IDs.

cleanup_old_results(max_age_hours: int = 24) int

Clean up results older than max_age_hours. Supports both new directory structure and legacy flat file structure.

Parameters:

max_age_hours – Maximum age in hours before deletion

Returns:

Number of items deleted (directories or files)

delete_result(result_id: str) bool

Delete a result by identifier (UUID or human-readable ID). Supports both new directory structure and legacy flat file structure.

Parameters:

result_id – Result identifier (UUID or human-readable)

Returns:

True if deletion was successful, False otherwise

get_result(result_id: str) Any | None

Get result data by identifier (UUID or human-readable ID). Supports both new directory structure and legacy flat file structure.

Parameters:

result_id – Result identifier (UUID or human-readable)

Returns:

The stored data or None if not found

get_result_directory(result_id: str) Path

Get the directory path for a result.

Parameters:

result_id – UUID of the result

Returns:

Path to the result directory

get_storage_info() dict[str, Any]

Get information about the UI storage. Supports both new directory structure and legacy flat file structure.

Returns:

Dictionary with storage statistics

result_exists(result_id: str) bool

Check if a result exists. Supports both new directory structure and legacy flat file structure.

Parameters:

result_id – Result identifier (UUID or human-readable)

Returns:

True if result exists, False otherwise

save_diagram_file(result_id: str, diagram_id: str, diagram_data: str, format: str = 'csv') bool

Save a diagram file to the result’s diagrams directory.

Parameters:
  • result_id – UUID of the result

  • diagram_id – Identifier for the diagram

  • diagram_data – Diagram data as string (CSV format)

  • format – Diagram format (csv, txt, etc.)

Returns:

True if successful, False otherwise

save_image_file(result_id: str, image_id: str, image_data: bytes, format: str) bool

Save an image file to the result’s images directory.

Parameters:
  • result_id – UUID of the result

  • image_id – Identifier for the image

  • image_data – Raw image data as bytes

  • format – Image format (png, svg, jpg, etc.)

Returns:

True if successful, False otherwise

save_result(data: Any) str

Save result data and return a UUID.

Parameters:

data – The data to save

Returns:

UUID string identifier for the saved result

Raises:

Exception – If saving fails

save_result_with_id(result_id: str, data: Any) str

Save result with specific ID. Creates a UUID directory structure with pickle file and images subdirectory.

Parameters:
  • result_id – The UUID to use

  • data – The data to save

Returns:

The result_id

Raises:

Exception – If saving fails

save_script_data(result_id: str, data_id: str, data: dict, format: str = 'csv') bool

Save plot data as CSV or NPZ to results/<uuid>/scripts/<data_id>.<format>.

Parameters:
  • result_id – UUID of the result

  • data_id – Base name without extension (e.g. ‘reflectivity_data’)

  • data – Dict mapping column/array names to values

  • format – ‘csv’ or ‘npz’

Returns:

True if successful, False otherwise

save_script_file(result_id: str, script_id: str, script_content: str) bool

Save a Python script to results/<uuid>/scripts/<script_id>.py.

Parameters:
  • result_id – UUID of the result

  • script_id – Base name without extension (e.g. ‘plot_reflectivity’)

  • script_content – Full text content of the script

Returns:

True if successful, False otherwise

save_table_file(result_id: str, table_id: str, table_data: str, format: str = 'csv') bool

Save a table file to the result’s tables directory.

Parameters:
  • result_id – UUID of the result

  • table_id – Identifier for the table

  • table_data – Table data as string (CSV format)

  • format – Table format (csv, txt, etc.)

Returns:

True if successful, False otherwise

save_text_file(result_id: str, filepath: str, content: str) bool

Save an arbitrary text file at a relative path within the result directory.

Parameters:
  • result_id – UUID of the result

  • filepath – Relative path within the result dir (e.g. ‘scripts/README.md’)

  • content – Text content to write

Returns:

True if successful, False otherwise

vipr.plugins.api.result_storage.api_result_exists(result_id: str) bool

Check if API result exists.

vipr.plugins.api.result_storage.delete_api_result(result_id: str) bool

Delete API result by UUID.

vipr.plugins.api.result_storage.get_api_result(result_id: str) Any | None

Get API result by UUID.

vipr.plugins.api.result_storage.save_api_result(data: Any) str

Save API result and return UUID.

vipr.plugins.api.visualization_config module

Visualization configuration models for the VIPR Framework.

Provides PlotStyle, VisualizationConfig and the resolve_plot_style() helper that plugins use to look up per-diagram style overrides from the vipr YAML:

vipr:
visualization:
plot_style:
export:

format: svg dpi: 150

figure:

figsize: [10, 6]

rc:

font.size: 11

diagrams:
reflectivity_matplotlib:
figure:

figsize: [12, 7]

Usage in a plugin hook / visualizer:

from vipr.plugins.api.visualization_config import resolve_plot_style

style = resolve_plot_style(app, “reflectivity_matplotlib”) fig = make_plot(…, figsize=style.figsize) # optional override style.apply_figure(fig) dc.image(“reflectivity_matplotlib”, title).set_from_matplotlib(

fig, **style.to_export_kwargs()

)

class vipr.plugins.api.visualization_config.ExportStyle(*, format: Literal['svg', 'png'] = 'svg', dpi: Annotated[int, Ge(ge=72), Le(le=600)] = 150)

Bases: BaseModel

Export-related options for matplotlib save operations.

dpi: int
format: Literal['svg', 'png']
model_config: ClassVar[ConfigDict] = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class vipr.plugins.api.visualization_config.FigureStyle(*, figsize: tuple[float, float] | None = None)

Bases: BaseModel

Figure-related options applied directly to Figure objects.

figsize: tuple[float, float] | None
model_config: ClassVar[ConfigDict] = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class vipr.plugins.api.visualization_config.PlotStyle(*, export: ~vipr.plugins.api.visualization_config.ExportStyle = <factory>, figure: ~vipr.plugins.api.visualization_config.FigureStyle = <factory>, rc: dict[str, ~typing.Any] = <factory>)

Bases: BaseModel

Style parameters for a single plot / diagram.

export controls save/export parameters and always has safe defaults. figure controls direct figure overrides (currently figsize). rc accepts arbitrary matplotlib rcParams keys (e.g. font.size).

Backward-compatible flat keys are still accepted:
  • format / dpi -> export

  • figsize -> figure.figsize

  • font_size / tick_size -> mapped into rc

apply_figsize(fig) None

Backward-compatible alias (deprecated, prefer apply_figure).

apply_figure(fig) None

Apply generic figure-level style options in one place.

Keeps callsites stable: a single call supports new options over time without adding new apply_* methods at each plugin use site.

property dpi: int

Compatibility accessor for existing callsites.

export: ExportStyle
property figsize: tuple[float, float] | None

Compatibility accessor for existing callsites.

figure: FigureStyle
property format: str

Compatibility accessor for existing callsites.

model_config: ClassVar[ConfigDict] = {'extra': 'ignore'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

rc: dict[str, Any]
rc_context()

Return a matplotlib rc_context for this style.

Intended use:
with style.rc_context():

fig, ax = plt.subplots(…)

to_export_kwargs() dict

Return kwargs suitable for set_from_matplotlib() / fig.savefig().

class vipr.plugins.api.visualization_config.VisualizationConfig(*, plot_style: ~vipr.plugins.api.visualization_config.PlotStyle = <factory>, diagrams: dict[str, ~vipr.plugins.api.visualization_config.PlotStyle] = <factory>)

Bases: BaseModel

Top-level visualization configuration parsed from vipr.visualization.

Merge priority (highest wins):

Built-in defaults → plot_style (global) → diagrams.<plot_id>

diagrams: dict[str, PlotStyle]
model_config: ClassVar[ConfigDict] = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

plot_style: PlotStyle
resolve(plot_id: str) PlotStyle

Return a resolved PlotStyle for plot_id.

Always returns a fresh copy — callers may not mutate the returned object and expect changes to affect other diagrams.

Parameters:

plot_id – The diagram / image ID string (must match the key used in dc.diagram() or dc.image()).

Returns:

Merged PlotStyle (global defaults + per-diagram overrides).

vipr.plugins.api.visualization_config.resolve_plot_style(app, plot_id: str) PlotStyle

Convenience helper: resolve a PlotStyle from app.visualization_config.

Falls back to default PlotStyle when app has no visualization_config attribute (e.g. in unit tests or contexts without a running Inference).

Parameters:
  • app – The Cement application instance.

  • plot_id – The diagram / image ID string.

Returns:

Resolved PlotStyle — never raises.

Module contents

vipr.plugins.api.load(app)

Load UI plugin with automatic result storage.