Class Trial
- Namespace
- OptunaSharp
- Assembly
- OptunaSharp.dll
A trial is a process of evaluating an objective function.
Port of optuna/trial/_trial.py: Trial.
This object is passed to an objective function and provides interfaces to get parameter suggestion, manage the trial's state, and set/get user-defined attributes of the trial.
Note that the direct use of this constructor is not recommended. This object is seamlessly instantiated and passed to the objective function behind the Optimize(Func<Trial, double>, int?, double?, int, Type[]?, IEnumerable<Action<Study, FrozenTrial>>?, bool, bool, TrialExecutorOptions?, CancellationToken) method; hence library users do not care about instantiation of this object.
public class Trial : BaseTrial
- Inheritance
-
Trial
- Inherited Members
- Extension Methods
Constructors
Trial(Study, int)
Binds to an existing trial record and invokes the sampler's BeforeTrial hook.
public Trial(Study study, int trialId)
Parameters
studyStudyStudy whose history and storage are used by the operation.
trialIdintStorage identifier of the trial; distinct from its per-study trial number.
Remarks
The trial keeps a private copy of the stored record. Python's Trial keeps the storage's own
object and later mutates it, after the storage has already replaced it with a copy-on-write update.
Other threads may still hold that object from GetAllTrials(deepcopy: false), so the mutation
was a data race on its dictionaries.
Exceptions
- KeyError
The trial identifier does not exist in storage.
- Exception
The configured storage or sampler hook fails; its original exception propagates.
Properties
CancellationToken
The cancellation token of the Optimize call running this trial (its ct argument), or
None for a trial from Ask(OrderedDict<string, BaseDistribution>?)
or one built directly. OptunaSharp only: Python interrupts a running objective with KeyboardInterrupt
instead.
public CancellationToken CancellationToken { get; }
Property Value
Remarks
An objective may poll it (ThrowIfCancellationRequested()) or hand it to
cancellable work, so that a long evaluation stops when the caller cancels the run. An
OperationCanceledException that escapes the objective while the token is cancelled stores
this trial as FAIL, as Python stores the trial its KeyboardInterrupt lands in, skips the callbacks,
and ends the Optimize call whatever its catch argument holds.
An objective that ignores the token runs to its end and is stored as it returns; the run stops before the next trial. Observing the token is the objective's choice, as in any cooperative .NET cancellation.
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
DatetimeStart
Return start datetime.
public override DateTime? DatetimeStart { get; }
Property Value
Distributions
Return distributions of parameters to be optimized.
public override IReadOnlyDictionary<string, BaseDistribution> Distributions { get; }
Property Value
Number
Return trial's number which is consecutive and unique in a study.
public override int Number { get; }
Property Value
Params
Return parameters to be optimized.
public override IReadOnlyDictionary<string, object?> Params { get; }
Property Value
Study
The parent Study.
public Study Study { get; }
Property Value
UserAttrs
Return user attributes.
public override IReadOnlyDictionary<string, object?> UserAttrs { get; }
Property Value
Methods
Report(double, long)
Report an objective function value for a given step.
The reported values are used by the pruners to determine whether this trial should be
pruned. If this method is called multiple times at the same step
in a trial, the reported value only the first time is stored and the reported values
from the second time are ignored.
public override void Report(double value, long step)
Parameters
valuedoubleA value returned from the objective function.
steplongStep of the trial (e.g., Epoch of neural network training). Note that pruners assume that
stepstarts at zero.stepmust be a non-negative integer. It is 64-bit, as Python's unboundedintis in journal, SQLite and in-memory storages; the PostgreSQL and MySQL schemas keep Optuna's 32-bit column, which refuses a larger step.
Exceptions
- UpdateFinishedTrialError
The storage record is already finished.
- KeyError
The trial was removed from storage.
- Exception
A configured storage or sampler implementation fails; its exception propagates.
- NotImplementedException
Reporting intermediate values is unsupported for multi-objective studies.
- ValueError
The reporting step is negative.
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.
- UpdateFinishedTrialError
The storage record is already finished.
- KeyError
The trial was removed from storage.
- Exception
A configured storage or sampler implementation fails; its exception propagates.
SetUserAttr(string, object?)
Set user attributes to the trial, accessible via UserAttrs.
public override void SetUserAttr(string key, object? value)
Parameters
keystringA key string of the attribute.
valueobjectA value of the attribute. The value should be JSON serializable.
Exceptions
- UpdateFinishedTrialError
The storage record is already finished.
- KeyError
The trial was removed from storage.
- Exception
A configured storage or sampler implementation fails; its exception propagates.
SetUserAttrs(IReadOnlyDictionary<string, object?>)
Set several user attributes to the trial at once (Rustuna's set_user_attrs; plan 13, item S8), with one
storage call: the stored and cached result is what SetUserAttr(string, object?) once per entry
leaves.
public override void SetUserAttrs(IReadOnlyDictionary<string, object?> attrs)
Parameters
attrsIReadOnlyDictionary<string, object>The attributes, set in enumeration order. The values should be JSON serializable.
Remarks
The storage writes the batch in one step (SetTrialUserAttrs(int, IReadOnlyDictionary<string, object?>)), and the trial's own copy is updated only after the storage accepted it, so a refused batch leaves both unchanged. Under the trial's monitor, like SetUserAttr(string, object?), so a concurrent read of this trial's attributes sees the batch whole or not at all.
Exceptions
- ArgumentNullException
attrsis null.- UpdateFinishedTrialError
The storage record is already finished; nothing is set.
- KeyError
The trial was removed from storage; nothing is set.
- Exception
A configured storage fails; its exception propagates.
ShouldPrune()
Suggest whether the trial should be pruned or not.
The suggestion is made by a pruning algorithm associated with the trial and is based on previously reported values. The algorithm can be specified when constructing a Study.
public override bool ShouldPrune()
Returns
- bool
True if the configured pruner recommends stopping the trial.
Exceptions
- NotImplementedException
Pruning through Trial is unsupported for multi-objective studies.
- Exception
The configured pruner or storage provider fails.
SuggestCategorical(string, CategoricalDistribution)
Suggest a value for the categorical parameter from a prebuilt, reusable distribution — the allocation-free sibling of SuggestCategorical(string, IEnumerable<CategoricalChoice>) for callers that suggest the same fixed domain on every trial (a GA genome does this for every gene of every trial, where rebuilding a hundreds-of-choices distribution per call dominates the loop).
public override CategoricalChoice SuggestCategorical(string name, CategoricalDistribution distribution)
Parameters
namestringParameter name; repeated suggestions refer to the same parameter.
distributionCategoricalDistributionThe reusable distribution. Treat it as immutable and shared: live trials store this very instance into their record and the study's parameter registry (which is what makes the per-suggest compatibility check O(1) by reference), so mutating it afterwards would corrupt recorded trials.
Returns
- CategoricalChoice
The suggested or previously recorded categorical value.
Remarks
The base implementation forwards to the sequence overload (a copy, but correct) so every BaseTrial subclass — replay trials included — accepts it; Trial overrides it to reuse the instance without any copy.
Exceptions
- ValueError
A required stored parameter is missing, or a repeated suggestion changes its distribution kind or categorical choices.
- ArgumentNullException
The distribution is null.
SuggestCategorical(string, IEnumerable<CategoricalChoice>)
Suggest a value for the categorical parameter. The value is sampled from
choices.
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 suggested or previously recorded 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.
- UpdateFinishedTrialError
The storage record is already finished.
- KeyError
The trial was removed from storage.
- Exception
A configured storage or sampler implementation fails; its exception propagates.
- TypeError
A stored or sampled value is not a supported categorical scalar.
- ArgumentNullException
The choices sequence is null.
SuggestFloat(string, double, double, double?, bool)
Suggest a value for the floating point parameter.
public override double SuggestFloat(string name, double low, double high, double? step = null, bool log = false)
Parameters
namestringA parameter name.
lowdoubleLower endpoint of the range of suggested values.
lowis included in the range.lowmust be less than or equal tohigh. Iflogistrue,lowmust be larger than 0.highdoubleUpper endpoint of the range of suggested values.
highis included in the range.stepdouble?A step of discretization. Cannot be combined with
log.logboolA flag to sample the value from the log domain or not.
Returns
- double
A suggested float 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.
- UpdateFinishedTrialError
The storage record is already finished.
- KeyError
The trial was removed from storage.
- Exception
A configured storage or sampler implementation fails; its exception propagates.
- TypeError
The stored or sampled value cannot be converted to a float.
SuggestInt(string, long, long, long, bool)
Suggest a value for the integer parameter. The value is sampled from the integers in
[low, high].
public override long SuggestInt(string name, long low, long high, long step = 1, bool log = false)
Parameters
namestringA parameter name.
lowlongLower endpoint of the range of suggested values (included).
highlongUpper endpoint of the range of suggested values (included).
steplongPositive integer spacing; logarithmic sampling requires a step of one.
logboolA flag to sample the value from the log domain or not.
Returns
- long
The suggested or previously recorded integer 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.
- UpdateFinishedTrialError
The storage record is already finished.
- KeyError
The trial was removed from storage.
- Exception
A configured storage or sampler implementation fails; its exception propagates.
- FormatException
A stored or sampled string is not an integer.
- OverflowException
An integer conversion exceeds Int64.
- InvalidCastException
The value does not support integer conversion.