Class BaseTrial
- Namespace
- OptunaSharp
- Assembly
- OptunaSharp.dll
Base class for trials. Port of optuna/trial/_base.py: BaseTrial.
Note that this class is not supposed to be directly accessed by library users.
public abstract class BaseTrial
- Inheritance
-
BaseTrial
- Derived
- Inherited Members
- Extension Methods
Properties
Constraints
Gets named constraint values; feasibility requires every value to be nonpositive.
public abstract OrderedDict<string, double> Constraints { get; }
Property Value
DatetimeStart
Gets the trial creation or start time, or null for a waiting trial.
public abstract DateTime? DatetimeStart { get; }
Property Value
Distributions
Gets the distribution recorded for each suggested parameter.
public abstract IReadOnlyDictionary<string, BaseDistribution> Distributions { get; }
Property Value
Number
Gets the zero-based trial number within the study or replay context.
public abstract int Number { get; }
Property Value
Params
Gets parameters already suggested through this trial, using their external values.
public abstract IReadOnlyDictionary<string, object?> Params { get; }
Property Value
UserAttrs
Gets the user metadata attached to this trial.
public abstract IReadOnlyDictionary<string, object?> UserAttrs { get; }
Property Value
Methods
Report(double, long)
Records the first intermediate objective value for a nonnegative step.
public abstract void Report(double value, long step)
Parameters
valuedoubleIntermediate objective value; ignored by replay trials.
steplongNonnegative reporting step; duplicate reports retain the first observation. 64-bit because Python's
stepis an unboundedint: a study Python wrote with a step past 2^31 must stay readable.
SetComponentLosses(ReadOnlySpan<double>)
Expose this trial's observed-components vector — the per-trial residual terms
r = (r_1, …, r_m) of an objective that decomposes as f(x) = mean_i r_i(x) — on
the Key user attribute. Samplers that exploit residual
structure (notably JanusSampler in its recommended component mode)
read it back through TryGetComponentLosses(out double[]). The vector must be
non-empty and all-finite (a non-finite entry raises ValueError); see
ComponentLosses for the full contract.
public void SetComponentLosses(ReadOnlySpan<double> components)
Parameters
componentsReadOnlySpan<double>The residual vector; use a length consistent across trials.
Exceptions
- ValueError
The vector is empty or contains NaN or infinity.
- UpdateFinishedTrialError
An active storage-backed trial has already finished.
SetConstraint(string, double)
Records the first value of a named constraint; nonpositive values are feasible.
public abstract 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.
SetUserAttr(IReadOnlyDictionary<string, object?>)
Optuna's set_user_attr name for SetUserAttrs(IReadOnlyDictionary<string, object?>): several user attributes in one call.
public void SetUserAttr(IReadOnlyDictionary<string, object?> attrs)
Parameters
attrsIReadOnlyDictionary<string, object>The attributes, set in enumeration order.
Exceptions
- ArgumentNullException
attrsis null.- Exception
Whatever SetUserAttrs(IReadOnlyDictionary<string, object?>) throws.
SetUserAttr(string, object?)
Stores a user attribute by name.
public abstract void SetUserAttr(string key, object? value)
Parameters
keystringAttribute name; an existing attribute is overwritten.
valueobjectAttribute value; persistent backends require JSON-serializable data.
SetUserAttrs(IReadOnlyDictionary<string, object?>)
Stores several user attributes at once (Rustuna's set_user_attrs; Rustuna plan 13, item S8). Optuna has
no such call: the result is what SetUserAttr(string, object?) once per entry, in the dictionary's
order, leaves.
public virtual void SetUserAttrs(IReadOnlyDictionary<string, object?> attrs)
Parameters
attrsIReadOnlyDictionary<string, object>The attributes, set in enumeration order; persistent backends require JSON-serializable values.
Remarks
This default calls SetUserAttr(string, object?) per entry. Trial overrides it to write the whole batch through one storage call (one lock, journal append or transaction), so an unknown or finished trial gets nothing written.
Exceptions
- ArgumentNullException
attrsis null.- Exception
Whatever SetUserAttr(string, object?) throws for an entry.
ShouldPrune()
Asks the study pruner whether the current trial should stop early.
public abstract bool ShouldPrune()
Returns
- bool
True if the configured pruner recommends stopping the trial.
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 virtual 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 abstract 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.
- ArgumentNullException
The choices sequence is null.
SuggestCategorical(string, IEnumerable<bool>)
Suggests a categorical parameter value for the objective.
public bool SuggestCategorical(string name, IEnumerable<bool> choices)
Parameters
namestringParameter name; repeated suggestions refer to the same parameter.
choicesIEnumerable<bool>Nonempty sequence of categorical candidates; order is retained and determines stored indices.
Returns
- bool
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.
- ArgumentNullException
The choices sequence is null.
- InvalidCastException
The delegated suggestion has an underlying CLR type incompatible with this typed overload, for example when replaying a Python-equal value of a different scalar kind.
SuggestCategorical(string, IEnumerable<double>)
Suggests a categorical parameter value for the objective.
public double SuggestCategorical(string name, IEnumerable<double> choices)
Parameters
namestringParameter name; repeated suggestions refer to the same parameter.
choicesIEnumerable<double>Nonempty sequence of categorical candidates; order is retained and determines stored indices.
Returns
- double
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.
- ArgumentNullException
The choices sequence is null.
- InvalidCastException
The delegated suggestion has an underlying CLR type incompatible with this typed overload, for example when replaying a Python-equal value of a different scalar kind.
SuggestCategorical(string, IEnumerable<int>)
Suggests a categorical parameter value for the objective.
public long SuggestCategorical(string name, IEnumerable<int> choices)
Parameters
namestringParameter name; repeated suggestions refer to the same parameter.
choicesIEnumerable<int>Nonempty sequence of categorical candidates; order is retained and determines stored indices.
Returns
- long
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.
- ArgumentNullException
The choices sequence is null.
- InvalidCastException
The delegated suggestion has an underlying CLR type incompatible with this typed overload, for example when replaying a Python-equal value of a different scalar kind.
SuggestCategorical(string, IEnumerable<long>)
Suggests a categorical parameter value for the objective.
public long SuggestCategorical(string name, IEnumerable<long> choices)
Parameters
namestringParameter name; repeated suggestions refer to the same parameter.
choicesIEnumerable<long>Nonempty sequence of categorical candidates; order is retained and determines stored indices.
Returns
- long
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.
- ArgumentNullException
The choices sequence is null.
- InvalidCastException
The delegated suggestion has an underlying CLR type incompatible with this typed overload, for example when replaying a Python-equal value of a different scalar kind.
SuggestCategorical(string, IEnumerable<string>)
Suggests a categorical parameter value for the objective.
public string SuggestCategorical(string name, IEnumerable<string> choices)
Parameters
namestringParameter name; repeated suggestions refer to the same parameter.
choicesIEnumerable<string>Nonempty sequence of categorical candidates; order is retained and determines stored indices.
Returns
- string
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.
- ArgumentNullException
The choices sequence is null.
- InvalidCastException
The delegated suggestion has an underlying CLR type incompatible with this typed overload, for example when replaying a Python-equal value of a different scalar kind.
SuggestCategorical<TEnum>(string)
Suggests a categorical parameter over every declared member of TEnum.
Choice order follows GetNames<TEnum>() — sorted by underlying value,
not source-declaration order — which fixes the stored categorical indices; pass an
explicit sequence to the sibling overload when a specific order or a subset is required.
public TEnum SuggestCategorical<TEnum>(string name) where TEnum : struct, Enum
Parameters
namestringParameter name; repeated suggestions refer to the same parameter.
Returns
- TEnum
The suggested (or previously recorded) enum member.
Type Parameters
TEnumThe enum whose declared members are the choices.
Exceptions
- ValueError
The enum has no members, a required stored parameter is missing, a repeated suggestion changes the choices, or a stored string is not a declared member of
TEnum.- TypeError
A stored categorical value is not a member-name string.
SuggestCategorical<TEnum>(string, IEnumerable<TEnum>)
Suggests a categorical parameter over a chosen subset of TEnum members,
preserving the given order (which determines the stored categorical indices).
public TEnum SuggestCategorical<TEnum>(string name, IEnumerable<TEnum> choices) where TEnum : struct, Enum
Parameters
namestringParameter name; repeated suggestions refer to the same parameter.
choicesIEnumerable<TEnum>Nonempty sequence of members; order is retained and determines stored indices.
Returns
- TEnum
The suggested (or previously recorded) enum member.
Type Parameters
TEnumThe enum whose members form the choices.
Exceptions
- ArgumentNullException
The choices sequence is null.
- ArgumentException
A supplied member is not a single declared value (a
[Flags]combination or an undefined value has no categorical name).- ValueError
The choices are empty, a required stored parameter is missing, a repeated suggestion changes the choices, or a stored string is not among the given members.
- TypeError
A stored categorical value is not a member-name string.
SuggestDiscreteUniform(string, double, double, double)
Uses the deprecated float-suggestion alias and emits a FutureWarning.
[Obsolete("suggest_discrete_uniform has been deprecated in v3.0.0. This feature will be removed in v6.0.0. See https://github.com/optuna/optuna/releases/tag/v3.0.0. Use suggest_float(..., step=...) instead.")]
public virtual double SuggestDiscreteUniform(string name, double low, double high, double q)
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.
qdoublePositive float discretization step.
Returns
- double
The value returned by SuggestFloat.
Exceptions
- ValueError
The bounds or discretization are invalid, or the delegated suggestion is incompatible with the stored parameter.
SuggestFloat(string, double, double, double?, bool)
Suggests a floating-point parameter value for the objective.
public abstract 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 suggested or previously recorded floating-point 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.
- 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)
Suggests a integer parameter value for the objective.
public abstract 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 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.
SuggestLogUniform(string, double, double)
Uses the deprecated float-suggestion alias and emits a FutureWarning.
[Obsolete("suggest_loguniform has been deprecated in v3.0.0. This feature will be removed in v6.0.0. See https://github.com/optuna/optuna/releases/tag/v3.0.0. Use suggest_float(..., log=True) instead.")]
public virtual double SuggestLogUniform(string name, double low, double high)
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.
Returns
- double
The value returned by SuggestFloat.
Exceptions
- ValueError
The bounds or discretization are invalid, or the delegated suggestion is incompatible with the stored parameter.
SuggestUniform(string, double, double)
Uses the deprecated float-suggestion alias and emits a FutureWarning.
[Obsolete("suggest_uniform has been deprecated in v3.0.0. This feature will be removed in v6.0.0. See https://github.com/optuna/optuna/releases/tag/v3.0.0. Use suggest_float instead.")]
public virtual double SuggestUniform(string name, double low, double high)
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.
Returns
- double
The value returned by SuggestFloat.
Exceptions
- ValueError
The bounds or discretization are invalid, or the delegated suggestion is incompatible with the stored parameter.