/gpcam:cost-functionsfrom gpcam
Designs cost functions for gpCAM that penalize expensive moves between measurement points — motor travel time, settling, directional costs, sample damage, beam time, or zone-based penalties.
Ships in gpcam. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Verified against gpCAM 8.7.0 / fvgp 4.11.1 — last checked 2026-10-28 (gpCAM a21385a).
Design cost functions that account for the real expense of moving between measurement points — motor travel time, sample damage, beam time, etc.
The cost function modifies the acquisition score:
effective_score(x) = acquisition_score(x) / cost(origin, x)
Points that are expensive to reach get penalized. The optimizer still picks high-value points, but prefers nearby high-value points over distant ones.
gpCAM calls the cost function with exactly two positional arguments:
def my_cost(origin, x):
"""
Parameters
----------
origin : np.ndarray, shape (D,) or (1, D)
The current position (where we are now), as passed to ask(position=...).
x : np.ndarray, shape (V, D)
The candidate destination positions.
Returns
-------
cost : np.ndarray, shape (V,)
Cost of moving from origin to each point in x.
Must be > 0. Higher cost = less desirable to visit.
"""
Key rules:
> 0) and return a 1-D array of shape (V,) — it is used as a divisor (surrogate_model.py:265), so zero cost causes division by zero. Always include a positive base offset (e.g., measurement overhead time).position=current_position to ask(): gpCAM only evaluates cost_function(origin, x) when origin is not None (surrogate_model.py:264). Omitting position= in ask() silently disables the cost function.n > 1) follow a path: each greedy pick is chosen with the cost from the previous pick, not from position — the instrument's route through the batch. f_a(x) reports each pick's acquisition value divided by that cost.args dict or trainable hyperparameters: cost_function is always called with 2 arguments cost_function(origin, x) and is not optimized during train(). Parameterize it with functools.partial (which survives pickle.dumps(gpo) for checkpointing; see the experiment-designer skill for the full args dispatch table).functools.partial)from functools import partial
import numpy as np
def travel_cost(origin, x, offset=1.0, weights=1.0):
"""
Base overhead `offset` (> 0) plus weighted Euclidean travel time.
Pass `weights` as a scalar or shape-(D,) per-axis array via functools.partial.
"""
diff = (x - origin) * np.asarray(weights, dtype=float)
return offset + np.linalg.norm(diff, axis=1)
my_cost = partial(travel_cost, offset=1.0, weights=[1.0, 3.0])
For axis-by-axis (Manhattan) stages, replace np.linalg.norm(diff, axis=1) with np.sum(np.abs(diff), axis=1).
Combine asymmetric step costs, step-function settling times, or expensive-region penalties into the same positive 1-D return vector:
def stage_cost(origin, x):
"""Asymmetric axis-0 motion + long-move settling time + zone penalty."""
base = 1.0
diff = x - origin
axis0_cost = np.maximum(diff[:, 0], 0.0) * 1.0 + np.maximum(-diff[:, 0], 0.0) * 5.0
settling = np.where(np.linalg.norm(diff, axis=1) > 2.0, 3.0, 0.0)
zone_penalty = np.where(x[:, 0] > 8.0, 10.0, 0.0)
return base + axis0_cost + settling + zone_penalty
gpo = GPOptimizer(
x_data=x_data,
y_data=y_data,
cost_function=my_cost,
)
current_position = np.array([[0.0, 0.0]]) # where the instrument is now
for i in range(N_ITERATIONS):
next_x = gpo.ask(
input_set=parameter_bounds,
position=current_position, # REQUIRED — sets `origin`
acquisition_function="variance",
)["x"]
y = measure(next_x)
gpo.tell(next_x, y)
current_position = next_x # advance the origin
If you don't know the cost parameters ahead of time, record the real cost of each move during the experiment and fit them offline. There is no gpCAM helper for this — write the fit yourself; it is a few lines:
import numpy as np
from scipy.optimize import curve_fit
# Record every move as you go:
observations = [] # (origin, destination, measured_cost) triples
# ... inside the loop: observations.append((current_position[0], next_x[0], elapsed_seconds))
origins = np.array([o for o, _, _ in observations])
dests = np.array([d for _, d, _ in observations])
costs = np.array([c for _, _, c in observations])
distances = np.linalg.norm(dests - origins, axis=1)
# Drop outliers beyond 2 sigma of cost-per-distance (instrument glitches)
rate = costs / np.maximum(distances, 1e-9)
keep = np.abs(rate - rate.mean()) <= 2.0 * rate.std()
(offset, speed), _ = curve_fit(lambda d, a, b: a + b * d,
distances[keep], costs[keep], p0=[1.0, 1.0])
print(f"offset={offset:.3f} s, speed={speed:.3f} s per unit distance")
gpo.cost_function = partial(travel_cost, offset=offset, weights=speed)
Fitting on measured seconds makes the cost units meaningful, which matters because the acquisition is divided by it — see the balance pitfall below.
position= in ask(): The most common failure. Without it, origin is None and gpCAM skips the cost function entirely — silently.args to reach the cost function: It does not. Use a closure or functools.partial.gpo.evaluate_acquisition_function(x_grid)) and rescale so neither swamps the other.V, matching the number of candidate points.origin: Update the position you pass to ask() after every move, or the cost is computed from a stale location.x is a batch — use numpy operations, not loops.What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub lbl-camera/gpcam --plugin gpcam11 skills in this plugin
/acquisition-functionsUse when choosing or writing an acquisition function for gpCAM — selecting a built-in criterion for exploration, optimization, batch, or multi-task runs, or implementing a custom callable for UCB/LCB, minimization EI, constraints, radical gradient, or threshold finding./experiment-designerUse for end-to-end autonomous experiment design with gpCAM. Translates a scientist's description of their measurement into a complete, runnable gpCAM script — useful for replacing raster scans with adaptive sampling, peak-finding, or parameter optimization./gp2scale-advancedUse for large-scale gpCAM experiments (>10k points up to millions) using sparse compactly-supported kernels and Dask distributed computing for exact GP computation at scale./kernel-designerUse when designing or composing custom kernel (covariance) functions for gpCAM — smoothness, periodicity, symmetry, anisotropy, non-stationary amplitude/length-scale kernels (`non_stat_kernel`, Gibbs), non-Euclidean inputs, or neural-network-warped deep kernels (`Network`)./multi-task-advancedUse for multi-output, vector-valued, or function-valued gpCAM experiments using GPOptimizer with several output columns and multi_task_mode (or migrating legacy fvGPOptimizer code) — useful when a single measurement returns multiple correlated quantities (e.g., spectra, multi-channel detectors)./noise-functionsUse when modeling position-dependent, heteroscedastic, or otherwise structured noise in gpCAM — e.g., detector characteristics, count-rate-dependent variance, or non-uniform measurement uncertainty.Other plugins' skills for the same job