Skip to main content

Trial

Struct Trial 

Source
pub struct Trial { /* private fields */ }
Expand description

A single evaluation of the objective function.

Each trial has a unique ID and stores the sampled parameters along with their distributions. The trial progresses through states: RunningComplete / Failed / Pruned.

Trials use a Sampler to generate parameter values. When created through Study::create_trial, the trial receives the study’s sampler and access to the history of completed trials for informed sampling.

§Examples

use optimizer::Trial;
use optimizer::parameter::{FloatParam, Parameter};

let mut trial = Trial::new(0);
let x = FloatParam::new(-5.0, 5.0).suggest(&mut trial).unwrap();

Implementations§

Source§

impl Trial

Source

pub fn new(id: u64) -> Self

Create a new trial with the given ID.

The trial starts in the Running state with no parameters sampled. This constructor creates a trial without a sampler, which will fall back to random sampling for suggest_param calls.

For trials that use the study’s sampler, the study creates them internally via Trial::with_sampler.

§Arguments
  • id - A unique identifier for this trial.
§Examples
use optimizer::Trial;

let trial = Trial::new(0);
assert_eq!(trial.id(), 0);
Source

pub fn id(&self) -> u64

Return the unique ID of this trial.

Source

pub fn state(&self) -> TrialState

Return the current state of this trial.

Source

pub fn params(&self) -> &HashMap<ParamId, ParamValue>

Return a reference to the sampled parameters, keyed by ParamId.

Source

pub fn distributions(&self) -> &HashMap<ParamId, Distribution>

Return a reference to the parameter distributions, keyed by ParamId.

Source

pub fn param_labels(&self) -> &HashMap<ParamId, String>

Return a reference to the parameter labels, keyed by ParamId.

Source

pub fn report(&mut self, step: u64, value: f64)

Report an intermediate objective value at a given step.

Call this during iterative training (e.g., once per epoch) so the Pruner can decide whether to stop the trial early. Steps should be monotonically increasing; duplicate steps overwrite the previous value.

§Examples
use optimizer::Trial;

let mut trial = Trial::new(0);
for epoch in 0..10 {
    let loss = 1.0 / (epoch as f64 + 1.0);
    trial.report(epoch, loss);
}
assert_eq!(trial.intermediate_values().len(), 10);
Source

pub fn should_prune(&self) -> bool

Ask whether this trial should be pruned at the current step.

Return true if the pruner recommends stopping this trial based on the intermediate values reported so far. When true, the objective should return early with Err(TrialPruned)?.

Always returns false when no pruner is configured.

Source

pub fn intermediate_values(&self) -> &[(u64, f64)]

Return all intermediate values reported so far as (step, value) pairs.

Source

pub fn set_user_attr( &mut self, key: impl Into<String>, value: impl Into<AttrValue>, )

Set a user attribute on this trial.

User attributes are arbitrary key-value pairs for logging, debugging, or analysis. Values can be f64, i64, String, &str, or bool (anything implementing Into<AttrValue>).

§Examples
use optimizer::Trial;

let mut trial = Trial::new(0);
trial.set_user_attr("gpu", "A100");
trial.set_user_attr("batch_size", 64_i64);
trial.set_user_attr("accuracy", 0.95);
Source

pub fn user_attr(&self, key: &str) -> Option<&AttrValue>

Return a user attribute by key, or None if it does not exist.

Source

pub fn user_attrs(&self) -> &HashMap<String, AttrValue>

Return all user attributes as a map.

Source

pub fn set_constraints(&mut self, values: Vec<f64>)

Set constraint values for this trial.

Each element represents one constraint. A value ≤ 0.0 means the constraint is satisfied (feasible); a value > 0.0 means violated. Constrained samplers (e.g., NSGA-II with constraints) use these values to prefer feasible solutions.

§Examples
use optimizer::Trial;

let mut trial = Trial::new(0);
// Two constraints: first satisfied, second violated
trial.set_constraints(vec![-0.5, 0.3]);
assert_eq!(trial.constraint_values(), &[-0.5, 0.3]);
Source

pub fn constraint_values(&self) -> &[f64]

Return the constraint values for this trial.

Source

pub fn suggest_param<P: Parameter>(&mut self, param: &P) -> Result<P::Value>

Suggest a parameter value using a Parameter definition.

This is the primary entry point for sampling parameters. It handles validation, caching, conflict detection, sampling, and conversion.

§Arguments
  • param - The parameter definition.
§Errors

Returns an error if:

  • The parameter fails validation
  • The parameter conflicts with a previously suggested parameter of the same id
  • Sampling or conversion fails
§Examples
use optimizer::Trial;
use optimizer::parameter::{BoolParam, FloatParam, IntParam, Parameter};

let x_param = FloatParam::new(0.0, 1.0);
let n_param = IntParam::new(1, 10);
let flag_param = BoolParam::new();

let mut trial = Trial::new(0);

let x = trial.suggest_param(&x_param).unwrap();
let n = trial.suggest_param(&n_param).unwrap();
let flag = trial.suggest_param(&flag_param).unwrap();

Trait Implementations§

Source§

impl Clone for Trial

Source§

fn clone(&self) -> Trial

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Trial

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl Freeze for Trial

§

impl !RefUnwindSafe for Trial

§

impl Send for Trial

§

impl Sync for Trial

§

impl Unpin for Trial

§

impl !UnwindSafe for Trial

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.