# Problem

relationalai.semantics.reasoners.prescriptive.problem

```python
Problem(model: b.Model, numeric_type: b.Concept, *, name: str | None = None)
```

Define and solve a decision problem on a model.

Use [`Problem.solve_for`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-solve_for) to declare decision variables, [`Problem.minimize`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-minimize)/
[`Problem.maximize`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-maximize) to add objectives, and [`Problem.satisfy`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-satisfy) to add constraints.
Then call [`Problem.solve`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-solve) for eager execution, or [`Problem.configure`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-configure) to
register a declarative request for model deployment. Read eager results via
populated properties (the default — e.g. `model.select(X.v)`), the
`Variable.values` Property for engine-side queries
(`model.select(sol_idx, val).where(var.values(sol_idx, val))`), or
[`Problem.solve_info`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-solve_info) for a Python-side metadata snapshot. Pass
`solve(sensitivity=True)` for post-solve duals (reduced costs, shadow
prices, basis statuses) or `solve(conflict=True)` to diagnose an infeasible
model (an irreducible infeasible subsystem); see [`Problem.solve`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-solve) and the
`Variable` / `Constraint` accessors below.

With model deployments enabled, read a Problem's relation by defining a
relationship of your own from it and selecting that; see [`Problem.configure`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-configure).

## Parameters

- `model` (`Model`) - The [`Model`](/api/python/v2.2/semantics/frontend/base/model_class/index.md) to attach solver constructs (variables, objectives, constraints, and results) to.
- `numeric_type` (`Concept`) - Numeric type used for bounds, solution values, and numeric literals. Use [`semantics.frontend.core.Float`](/api/python/v2.2/semantics/frontend/core/float/index.md) for HiGHS/Gurobi/Ipopt (even for MIPs), and [`semantics.frontend.core.Integer`](/api/python/v2.2/semantics/frontend/core/integer/index.md) for MiniZinc.
- `name` (`str`, default: `None`) - Stable deployment name. Required on every Problem when more than one Prescriptive Problem is configured on the same Model.

## Examples

Declare a variable and objective:

```python
from relationalai.semantics import Float, Model
from relationalai.semantics.reasoners.prescriptive import Problem

m = Model("demo")
x = m.Relationship(f"{Float:x}")
problem = Problem(m, Float)
problem.solve_for(x, name="x", lower=0)
problem.minimize(x)
```

## Notes

Calling [`Problem.solve`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-solve) invalidates the Python-side `solve_info()` cache.
Result accessors like `termination_status()` return engine-side
Relationships that reflect the most recent successful solve.

## Attributes

### .`numeric_type`

```python
Problem.numeric_type: Concept
```

[`semantics.frontend.core.Float`](/api/python/v2.2/semantics/frontend/core/float/index.md) or [`semantics.frontend.core.Integer`](/api/python/v2.2/semantics/frontend/core/integer/index.md).

### .`variables`

```python
Problem.variables: list[ProblemVariable]
```

Variable components registered via [`Problem.solve_for`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-solve_for).

### .`objectives`

```python
Problem.objectives: list[ProblemObjective]
```

Objective components registered via [`Problem.minimize`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-minimize) / [`Problem.maximize`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-maximize).

### .`constraints`

```python
Problem.constraints: list[ProblemConstraint]
```

Constraint components registered via [`Problem.satisfy`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-satisfy).

### .`Variable`

```python
Problem.Variable: Concept
```

Engine-side aggregate Concept covering all declared decision variables.
Use it to query across all variables of this problem — for example,
`model.select(p.Variable.name, p.Variable.lower).where(p.Variable)`
to list every variable's name and lower bound. After
`solve(sensitivity=True)` / `solve(conflict=True)` it also carries
`reduced_cost`, `basis_status`, and the `*_in_conflict` predicates
(see `ProblemVariable`).

### .`Objective`

```python
Problem.Objective: Concept
```

Engine-side aggregate Concept covering all objectives. Each
`ProblemObjective` extends this Concept; use it to query
names, types, (in future) duals, and — after
[`Problem.install_display_strings`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-install_display_strings) — `display_string`.

### .`Constraint`

```python
Problem.Constraint: Concept
```

Engine-side aggregate Concept covering all constraints. Each
`ProblemConstraint` extends this Concept; use it to query names
and types, after `solve(sensitivity=True)` /
`solve(conflict=True)` — `shadow_price`, `basis_status`, and
`in_conflict` (see `ProblemConstraint`) — and after
[`Problem.install_display_strings`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-install_display_strings) — `display_string`.

## Methods

### .`install_display_strings`()

```python
Problem.install_display_strings() -> None
```

Install the rules that render each expression's `display_string`.

Binds `Expression.display_string` to each expression's
rendered text — for example `"(x_0 ^ 2.0) + x_0 >= 1.0"` — making it
queryable, as in `model.select(cap.name, cap.display_string)`
for a constraint `cap` returned by [`Problem.satisfy`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-satisfy), or, with
deployments enabled, through a relationship of your own:

```
Text = model.Relationship(f"constraint reads {String:text}")
model.define(Text(cap.display_string))
```

Adding `cap.name` keys the text by name, and a constraint with no
name then has no row. `display_string` is always declared, so querying it
is valid without this call, but every `display_string` is null until
the rules are installed.

Call this whenever you query `display_string` yourself. Only
[`Problem.display`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-display) installs on demand, through [`Problem.install_display`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-install_display)
and only with deployments disabled; a direct select does not, and
every row comes back null with no error to say why. Under Deploy Mode
call it before deploying, since the rules must exist at deploy time. A
problem that neither displays nor installs pays no rendering cost.

Installing is cheap; what follows it is not free. On the SQL backend
the first query after an install renders every expression in the
problem, even one that selects no `display_string`, and mutating the
model makes the next query render them again. What it costs tracks the
number of constraint
DECLARATIONS rather than the number of expressions, because installing
re-plans every block in the model: twenty-five constraints declared
separately cost about nine times what the same twenty-five cost
when they are grounded from one declaration. Install once, after the
model is fully declared, rather than per query: any later mutation,
a new Concept or objective included, re-pays on the next query. With
several problems on one model install for all of them before
displaying any -- installing
lazily, one display at a time, costs O(N^2) over N problems for the
same reason. An expression declared after the install is installed as
it is added, so the order of the two does not matter. A second call is
a no-op.

One rule renders one expression however tall it is, so height is close
to free: a chain of twenty binary operators renders in about two
seconds on the SQL backend. Rules are counted per nesting LEVEL of
aggregates and references, not per expression, so what grows the
family is a model with many separate constraints rather than one deep
one.

A match or union over a decision variable adds one rule per arm, so a
level holding several of them grows with their total number of arms.

**Notes:**

Rendering is supported on the LQP and SQL backends.

A row with no rendered string has a null `display_string`, and
[`Problem.display`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-display) shows it as `<unrendered>`. Reaching that state means
the rules are not installed or the engine read came back incomplete. A
direct query keeps the row and returns a null; only a `where` on the
property drops it.

A decision variable declared without `name=` also leaves a row
unrendered, and re-installing does not fix it -- a second call is a
no-op -- but that state never reaches [`Problem.display`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-display), which refuses to
print unless every variable is named. Calling this method yourself and
reading `display_string` directly shows it. Inside a bag
an unnamed variable drops that member alone rather than the whole
string.

Bag arguments (`sum` terms and the like) print sorted as text rather
than numerically, so a member reading `x_10` precedes one reading
`x_2`; a special ordered set's members print in the user's index
order. The variable table sorts on the name text too. A float value
from the data in `[1e6, 1e16)` renders differently on LQP than on
the SQL backend; a literal written in the expression is formatted in
Python and prints alike on both.

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Prescriptive reasoning](/build/reasoning/prescriptive/index.md) / [Solve a decision problem](/build/reasoning/prescriptive/decision-problems/index.md)1) [Add constraints](/build/reasoning/prescriptive/decision-problems/constraints/index.md)1. [Read the text of a constraint or objective](/build/reasoning/prescriptive/decision-problems/constraints/index.md#read-the-text-of-a-constraint-or-objective)
         2) [Solve a decision problem](/build/reasoning/prescriptive/decision-problems/solve/index.md)1) [Avoid common pitfalls](/build/reasoning/prescriptive/decision-problems/solve/index.md#avoid-common-pitfalls)

### .`install_solve_info`()

```python
Problem.install_solve_info() -> b.Relationship
```

Publish the solver's result metadata as a relationship and return it.

The relationship is named `<name>_solve_info` from the Problem's
`name` (`default_solve_info` for a Problem with no name), and each
row's `key` and `value` fields are strings. With model deployments
enabled it is a public view, which [`Problem.solve_info`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-solve_info) reads; call this
in the model definition, before deploying. A second call returns the
same relationship.

Inside rules, read typed values through the accessors instead, such as
[`Problem.termination_status`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-termination_status) and [`Problem.objective_value`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-objective_value).

**Returns:**

- `Relationship` - The `(key, value)` relationship.

**Examples:**

```python
info = problem.install_solve_info()
model.select(info["key"], info["value"]).to_df()  # or problem.solve_info()
```

### .`install_display`()

```python
Problem.install_display() -> DisplayTables
```

Publish the problem's variables, objectives and constraints as tables and return them.

Call this in the model definition, before deploying: with model
deployments enabled, [`Problem.display`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-display) reads these tables and nothing
else. They are named from the Problem's `name` (`default` for a
Problem with no name), one row per entity:

- `<name>_variables(variable, name, type, lower, upper)`, where
  `type` is `"cont"`, `"int"` or `"bin"`;
- `<name>_objectives(objective, name, sense, text)`, where `sense`
  is `"minimize"` or `"maximize"`;
- `<name>_constraints(constraint, name, text)`.

`text` is the rendered expression, such as
`"(x_0 ^ 2.0) + x_0 >= 1.0"`, and a missing value, such as an absent
bound or name, is null. This calls [`Problem.install_display_strings`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-install_display_strings), so
every refresh then renders the problem's expressions. With deployments
disabled, [`Problem.display`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-display) installs the tables on demand. A second call
returns the same tables. Give each Problem in a model a distinct
`name` so its tables say which Problem they belong to, and one whose
table names the model doesn't already use: deployed views that would
share a name are told apart with a numeric suffix, which can go to one
of the model's own views (a `Plan.constraints` relationship beside a
Problem named `plan` becomes `Plan_constraints_2`). [`Problem.display`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-display)
reads its tables under whichever name they get.

**Returns:**

- `DisplayTables` - The `variables`, `objectives` and `constraints` Concepts.

**Examples:**

```python
tables = problem.install_display()
c = tables.constraints
model.select(c.name, c.text).to_df()  # or problem.display()
```

### .`solve_for`()

```python
Problem.solve_for(
    expr: b.Relationship | b.Chain | b.Expression,
    where: Optional[list[Any]] = None,
    populate: bool = True,
    name: Optional[Any | list[Any]] = None,
    type: Optional[str] = None,
    lower: Optional[std.NumberValue] = None,
    upper: Optional[std.NumberValue] = None,
    start: Optional[std.NumberValue] = None,
) -> "ProblemVariable"
```

Declare decision variables for the problem.

Call this before adding objectives or constraints. The returned
`ProblemVariable` IS a Concept — use it directly with
`model.define()`, `model.select()`, and `.ref()` to annotate and
query declared variables.

**Parameters:**

- `expr` (`Relationship or Chain or Expression`) - Expression describing the variable(s) to create (for example, a scalar relationship like `x` or an indexed property like `Item.cost`).
- `where` (`list`\[`Any`], default: `None`) - Optional conditions restricting which variable instances are created.
- `populate` (`bool`, default: `True`) - If True (default), write solved values back to the original relationship/property after [`Problem.solve`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-solve). Set to False when you create multiple [`Problem`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md) instances that solve for the same relationship on the same model.
- `name` (`Any or list`\[`Any`], default: `None`) - Display name for variables. Use a string for scalars or a list pattern for indexed variables (for example, `["x", Item.i]`). The name has to discriminate: [`Problem.display`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-display) rejects only null names, so a constant `name="x"` on a variable that grounds once per entity gives every instance the same name and every constraint the same rendered text, with no warning.
- `type` (`str`, default: `None`) - Variable type: `"cont"` (default for `Float`), `"int"` (default for `Integer`), or `"bin"` (binary 0/1).
- `lower` (`Variable or float or int or Decimal`, default: `None`) - Lower/upper bounds and an optional initial value hint.
- `upper` (`Variable or float or int or Decimal`, default: `None`) - Lower/upper bounds and an optional initial value hint.
- `start` (`Variable or float or int or Decimal`, default: `None`) - Lower/upper bounds and an optional initial value hint.

**Returns:**

- `ProblemVariable` - The variable subconcept. Annotate via
  `model.define(var.lower(0))`, query values after solve via
  `model.select(sol_idx, val).where(var.values(sol_idx, val))`.

  **Back-pointer fields.** The subconcept exposes one property per
  non-value field of the underlying relationship, named after the
  field's own name (the explicit `:name` from the format string,
  or the lowercased type name if no explicit name was given). Use
  these to query "which domain entity does this variable
  represent?". Examples for the common shapes:

  ```
  # Entity property: f"{Queen} is in {Integer:column}"
  #   → var.queen   (back to the Queen instance)
  var = p.solve_for(Queen.column, ...)
  model.select(sol_idx, var.queen.row, val).where(var.values(sol_idx, val))

  # Explicit field name: f"{Edge:e} has {Float:flow}"
  #   → var.e       (uses the explicit name, not "edge")
  var = p.solve_for(Edge.flow, ...)
  model.select(sol_idx, var.e.id, val).where(var.values(sol_idx, val))

  # Multi-arity entity property:
  # f"{Player} in {Integer:week} is in {Integer:group}"
  #   → var.player + var.week
  var = p.solve_for(Player.assign(w, x), ...)
  model.select(sol_idx, var.player.p, var.week, val).where(var.values(sol_idx, val))

  # Bare multi-arity (no entity):
  # f"cell {Integer:i} {Integer:j} is {Integer:x}"
  #   → var.i + var.j
  var = p.solve_for(cell(i, j, x), ...)
  model.select(sol_idx, var.i, var.j, val).where(var.values(sol_idx, val))

  # Bare scalar relationship: f"{Float:x}" — no back-pointer.
  #   Query var.values directly.
  var = p.solve_for(x, name="x", ...)
  model.select(sol_idx, val).where(var.values(sol_idx, val))
  ```

**Raises:**

- `ValueError` - If variables are already defined for this relationship, if an
  argument has an invalid value (for example, an unknown `type`),
  or if a non-value field name would shadow an intrinsic attribute
  on the Variable subconcept. Shadow categories include engine-side
  Properties (`name`, `type`, `lower`, `upper`, `start`,
  `values`), Python `@property` descriptors (`dsl_expr`,
  `concept_name`, `property_name`, `var_type`, `var_where`,
  `populate`), and `Concept.RESERVED_NAMES` methods (`ref`,
  `new`, `alias`, `where`, `select`, `define`, `require`,
  etc.). See `Problem._reserved_variable_field_names` for the
  authoritative list — the error message lists the full set. Rename
  the conflicting field in the relationship's format string. A
  ValueError is also raised if the value field's declared type
  (`Integer` / `Float`) does not match the Problem's numeric type:
  a decision variable's value field must match `Problem(model, …)`;
  set integrality with `type='int'` / `'bin'`, not the property type.
  Also raised when `populate=True` targets an identifying property.
- `TypeError` - If an argument has an invalid type.

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Prescriptive reasoning](/build/reasoning/prescriptive/index.md) / [Solve a decision problem](/build/reasoning/prescriptive/decision-problems/index.md)1) [Overview](/build/reasoning/prescriptive/decision-problems/index.md)1. [How solving a decision problem works](/build/reasoning/prescriptive/decision-problems/index.md#how-solving-a-decision-problem-works)
         2) [Create a Problem object](/build/reasoning/prescriptive/decision-problems/create/index.md)1) [Choose a default numeric type](/build/reasoning/prescriptive/decision-problems/create/index.md#choose-a-default-numeric-type)
         3) [Add decision variables](/build/reasoning/prescriptive/decision-problems/variables/index.md)1) [Declare decision variables](/build/reasoning/prescriptive/decision-problems/variables/index.md#declare-decision-variables)
            2) [Choose variable types and bounds](/build/reasoning/prescriptive/decision-problems/variables/index.md#choose-variable-types-and-bounds)
         4) [Add constraints](/build/reasoning/prescriptive/decision-problems/constraints/index.md)
         5) [Solve a decision problem](/build/reasoning/prescriptive/decision-problems/solve/index.md)1) [Diagnose infeasible problems](/build/reasoning/prescriptive/decision-problems/solve/index.md#diagnose-infeasible-problems)
            2) [Avoid common pitfalls](/build/reasoning/prescriptive/decision-problems/solve/index.md#avoid-common-pitfalls)
         6) [Work with solutions](/build/reasoning/prescriptive/decision-problems/solutions/index.md)1) [Determine how to access results](/build/reasoning/prescriptive/decision-problems/solutions/index.md#determine-how-to-access-results)

### .`minimize`()

```python
Problem.minimize(
    expr: b.Variable | float | int | b.Fragment, name: Optional[Any | list[Any]] = None
) -> "ProblemObjective"
```

Add a minimization objective. A Problem takes one objective, so a second raises.

The expression must reference at least one decision variable declared via
[`Problem.solve_for`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-solve_for).

**Parameters:**

- `expr` (`Variable or float or int or Fragment`) - Objective expression to minimize.
- `name` (`Any or list`\[`Any`], default: `None`) - Optional objective name (string for scalar, or a list pattern for indexed objectives).

**Returns:**

- `ProblemObjective` - The objective subconcept (IS a Concept).

**Raises:**

- `ValueError` - If the Problem already has an objective, or the objective does not
  reference any declared decision variables.

**Notes:**

An aggregate over no members has no value, as everywhere in PyRel, so
`sum(X.v) + sum(Empty.v)` has no value when `Empty` has no rows, and neither
does `sum(X.v).where(<filter matching no rows>)`. An objective with no value at
all would leave the solver nothing to optimize, so [`Problem.solve`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-solve) raises
`ValueError`. A deployed refresh has no client to raise it, so the export also
adds a constant `1 <= 0` constraint named `objective_has_no_value`: the problem
is infeasible. With model deployments disabled, [`Problem.solve_info`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-solve_info) then warns which
objectives have no value; with them enabled it gives no such warning. Give each
term that can be empty a default:
`(sum(X.v) | 0) + (sum(Empty.v) | 0)`.

An objective with rows at some groupings of `...per(X.group)` and not others
registers for the groupings that have rows. The solver takes one objective row,
so a solve with two or more reports OTHER\_ERROR, and its error says so.

An aggregate over decision variables whose members PyRel and the solver
could count differently raises `ValueError` when the objective or
constraint is added, and the error names an alternative:

- a `sum`/`count` names each member's identifying keys:
  `sum(Item, value).where(Item.x(value))`, not `sum(value)`; keys the
  value itself reads from are already named, so `sum(Item.x)` is keyed;
- an outer `sum`/`count` over an inner aggregate names every inner
  group key or reads it in its own body: `sum(I, sum(I.x).per(I))` and
  `sum(I.c * sum(I.x).per(I))`, not `sum(sum(I.x).per(I))`. A row-wise
  inner aggregate such as `rank` keeps a row per input, so its keys
  count too: `count(Y, X.x * rank(Y.w) >= 1)`. So do the keys of an
  inner aggregate read in a filter, projection or group key:
  `sum(Y, X.x).where(count(Y).per(Y) >= 1)`, not
  `sum(X.x).where(count(Y).per(Y) >= 1)`; an ungrouped inner such as
  `count(Y) >= 1` adds no keys. For one total per group
  of a property value, bind it to a ref,
  `sum(g, sum(I.x).where(I.g(g)).per(g))`, since
  `sum(I.g, sum(I.x).per(I.g))` counts each group's total once per `I`;
- `model.union` over decision variables is supported only under
  `min`/`max`; total independent contributions with
  `(sum(a) | 0) + (sum(b) | 0)` instead;
- a `|` (match) fallback is grounded like the other arms, unless the
  enclosing query or grouping supplies the keys:
  `sum(X.a | model.select(0).where(X))` is a per-X fallback, and
  `sum(X.a) | 0` defaults an empty total. An aggregate arm is keyed by
  its `.per()` keys, so `min(sum(X.x).per(X)) | 1.0` defaults an empty
  minimum where `min(sum(X.x).per(X) | 1.0)` is refused.

The alternatives count every keyed member, which can differ from PyRel's
distinct-value reading of the rejected spelling. `min`/`max` are exempt
from the first two rules, and an aggregate that reads no decision variable is
evaluated by PyRel unchanged. `avg` and `string_join` over decision
variables are rejected.

[`Problem.num_min_objectives`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-num_min_objectives) returns the count as a Relationship. To
read it as a Python scalar, query the model:
`n = model.select(p.num_min_objectives()).to_df().iloc[0, 0]`, or,
with deployments enabled, a relationship defined from it (see
[`Problem.configure`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-configure)).

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Prescriptive reasoning](/build/reasoning/prescriptive/index.md) / [Solve a decision problem](/build/reasoning/prescriptive/decision-problems/index.md)1) [Solve a decision problem](/build/reasoning/prescriptive/decision-problems/solve/index.md)1. [Solve optimally](/build/reasoning/prescriptive/decision-problems/solve/index.md#solve-optimally)

### .`maximize`()

```python
Problem.maximize(
    expr: b.Variable | float | int | b.Fragment, name: Optional[Any | list[Any]] = None
) -> "ProblemObjective"
```

Add a maximization objective. A Problem takes one objective, so a second raises.

The expression must reference at least one decision variable declared via
[`Problem.solve_for`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-solve_for).

**Parameters:**

- `expr` (`Variable or float or int or Fragment`) - Objective expression to maximize.
- `name` (`Any or list`\[`Any`], default: `None`) - Optional objective name (string for scalar, or a list pattern for indexed objectives).

**Returns:**

- `ProblemObjective` - The objective subconcept (IS a Concept).

**Raises:**

- `ValueError` - If the Problem already has an objective, or the objective does not
  reference any declared decision variables.

**Notes:**

See [`Problem.minimize`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-minimize) Notes — the empty-body relational semantics
and the aggregate admission rules apply identically here.
[`Problem.num_max_objectives`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-num_max_objectives) returns the count as
a Relationship; query as a scalar via
`model.select(p.num_max_objectives()).to_df().iloc[0, 0]`, or, with
deployments enabled, a relationship defined from it (see [`Problem.configure`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-configure)).

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Prescriptive reasoning](/build/reasoning/prescriptive/index.md) / [Solve a decision problem](/build/reasoning/prescriptive/decision-problems/index.md)1) [Solve a decision problem](/build/reasoning/prescriptive/decision-problems/solve/index.md)1. [Solve optimally](/build/reasoning/prescriptive/decision-problems/solve/index.md#solve-optimally)

### .`satisfy`()

```python
Problem.satisfy(
    expr: b.Fragment,
    name: Optional[Any | list[Any]] = None,
    keyed_by: Optional[dict[str, Any]] = None,
) -> "ProblemConstraint"
```

Add constraints from a `model.require(...)` fragment.

Use this to turn a require-clause fragment into solver constraints.
The returned `ProblemConstraint` IS a Concept — annotate via
`model.define(constr.name("budget"))`, query via
`model.select(constr.name).where(constr)`.

Passing a `model.require(...)` fragment to `satisfy` detaches it
from the model's active integrity constraints — the solver enforces
it instead, and it no longer fires engine-side. To also check it
engine-side against the current solution after [`Problem.solve`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-solve), call
[`Problem.verify`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-verify) — it temporarily reinstalls the fragment as an IC,
evaluates it, and removes it (one-shot).

.. note:

```
LP and MIP solvers return floating-point solutions that satisfy
constraints within solver tolerance (e.g. ``1e-8``), but engine
ICs check exact inequality.  For continuous-variable constraints,
use a tolerant ``model.require()`` post-solve instead
(e.g. ``model.require(x <= bound + 1e-6)``).
```

**Parameters:**

- `expr` (`Fragment`) - A fragment created by [`Model.require`](/api/python/v2.2/semantics/frontend/base/model_class/index.md#method-require) (optionally scoped with [`Model.where`](/api/python/v2.2/semantics/frontend/base/model_class/index.md#method-where)).
- `name` (`Any or list`\[`Any`], default: `None`) - Optional constraint name (string for scalar, or a list pattern for indexed constraints).
- `keyed_by` (`dict`\[`str`, `ref`], default: `None`) - Maps a back-pointer name to the grounding reference each constraint instance is 1:1 with. The reference is an entity (`{"shift": Shift}`, so `con.shift` joins to the shift's data) or a value such as an identifier (`{"i": X.i}`, so `con.i` is the scalar index); a bare primitive type is rejected. Each entry becomes an *identifying* Property on the constraint, so the instance is identified by — and joins to the model by — its key (`con.shift.min_coverage`), the same way a variable points back to its entity (`var.food`). The keys must uniquely determine the constraint: a key set that does not (including two conjuncts of a single `require(A, B)` sharing keys) makes two instances collide on one identity and raises at solve (an engine-side functional-dependency error). `name=` plays no part in this identity — it is a display label only; a family is read back by key only if `keyed_by` declares one. Key names must be valid identifiers and must not clash with the managed constraint properties (`root`, `name`, `type`, `display_string`, `shadow_price`, `basis_status`, `in_conflict`, `id`). Each reference must be something the where clause names, or an identify\_by field of it (`{"i": X.i}` under `where(X)`), so every row of the where clause has its key. Omit it for constraints whose marginals you do not read back by key.

**Returns:**

- `ProblemConstraint` - The constraint subconcept (IS a Concept).

**Raises:**

- `TypeError` - If `expr` is not a fragment.
- `ValueError` - If the fragment has no require clause, or if it includes select/define
  clauses; if the constraint is indexed by something its where clause does
  not name (see Notes); if a `keyed_by` name is not an identifier, clashes
  with a managed constraint property, or its reference is neither an entity
  nor a value reference, or is not named by the where clause; or, at solve,
  if the `keyed_by` key set is not 1:1
  with the constraint instances (an engine-side functional-dependency
  error).

**Notes:**

A constraint means what PyRel's `require` means: the require clause
is checked once per row of the `where(...)` clause. So the where clause
names what the constraint is indexed by -- `model.where(X).require(X.v <=
X.cap)` is one constraint per `X` -- and names an aggregate's group too:
`model.where(G).require(sum(X.v).where(X.group == G).per(G) <= c)`, or
with a value key `g = String.ref()`,
`model.where(X.group(g)).require(sum(X.v).where(X.group == g).per(g) <= c)`.
In PyRel a value only the require clause mentions needs just one row to
pass, which no solver constraint states, so a constraint indexed by
something its where clause does not name raises `ValueError`. A scalar
check such as `model.require(sum(X.v) <= 5)` needs no where clause, and
where rows whose checks are the same share one instance:
`model.where(X).require(sum(X.v) <= 5)` exports one constraint, so a `name`
or `keyed_by` value that varies across those rows does not tell them apart.

A where row the require clause has no value for -- a group with no
members, a cell with no decision variable, `sum(X.v)` with no `X` --
fails PyRel's check at every point, so it becomes a constant `1 <= 0`
instance of the constraint, named and keyed as that row's instance would
be, and the problem is infeasible. The solve reports `INFEASIBLE`, or
`OTHER_ERROR` on MiniZinc, which cannot write a constraint with no
variables. With model deployments disabled, [`Problem.solve_info`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-solve_info) then warns which
constraints have these rows; with them enabled it gives no such warning. HiGHS can
still return a point, so read the status. To leave empty
groups out, name only groups that have members:
`model.where(X.group(G)).require(...)`.
`implies`, `all_different` and special ordered sets are solver-only:
PyRel does not evaluate them, so [`Problem.verify`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-verify) cannot check them.
`all_different` and a special ordered set constrain the members
present; `implies` follows the rules above.

Aggregates in a require clause follow the same member-identity and
grounding admission rules as objectives (see [`Problem.minimize`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-minimize)).

[`Problem.num_constraints`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-num_constraints) returns the count as a Relationship. To read
it as a Python scalar, query the model:
`n = model.select(p.num_constraints()).to_df().iloc[0, 0]`, or, with
deployments enabled, a relationship defined from it (see [`Problem.configure`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-configure)).

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Prescriptive reasoning](/build/reasoning/prescriptive/index.md) / [Solve a decision problem](/build/reasoning/prescriptive/decision-problems/index.md)1) [Overview](/build/reasoning/prescriptive/decision-problems/index.md)
         2) [Add constraints](/build/reasoning/prescriptive/decision-problems/constraints/index.md)1) [Add constraints with `Problem.satisfy()`](/build/reasoning/prescriptive/decision-problems/constraints/index.md#add-constraints-with-problemsatisfy)
            2) [Avoid common pitfalls](/build/reasoning/prescriptive/decision-problems/constraints/index.md#avoid-common-pitfalls)
         3) [Solve a decision problem](/build/reasoning/prescriptive/decision-problems/solve/index.md)1) [Diagnose infeasible problems](/build/reasoning/prescriptive/decision-problems/solve/index.md#diagnose-infeasible-problems)

### .`verify`()

```python
Problem.verify(*fragments: b.Fragment) -> None
```

One-shot constraint verification against the current solution.

Temporarily installs each fragment as an integrity constraint,
triggers a model query to evaluate them, then removes them.
A `ModelWarning` is raised if
any constraint is violated.

Emits a `UserWarning` and returns without checking if the
most recent solve did not produce a successful solution (i.e.
`termination_status` is not `OPTIMAL`, `LOCALLY_SOLVED`,
or `SOLUTION_LIMIT`).

.. note:

```
LP and MIP solvers return floating-point solutions that satisfy
constraints within solver tolerance (e.g. ``1e-8``), but engine
ICs check exact inequality.  For continuous-variable constraints,
use a tolerant ``model.require()`` post-solve instead
(e.g. ``model.require(x <= bound + 1e-6)``).
```

.. note:

```
``verify()`` re-evaluates the accepted PyRel constraints on the
returned solution. Aggregate admission refuses the spellings known to
count members differently from the solver; on the SQL backend, an outer
aggregate over an inner total can still read back differently.
Solver tolerances still apply when interpreting numeric residuals.
```

**Parameters:**

- `*fragments` (`Fragment`, default: `()`) - One or more fragments previously passed to [`Problem.satisfy`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-satisfy).

**Raises:**

- `NotImplementedError` - If fragments are passed while model deployments are enabled. Define
  the fragment's failing rows into a relationship of your own instead,
  as the error shows. When the Problem has no solution, an empty
  relationship does not show the constraint holds, so read it together
  with [`Problem.solve_info`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-solve_info)'s `termination_status`.

### .`num_variables`()

```python
Problem.num_variables() -> b.Relationship
```

Number of declared decision variables. Usable in rules and ICs.

**Returns:**

- `Relationship` - An Integer Relationship counting the declared variables.

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Prescriptive reasoning](/build/reasoning/prescriptive/index.md) / [Solve a decision problem](/build/reasoning/prescriptive/decision-problems/index.md)1) [Add decision variables](/build/reasoning/prescriptive/decision-problems/variables/index.md)1. [Inspect `Problem` variables](/build/reasoning/prescriptive/decision-problems/variables/index.md#inspect-problem-variables)
         2) [Solve a decision problem](/build/reasoning/prescriptive/decision-problems/solve/index.md)1) [Validate before you solve](/build/reasoning/prescriptive/decision-problems/solve/index.md#validate-before-you-solve)
            2) [Avoid common pitfalls](/build/reasoning/prescriptive/decision-problems/solve/index.md#avoid-common-pitfalls)

### .`num_constraints`()

```python
Problem.num_constraints() -> b.Relationship
```

Number of declared constraints. Usable in rules and ICs.

**Returns:**

- `Relationship` - An Integer Relationship counting the declared constraints.

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Prescriptive reasoning](/build/reasoning/prescriptive/index.md) / [Solve a decision problem](/build/reasoning/prescriptive/decision-problems/index.md)1) [Add constraints](/build/reasoning/prescriptive/decision-problems/constraints/index.md)1. [Inspect `Problem` constraints](/build/reasoning/prescriptive/decision-problems/constraints/index.md#inspect-problem-constraints)
            2. [Avoid common pitfalls](/build/reasoning/prescriptive/decision-problems/constraints/index.md#avoid-common-pitfalls)
         2) [Solve a decision problem](/build/reasoning/prescriptive/decision-problems/solve/index.md)

### .`num_min_objectives`()

```python
Problem.num_min_objectives() -> b.Relationship
```

Number of minimization objectives. Usable in rules and ICs.

**Returns:**

- `Relationship` - An Integer Relationship counting the minimization objectives.

### .`num_max_objectives`()

```python
Problem.num_max_objectives() -> b.Relationship
```

Number of maximization objectives. Usable in rules and ICs.

**Returns:**

- `Relationship` - An Integer Relationship counting the maximization objectives.

### .`termination_status`()

```python
Problem.termination_status() -> b.Relationship
```

Solver termination status (e.g. `"OPTIMAL"`). Usable in rules and ICs.

**Returns:**

- `Relationship` - A String Relationship containing the termination status.

### .`objective_value`()

```python
Problem.objective_value() -> b.Relationship
```

Objective value reported by the solver. Usable in rules and ICs.

Solvers report a single objective per solve (the primary/best
solution), not per-point objectives. This Relationship reflects the
solver-reported value.

**Returns:**

- `Relationship` - A numeric Relationship containing the objective value.

### .`solve_time_sec`()

```python
Problem.solve_time_sec() -> b.Relationship
```

Solve time in seconds (Float Relationship). Usable in rules and ICs.

**Returns:**

- `Relationship` - A Float Relationship containing the solve time in seconds.

### .`num_points`()

```python
Problem.num_points() -> b.Relationship
```

Number of solution points. Usable in rules and ICs.

**Returns:**

- `Relationship` - An Integer Relationship counting the solution points.

### .`solver_version`()

```python
Problem.solver_version() -> b.Relationship
```

Solver version string. Usable in rules and ICs.

**Returns:**

- `Relationship` - A String Relationship containing the solver version.

### .`error`()

```python
Problem.error() -> b.Relationship
```

Solver error message(s). Usable in rules and ICs.

A message here is not necessarily a whole-request failure: a successful
solve whose *secondary* step failed (e.g. conflict/IIS extraction, with
`conflict_status == "FAILED"`) reports its reason here alongside a valid
result. Read a failure's scope from the accompanying status, not from the
mere presence of a message.

**Returns:**

- `Relationship` - A String Relationship containing solver error messages.

### .`display`()

```python
Problem.display(
    *removed_positional: Any,
    limit: int | None = None,
    print_output: bool = True,
    **removed: Any
) -> str
```

Print and return a human-readable summary of the problem.

.. versionchanged:: 1.29.0
`part` and `where` were removed. Select from the tables
[`Problem.install_display`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-install_display) returns instead, as shown below, and filter
with a `where`. To cap a
scoped read, use `std.aggregates.limit` in a `where` clause,
also shown below; `Fragment.limit` is not the replacement, since
it raises "Feature unavailable" when querying RAI directly.
`limit` survives, but only in its whole-problem form: it caps the
printed tables and no longer takes a `part`. It also samples
different rows, since it now takes the first N of the plain-text
sort rather than 1.28's natural-sort top N: over `x_1`..`x_12`,
`limit=5` prints `x_1, x_10, x_11, x_12, x_2` where 1.28
printed `x_1`..`x_5`.

One other change is visible in the output: a problem with an
unnamed decision variable now raises `ValueError` instead of
printing a table that cannot name it. Row ordering also changed;
see below.

With no `limit`, renders a count summary and full tables of
variables, objectives, and constraints.

It reads the three tables [`Problem.install_display`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-install_display) publishes. With
model deployments enabled, call [`Problem.install_display`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-install_display) in the model
definition, before deploying. With deployments disabled, this method
installs them on its first use, which makes the next query in the
session render every expression, whether or not it selects one.

To render a subset, or to get composable data rather than formatted
text, select from those tables, which works in both modes:

```
c = problem.install_display().constraints
model.select(c.name, c.text).to_df()
```

A `where` narrows it, in place of the removed `where=`:

```
model.select(c.name, c.text).where(c.name == "cap_3").to_df()
```

and `std.aggregates.limit` caps a scoped read's row count, which
`limit` no longer does:

```
model.where(std.aggregates.limit(3, c)).select(c.name, c.text).to_df()
```

Everything printed sorts as plain text: bag arguments (`sum`,
`min`, `max`, `count`, `all_different` members) inside the
model, the variable table and expression rows on the client. So
`x_10` precedes `x_2` throughout. See
[`Problem.install_display_strings`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-install_display_strings) for the ordering's current limits.

An expression the renderer cannot render prints `<unrendered>`
in place of its text. This method installs the rules first, so a
missing install is not a cause here; the causes that remain are
listed under [`Problem.install_display_strings`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-install_display_strings).

**Parameters:**

- `limit` (`(int, keyword - only)`, default: `None`) - Cap each printed table at its first `limit` rows, after the sort described above, so a large problem prints a readable sample. The counts in the summary header stay true, so they still report the whole problem. `None`, the default, prints every row.
- `print_output` (`(bool, keyword - only)`, default: `True`) - If `True`, print the formatted output to stdout. Set to `False` to receive the string without printing.

**Returns:**

- `str` - The formatted summary.

**Raises:**

- `TypeError` - If `part` or `where` is passed, or any positional argument
  is. Both were removed in 1.29.0; the message carries the
  replacement shown above.
- `ValueError` - If `limit` is not a positive integer, if model deployments are
  enabled and [`Problem.install_display`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-install_display) was not called, or if any
  decision variable is unnamed. Every variable is identified by name
  in the output, and an expression over an unnamed variable renders
  no string at all.

**Examples:**

:

```
problem.display()
```

or, on a large problem, a capped sample:

```
problem.display(limit=5)
```

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Prescriptive reasoning](/build/reasoning/prescriptive/index.md) / [Solve a decision problem](/build/reasoning/prescriptive/decision-problems/index.md)1) [Create a Problem object](/build/reasoning/prescriptive/decision-problems/create/index.md)1. [Inspect a Problem with `display()`](/build/reasoning/prescriptive/decision-problems/create/index.md#inspect-a-problem-with-display)
         2) [Add constraints](/build/reasoning/prescriptive/decision-problems/constraints/index.md)1) [Inspect `Problem` constraints](/build/reasoning/prescriptive/decision-problems/constraints/index.md#inspect-problem-constraints)
            2) [Read the text of a constraint or objective](/build/reasoning/prescriptive/decision-problems/constraints/index.md#read-the-text-of-a-constraint-or-objective)
         3) [Solve a decision problem](/build/reasoning/prescriptive/decision-problems/solve/index.md)1) [Diagnose infeasible problems](/build/reasoning/prescriptive/decision-problems/solve/index.md#diagnose-infeasible-problems)
            2) [Avoid common pitfalls](/build/reasoning/prescriptive/decision-problems/solve/index.md#avoid-common-pitfalls)

### .`configure`()

```python
Problem.configure(
    solver: str,
    *,
    time_limit_sec: float | None = None,
    silent: bool | None = None,
    solution_limit: int | None = None,
    relative_gap_tolerance: float | None = None,
    absolute_gap_tolerance: float | None = None,
    log_to_console: bool = False,
    print_only: bool = False,
    print_format: str | None = None,
    sensitivity: bool = False,
    conflict: bool = False,
    **solver_params: int | float | str | bool
) -> None
```

Configure this problem for declarative execution in a model deployment.

This method validates and stores the same solver request accepted by
[`Problem.solve`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-solve). It performs no exports, queries, or service calls. A
Problem may be configured once; a Model may contain multiple configured
Problems, each with a unique `name`. A Problem that reads another
Problem's results needs that one configured too, without
`print_only=True`: a deployment refuses it otherwise, since no refresh
would write those results.

The Problem's own declarations (variables, constraints, solver result
tables, and accessors such as `objective_value()`) are `synthetic`: a
deployment stores them in its meta schema, not the deployment schema. The
properties passed to `solve_for` stay yours. To read a result, define a
relationship of your own from it and select that:

```
RunStatus = model.Relationship(f"run status {String:s}")
model.define(RunStatus(problem.termination_status()))
model.select(RunStatus).to_df()
```

To publish a result in the deployment schema, define it on a concept of
your own:

```
Plan = model.Concept("Plan", identify_by={"name": String})
Plan.total = model.Property(f"{Plan} has {Float:total}")
v = Float.ref()
model.where(problem.objective_value()(v)).define(
    plan := Plan.new(name="default"), plan.total(v)
)
```

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use RelationalAI with AI Agents](/build/agents/index.md)1) [Get started with a coding agent](/build/agents/start-with-a-coding-agent/index.md)1. [Find optimal actions with prescriptive reasoning](/build/agents/start-with-a-coding-agent/index.md#find-optimal-actions-with-prescriptive-reasoning)

### .`solve`()

```python
Problem.solve(
    solver: str,
    *,
    time_limit_sec: float | None = None,
    silent: bool | None = None,
    solution_limit: int | None = None,
    relative_gap_tolerance: float | None = None,
    absolute_gap_tolerance: float | None = None,
    log_to_console: bool = False,
    print_only: bool = False,
    print_format: str | None = None,
    sensitivity: bool = False,
    conflict: bool = False,
    **solver_params: int | float | str | bool
) -> None
```

Solve the decision problem using a solver backend.

Declare decision variables first with [`Problem.solve_for`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-solve_for). After solving,
read back solution values via the populated properties (e.g.
`model.select(X.v)`) or the `Variable.values` Property for engine-side
queries, result accessors such as [`Problem.termination_status`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-termination_status) and
[`Problem.objective_value`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-objective_value), or [`Problem.solve_info`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-solve_info) for a Python-side snapshot.

**Parameters:**

- `solver` (`str`) - Solver name (for example `"highs"`, `"minizinc"`, `"ipopt"`).
- `time_limit_sec` (`float`, default: `None`) - Maximum solve time in seconds. The solver service defaults to 300s if not provided.
- `silent` (`bool`, default: `None`) - Whether to suppress solver output.
- `solution_limit` (`int`, default: `None`) - Maximum number of solutions to return (when supported).
- `relative_gap_tolerance` (`float`, default: `None`) - Relative optimality gap tolerance in `[0, 1]`.
- `absolute_gap_tolerance` (`float`, default: `None`) - Absolute optimality gap tolerance (>= 0).
- `log_to_console` (`bool`, default: `False`) - Whether to stream solver logs to stdout while the job runs.
- `print_only` (`bool`, default: `False`) - If True, build the problem in the solver service without solving it. With `print_format`, this prints the model without solving it.
- `print_format` (`str`, default: `None`) - Text format for the printed model, read afterward with [`Problem.read_printed_model`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-read_printed_model) or written to a file with [`Problem.write_printed_model`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-write_printed_model). Supported formats: `"moi"` (MOI text), `"latex"`, `"mof"` (MOI JSON), `"lp"`, `"mps"`, `"nl"` (AMPL).
- `sensitivity` (`bool`, default: `False`) - Request post-solve sensitivity analysis — reduced costs, shadow prices, and basis statuses — exposed via `Variable.reduced_cost`, `Constraint.shadow_price`, and `.basis_status`. Requires an objective and is incompatible with `solution_limit` (sensitivity is defined for the single optimal point). Meaningful for continuous (LP/QP) solves; integer/MIP models have no meaningful duals, so the accessors come back empty (a warning is emitted). Coefficient/RHS ranging (allowable increase/decrease) is not provided. Uses wire schema version 2. Read them straight off the returned variable/constraint, the same attribute style as `.name`/`.lower` — e.g. `model.select(var.name, var.reduced_cost)`; see `ProblemVariable` / `ProblemConstraint` for the query idiom and the dual sign convention (it depends on the objective sense *and* the constraint direction / active bound — not the objective sense alone).
- `conflict` (`bool`, default: `False`) - For an infeasible model, request a conflict / irreducible infeasible subsystem (IIS) — the constraints and variable bounds that cannot all be satisfied — exposed via `Constraint.in_conflict` and `Var.{lower,upper,integrality}_in_conflict`, with the overall outcome in `solve_info().conflict_status`. Needs no objective (unlike `sensitivity`), so a pure feasibility problem can be diagnosed too. Uses wire schema version 2. Read membership with the bare predicate, e.g. `where(con.in_conflict)` (see `ProblemConstraint`).
- `**solver_params` (`int or float or str or bool`, default: `{}`) - Raw solver-specific parameters passed through to the solver service.

**Raises:**

- `ValueError` - If no decision variables have been declared via [`Problem.solve_for`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-solve_for);
  if the problem reads another Problem's results — a property that
  Problem's `solve_for` populates, its `Variable.values`,
  `objective_value()` or any other result accessor, directly or through
  rules derived from them — and that Problem has not been solved, or was
  last solved with `print_only=True`: those results are empty until it
  solves, so solve it first, or, if it is configured for deployment,
  [`Problem.configure`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-configure) this problem too, with any unconfigured Problem it
  reads, so a deployed refresh solves them in order, which needs that
  Problem configured without `print_only=True`;
  if the problem grounds to nothing — no objective terms *and* no
  constraints, which is a grounding accident far more often than an
  intended feasibility problem; if `print_only=True` is combined with
  `sensitivity` or `conflict`; if `sensitivity=True` is combined
  with a satisfaction problem (no objective) or with `solution_limit`;
  or if the solver service is too old for the request's wire schema
  version (3 with `print_format`, else 2; upgrade the RelationalAI
  Native App).
- `TypeError` - If any solver-specific parameter value is not an `int`, `float`,
  `str`, or `bool`, or if `numeric_type` is passed via
  `**solver_params` (declare it via `Problem(model, Float)` or
  `Problem(model, Integer)` instead).
- `NotImplementedError` - If deployments are enabled in the model configuration. Use
  [`Problem.configure`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-configure) to declare deployment execution instead.
- `RuntimeError` - If this Problem has already been configured for deployment, or if the
  solver job fails.
- `TimeoutError` - If the solver job does not reach a terminal state in time.

**Notes:**

Passing `**solver_params` emits a warning because options may not be
portable across solvers.

A failed solve leaves prior result *data* intact. If a solve raises — a
rejected request (`ValueError`), a failed job (`RuntimeError`), or a
timeout (`TimeoutError`) — the last *successful* solve's values,
[`Problem.solve_info`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-solve_info), and any sensitivity / conflict data all remain
queryable, `solve_info()` still describes that last successful solve, and
the failed attempt's partial output is never imported. A fresh successful
solve replaces the prior results; if the first solve fails before any data
loads, a retry simply re-runs it.

Every solve sends wire schema version 2, or 3 with `print_format`, so
one Problem may freely mix plain, `sensitivity`, and `conflict` solves.
Re-solving with a narrower set of flags clears the dropped family's
earlier rows rather than leaving them stale.

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Prescriptive reasoning](/build/reasoning/prescriptive/index.md)1) [Choose a backend](/build/reasoning/prescriptive/backends/index.md)1. [Use Gurobi](/build/reasoning/prescriptive/backends/gurobi/index.md)1) [Example](/build/reasoning/prescriptive/backends/gurobi/index.md#example)
            2. [Use Ipopt](/build/reasoning/prescriptive/backends/ipopt/index.md)1) [Example](/build/reasoning/prescriptive/backends/ipopt/index.md#example)
            3. [Use MiniZinc](/build/reasoning/prescriptive/backends/minizinc/index.md)1) [Example](/build/reasoning/prescriptive/backends/minizinc/index.md#example)
         2) [Solve a decision problem](/build/reasoning/prescriptive/decision-problems/index.md)1) [Overview](/build/reasoning/prescriptive/decision-problems/index.md)
            2) [Solve a decision problem](/build/reasoning/prescriptive/decision-problems/solve/index.md)1) [What happens when you solve a problem](/build/reasoning/prescriptive/decision-problems/solve/index.md#what-happens-when-you-solve-a-problem)
               2) [Solve for feasibility](/build/reasoning/prescriptive/decision-problems/solve/index.md#solve-for-feasibility)
               3) [Solve optimally](/build/reasoning/prescriptive/decision-problems/solve/index.md#solve-optimally)
               4) [Set a time limit](/build/reasoning/prescriptive/decision-problems/solve/index.md#set-a-time-limit)
               5) [Accept a near-optimal solution](/build/reasoning/prescriptive/decision-problems/solve/index.md#accept-a-near-optimal-solution)
               6) [Tune solver backend behavior](/build/reasoning/prescriptive/decision-problems/solve/index.md#tune-solver-backend-behavior)
               7) [Print the translated solver model](/build/reasoning/prescriptive/decision-problems/solve/index.md#print-the-translated-solver-model)
               8) [Check error details when termination status is not `OPTIMAL`](/build/reasoning/prescriptive/decision-problems/solve/index.md#check-error-details-when-termination-status-is-not-optimal)
               9) [Diagnose infeasible problems](/build/reasoning/prescriptive/decision-problems/solve/index.md#diagnose-infeasible-problems)
               10) [Handle solve failures](/build/reasoning/prescriptive/decision-problems/solve/index.md#handle-solve-failures)
            3) [Work with solutions](/build/reasoning/prescriptive/decision-problems/solutions/index.md)
   2) [What's new](/release-notes/index.md)1) [Python package and CLI release notes](/release-notes/python/index.md)1. [Python package and CLI 2.0.1](/release-notes/python/2.0.1/index.md)1) [Bug Fixes](/release-notes/python/2.0.1/index.md#bug-fixes)

### .`solve_info`()

```python
Problem.solve_info() -> SolveInfoData
```

Return solver result metadata as a cached `SolveInfoData`.

Fetches all result metadata in a single query. Eager results are cached
until the next [`Problem.solve`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-solve). Configured deployment results are queried
on every call because a scheduled deployment may refresh them without a
local Python method call.

With model deployments enabled it reads the relationship
[`Problem.install_solve_info`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-install_solve_info) publishes, so call that before deploying. It
then does not warn of rows with no value for a require clause after a
failed solve.

**Returns:**

- `SolveInfoData` - Frozen dataclass with typed fields. Beyond the always-present
  `termination_status` / `objective_value` / `solve_time_sec` /
  `num_points`, it carries the boolean `sensitivity` / `conflict`
  flags echoing what the solve requested, `conflict_status` (after
  `solve(conflict=True)`), `primal_status` / `dual_status` (from
  `point_summary`, populated on every solve; `None` when the service
  emits no point, e.g. infeasible), and a raw `ancillary` map of any other
  solver metadata the service reports; see `SolveInfoData`. Use
  `print(si)` or `si.display()` for a formatted summary. If
  [`Problem.solve`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-solve) has not been called, all fields are None (`error` is `()`).

**Raises:**

- `ValueError` - If model deployments are enabled and [`Problem.install_solve_info`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-install_solve_info) was
  not called.

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Prescriptive reasoning](/build/reasoning/prescriptive/index.md) / [Solve a decision problem](/build/reasoning/prescriptive/decision-problems/index.md)1) [Overview](/build/reasoning/prescriptive/decision-problems/index.md)
         2) [Solve a decision problem](/build/reasoning/prescriptive/decision-problems/solve/index.md)1) [Inspect solve metadata](/build/reasoning/prescriptive/decision-problems/solve/index.md#inspect-solve-metadata)
            2) [Print the translated solver model](/build/reasoning/prescriptive/decision-problems/solve/index.md#print-the-translated-solver-model)
            3) [Check error details when termination status is not `OPTIMAL`](/build/reasoning/prescriptive/decision-problems/solve/index.md#check-error-details-when-termination-status-is-not-optimal)
            4) [Handle solve failures](/build/reasoning/prescriptive/decision-problems/solve/index.md#handle-solve-failures)
         3) [Work with solutions](/build/reasoning/prescriptive/decision-problems/solutions/index.md)

### .`read_printed_model`()

```python
Problem.read_printed_model() -> str | None
```

Return the model text the last solve printed with `print_format`.

Holds the whole print in memory; [`Problem.write_printed_model`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-write_printed_model) writes a large
print to a file using far less. With model deployments enabled it reads the
relationship [`Problem.install_solve_info`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-install_solve_info) publishes, like [`Problem.solve_info`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-solve_info).

**Returns:**

- `str or None` - The printed model, or None if the result carries none: the solve did
  not set `print_format`, or the print failed, which
  `solve_info().error` then reports.

**Raises:**

- `ValueError` - If model deployments are enabled and [`Problem.install_solve_info`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-install_solve_info) was
  not called.
- `RuntimeError` - If the result carries the print in malformed parts.

### .`write_printed_model`()

```python
Problem.write_printed_model(path: str | os.PathLike[str]) -> None
```

Write the model text the last solve printed with `print_format` to a file.

The file holds the text as UTF-8, exactly as the solver printed it, and
replaces any file at `path`. It appears only once the whole print has
arrived and checked out, so a failed write leaves `path` as it was.

A print larger than 8 MiB arrives in parts, which this reads a few at a
time, so it needs far less memory than [`Problem.read_printed_model`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-read_printed_model). The
exception is a model with deployments enabled: a scheduled refresh could
replace the parts between two queries, so the whole print is read in one,
from the relationship [`Problem.install_solve_info`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-install_solve_info) publishes.

**Parameters:**

- `path` (`str or os.PathLike`) - The file to write.

**Raises:**

- `ValueError` - If model deployments are enabled and [`Problem.install_solve_info`](/api/python/v2.2/semantics/reasoners/prescriptive/problem/problem_class/index.md#method-install_solve_info) was
  not called.
- `RuntimeError` - If the result carries no printed model (`solve_info().error` reports
  a failed print), or carries one in malformed parts.

**Examples:**

```python
problem.solve("highs", print_only=True, print_format="mps")
problem.write_printed_model("model.mps")
```

## Referenced By

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use RelationalAI with AI Agents](/build/agents/index.md)1) [Get started with a coding agent](/build/agents/start-with-a-coding-agent/index.md)1. [Find optimal actions with prescriptive reasoning](/build/agents/start-with-a-coding-agent/index.md#find-optimal-actions-with-prescriptive-reasoning)
      2. [Use advanced reasoning](/build/reasoning/index.md) / [Prescriptive reasoning](/build/reasoning/prescriptive/index.md)1) [Choose a backend](/build/reasoning/prescriptive/backends/index.md)1. [Use HiGHS](/build/reasoning/prescriptive/backends/highs/index.md)1) [Example](/build/reasoning/prescriptive/backends/highs/index.md#example)
            2. [Use Gurobi](/build/reasoning/prescriptive/backends/gurobi/index.md)1) [Example](/build/reasoning/prescriptive/backends/gurobi/index.md#example)
            3. [Use Ipopt](/build/reasoning/prescriptive/backends/ipopt/index.md)1) [Example](/build/reasoning/prescriptive/backends/ipopt/index.md#example)
            4. [Use MiniZinc](/build/reasoning/prescriptive/backends/minizinc/index.md)1) [Example](/build/reasoning/prescriptive/backends/minizinc/index.md#example)
         2) [Solve a decision problem](/build/reasoning/prescriptive/decision-problems/index.md)1) [Overview](/build/reasoning/prescriptive/decision-problems/index.md)1. [How PyRel represents a decision problem](/build/reasoning/prescriptive/decision-problems/index.md#how-pyrel-represents-a-decision-problem)
               2. [How solving a decision problem works](/build/reasoning/prescriptive/decision-problems/index.md#how-solving-a-decision-problem-works)
            2) [Create a Problem object](/build/reasoning/prescriptive/decision-problems/create/index.md)1) [Choose a default numeric type](/build/reasoning/prescriptive/decision-problems/create/index.md#choose-a-default-numeric-type)
               2) [Create a Problem object](/build/reasoning/prescriptive/decision-problems/create/index.md#create-a-problem-object)
               3) [Inspect a Problem with `display()`](/build/reasoning/prescriptive/decision-problems/create/index.md#inspect-a-problem-with-display)
            3) [Add decision variables](/build/reasoning/prescriptive/decision-problems/variables/index.md)1) [Declare decision variables](/build/reasoning/prescriptive/decision-problems/variables/index.md#declare-decision-variables)
               2) [Choose variable types and bounds](/build/reasoning/prescriptive/decision-problems/variables/index.md#choose-variable-types-and-bounds)
               3) [Inspect `Problem` variables](/build/reasoning/prescriptive/decision-problems/variables/index.md#inspect-problem-variables)
            4) [Add constraints](/build/reasoning/prescriptive/decision-problems/constraints/index.md)1) [Add constraints with `Problem.satisfy()`](/build/reasoning/prescriptive/decision-problems/constraints/index.md#add-constraints-with-problemsatisfy)
               2) [Inspect `Problem` constraints](/build/reasoning/prescriptive/decision-problems/constraints/index.md#inspect-problem-constraints)
               3) [Read the text of a constraint or objective](/build/reasoning/prescriptive/decision-problems/constraints/index.md#read-the-text-of-a-constraint-or-objective)
               4) [Avoid common pitfalls](/build/reasoning/prescriptive/decision-problems/constraints/index.md#avoid-common-pitfalls)
            5) [Solve a decision problem](/build/reasoning/prescriptive/decision-problems/solve/index.md)1) [What happens when you solve a problem](/build/reasoning/prescriptive/decision-problems/solve/index.md#what-happens-when-you-solve-a-problem)
               2) [Validate before you solve](/build/reasoning/prescriptive/decision-problems/solve/index.md#validate-before-you-solve)
               3) [Solve for feasibility](/build/reasoning/prescriptive/decision-problems/solve/index.md#solve-for-feasibility)
               4) [Solve optimally](/build/reasoning/prescriptive/decision-problems/solve/index.md#solve-optimally)
               5) [Inspect solve metadata](/build/reasoning/prescriptive/decision-problems/solve/index.md#inspect-solve-metadata)
               6) [Set a time limit](/build/reasoning/prescriptive/decision-problems/solve/index.md#set-a-time-limit)
               7) [Accept a near-optimal solution](/build/reasoning/prescriptive/decision-problems/solve/index.md#accept-a-near-optimal-solution)
               8) [Tune solver backend behavior](/build/reasoning/prescriptive/decision-problems/solve/index.md#tune-solver-backend-behavior)
               9) [Print the translated solver model](/build/reasoning/prescriptive/decision-problems/solve/index.md#print-the-translated-solver-model)
               10) [Check error details when termination status is not `OPTIMAL`](/build/reasoning/prescriptive/decision-problems/solve/index.md#check-error-details-when-termination-status-is-not-optimal)
               11) [Diagnose infeasible problems](/build/reasoning/prescriptive/decision-problems/solve/index.md#diagnose-infeasible-problems)
               12) [Handle solve failures](/build/reasoning/prescriptive/decision-problems/solve/index.md#handle-solve-failures)
               13) [Avoid common pitfalls](/build/reasoning/prescriptive/decision-problems/solve/index.md#avoid-common-pitfalls)
            6) [Work with solutions](/build/reasoning/prescriptive/decision-problems/solutions/index.md)1) [Determine how to access results](/build/reasoning/prescriptive/decision-problems/solutions/index.md#determine-how-to-access-results)
               2) [Read solver-level variable values](/build/reasoning/prescriptive/decision-problems/solutions/index.md#read-solver-level-variable-values)
   2) [What's new](/release-notes/index.md)1) [Python package and CLI release notes](/release-notes/python/index.md)1. [Python package and CLI 2.0.1](/release-notes/python/2.0.1/index.md)1) [Bug Fixes](/release-notes/python/2.0.1/index.md#bug-fixes)
