SDK

Quick Start

Get logging in 5 minutes with the OptixLog SDK

Quick Start

Get logging in 5 minutes with the OptixLog SDK.

1. Install

pip install optixlog

2. Get Your API Key

Sign up and get your API key from optixlog.com.

3. Your First Run

Create a new Python file first_run.py:

from optixlog import Optixlog

# Create client with your API key
client = Optixlog(api_key="your_api_key_here")

# Get or create a project
project = client.project(name="MyFirstProject")

# Create a run
run = project.run(name="hello_world")

# Log a metric
run.log(step=0, message="Hello, OptixLog!")

print("✓ Run complete! Visit optixlog.com to see your data")

Run it:

python first_run.py

4. View Results

Go to optixlog.com → MyFirstProject → hello_world


Complete Example

Here's a more complete example showing the key features:

from optixlog import Optixlog
import numpy as np
import matplotlib.pyplot as plt

# Initialize client
client = Optixlog(api_key="your_api_key_here")

# Get project
project = client.project(name="QuickStartDemo")

# Create run with configuration
run = project.run(
    name="training_demo",
    config={
        "learning_rate": 0.001,
        "batch_size": 32,
        "epochs": 100
    }
)

# Log metrics during training
print("Logging metrics...")
for step in range(100):
    # Simulate training metrics
    loss = 1.0 / (step + 1) + np.random.normal(0, 0.01)
    accuracy = 1 - np.exp(-step / 20) + np.random.normal(0, 0.02)

    # Log to OptixLog
    run.log(step=step, loss=loss, accuracy=accuracy)

    if step % 20 == 0:
        print(f"  Step {step}: loss={loss:.4f}, accuracy={accuracy:.4f}")

# Create and log a plot
print("Creating visualization...")
fig, ax = plt.subplots(figsize=(10, 6))
steps = np.arange(100)
losses = 1.0 / (steps + 1)
ax.plot(steps, losses, 'b-', linewidth=2)
ax.set_xlabel('Step')
ax.set_ylabel('Loss')
ax.set_title('Training Loss')
ax.grid(True, alpha=0.3)

run.log_matplotlib("training_loss", fig)
plt.close()

print("✓ Demo complete! Check optixlog.com")

This example:

  1. Creates a client and project
  2. Creates a run with configuration
  3. Logs 100 steps of metrics
  4. Creates and logs a matplotlib plot

Key Concepts

1. Client

The entry point to the SDK:

from optixlog import Optixlog

client = Optixlog(
    api_key="your_key",
    api_url="https://optixlog.com"  # Optional, defaults to optixlog.com
)

2. Project

Container for related experiments:

# Get existing project or create new one
project = client.project(name="MyProject")

# Explicit creation control
project = client.project(name="NewProject", create_if_not_exists=True)

3. Run

Individual experiment instance:

# Simple run
run = project.run(name="experiment_1")

# Run with configuration
run = project.run(
    name="experiment_2",
    config={"lr": 0.001, "batch_size": 32}
)

4. Logging

Log various types of data:

# Metrics
run.log(step=0, loss=0.5, accuracy=0.95)

# Images
run.log_matplotlib("plot", fig)
run.log_image("photo", pil_image)

# Files
run.log_file("results", "data.csv", "text/csv")

# Arrays as heatmaps
run.log_array_as_image("field", array, cmap='hot')

Common Patterns

Context Manager

Use with for automatic status reporting:

run = project.run(name="experiment")
with run:
    run.log(step=0, loss=0.5)
    run.log(step=1, loss=0.4)
# Prints "✓ Run completed successfully"

Parameter Sweeps

Loop through different configurations:

from optixlog import Optixlog

client = Optixlog(api_key="your_key")
project = client.project(name="Sweep")

for lr in [0.001, 0.01, 0.1]:
    for batch_size in [16, 32, 64]:
        run = project.run(
            name=f"lr{lr}_bs{batch_size}",
            config={"lr": lr, "batch_size": batch_size}
        )

        # Train and log
        for step in range(50):
            loss = train_step(lr, batch_size)
            run.log(step=step, loss=loss)

Quick Plotting

Create and log plots in one line:

# Line plot
run.log_plot("spectrum", frequencies, transmission,
             title="Transmission Spectrum",
             xlabel="Frequency (THz)",
             ylabel="Transmission")

# Histogram
run.log_histogram("distribution", data, bins=50,
                  title="Error Distribution")

# Scatter plot
run.log_scatter("correlation", x, y,
                title="X vs Y Correlation")

# Multiple lines
run.log_multiple_plots("comparison", [
    (steps, train_loss, "Train"),
    (steps, val_loss, "Validation"),
], title="Loss Curves")

Batch Logging

Upload many metrics in parallel:

# Prepare data
metrics = []
for step in range(1000):
    metrics.append({
        "step": step,
        "loss": compute_loss(step),
        "accuracy": compute_accuracy(step)
    })

# Upload in parallel (faster!)
result = run.log_batch(metrics, max_workers=4)
print(f"Uploaded {result.successful}/{result.total} metrics")

Configuration

API Key

Three ways to provide your API key:

  1. Direct (recommended for getting started):

    client = Optixlog(api_key="your_key")
  2. Environment variable (optional, not required):

    export OPTIX_API_KEY="your_key"
    import os
    client = Optixlog(api_key=os.getenv("OPTIX_API_KEY"))
  3. Config file (for teams):

    import json
    with open("config.json") as f:
        config = json.load(f)
    client = Optixlog(api_key=config["api_key"])

Custom API URL

For self-hosted or development:

client = Optixlog(
    api_key="your_key",
    api_url="http://localhost:3000"
)

Or via environment variable:

export OPTIX_API_URL="http://localhost:3000"

MPI Support

For parallel simulations, MPI is detected automatically:

# Install MPI support
pip install mpi4py

# Run with MPI
mpirun -n 4 python simulation.py
from optixlog import Optixlog

client = Optixlog(api_key="your_key")

# MPI info automatically detected
print(f"Rank: {client.rank}/{client.size}")
print(f"Is master: {client.is_master}")

# Only master logs
run = client.project(name="Parallel").run(name="simulation")
run.log(step=0, result=42)  # Only rank 0 uploads

No code changes needed - the SDK handles everything!


What to Log

TypeWhen to UseMethod
MetricsScalars over time (loss, accuracy, power)log()
PlotsVisualizations (spectra, fields, curves)log_matplotlib(), log_plot()
ImagesPhotos, screenshots, diagramslog_image()
ArraysField data, heatmapslog_array_as_image()
FilesCSV, HDF5, JSON, videoslog_file()
ConfigHyperparameters, settingsconfig={} in run()

Real-World Example

Photonic waveguide simulation:

from optixlog import Optixlog
import numpy as np

client = Optixlog(api_key="your_key")
run = client.project(name="Photonics").run(
    name="waveguide_sweep",
    config={
        "wavelength": 1.55,
        "resolution": 30,
        "pml_thickness": 1.0
    }
)

# Simulate
for step in range(200):
    # Your simulation code
    field = simulate_step()
    power = calculate_power(field)
    transmission = calculate_transmission(field)

    # Log metrics
    run.log(step=step, power=power, transmission=transmission)

    # Log field visualization every 20 steps
    if step % 20 == 0:
        run.log_array_as_image(
            f"field_{step}",
            field,
            cmap='RdBu',
            title=f"E-field at step {step}"
        )

print("Simulation complete!")

Troubleshooting

"Invalid API Key"

Make sure your API key is correct:

client = Optixlog(api_key="opti_...")  # Should start with "opti_" or "proj_"

Get your API key from: optixlog.com/settings

"Project not found"

Create the project first or use auto-creation:

project = client.project(name="MyProject", create_if_not_exists=True)

Import Error

Make sure OptixLog is installed:

pip install optixlog
python -c "import optixlog; print(optixlog.__version__)"

Connection Error

Check your API URL:

client = Optixlog(
    api_key="your_key",
    api_url="https://optixlog.com"  # Make sure this is correct
)

Next Steps

Now that you've completed the quick start:

Need Help?

On this page