Class FrozenTrial
- Namespace
- OptunaSharp
- Assembly
- OptunaSharp.dll
Status and results of a Trial. Port of optuna/trial/_frozen.py.
An object of this class has the same methods as Trial, but is not associated with, nor has any references to a Study.
It will suggest the parameter values stored in Params and will not sample values from any distributions. It can be passed to objective functions and is useful for deploying optimization results.
public class FrozenTrial : BaseTrial
- Inheritance
-
FrozenTrial
- Inherited Members
- Extension Methods
Remarks
Instances are mutable, despite the name.
Constructors
FrozenTrial(int, TrialState, double?, DateTime?, DateTime?, OrderedDict<string, object?>, OrderedDict<string, BaseDistribution>, OrderedDict<string, object?>, OrderedDict<string, object?>, OrderedDict<long, double>, int, IEnumerable<double>?)
Constructs a mutable trial record, retaining the supplied dictionaries by reference.
public FrozenTrial(int number, TrialState state, double? value, DateTime? datetimeStart, DateTime? datetimeComplete, OrderedDict<string, object?> @params, OrderedDict<string, BaseDistribution> distributions, OrderedDict<string, object?> userAttrs, OrderedDict<string, object?> systemAttrs, OrderedDict<long, double> intermediateValues, int trialId, IEnumerable<double>? values = null)
Parameters
numberintPer-study trial number; use -1 for a record not yet assigned by storage.
stateTrialStateTrial state to record or inspect.
valuedouble?Single objective value; mutually exclusive with values.
datetimeStartDateTime?Local start time, or null when the trial or study has not started.
datetimeCompleteDateTime?Local completion time, or null for an unfinished trial.
paramsOrderedDict<string, object>Parameter names mapped to their external values.
distributionsOrderedDict<string, BaseDistribution>Distribution for each parameter, keyed by the same names as the parameter values.
userAttrsOrderedDict<string, object>User metadata; values should be JSON serializable for persistent storage.
systemAttrsOrderedDict<string, object>Internal metadata used by samplers and storage; preserve reserved keys.
intermediateValuesOrderedDict<long, double>Objective observations keyed by reporting step.
trialIdintStorage identifier of the trial; distinct from its per-study trial number.
valuesIEnumerable<double>Objective values in study direction order, or null when no objective values are recorded.
Remarks
Construction does not run full state validation. CreateTrial validates timestamps, state, objective values, and parameter distributions before returning.
Exceptions
- ValueError
Both value and values are supplied.
Properties
Constraints
Returns constraint values. The trial is considered feasible when all constraint values are zero or less.
public override OrderedDict<string, double> Constraints { get; }
Property Value
DatetimeComplete
Datetime where the trial finished.
public DateTime? DatetimeComplete { get; set; }
Property Value
DatetimeStart
Datetime where the trial started.
public override DateTime? DatetimeStart { get; }
Property Value
Distributions
Dictionary that contains the distributions of Params.
public override IReadOnlyDictionary<string, BaseDistribution> Distributions { get; }
Property Value
Remarks
On a compact record (see Params), a read-only view that every trial of the same parameter schema shares; DistributionsDict returns a real dictionary in every case.
DistributionsDict
Gets or replaces the mutable distribution dictionary; entries are shared distribution objects.
public OrderedDict<string, BaseDistribution> DistributionsDict { get; set; }
Property Value
Remarks
A compact record gets a dictionary of its own on the first read, as ParamsDict does.
Duration
Return the elapsed time taken to complete the trial.
public TimeSpan? Duration { get; }
Property Value
IntermediateValues
Intermediate objective values set with Report(double, long), keyed by step. Steps are 64-bit, like
Python's unbounded int steps in journal, SQLite and in-memory storages.
public OrderedDict<long, double> IntermediateValues { get; set; }
Property Value
Remarks
On a record an InMemoryStorage built with compactFinishedTrials: true compacted
while it had no intermediate values, the first read gives the record its own empty dictionary and keeps it, so
the dictionary returned here is always the record's and a change to it stays (plan 13, item S12).
LastStep
Return the maximum step of IntermediateValues in the trial (64-bit, like the steps).
public long? LastStep { get; }
Property Value
- long?
Number
Unique and consecutive number of Trial for each Study. Note that this field uses zero-based numbering.
public override int Number { get; }
Property Value
Params
Dictionary that contains suggested parameters (external representations).
public override IReadOnlyDictionary<string, object?> Params { get; }
Property Value
Remarks
On a finished record of an InMemoryStorage built with compactFinishedTrials: true
this is a read-only view over the trial's internal values (plan 13, item S12): the same entries in the same
order, each numeric value a new box with the stored bits on every read, and not an
OrderedDict<TKey, TValue>. ParamsDict returns a real dictionary in every case.
ParamsDict
The mutable parameter dictionary (Python's params setter).
public OrderedDict<string, object?> ParamsDict { get; set; }
Property Value
Remarks
A compact record (see Params) gets a dictionary of its own on the first read, which it keeps: every later read returns that dictionary, and a change to it is the trial's change. It costs the memory the compact form saved, so internal readers that only read use Params.
State
TrialState of the trial.
public TrialState State { get; set; }
Property Value
SystemAttrs
Dictionary that contains the optuna-internal attributes. Still part of Optuna 5.0.0's
FrozenTrial (only BaseTrial/Trial/Study lost theirs in #6834), so samplers
read system attributes of finished trials through it.
public IReadOnlyDictionary<string, object?> SystemAttrs { get; }
Property Value
Remarks
On a compact record, a read-only view as UserAttrs describes.
Exceptions
- Exception
The deferred storage loader fails; the loader remains available for a later attempt.
SystemAttrsDict
Gets or replaces internal attributes, resolving any deferred storage lookup once.
public OrderedDict<string, object?> SystemAttrsDict { get; set; }
Property Value
Remarks
A compact record gets a dictionary of its own on the first read, as ParamsDict does.
Exceptions
- Exception
The deferred storage loader fails; the loader remains available for a later attempt.
UserAttrs
Dictionary that contains the user attributes.
public override IReadOnlyDictionary<string, object?> UserAttrs { get; }
Property Value
Remarks
On a compact record (see Params), a read-only view: long ASCII strings come back as new string instances with the stored characters, every other value as the stored object.
UserAttrsDict
Gets or replaces the mutable user-attribute dictionary.
public OrderedDict<string, object?> UserAttrsDict { get; set; }
Property Value
Remarks
A compact record gets a dictionary of its own on the first read, as ParamsDict does.
Value
Objective value of the trial. Throws for multi-objective trials.
public double? Value { get; set; }
Property Value
Exceptions
- RuntimeError
The trial holds more than one objective value.
- ArgumentOutOfRangeException
The values list is non-null but empty when read.
Values
Sequence of objective values of the trial (length > 1 for multi-objective).
public List<double>? Values { get; set; }
Property Value
Methods
CreateTrial(TrialState, double?, IEnumerable<double>?, OrderedDict<string, object?>?, OrderedDict<string, BaseDistribution>?, OrderedDict<string, object?>?, OrderedDict<string, object?>?, OrderedDict<long, double>?, OrderedDict<string, double>?)
Create a new FrozenTrial. Port of optuna/trial/_frozen.py: create_trial.
When state is Complete, params,
distributions and value (or values) are required.
public static FrozenTrial CreateTrial(TrialState state = TrialState.Complete, double? value = null, IEnumerable<double>? values = null, OrderedDict<string, object?>? @params = null, OrderedDict<string, BaseDistribution>? distributions = null, OrderedDict<string, object?>? userAttrs = null, OrderedDict<string, object?>? systemAttrs = null, OrderedDict<long, double>? intermediateValues = null, OrderedDict<string, double>? constraints = null)
Parameters
stateTrialStateTrial state to record or inspect.
valuedouble?Single objective value, mutually exclusive with values.
valuesIEnumerable<double>Objective values in study direction order, or null when no objective values are recorded.
paramsOrderedDict<string, object>Parameter names mapped to their external values.
distributionsOrderedDict<string, BaseDistribution>Distribution for each parameter, keyed by the same names as the parameter values.
userAttrsOrderedDict<string, object>User metadata; values should be JSON serializable for persistent storage.
systemAttrsOrderedDict<string, object>Internal metadata used by samplers and storage; preserve reserved keys.
intermediateValuesOrderedDict<long, double>Objective observations keyed by reporting step.
constraintsOrderedDict<string, double>Optional named constraints; zero or negative values are feasible.
Returns
- FrozenTrial
A validated trial with placeholder number and storage identifier of -1.
Exceptions
- ValueError
Both value forms are supplied, the state has invalid values, parameter/distribution keys or bounds disagree, or a constraint is NaN.
DeepCopy()
Python copy.deepcopy(trial).
public FrozenTrial DeepCopy()
Returns
- FrozenTrial
A new trial with copied value lists and supported nested attribute containers; distribution instances remain shared.
Remarks
The copy always holds real dictionaries, including the copy of a compact record (plan 13, item S12), which is read through its views and left compact itself.
Equals(object?)
Python eq: full state comparison.
public override bool Equals(object? obj)
Parameters
objobjectObject to compare with this instance.
Returns
- bool
True when the other value has the same type and equal recorded fields.
GetHashCode()
Computes a hash from the fields participating in equality.
public override int GetHashCode()
Returns
- int
Hash code consistent with this type's equality contract.
Report(double, long)
Interface of report function.
Since FrozenTrial is not pruned, this report function does nothing.
public override void Report(double value, long step)
Parameters
valuedoubleIntermediate objective value; ignored by replay trials.
steplongZero-based reporting step (64-bit, like every trial's); ignored by replay trials.
SetConstraint(string, double)
Set a constraint value for the trial. The trial is considered feasible when all constraint values are zero or less.
public override void SetConstraint(string key, double value)
Parameters
keystringConstraint name; later writes of the same name are ignored with a warning.
valuedoubleConstraint value; zero or negative is feasible and NaN is forbidden.
Exceptions
- ValueError
The constraint value is NaN.
SetDatetimeStart(DateTime?)
Replaces the recorded trial start time.
public void SetDatetimeStart(DateTime? value)
Parameters
valueDateTime?New start timestamp, or null for a waiting trial.
SetNumber(int)
Internal setter mirroring Python's number property setter (used by storages).
public void SetNumber(int value)
Parameters
valueintNew per-study trial number assigned by storage.
SetUserAttr(string, object?)
Updates the local user attribute by name.
public override void SetUserAttr(string key, object? value)
Parameters
keystringAttribute name; an existing attribute is overwritten.
valueobjectValue retained in this replay record's local attribute dictionary.
Remarks
Writes through UserAttrsDict, so a compact record gets a dictionary of its own first.
ShouldPrune()
Suggest whether the trial should be pruned or not.
The suggestion is always false regardless of a pruning algorithm.
public override bool ShouldPrune()
Returns
- bool
Always false.
SuggestCategorical(string, IEnumerable<CategoricalChoice>)
Replays a stored categorical parameter value for the objective.
public override CategoricalChoice SuggestCategorical(string name, IEnumerable<CategoricalChoice> choices)
Parameters
namestringParameter name; repeated suggestions refer to the same parameter.
choicesIEnumerable<CategoricalChoice>Nonempty sequence of categorical candidates; order is retained and determines stored indices.
Returns
- CategoricalChoice
The stored categorical value.
Exceptions
- ValueError
The distribution is invalid, a required stored parameter is missing, or a repeated suggestion changes its distribution kind, logarithmic scale, or categorical choices.
- TypeError
A stored or sampled value is not a supported categorical scalar.
- ArgumentNullException
The choices sequence is null.
SuggestFloat(string, double, double, double?, bool)
Replays a stored floating-point parameter value for the objective.
public override double SuggestFloat(string name, double low, double high, double? step = null, bool log = false)
Parameters
namestringParameter name; repeated suggestions refer to the same parameter.
lowdoubleInclusive lower endpoint of the parameter range.
highdoubleInclusive upper endpoint; a stepped range may lower it to the last reachable grid point.
stepdouble?Positive float grid spacing, or null for a continuous range; cannot be combined with log.
logboolWhether to sample in the logarithmic domain, which requires a strictly positive lower endpoint.
Returns
- double
The stored floating-point value.
Remarks
Numeric values outside the requested range are returned with a warning when replaying stored parameters.
Exceptions
- ValueError
The distribution is invalid, a required stored parameter is missing, or a repeated suggestion changes its distribution kind, logarithmic scale, or categorical choices.
- TypeError
The stored or sampled value cannot be converted to a float.
- FormatException
A stepped bound or step is nonfinite and cannot be parsed as a decimal.
- DivideByZeroException
The positive step rounds to zero in decimal arithmetic while aligning the upper endpoint.
SuggestInt(string, long, long, long, bool)
Replays a stored integer parameter value for the objective.
public override long SuggestInt(string name, long low, long high, long step = 1, bool log = false)
Parameters
namestringParameter name; repeated suggestions refer to the same parameter.
lowlongInclusive lower endpoint of the parameter range.
highlongInclusive upper endpoint; a stepped range may lower it to the last reachable grid point.
steplongPositive integer grid spacing; must be one for logarithmic sampling.
logboolWhether to sample in the logarithmic domain, which requires a strictly positive lower endpoint.
Returns
- long
The stored integer value.
Remarks
Numeric values outside the requested range are returned with a warning when replaying stored parameters.
Exceptions
- ValueError
The distribution is invalid, a required stored parameter is missing, or a repeated suggestion changes its distribution kind, logarithmic scale, or categorical choices.
- FormatException
A stored or sampled string is not an integer.
- OverflowException
An integer conversion exceeds Int64.
- InvalidCastException
The value does not support integer conversion.
ToString()
Python repr (used in logs and debugging).
public override string ToString()
Returns
- string
Python-style representation of the recorded trial fields.
TryGetComponentLosses(out double[])
Read this trial's observed-components vector (the residual terms written with
SetComponentLosses(ReadOnlySpan<double>)) from its user attributes. Returns false
when the trial carries no valid component vector — see ComponentLosses for the
contract (list-or-array tolerant, non-finite / empty rejected). On success
components is a fresh, caller-owned copy.
public bool TryGetComponentLosses(out double[] components)
Parameters
componentsdouble[]Caller-owned finite component vector on success; otherwise an empty array.
Returns
- bool
True when valid component losses were found; false leaves an empty array.
Operators
operator >(FrozenTrial, FrozenTrial)
Applies the > comparison by trial number.
public static bool operator >(FrozenTrial left, FrozenTrial right)
Parameters
leftFrozenTrialLeft operand of the comparison.
rightFrozenTrialRight operand of the comparison.
Returns
- bool
True when the comparison holds.
operator >=(FrozenTrial, FrozenTrial)
Applies the >= comparison by trial number.
public static bool operator >=(FrozenTrial left, FrozenTrial right)
Parameters
leftFrozenTrialLeft operand of the comparison.
rightFrozenTrialRight operand of the comparison.
Returns
- bool
True when the comparison holds.
operator <(FrozenTrial, FrozenTrial)
Applies the < comparison by trial number.
public static bool operator <(FrozenTrial left, FrozenTrial right)
Parameters
leftFrozenTrialLeft operand of the comparison.
rightFrozenTrialRight operand of the comparison.
Returns
- bool
True when the comparison holds.
operator <=(FrozenTrial, FrozenTrial)
Applies the <= comparison by trial number.
public static bool operator <=(FrozenTrial left, FrozenTrial right)
Parameters
leftFrozenTrialLeft operand of the comparison.
rightFrozenTrialRight operand of the comparison.
Returns
- bool
True when the comparison holds.