Designs over a Constrained Region#
Factor limits are rarely independent. A reactor may run hot, or run long, but not both, because the heat load would exceed what the jacket can remove. The feasible region is then the factor box with a corner cut off, and a classical design (a factorial, a CCD, a Box-Behnken) places runs in that corner.
generate_design accepts such limits as Constraint
objects. When constraints are given it builds a D-optimal design, choosing every run
from the feasible region.
How the design is chosen#
Candidate set. A grid over the factor box (5 levels per continuous factor, fewer for many factors), plus the points where each constraint boundary crosses a grid edge, located by bisection, and the vertices where linear constraints meet (see Many factors with limits on group totals for a region with too many to list). Infeasible points are dropped. The metadata reports the counts:
m = result.metadata print(m["constraints_enforced"], m["n_grid_points"], m["n_boundary_points"], m["n_candidates"]) # True 25 7 21
Model matrix. Each candidate is expanded into the columns of the requested
model_type: intercept, main effects, two-factor interactions and, for"quadratic", squared terms. A categorical factor withLlevels contributesL - 1effect-coded (sum-to-zero) columns, the codingevaluate_designuses.Exchange. A Fedorov exchange swaps one design run for one candidate at a time, taking the swap that increases the determinant of
X'Xmost, until no swap improves it. Five random starts guard against a poor local optimum;random_statemakes the result reproducible.
Writing constraints#
Use factor names and actual units:
"3*T + 5*D <= 600".<,<=,>and>=are accepted; a chained comparison such as"400 <= 3*T + 5*D <= 600"gives a lower and an upper limit.Nonlinear limits are allowed, with
+ - * / **andabs,sqrt,exp,log,log10:Constraint(expression="T * D <= 6000", type="nonlinear").Equalities are refused. A region with
A + B == 1has no volume to place runs in; proportions that sum to one are mixture factors.A constraint may also name categorical factors, to disallow a combination of levels or to limit a continuous factor on some levels only; see Combinations of levels that cannot be run. Categorical factors that no constraint names are crossed with the constrained continuous region.
A constraint may limit how many factors a run uses, a factor at 0 being left out:
"count_nonzero(A, B, C, D) <= 2"; see How many ingredients a run uses.
The expression is parsed into an arithmetic tree and evaluated with numpy; it is never
passed to eval, so an expression from an untrusted source can only compute a number.
Limits on the Settings shows how to check what a set of limits leaves, propose a limit from
the settings that cannot be run, and draw the region.
Combining with other options#
fixed_runskeeps runs already performed (continuous factors in coded units, categorical as labels) and fills the rest of the budget around them. A fixed run outside the region is kept and a warning is logged.hard_to_change(split-plot) keeps to the constraints too, on the grid of levels inside them, and keepsfixed_runsas the design’s first runs: a whole plot that holds one keeps its hard-to-change settings. With a candidate set or blocks it is ignored and recorded asmetadata["hard_to_change_ignored"].Other design types do not enforce constraints. They log a warning and set
metadata["constraints_enforced"] = False. A constraint that names a categorical factor is refused instead, since it usually marks a combination that cannot be run at all, and so is a limit on how many factors a run uses.
Many factors with limits on group totals#
A formulation often has many ingredients in groups, with a limit on each group’s total and on the total of them all. Below, 15 ingredients sit in 5 buckets of 3. Each bucket supplies between 5% and 20% of the product, so every bucket is represented, and the 15 together supply at most 60%; the base makes up the rest.
buckets = [[f"B{b}_{i}" for i in (1, 2, 3)] for b in (1, 2, 3, 4, 5)]
ingredients = [name for bucket in buckets for name in bucket]
bucket_limits = [f"5 <= {' + '.join(bucket)} <= 20" for bucket in buckets]
total_limit = f"{' + '.join(ingredients)} <= 60"
screening = generate_design(
[Factor(name=name, low=0, high=20, units="%") for name in ingredients],
budget=30,
constraints=[*bucket_limits, total_limit],
model_type="main_effects",
random_state=1,
)
amounts = screening.design_actual[ingredients]
print(screening.metadata["vertices_sampled"]) # True
print(amounts[buckets[0]].sum(axis=1).between(5 - 1e-9, 20 + 1e-9).all()) # True
print(amounts.sum(axis=1).max().round(6) <= 60) # True
No point of a grid on 15 factors has every bucket’s total inside its limits, and the
region has too many vertices to list. The candidates are then vertices of the region
found by linear programming, each one the furthest point of the region in some
direction, with the midpoints between them. metadata["vertices_sampled"] records
it. A region the grid covers keeps the candidates described above.
The lower limit on a bucket’s total is what keeps the bucket represented: a total of at least 5% needs at least one of its ingredients. For a main-effects model the runs sit on vertices, and a vertex of this region has one ingredient in most buckets. Such a design estimates the effect of each ingredient on its own; how two ingredients of one bucket act together needs their interaction in the model, and more runs.
An ingredient that is left out, or used at no less than a minimum#
An ingredient is often either left out or added in an amount that can be dosed and
tasted: 0, or at least 5 ppm, and never a trace in between. min_when_used on the
factor says so. It needs low=0.
flavours = [
Factor(name="vanillin", low=0, high=50, units="ppm", min_when_used=5),
Factor(name="maltol", low=0, high=50, units="ppm", min_when_used=30),
Factor(name="sugar", low=10, high=20, units="%"),
]
blend = generate_design(flavours, budget=14, model_type="quadratic", random_state=1)
print(blend.design_type) # d_optimal, chosen because a factor has a minimum
print(sorted(set(blend.design_actual["vanillin"]))) # [0.0, 25.0, 50.0]
print(sorted(set(blend.design_actual["maltol"]))) # [0.0, 30.0, 50.0]
No run sets a factor between 0 and its minimum. The middle level of maltol would
be 25 ppm, below its minimum of 30, so the candidates hold 30 in its place: the factor
still takes three levels, which its squared term needs. The same holds beside
constraints, and beside limits on group totals, where a lower limit on a group’s total
equal to the smallest minimum in the group says that at least one of its ingredients is
used.
from process_improve.experiments import DesignRegion
region = DesignRegion(flavours, ["vanillin + maltol <= 60"])
# vanillin at 2.5 ppm, then at 5 ppm; maltol at 0; sugar at 15%. Coded units.
print(region.feasible([[-0.9, -1.0, 0.0], [-0.8, -1.0, 0.0]])) # [False True]
print(region.broken_limits([[-0.9, -1.0, 0.0]])) # [['vanillin = 0 or vanillin >= 5']]
A classical design takes its levels from the factor’s range alone. One that would set
the factor between 0 and its minimum, in a run or in its center points, is refused,
with the factor’s name; fixed_runs are kept as given.
Such a region is made of pieces, one for each set of the ingredients in use, and the
pieces have different dimensions, so no single volume measures them all.
DesignRegion.sample draws from the measure under which each such ingredient is left
out as often as it is used, before the constraints act, and is uniform between its
minimum and its high level when it is used. The constraints then condition it: of the
four sets of vanillin and maltol, the limit below cuts only the one that uses
both, to a third of its settings, so each is left out in 60% of the points. I- and
G-optimal designs, and the prediction variance evaluate_design reports, average
over those points.
import numpy as np
points = region.sample(20_000, np.random.default_rng(1))
print(region.feasible(points).all()) # True
print(round(float((points[:, 0] == -1).mean()), 1)) # 0.6: vanillin is left out (coded -1)
optimize_responses searches the same region, and how it does so depends on the
models (How the optimum is found, and when it is proven). The model below has an interaction, so the
optimum is searched for: a search cannot step from 0 to the minimum, so each one keeps
the set of ingredients its start uses, and the sets next to the best results are then
tried. The optimum leaves vanillin out: in coded units the response gains 2 from it
and 3 from maltol, and loses 6 times their product, so either alone beats both
together.
from process_improve.experiments import optimize_responses
terms = {"Intercept": 10.0, "vanillin": 2.0, "maltol": 3.0, "sugar": 0.5, "vanillin:maltol": -6.0}
liking = {
"response_name": "liking",
"factor_names": ["vanillin", "maltol", "sugar"],
"coefficients": [{"term": term, "coefficient": value} for term, value in terms.items()],
}
best = optimize_responses(
[liking],
goals=[{"response": "liking", "goal": "maximize", "low": 0.0, "high": 30.0}],
region=region,
factor_ranges={f.name: {"low": f.low, "high": f.high} for f in flavours},
)["desirability"]
print({name: round(value, 6) for name, value in best["optimal_actual"].items()})
# {'vanillin': 0.0, 'maltol': 50.0, 'sugar': 20.0}
How the optimum is found, and when it is proven#
Which ingredients to use is a choice among very many sets (26 ingredients of which 8
to 14 are used give more than 40 million), and a search that tries the sets one at a
time can end at a good set that is not the best. optimize_responses therefore
takes one of two routes, and the result says which in proven_optimal.
Every model and every constraint is a straight line. This is the usual case for a
formulation of many ingredients, whose runs support a model without interactions. Each
desirability is then a ramp that is a straight line in the ingredients, and the best
setting is found by mixed-integer linear programming, which does not search from
starting points: it bounds the desirability of every set of ingredients and returns
the setting together with the proof that no setting of the region scores higher (to
one part in a million of the composite desirability). Several responses, targets,
in_range limits, weights and importances are all covered, as are ingredients left
out or used at no less than a minimum, limits on how many are used, group totals, and
blends beside process factors. Where ingredients can be left out, that setting is the
one reported and proven_optimal is True. Where none can, the region is one piece
and the setting reported is still the search’s own, so that a study kept earlier shows
the settings it showed; proven_optimal then says whether that setting reaches the
bound (the search can stop a little short along a factor of small effect). One
condition for the proof where ingredients are left out: every
ingredient that a count_nonzero rule counts has a min_when_used. Without one
the ingredient counts as used at any amount above 0, the best setting may be one that
is approached and never reached, and the optimum is searched for instead.
A model has an interaction or a squared term, or a constraint is curved. No such
proof is to be had at a cost worth paying, so the optimum is searched for, with three
aids. The searches start from the most promising settings of as many different sets
of ingredients, chosen among the region’s candidate blends. From the best results the
sets next to them are tried: one ingredient left out or brought in, or one exchanged
for another. And each model is replaced by its tangent at the best setting, a straight
line, for which the best set is found exactly as above; the search then continues on
the models themselves from there. Against the best of every allowed set of ten
ingredients, with blending interactions in three responses, this found the best
setting in all of 44 cases; it is still a search, and proven_optimal is False,
unless the composite desirability reaches 1, which nothing exceeds.
A Pareto front (method="pareto_front") keeps the sets its starts use.
How many ingredients a run uses#
A formulation may hold at most so many of the ingredients on offer, or at least so
many, or exactly one of a group. count_nonzero counts the factors it names that
are above 0 in a run, and the constraint compares that count with whole numbers:
"count_nonzero(A, B, C, D) <= 2": at most two of the four are used;"count_nonzero(A, B, C) >= 1": at least one of the three is used;"3 <= count_nonzero(A, B, C, ...) <= 5": between 3 and 5 of them are used;"count_nonzero(A, B, C) == 1": exactly one of the three is used.
The factors it names are amounts: continuous factors, or mixture components, whose
low is 0 or more. A factor at 0 is left out. One with a min_when_used
(An ingredient that is left out, or used at no less than a minimum) is left out or set at no less than that minimum, so
“used” means a real amount; one without it counts as used at any amount above 0. A
factor whose low is above 0 is in every run, and always counts.
amounts = [Factor(name=name, low=0, high=10, units="g", min_when_used=2) for name in "ABCD"]
at_most_two = generate_design(
amounts,
budget=14,
model_type="interactions",
constraints=["count_nonzero(A, B, C, D) <= 2"],
random_state=1,
)
in_use = (at_most_two.design_actual[list("ABCD")] > 1e-9).sum(axis=1)
print(int(in_use.max())) # 2
The settings such a constraint allows are not one region but pieces of one, a piece for each set of the factors in use: on a piece the factors left out are at 0, and the others range from their minimum to their high level, within the other constraints. The candidates are found piece by piece, as vertices of the piece and the points between them. Every allowed set gives a piece when the factors that can be left out are few (up to 10); with more, a sample of the allowed sets does.
Two factors that no run uses together have no interaction to estimate. With exactly
one of A, B and C in use, the design is built without their three
interactions, a warning names them, and metadata["inestimable_columns"] records
them:
one_of_three = generate_design(
amounts,
budget=12,
model_type="interactions",
constraints=["count_nonzero(A, B, C) == 1"],
random_state=1,
)
print(one_of_three.metadata["inestimable_columns"]) # {'A:B': 1, 'A:C': 1, 'B:C': 1}
evaluate_design leaves the same columns out, so the design is judged on the model
it was built for, and says so in a note. The default model of analyze_experiment
leaves those interactions out too, with a warning that no run has the two factors
both above their lowest values.
from process_improve.experiments import evaluate_design
judged = evaluate_design(one_of_three, model="interactions", metric="vif")
print(list(judged["vif"])) # ['A', 'B', 'C', 'D', 'A:D', 'B:D', 'C:D']
print("inestimable_columns" in judged["notes"]) # True
DesignRegion knows the rule. A run that uses too many factors, or too few, is
outside the region, and sample draws only sets that the rule allows: before the
rule acts each of the four factors is left out half the time, so the 11 sets of at most
two of them are as likely as one another, and 6 of the 11 use two factors.
pieces = DesignRegion(amounts, ["count_nonzero(A, B, C, D) <= 2"])
# A, B and C at 7.5 g with D left out; then A and B at 10 g with C and D left out. Coded units.
print(pieces.feasible([[0.5, 0.5, 0.5, -1.0], [1.0, 1.0, -1.0, -1.0]])) # [False True]
print(pieces.broken_limits([[0.5, 0.5, 0.5, -1.0]])) # [['count_nonzero(A, B, C, D) <= 2']]
drawn = pieces.sample(20_000, np.random.default_rng(1))
print(round(float(((drawn > -1 + 1e-9).sum(axis=1) == 2).mean()), 1)) # 0.5, as 6 of 11
optimize_responses returns an optimum that the rule allows. Below, every factor
adds to the response and A adds the most, so with at most one factor in use the
optimum is A alone. The model has no interaction and the rule is a count, so the
optimum is proven (How the optimum is found, and when it is proven).
gains = {"Intercept": 10.0, "A": 3.0, "B": 2.0, "C": 1.0, "D": 0.5}
yield_model = {
"response_name": "y",
"factor_names": list("ABCD"),
"coefficients": [{"term": term, "coefficient": value} for term, value in gains.items()],
}
one = optimize_responses(
[yield_model],
goals=[{"response": "y", "goal": "maximize", "low": 0.0, "high": 30.0}],
region=DesignRegion(amounts, ["count_nonzero(A, B, C, D) <= 1"]),
factor_ranges={name: {"low": 0, "high": 10} for name in "ABCD"},
)["desirability"]
print({name: round(value, 6) for name, value in one["optimal_actual"].items()})
# {'A': 10.0, 'B': 0.0, 'C': 0.0, 'D': 0.0}
print(one["proven_optimal"]) # True
A design type that cannot follow the rule, such as a factorial or a central composite
design, is refused. The descriptions of one convex region (vertices,
volume_fraction, implied_bounds and the pictures) are refused too, since the
rule leaves a piece for each set of factors; is_empty answers from the pieces. The
rule works on mixture components as well, where a blend then uses an allowed number of
them, and beside process factors.
Combinations of levels that cannot be run#
Some combinations of categorical levels cannot be run, and some levels allow only part of a continuous factor’s range. Both are written as constraints on the levels, and the optimal design then places runs only where they are allowed.
A reaction is run with catalyst A, B or C in solvent X or Y, between 150 and 200 degC and 1 and 5 bar. Catalyst B decomposes in solvent Y, and loses activity above 180 degC.
from process_improve.experiments import DesignRegion, Factor, generate_design
reaction = [
Factor(name="T", low=150, high=200, units="degC"),
Factor(name="P", low=1, high=5, units="bar"),
Factor(name="catalyst", type="categorical", levels=["A", "B", "C"]),
Factor(name="solvent", type="categorical", levels=["X", "Y"]),
]
reaction_rules = [
"not (catalyst == 'B' and solvent == 'Y')", # B decomposes in solvent Y
"not (catalyst == 'B' and T > 180)", # B loses activity above 180 degC
]
reaction_result = generate_design(reaction, budget=20, constraints=reaction_rules, random_state=1)
runs = reaction_result.design_actual
print(runs.groupby(["catalyst", "solvent"]).size().to_string())
print(runs.groupby("catalyst")["T"].max().to_string())
print(reaction_result.metadata["inestimable_columns"])
catalyst solvent
A X 4
Y 4
B X 4
C X 4
Y 4
catalyst
A 200.0
B 180.0
C 200.0
{'catalyst:solvent': 1}
The 20 runs are spread evenly over the five allowed pairs, and catalyst B never goes above 180 degC while the other two reach 200 degC.
A disallowed pair is a missing cell, and it costs the interaction of the two factors
part of its information in every design over this region: the six cells of catalyst
by solvent would estimate the intercept, the two main effects and the interaction’s
two columns, and five cells leave one of those columns out. The design is built for
the columns that can be estimated, a warning names the term and the missing pair, and
metadata["inestimable_columns"] records it. evaluate_design drops the same
column, so the design is judged on the model it was built for, and says so in
result["notes"]["inestimable_columns"].
analyze_experiment cannot estimate the full interaction either. Its default
interactions model leaves out catalyst by solvent, with a warning that names the
missing pair, and fits every other interaction; the one column of catalyst by solvent
that could be estimated is left out with it.
The region describes itself one combination at a time:
reaction_region = DesignRegion(reaction, reaction_rules)
print(reaction_region.allowed_combinations())
print(reaction_region.given(catalyst="B", solvent="X").implied_bounds())
catalyst solvent limits
0 A X []
1 A Y []
2 B X [T <= 180]
3 C X []
4 C Y []
{'T': (150.0, 180.0), 'P': (1.0, 5.0)}
given() returns the region of
continuous settings for one combination, on which every diagnostic of
Limits on the Settings works. A diagnostic asked of the whole region refuses and points
to given, since the region holds one such region per allowed combination.
Writing the rules:
Compare a categorical factor with its levels:
catalyst == 'B',catalyst != 'B',catalyst in ('A', 'C'),catalyst not in ('A', 'C'). A level the factor does not have is an error, so a misspelt level cannot leave every combination allowed.Join comparisons with
and,orandnot."not (...)"reads as “this combination is not run”.An inequality inside a rule applies only on the levels the rule names:
"catalyst != 'C' or (T <= 170 and P <= 4)"keeps catalyst C at or below 170 degC and 4 bar.Two inequalities joined by
orare refused: the settings either one allows do not form a convex region, which the design needs for each combination of levels.A level that the rules leave with no allowed run is refused; remove it from the factor.
Only the optimal designs follow these rules, and not yet beside mixture components.
The I-criterion and
evaluate_designaverage over every setting the rules allow, so each allowed combination weighs as much as the volume of its settings: here, B in solvent X keeps 150 to 180 of 150 to 200 degC, and counts 0.6 times as much as each other pair. A combination whose limits leave no volume does not count in the average.
Judging the design over its own region#
A constrained design should be judged on the settings it may visit. The average
prediction variance (the I-criterion, lower is better) averages it over the region, and
the G-efficiency is based on its worst case. Over the full box, both are dominated by the cut-off corner, where the
model has to extrapolate. generate_design records the region in
result.metadata["region"], and evaluate_design uses it by default:
from process_improve.experiments import evaluate_design
metrics = ["average_prediction_variance", "g_efficiency"]
inside = evaluate_design(result, model="quadratic", metric=metrics)
cube = evaluate_design(result, model="quadratic", metric=metrics, region="cuboidal")
print(f"{inside['average_prediction_variance']:.2f} {inside['g_efficiency']:.0f}") # 0.50 73
print(f"{cube['average_prediction_variance']:.2f} {cube['g_efficiency']:.1f}") # 1.44 3.5
Inside the region the average prediction variance is a third of its value over the box, and the worst case is about a twentieth. The box figure describes settings the plant cannot run, so it says nothing about the design’s quality for this process.
The region is sampled uniformly by rejection, and its boundary points (the feasible
grid corners and the constraint crossings) are added, since that is where the worst
case of a second-order model sits. Pass region=DesignRegion(factors, constraints)
to evaluate a design held as a plain DataFrame.
Choosing the criterion: D, I or A#
The exchange maximizes one number, and the three criteria ask different questions:
D-optimal (
design_type="d_optimal") maximizesdet(X'X): the model coefficients are estimated jointly as precisely as possible.I-optimal (
"i_optimal") minimizes the average prediction variance over the region, whichevaluate_designreports asaverage_prediction_variance. It suits a study whose purpose is prediction or optimization.A-optimal (
"a_optimal") minimizes the summed variance of the coefficients.E-optimal (
"e_optimal") maximizes the smallest eigenvalue ofX'X, so no combination of the coefficients is left poorly estimated.
On the heat-budget example, with ten runs for a quadratic model, each design is best on its own measure:
Design |
D-efficiency (higher is better) |
Summed coefficient variance (lower is better) |
Smallest eigenvalue (higher is better) |
|---|---|---|---|
D-optimal |
29.6 |
5.67 |
0.272 |
A-optimal |
27.8 |
4.95 |
0.322 |
E-optimal |
26.0 |
5.09 |
0.325 |
For the I-optimal design the average is taken over the constrained region itself,
sampled uniformly, so the design is chosen for the same region evaluate_design
uses to judge it:
for design_type in ["d_optimal", "i_optimal"]:
r = generate_design(factors, design_type=design_type, budget=10, constraints=[heat], model_type="quadratic")
m = evaluate_design(r, model="quadratic", metric=["d_efficiency", "average_prediction_variance", "g_efficiency"])
print(design_type, {k: round(m[k], 3) for k in ("d_efficiency", "average_prediction_variance", "g_efficiency")})
# d_optimal {'d_efficiency': 29.57, 'average_prediction_variance': 0.499, 'g_efficiency': 73.341}
# i_optimal {'d_efficiency': 27.351, 'average_prediction_variance': 0.356, 'g_efficiency': 62.677}
Each design is best on its own criterion. The I-optimal design places more runs in the interior, so its average prediction variance is lower by a factor of 1.4, at the cost of a slightly less precise joint estimate of the coefficients and a larger worst case at the boundary.
These designs come from the built-in exchange, which is the default for every optimal
design, so the same call gives the same design whether or not the optional pyoptex
package is installed. A split-plot design (hard_to_change) comes from the built-in
coordinate exchange. pyoptex is used only when asked for with backend="pyoptex",
which is deprecated since 2.7.0 and will be removed in 3.0.
Choosing runs from a list: candidate sets#
Sometimes the region is not a formula but a list: the operating points in the plant
records, the discrete settings a piece of equipment offers, or the blends that can be
made up from stock. Pass them as candidates and the optimal design is chosen from
those rows only:
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
history = pd.DataFrame(
{"T": rng.uniform(100, 150, 30).round(1), "D": rng.uniform(20, 60, 30).round(1)},
index=[f"batch_{i:02d}" for i in range(30)],
)
result = generate_design(
factors, budget=8, candidates=history, constraints=[heat], model_type="interactions"
)
m = result.metadata
print(m["n_candidates_supplied"], m["n_candidates_infeasible"], m["n_candidates"]) # 30 13 17
print(m["selected_candidates"])
# {'batch_02': 2, 'batch_20': 2, 'batch_29': 2, 'batch_05': 1, 'batch_06': 1}
The 13 records that break the heat budget are dropped, and the eight runs are chosen
from the remaining 17. selected_candidates names the chosen rows by their index
label, so the design can be read as “rerun batches 2, 20 and 29 twice, and batches 5
and 6 once”.
The candidates are given in actual units, one column per factor (labels for
categorical factors, proportions for mixtures). A candidate set replaces the generated
grid, so for an I-optimal design it is also the region the average prediction variance
is taken over. Without design_type, a candidate set selects "d_optimal".
Candidates outside the factors’ low/high range are kept with a warning, since
the coding extrapolates beyond plus or minus one.
Running the design in blocks#
When the runs cannot all be made under the same conditions (on two days, from two lots
of raw material), pass n_blocks. The analysis then fits a level for each block, so
what the design has to estimate well is the factor effects once the differences
between blocks are taken out. The D-, A- and I-optimal designs choose their runs for
exactly that model: each block gets its own copy of the candidates, a run is only ever
exchanged for a candidate of its own block, and the criterion is that of the factor
effects adjusted for the blocks.
result = generate_design(factors, budget=12, n_blocks=2, constraints=[heat], model_type="quadratic")
print(result.metadata["blocking"]["method"]) # optimal_exchange
print(result.design_actual.sort_values(["Block", "T", "D"]).to_string(index=False))
RunOrder T D Block
4 100.0 20.0 1
6 100.0 40.0 1
5 100.0 60.0 1
2 125.0 20.0 1
3 125.0 45.0 1
1 150.0 30.0 1
10 100.0 20.0 2
11 100.0 40.0 2
8 100.0 60.0 2
12 125.0 20.0 2
7 125.0 45.0 2
9 150.0 20.0 2
Each day’s six runs cover the region’s vertices and edge midpoints, so each block is nearly a quadratic design on its own, and a shift from one day to the next moves both blocks’ averages without biasing the factor effects. The run sheet takes the blocks in turn, shuffled within each.
The most useful case is a follow-up experiment. Pass the runs already made as
fixed_runs: with n_blocks they are the first block, kept first and in their
order, and the new runs fill the other blocks, chosen knowing that the new day may
differ from the old one.
first_day = generate_design(factors, budget=6, constraints=[heat], model_type="interactions").design
follow_up = generate_design(
factors,
budget=12,
n_blocks=2,
fixed_runs=first_day[["T", "D"]],
constraints=[heat],
model_type="quadratic",
)
print(follow_up.design["Block"].tolist()) # [1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2]
For the analysis with a day effect, this follow-up is 3.7% more D-efficient than the same augmentation chosen as if both days were one (13% for a 2x2 factorial followed by five runs). Splitting an optimal design into blocks after choosing it, the only option before, was within 1% of the joint design for equal blocks over a regular region; the gain is in follow-ups, in many small blocks (2 to 5% for blocks of two runs), and it cannot hurt.
metadata["log_det_information"] (or trace_criterion) is then the value for the
factor effects adjusted for the blocks, and metadata["blocking"]["method"] is
"optimal_exchange". E-, G- and K-optimal designs, mixtures, split-plot designs and
replicated designs are still split into blocks after they are chosen ("exchange"),
and cannot be combined with fixed_runs. Each block needs at least two new runs, and
the budget is raised, with a warning, when the block effects leave too few.
Optimizing inside the region#
An optimum is only useful if the process can run it. Passing the same region to
optimize_responses turns each constraint into an SLSQP inequality constraint and
starts the search from feasible points. Here, a fitted quadratic model whose maximum
over the box is the forbidden corner:
from process_improve.experiments import DesignRegion, optimize_responses
model = {
"response_name": "y",
"factor_names": ["T", "D"],
"coefficients": [
{"term": "Intercept", "coefficient": 60.0},
{"term": "T", "coefficient": 8.0},
{"term": "D", "coefficient": 6.0},
{"term": "I(T ** 2)", "coefficient": -2.0},
{"term": "I(D ** 2)", "coefficient": -3.0},
],
}
goal = [{"response": "y", "goal": "maximize", "low": 40, "high": 75}]
ranges = {"T": {"low": 100, "high": 150}, "D": {"low": 20, "high": 60}}
region = DesignRegion.from_dict(result.metadata["region"])
best = optimize_responses([model], goal, factor_ranges=ranges, region=region)["desirability"]
print(f"{best['optimal_actual']['T']:.1f} {best['optimal_actual']['D']:.1f}", best["within_region"])
# 140.7 35.6 True: on the heat line 3*T + 5*D = 600
Without region the same call returns (150 degC, 60 min), with a heat load of 750.
method="pareto_front" accepts region too; the other methods ignore it and log
a warning.
Constrained mixtures#
In a formulation the components are proportions that sum to one, and each is usually bounded: at least 10% polymer, at most 30% filler. Bounds and linear constraints cut the simplex down to a polygon (a polytope in more than three components), and the design is built from its geometry.
factors = [
Factor(name="polymer", type="mixture", low=0.10, high=0.50),
Factor(name="solvent", type="mixture", low=0.10, high=0.70),
Factor(name="filler", type="mixture", low=0.05, high=0.30),
]
cap = Constraint(expression="polymer + solvent <= 0.85")
ev = generate_design(factors, constraints=[cap])
print(ev.metadata["method"], ev.n_runs, ev.metadata["n_vertices"]) # extreme_vertices 11 5
dopt = generate_design(factors, budget=12, constraints=[cap])
print(dopt.metadata["method"]) # d_optimal_extreme_vertices
Extreme vertices. In
qcomponents, a vertex is a blend whereq - 1constraints hold with equality. Constraints implied by the others are dropped, every choice ofq - 1of the rest is solved as one linear system, in batches, and the feasible solutions are the vertices.Without a budget the vertices and the centroid are returned, plus the edge midpoints for a quadratic model and the centroids of the 2-dimensional faces for a special cubic one. Those faces are the constrained counterpart of ternary blends, which the
x_i x_j x_kterms need. A full cubic model takes the 2-face centroids and, in place of the midpoints, the points a third and two thirds of the way along each edge: along an edge the model is a cubic polynomial, which needs four points on that edge. When that is more than three runs per model term, as it soon is with many bounded components, a D-optimal design with five runs more than the model has terms is returned instead.With a budget a D-optimal subset is chosen from the vertices, edge midpoints, edge third-points, 2-face and facet centroids, centroid and axial check blends, by the same exchange as above. Blends can repeat, which gives replicates for a pure-error estimate.
Mixture constraints must be linear in the proportions, since the vertex enumeration
relies on flat faces. A ratio of two linear expressions against a number is one of them:
"polymer / filler <= 4" is read as "polymer <= 4 * filler", and
"0.5 <= polymer / (solvent + filler) <= 2" as two such limits. Multiplying through
keeps the inequality only where the denominator is positive, so the component bounds must
hold it above zero; where they do not, the constraint is refused with the limit to write
in its place.
On the full simplex (no bounds, no constraints) the design is
sized to the model: the pure components and the overall centroid for a linear model,
plus the binary 50:50 blends for a quadratic one (the {q, 2} simplex lattice), plus
the ternary blends for a special cubic one. With three components that is the 7-run
simplex centroid. The full cubic model ("scheffe_cubic", or "cubic") adds a term
x_i x_j (x_i - x_j) for each pair of components, which is zero at every one of those
blends. Its design is the {q, 3} simplex lattice, every blend in thirds, plus the
overall centroid for four or more components. A budget below that size gives a D-optimal
subset instead.
Analyze the runs with a Scheffé model. It has no intercept, because the proportions sum to one:
import numpy as np
from process_improve.experiments import analyze_experiment
blends = ev.design_actual[["polymer", "solvent", "filler"]]
# A simulated response stands in for the measurements here.
rng = np.random.default_rng(1)
blends["y"] = (
10 * blends["polymer"] + 6 * blends["solvent"] + 3 * blends["filler"]
+ 8 * blends["polymer"] * blends["solvent"] + rng.normal(0, 0.1, len(blends))
)
fit = analyze_experiment(
blends, response_column="y", model="scheffe_quadratic", analysis_type=["coefficients", "anova"]
)
print(fit["model_summary"]["formula"]) # y ~ -1 + (polymer + solvent + filler) ** 2
"scheffe_linear", "scheffe_quadratic", "scheffe_special_cubic" and
"scheffe_cubic" are accepted by analyze_experiment and evaluate_design. In a
formula the full cubic’s terms are written I(polymer * solvent * (polymer - solvent)).
statsmodels recognizes that the proportions carry an implicit intercept, so R-squared is
centered and the model degrees of freedom are one less than the number of terms, as for a
model with an intercept.
A blending coefficient tested against zero asks whether a pure component gives a
response of zero, which is rarely the question. So for a Scheffé model the ANOVA tests
the linear blending terms jointly (do the components blend differently at all?) and
each non-linear blending term, such as polymer:solvent, on its own. Effects are
reported in the Cox direction (each linear coefficient minus the mean of the others),
and Lenth’s method is not applied.
evaluate_design defaults to the Scheffé quadratic model for a mixture
design and samples its constrained simplex. optimize_responses with the mixture
region searches the polytope and returns a blend that sums to one.
Many components, groups held to a total, and components left out#
Three things happen in a blend of many components that are grouped, as when the ingredients of a formulation sit in buckets and the whole formulation is the mixture.
Too many vertices to list. Fifteen components in five buckets, each bucket between 5%
and 30% of the blend, need millions of linear systems to list every vertex. Some of the
vertices are then found by linear programming, as for limits on group totals, with the points between them standing in for the edges and
faces, and metadata["vertices_sampled"] is True. Without a budget the design is
D-optimal, a few runs more than the model has terms.
A group held to a fixed total. Five buckets that may each supply at most 20% of a
blend supply exactly 20% each. The components of a bucket then sum to a constant in
every blend, as all the components together do, and one column of each bucket but the
first cannot be told from the others. The design is built for the columns that can be
estimated, a warning names the others, and metadata["inestimable_columns"] lists
them:
pairs = [[f"B{b}_{i}" for i in (1, 2)] for b in (1, 2, 3, 4, 5)]
components = [Factor(name=name, type="mixture", high=0.2) for pair in pairs for name in pair]
at_most_a_fifth = [f"{first} + {second} <= 0.2" for first, second in pairs]
fifths = generate_design(
components, budget=16, constraints=at_most_a_fifth, model_type="scheffe_linear", random_state=1
)
print(fifths.metadata["inestimable_columns"]) # ['B2_2', 'B3_2', 'B4_2', 'B5_2']
print(fifths.design_actual[pairs[0]].sum(axis=1).round(9).unique()) # [0.2]
Whichever column of a bucket is left out, the columns kept span the same model over
the region, so the design does not depend on the choice. evaluate_design leaves
the same columns out and says so in result["notes"]["inestimable_columns"].
A component left out, or used at no less than a minimum. min_when_used works on a
mixture component as on an amount (An ingredient that is left out, or used at no less than a minimum): the component is
left out of a blend or makes up no less than that share of it. count_nonzero limits
how many components a blend uses (How many ingredients a run uses). Candidate blends with a
trace are dropped, the design is D-optimal with or without a budget (the centroid of
the design used otherwise blends every component), and optimize_responses returns
a blend that leaves the component out or uses at least its minimum.
trio = [
Factor(name="x1", type="mixture", min_when_used=0.1),
Factor(name="x2", type="mixture", min_when_used=0.3),
Factor(name="x3", type="mixture"),
]
blended = generate_design(trio, budget=10, model_type="scheffe_quadratic", random_state=1)
print(sorted(set(blended.design_actual["x2"].round(6)))) # no share between 0 and 0.3
Such a mixture region is not sampled, since its pieces have no common measure the
sampler draws from: DesignRegion.sample raises, an I- or G-optimal design averages
over the candidate blends, and a search starts from the region’s vertices and edge
midpoints.
A component that a count_nonzero rule counts should have a min_when_used.
Without one it counts as used at any share above 0, so “at least three components” is
met by two of them and a trace of the third.
More blends beside the ones already made. Pass the blends that were made as
fixed_runs, with an optimal design_type. They are the first runs of the new
design, as given, the budget counts them, and the other runs are the blends that add
most to them for the model, under the same constraints. The model may be larger than
the one the first blends were chosen for.
made = blended.design_actual[["x1", "x2", "x3"]]
more = generate_design(
trio,
design_type="d_optimal",
budget=14,
model_type="scheffe_quadratic",
fixed_runs=made,
random_state=1,
)
print(more.metadata["n_fixed_runs"], len(more.design_actual)) # 10 14
print(more.design_actual[["x1", "x2", "x3"]].iloc[:10].equals(made)) # True
Mixture components with process factors#
A formulation is usually made under process conditions that also matter, such as a cure
temperature or a mixing speed. Give the components and the process factors together, and
generate_design builds one optimal design over the product of the constrained simplex
and the process box.
factors = [
Factor(name="mill1", type="mixture", low=0.1, high=0.8),
Factor(name="mill2", type="mixture", low=0.1, high=0.8),
Factor(name="mill3", type="mixture", low=0.1, high=0.8),
Factor(name="spray", low=-1, high=1),
Factor(name="oil", low=-1, high=1),
]
mills = generate_design(factors, model_type="scheffe_quadratic + main_effects", budget=12)
print(mills.design_type, mills.n_runs) # d_optimal 12
print(mills.metadata["formula"])
# -1 + mill1 + mill2 + mill3 + mill1:mill2 + mill1:mill3 + mill2:mill3 + spray + oil
This is the rolling-mill study of Goos and Jones (2011, section 6.2). Three mills share the
reduction in thickness of an aluminum sheet, and two coolant settings are the process
factors. The D-optimal design runs each of the six blends of the {3, 2} lattice twice,
once at each level of each coolant factor, as their Table 6.2 does.
The candidate runs are every candidate blend (the vertices, edge points, face centroids and centroid of the constrained simplex) at every candidate process setting (the grid, and the points where a constraint crosses it). The runs are chosen from them by the same exchange as the other optimal designs. A constraint limits either the components or the process factors; a constraint that names both is refused.
The model sets how the two kinds of factor combine. The counts are for three components and two process factors.
|
Terms |
Terms for 3 and 2 |
|---|---|---|
|
|
5 |
|
|
13 |
|
Those and |
15 |
|
A Scheffé model plus a process model without its intercept |
8 |
|
Each Scheffé term times each process term, the intercept included |
24 |
The first three are the polynomial of that order in all the factors, less the terms that
sum(x) = 1 makes redundant. The intercept is sum(x_i), a square x_i^2 is x_i
less its products with the other components, and a process main effect z_k is
sum(x_i z_k). Any Scheffé model can go on the left of + or *, and
"main_effects", "interactions" or "quadratic" on the right.
Both design and design_actual hold the components as proportions. The process
factors are coded in the first and in their own units in the second. The design records its
model’s formula and its region, and evaluate_design uses both:
quality = evaluate_design(mills, metric=["d_efficiency", "g_efficiency"])
print(round(quality["max_prediction_variance"], 3)) # 0.667
The largest prediction variance over the region is p / N = 8 / 12. No 12-run design for
this model can do better, since the variances at the runs average p / N. Goos and Jones
give the same two-thirds.
Fit the runs with the recorded formula. analyze_experiment keeps the components as
proportions, so the blending coefficients read as those of a Scheffé model do:
runs = mills.design.drop(columns="RunOrder")
# A simulated response stands in for the measurements here.
rng = np.random.default_rng(2)
runs["reflectivity"] = (
4.6 * runs["mill1"] + 5.0 * runs["mill2"] + 6.3 * runs["mill3"] + rng.normal(0, 0.01, len(runs))
)
fit = analyze_experiment(
runs, response_column="reflectivity", model=mills.metadata["formula"], analysis_type="coefficients"
)
print([round(row["coefficient"], 1) for row in fit["coefficients"][:3]]) # [4.6, 5.0, 6.3]
optimize_responses with the design’s region searches blends that sum to one at process
settings inside the region.
A process factor can also be categorical, such as a catalyst type or a supplier. It enters
the model in L - 1 sum-to-zero columns, so each level’s effect is measured from the
average over the levels:
resins = [
Factor(name="resin", type="mixture", low=0.2, high=0.7),
Factor(name="filler", type="mixture", low=0.05, high=0.5),
Factor(name="additive", type="mixture", low=0.05, high=0.3),
Factor(name="T", low=140, high=180, units="degC"),
Factor(name="catalyst", type="categorical", levels=["A", "B", "C"]),
]
cure = generate_design(resins, model_type="interactions", budget=24)
print(cure.metadata["n_parameters"]) # 17
The 17 terms are the six Scheffé blending terms, x_i:T and x_i:catalyst for each
component (three and six columns), and T:catalyst (two columns). A categorical factor
has no square, so "quadratic" adds only T^2.
A model of mixture components has no intercept, and patsy then gives a categorical factor
a column for every level wherever the term below it is absent from the formula:
T:catalyst in this model, where T enters only through x_i:T. Those columns add up
to ones the other terms already span, so the model could not be estimated.
evaluate_design and analyze_experiment therefore code every categorical factor of a
mixture-process model in L - 1 columns, and the recorded formula needs no change.
optimize_responses does not take categorical factors.
Split-plot designs (hard_to_change), fixed runs, candidate sets, blocks, and
constraints that join components and process factors are not yet available for
mixture-process designs, and generate_design refuses them.