API Reference
Complete reference for all OptixLog SDK classes, methods, and types
API Reference
Complete reference for the OptixLog Python SDK.
Quick Start
from optixlog import Optixlog
# Initialize client
client = Optixlog(api_key="your_api_key")
# Get or create a project
project = client.project(name="my_project", create_if_not_exists=True)
# Create a run
run = project.run(name="experiment_1", config={"lr": 0.001})
# Log metrics
run.log(step=0, loss=0.5, accuracy=0.95)
# Log a matplotlib figure
run.log_matplotlib("plot", fig)Optixlog
Main client class — entry point for all SDK operations.
Constructor
client = Optixlog(*, api_key: str, api_url: str = None)| Parameter | Type | Default | Description |
|---|---|---|---|
api_key | str | Required | Your OptixLog API key (keyword-only) |
api_url | str | https://optixlog.com | API endpoint URL |
Example:
from optixlog import Optixlog
client = Optixlog(api_key="your_api_key")Properties
| Property | Type | Description |
|---|---|---|
is_master | bool | True if master MPI process |
rank | int | MPI process rank (0 for master) |
size | int | Total MPI processes |
client.project()
Get or create a project.
project = client.project(*, name: str, create_if_not_exists: bool = False)| Parameter | Type | Default | Description |
|---|---|---|---|
name | str | Required | Project name or ID (keyword-only) |
create_if_not_exists | bool | False | Create project if not found |
Returns: Project instance
Example:
# Get existing project
project = client.project(name="MyProject")
# Create if doesn't exist
project = client.project(name="NewProject", create_if_not_exists=True)client.list_projects()
List all available projects.
projects = client.list_projects()Returns: List[Dict[str, Any]] — List of project dictionaries
Project
Represents an OptixLog project.
Properties
| Property | Type | Description |
|---|---|---|
id | str | Project ID |
name | str | Project name |
project.run()
Create a new run in this project.
run = project.run(*, name: str = None, config: dict = None)| Parameter | Type | Default | Description |
|---|---|---|---|
name | str | Auto-generated | Run name (keyword-only) |
config | dict | None | Configuration dictionary (keyword-only) |
Returns: Run instance
Example:
run = project.run(
name="experiment_1",
config={"wavelength": 1.55, "resolution": 32}
)Run
Represents a single experiment run with all logging capabilities.
Properties
| Property | Type | Description |
|---|---|---|
run_id | str | Unique run identifier |
name | str | Run name |
is_master | bool | True if master MPI process |
rank | int | MPI process rank |
size | int | Total MPI processes |
run.log()
Log metrics for a specific step.
result = run.log(step: int, **kwargs) -> MetricResult| Parameter | Type | Description |
|---|---|---|
step | int | Step number (≥ 0) |
**kwargs | Any | Metric key-value pairs |
Returns: MetricResult or None for worker processes
Example:
result = run.log(step=0, loss=0.5, accuracy=0.95, learning_rate=0.001)
if result.success:
print(f"Logged {len(result.metrics)} metrics")run.set_config()
Add or update configuration for this run. Chainable.
run = run.set_config(config: dict) -> RunExample:
run.set_config({"epochs": 100, "batch_size": 32})run.log_image()
Log a PIL Image.
result = run.log_image(
key: str,
pil_image: Image.Image,
meta: dict = None
) -> MediaResult| Parameter | Type | Description |
|---|---|---|
key | str | Unique identifier |
pil_image | PIL.Image | Image to upload |
meta | dict | Optional metadata |
Example:
from PIL import Image
img = Image.open("plot.png")
result = run.log_image("my_plot", img)
print(f"URL: {result.url}")run.log_file()
Log any file (CSV, HDF5, JSON, etc.).
result = run.log_file(
key: str,
path: str,
content_type: str = None,
meta: dict = None
) -> MediaResult| Parameter | Type | Description |
|---|---|---|
key | str | Unique identifier |
path | str | File path |
content_type | str | MIME type (auto-detected if None) |
meta | dict | Optional metadata |
Example:
result = run.log_file("results", "data.csv", "text/csv")
print(f"Uploaded {result.file_size / 1024:.1f} KB")run.log_matplotlib()
Log a matplotlib figure directly.
result = run.log_matplotlib(
key: str,
fig,
meta: dict = None
) -> MediaResultExample:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [1, 4, 9])
result = run.log_matplotlib("my_plot", fig)
plt.close(fig)run.log_plot()
Create and log a line plot in one call.
result = run.log_plot(
key: str,
x_data,
y_data,
title: str = None,
xlabel: str = None,
ylabel: str = None,
figsize: tuple = (8, 6),
style: str = '-',
meta: dict = None
) -> MediaResultExample:
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
result = run.log_plot("sine", x, y, title="Sine Wave", xlabel="x", ylabel="sin(x)")run.log_array_as_image()
Convert a 2D numpy array to a heatmap and log it.
result = run.log_array_as_image(
key: str,
array: np.ndarray,
cmap: str = 'viridis',
title: str = None,
colorbar: bool = True,
figsize: tuple = (8, 6),
meta: dict = None
) -> MediaResultExample:
field = np.random.rand(100, 100)
result = run.log_array_as_image("field", field, cmap='hot', title="E-field")run.log_histogram()
Create and log a histogram.
result = run.log_histogram(
key: str,
data,
bins: int = 50,
title: str = None,
xlabel: str = None,
ylabel: str = "Count",
figsize: tuple = (8, 6),
meta: dict = None
) -> MediaResultExample:
data = np.random.normal(0, 1, 1000)
result = run.log_histogram("residuals", data, bins=100)run.log_scatter()
Create and log a scatter plot.
result = run.log_scatter(
key: str,
x_data,
y_data,
title: str = None,
xlabel: str = None,
ylabel: str = None,
figsize: tuple = (8, 6),
s: int = 20,
alpha: float = 0.7,
meta: dict = None
) -> MediaResultrun.log_multiple_plots()
Log multiple lines on one plot.
result = run.log_multiple_plots(
key: str,
plots_data: list[tuple], # [(x, y, label), ...]
title: str = None,
xlabel: str = None,
ylabel: str = None,
figsize: tuple = (10, 6),
meta: dict = None
) -> MediaResultExample:
result = run.log_multiple_plots("comparison", [
(steps, train_loss, "Train"),
(steps, val_loss, "Validation"),
], title="Loss Curves")run.log_batch()
Log multiple metrics in parallel.
result = run.log_batch(
metrics_list: list[dict],
max_workers: int = 4
) -> BatchResultExample:
metrics = [
{"step": 0, "loss": 0.5},
{"step": 1, "loss": 0.4},
{"step": 2, "loss": 0.3},
]
result = run.log_batch(metrics)
print(f"Success rate: {result.success_rate:.1f}%")Context Manager
Run supports the context manager protocol:
with project.run(name="experiment") as run:
run.log(step=0, loss=0.5)
# Automatically prints completion statusQuery Functions
These functions are available at the module level for querying existing data.
optixlog.list_runs()
List recent runs.
runs = optixlog.list_runs(
api_url: str,
api_key: str,
project: str = None,
limit: int = 10
) -> list[RunInfo]Example:
import optixlog
runs = optixlog.list_runs(api_url, api_key, project="MyProject", limit=5)
for run in runs:
print(f"{run.name}: {run.run_id}")optixlog.get_run()
Get details about a specific run.
run = optixlog.get_run(
api_url: str,
api_key: str,
run_id: str
) -> RunInfo | Noneoptixlog.get_metrics()
Get all metrics for a run.
metrics = optixlog.get_metrics(
api_url: str,
api_key: str,
run_id: str
) -> dict[str, list]
# Returns: {"metric_name": [(step, value), ...], ...}optixlog.get_artifacts()
Get artifacts (images, files) for a run.
artifacts = optixlog.get_artifacts(
api_url: str,
api_key: str,
run_id: str
) -> list[ArtifactInfo]optixlog.download_artifact()
Download an artifact to a local file.
success = optixlog.download_artifact(
api_url: str,
api_key: str,
media_id: str,
output_path: str
) -> booloptixlog.compare_runs()
Compare metrics across multiple runs.
comparison = optixlog.compare_runs(
api_url: str,
api_key: str,
run_ids: list[str]
) -> ComparisonResult | Noneoptixlog.list_projects()
List all projects.
projects = optixlog.list_projects(
api_url: str,
api_key: str
) -> list[ProjectInfo]Utility Functions
optixlog.get_mpi_info()
Get MPI environment information.
info = optixlog.get_mpi_info() -> dict
# Returns: {"is_master": bool, "rank": int, "size": int, "has_mpi": bool}optixlog.is_master_process()
Check if current process is master.
is_master = optixlog.is_master_process() -> boolReturn Types
MetricResult
@dataclass
class MetricResult:
step: int
metrics: dict
success: bool
timestamp: datetime = None
error: str = NoneSupports boolean checks: if result: ...
MediaResult
@dataclass
class MediaResult:
key: str
success: bool
media_id: str = None
url: str = None
file_size: int = None
content_type: str = None
error: str = NoneSupports boolean checks: if result: ...
BatchResult
@dataclass
class BatchResult:
total: int
successful: int
failed: int
results: list
errors: list[str]
@property
def success_rate(self) -> floatRunInfo
@dataclass
class RunInfo:
run_id: str
name: str | None
project_id: str
project_name: str
config: dict
created_at: str
status: str = "running"ArtifactInfo
@dataclass
class ArtifactInfo:
media_id: str
key: str
kind: str
url: str
content_type: str
file_size: int = None
created_at: str = None
meta: dict = {}ProjectInfo
@dataclass
class ProjectInfo:
project_id: str
name: str
created_at: str
run_count: int = NoneComparisonResult
@dataclass
class ComparisonResult:
runs: list[RunInfo]
common_metrics: list[str]
metrics_data: dict[str, dict[str, list]]Exceptions
ValidationError
Raised for invalid inputs (NaN values, bad types, empty metrics).
from optixlog import ValidationError
try:
run.log(step=0, value=float('nan'))
except ValidationError as e:
print(f"Validation error: {e}")OxInvalidTaskError
Raised for task operation failures.
from optixlog import OxInvalidTaskErrorValueError
Raised for:
- Missing API key
- Project not found
- Authentication failures
- Server connection errors
Environment Variables
| Variable | Description | Default |
|---|---|---|
OPTIX_API_KEY | API key | None |
OPTIX_API_URL | API endpoint | https://optixlog.com |