Skip to main content

ParametricInstance

Struct ParametricInstance 

Source
pub struct ParametricInstance {
    pub description: Option<Description>,
    pub annotations: HashMap<String, String>,
    /* private fields */
}
Expand description

Optimization problem instance with parameters

§Mathematical operations

ParametricInstance owns the same root operations as Instance and also owns the parameter-specialization operation. Parameter IDs share the VariableID namespace with decision variables, so only the enclosing parametric instance can interpret an expression reference as a decision variable or a parameter.

Self::with_parameters applies a parameter assignment to produce a concrete Instance. This is a root operation: it substitutes parameter values out of every expression-bearing component while preserving structural constraint families whose member IDs must already be real decision variables.

§Invariants

§Special-constraint invariants

The same special-constraint invariants apply as on Instance, with one key difference: function bodies in indicator and regular constraints may reference parameter IDs (which are substituted via Self::with_parameters), but structural variable positions cannot — they must be real decision variables. Specifically:

These invariants are enforced at every construction or mutation entry point: ParametricInstance::builder (which mirrors Instance::builder and accepts active maps for all three kinds, plus removed maps for regular and indicator constraints, validating each), and the post-construction setters Self::add_constraint / Self::add_indicator_constraint / Self::add_one_hot_constraint / Self::add_sos1_constraint.

Self::with_parameters partially evaluates parameter IDs out of every expression that could contain one when materializing a parametric instance into an Instance: the active objective, output objective, active and removed regular constraint bodies, active and removed indicator constraint function bodies, named functions, and decision_variable_dependency RHS expressions. OneHot/SOS1 collections (active and removed) pass through unchanged because their variable sets are required to be real decision variables at construction time. The resulting Instance satisfies its own (stricter) invariants — no parameter IDs survive anywhere.

Fields§

§description: Option<Description>§annotations: HashMap<String, String>

User-defined or third-party extension annotations.

OMMX-reserved metadata is represented by explicit fields such as Self::description.

Implementations§

Source§

impl ParametricInstance

Source

pub fn with_parameters(self, parameters: Parameters) -> Result<Instance>

Materialize every parameter into an Instance.

§Postconditions

Materialization removes parameter IDs from both active and output objectives. An existing output objective remains explicit even if specialization makes it structurally equal to the active objective.

use ommx::{
    linear, v1::{Parameters, State}, ATol, Constraint, ConstraintID,
    DecisionVariable, Evaluate, Function, Instance, Sense, VariableID,
};
use std::collections::{BTreeMap, HashMap};

let variable = VariableID::from(1);
let source = Instance::builder()
    .sense(Sense::Minimize)
    .objective(Function::from(linear!(1)))
    .decision_variables(BTreeMap::from([(variable, DecisionVariable::binary())]))
    .constraints(BTreeMap::from([(
        ConstraintID::from(1),
        Constraint::equal_to_zero(Function::from(linear!(1))),
    )]))
    .build()
    .unwrap();
let parametric = source.uniform_penalty_method().unwrap();
let penalty = *parametric.parameters().keys().next().unwrap();
let mut parameters = Parameters::default();
parameters.entries.insert(penalty.into_inner(), 2.0);
let instance = parametric.with_parameters(parameters).unwrap();

assert!(instance.objective().required_ids().contains(&variable));
assert!(!instance.objective().required_ids().contains(&penalty));
assert_eq!(instance.output_objective().unwrap().sense(), Sense::Minimize);
assert!(!instance.output_objective().unwrap().preserves_optimality());
let solution = instance
    .evaluate(&State::from(HashMap::from([(1, 0.0)])), ATol::default())
    .unwrap();
assert_eq!(*solution.objective(), 0.0);
Source§

impl ParametricInstance

Source

pub fn format_summary(&self) -> String

Format a compact, context-aware summary of this parametric instance.

This is intended for user-facing print(instance) / Display output. It resolves decision-variable and parameter labels through the parametric instance while keeping large expressions bounded.

Source

pub fn format_function(&self, function: &Function) -> Result<String>

Format a function using this parametric instance’s decision-variable and parameter modeling labels.

This validates that every ID referenced by function belongs to exactly one of the decision-variable table or parameter table before applying any output budget.

Source

pub fn format_function_with( &self, function: &Function, opts: FunctionFormatOptions, ) -> Result<FormattedFunction>

Format a function using this parametric instance’s decision-variable and parameter modeling labels and explicit output limits.

An ID that resolves as both a decision variable and a parameter, or as neither, is rejected before any term or character truncation is applied.

Source§

impl ParametricInstance

Source

pub fn new( sense: Sense, objective: Function, decision_variables: BTreeMap<VariableID, DecisionVariable>, parameters: ParameterTable, constraints: BTreeMap<ConstraintID, Constraint>, ) -> Result<Self>

Source§

impl ParametricInstance

Source

pub fn builder() -> ParametricInstanceBuilder

Creates a new ParametricInstanceBuilder.

Source§

impl ParametricInstance

Source

pub fn to_v1_bytes(&self) -> Result<Vec<u8>>

Serialize this parametric instance using the v1 wire format.

§Errors

ommx.v1.ParametricInstance cannot represent the presence of a ParametricInstance::output_objective, even when it currently matches the active objective.

use ommx::{linear, DecisionVariable, Function, Instance, ParametricInstance, Sense, VariableID};
use std::collections::BTreeMap;

let mut source = Instance::builder()
    .sense(Sense::Maximize)
    .objective(Function::from(linear!(1)))
    .decision_variables(BTreeMap::from([(
        VariableID::from(1),
        DecisionVariable::binary(),
    )]))
    .constraints(BTreeMap::new())
    .build()
    .unwrap();
assert!(source.convert_active_objective(Sense::Minimize));
assert!(source.convert_active_objective(Sense::Maximize));
let instance = ParametricInstance::from(source);
assert_eq!(instance.output_objective().unwrap().function(), instance.objective());

assert!(instance.to_v1_bytes().is_err());
Source

pub fn to_v2_bytes(&self) -> Vec<u8>

Serialize this parametric instance using the v2 wire format.

§Postconditions

v2 serialization round-trips the parametric output objective.

use ommx::{linear, DecisionVariable, Function, Instance, ParametricInstance, Sense, VariableID};
use std::collections::BTreeMap;

let mut source = Instance::builder()
    .sense(Sense::Maximize)
    .objective(Function::from(linear!(1)))
    .decision_variables(BTreeMap::from([(
        VariableID::from(1),
        DecisionVariable::binary(),
    )]))
    .constraints(BTreeMap::new())
    .build()
    .unwrap();
assert!(source.convert_active_objective(Sense::Minimize));
let instance = ParametricInstance::from(source);

let restored = ParametricInstance::from_v2_bytes(&instance.to_v2_bytes()).unwrap();
assert_eq!(restored.output_objective().unwrap().sense(), Sense::Maximize);
assert_eq!(restored, instance);
Source

pub fn from_v1_bytes(bytes: &[u8]) -> Result<Self>

Source

pub fn from_v2_bytes(bytes: &[u8]) -> Result<Self>

Source§

impl ParametricInstance

Source

pub fn add_constraint( &mut self, constraint: Constraint, context: ConstraintContext, ) -> Result<ConstraintID>

Insert a new constraint with its context, picking an unused id.

Mirrors Instance::add_constraint for parametric instances. Returns the newly assigned ConstraintID. The context is drained into the per-constraint ConstraintContextStore; pass ConstraintContext::default for an unannotated constraint.

All IDs referenced by the constraint must already be present in either decision_variables or parameters, and must not be substitution- dependency keys.

Source

pub fn add_indicator_constraint( &mut self, constraint: IndicatorConstraint, context: ConstraintContext, ) -> Result<IndicatorConstraintID>

Insert a new indicator constraint with its context, picking an unused id.

Mirrors Instance::add_indicator_constraint for parametric instances. The function body may reference either decision variables or parameters, but the indicator variable itself must be a binary decision variable — substitution cannot replace a structural variable position, and the indicator semantics require Kind::Binary.

Source

pub fn add_one_hot_constraint( &mut self, constraint: OneHotConstraint, context: ConstraintContext, ) -> Result<OneHotConstraintID>

Insert a new one-hot constraint with its context, picking an unused id.

The one-hot set must be non-empty. All variables in the set are structural and must be binary decision variables (parameter ids and non-binary kinds are rejected). Dependency keys are also rejected.

Source

pub fn add_sos1_constraint( &mut self, constraint: Sos1Constraint, context: ConstraintContext, ) -> Result<Sos1ConstraintID>

Insert a new SOS1 constraint with its context, picking an unused id.

All variables in the SOS1 set are structural and must be decision variables (parameter ids are rejected). The set must be non-empty. Dependency keys are also rejected. Unlike one-hot, SOS1 does not require Kind::Binary.

Source

pub fn add_decision_variable( &mut self, id: VariableID, variable: DecisionVariable, label: DecisionVariableLabel, ) -> Result<VariableID>

Insert a decision variable with its modeling label.

The table key must not collide with any existing decision variable, parameter, or substitution-dependency key.

§Errors

Returns an error whose chain contains crate::DecisionVariableError::DuplicateID when id is already owned by a decision variable, or crate::ParameterIDCollision when it is already owned by a parameter.

Source§

impl ParametricInstance

Source§

impl ParametricInstance

Source

pub fn output_objective(&self) -> Option<&OutputObjective>

Return the preserved objective semantics used after specialization.

None means the active Self::sense and Self::objective define the output semantics directly.

Source

pub fn decision_variable_table(&self) -> &DecisionVariableTable

Access the decision-variable definition table.

Source

pub fn decision_variables(&self) -> &BTreeMap<VariableID, DecisionVariable>

Access decision-variable rows keyed by table-owned IDs.

Source

pub fn variable_labels(&self) -> &VariableLabelStore

Access the per-variable modeling-label store.

Source

pub fn set_variable_label( &mut self, id: VariableID, label: ModelingLabel, ) -> Result<()>

Replace the modeling label for a decision variable owned by this parametric instance.

Source

pub fn fixed_decision_variable_values(&self) -> &BTreeMap<VariableID, f64>

Access table-owned fixed decision-variable values.

Source

pub fn fixed_decision_variable_value(&self, id: VariableID) -> Option<f64>

Return the fixed value for one decision variable, if it is fixed.

Source

pub fn named_function_table(&self) -> &NamedFunctionTable<NamedFunction>

Access named-function rows plus their modeling labels.

Source

pub fn named_functions(&self) -> &BTreeMap<NamedFunctionID, NamedFunction>

Access named-function row payloads keyed by table-owned IDs.

Source

pub fn named_function_labels(&self) -> &NamedFunctionLabelStore

Access the per-named-function modeling-label store.

Source

pub fn set_named_function_label( &mut self, id: NamedFunctionID, label: ModelingLabel, ) -> Result<()>

Replace the modeling label for a named function owned by this parametric instance.

Source

pub fn constraints(&self) -> &BTreeMap<ConstraintID, Constraint>

Active constraints.

Source

pub fn removed_constraints( &self, ) -> &BTreeMap<ConstraintID, (Constraint, RemovedReason)>

Removed constraints.

Source

pub fn constraint_collection(&self) -> &ConstraintCollection<Constraint>

The full constraint collection (active + removed).

Source

pub fn constraint_context(&self) -> &ConstraintContextStore<ConstraintID>

Access the per-constraint context store.

Source

pub fn set_constraint_context( &mut self, id: ConstraintID, context: ConstraintContext, ) -> Result<()>

Replace the context for a regular constraint owned by this parametric instance.

Source

pub fn indicator_constraints( &self, ) -> &BTreeMap<IndicatorConstraintID, IndicatorConstraint>

Active indicator constraints.

Source

pub fn removed_indicator_constraints( &self, ) -> &BTreeMap<IndicatorConstraintID, (IndicatorConstraint, RemovedReason)>

Removed indicator constraints.

Source

pub fn indicator_constraint_collection( &self, ) -> &ConstraintCollection<IndicatorConstraint>

The full indicator constraint collection.

Source

pub fn indicator_constraint_context( &self, ) -> &ConstraintContextStore<IndicatorConstraintID>

Access the per-indicator-constraint context store.

Source

pub fn set_indicator_constraint_context( &mut self, id: IndicatorConstraintID, context: ConstraintContext, ) -> Result<()>

Replace the context for an indicator constraint owned by this parametric instance.

Source

pub fn one_hot_constraints( &self, ) -> &BTreeMap<OneHotConstraintID, OneHotConstraint>

Active one-hot constraints.

Source

pub fn removed_one_hot_constraints( &self, ) -> &BTreeMap<OneHotConstraintID, (OneHotConstraint, RemovedReason)>

Removed one-hot constraints.

Source

pub fn one_hot_constraint_collection( &self, ) -> &ConstraintCollection<OneHotConstraint>

The full one-hot constraint collection.

Source

pub fn one_hot_constraint_context( &self, ) -> &ConstraintContextStore<OneHotConstraintID>

Access the per-one-hot-constraint context store.

Source

pub fn set_one_hot_constraint_context( &mut self, id: OneHotConstraintID, context: ConstraintContext, ) -> Result<()>

Replace the context for a one-hot constraint owned by this parametric instance.

Source

pub fn sos1_constraints(&self) -> &BTreeMap<Sos1ConstraintID, Sos1Constraint>

Active SOS1 constraints.

Source

pub fn removed_sos1_constraints( &self, ) -> &BTreeMap<Sos1ConstraintID, (Sos1Constraint, RemovedReason)>

Removed SOS1 constraints.

Source

pub fn sos1_constraint_collection( &self, ) -> &ConstraintCollection<Sos1Constraint>

The full SOS1 constraint collection.

Source

pub fn sos1_constraint_context( &self, ) -> &ConstraintContextStore<Sos1ConstraintID>

Access the per-SOS1-constraint context store.

Source

pub fn set_sos1_constraint_context( &mut self, id: Sos1ConstraintID, context: ConstraintContext, ) -> Result<()>

Replace the context for an SOS1 constraint owned by this parametric instance.

Trait Implementations§

Source§

impl Clone for ParametricInstance

Source§

fn clone(&self) -> ParametricInstance

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Debug for ParametricInstance

Source§

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

Formats the value using the given formatter. Read more
Source§

impl Default for ParametricInstance

Source§

fn default() -> ParametricInstance

Returns the “default value” for a type. Read more
Source§

impl Display for ParametricInstance

Source§

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

Formats the value using the given formatter. Read more
Source§

impl FlatAnnotations for ParametricInstance

Source§

impl From<Instance> for ParametricInstance

Source§

fn from(_: Instance) -> Self

Converts to this type from the input type.
Source§

impl From<ParametricInstance> for ParametricInstance

Source§

fn from(value: ParametricInstance) -> Self

Converts to this type from the input type.
Source§

impl PartialEq for ParametricInstance

Source§

fn eq(&self, other: &ParametricInstance) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for ParametricInstance

Source§

impl Substitute for ParametricInstance

Source§

type Output = ParametricInstance

Source§

fn substitute_acyclic( self, acyclic: &AcyclicAssignments, ) -> Result<Self::Output, SubstitutionError>

Performs substitution using pre-validated acyclic assignments. Read more
Source§

fn substitute_one( self, assigned: VariableID, f: &Function, ) -> Result<Self::Output, SubstitutionError>

Substitutes a single variable with a function. Read more
Source§

fn substitute( self, assignments: impl IntoIterator<Item = (VariableID, Function)>, ) -> Result<Self::Output, SubstitutionError>

Performs substitution with cycle detection and validation. Read more
Source§

impl TryFrom<ParametricInstance> for ParametricInstance

Source§

type Error = ParseError

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

fn try_from(value: ParametricInstance) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl TryFrom<ParametricInstance> for ParametricInstance

Source§

type Error = Error

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

fn try_from(value: ParametricInstance) -> Result<Self>

Performs the conversion.

Auto Trait Implementations§

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> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

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

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
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> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

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

Source§

type Error = !

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

fn try_from(value: U) -> Result<T, !>

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.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more