diff --git a/src/specsolve/_engine/assembly.py b/src/specsolve/_engine/assembly.py index 8a62928eb..831fe5d29 100644 --- a/src/specsolve/_engine/assembly.py +++ b/src/specsolve/_engine/assembly.py @@ -19,7 +19,7 @@ from specsolve._answer.result import Diagnostics from specsolve._collect import collected, in_memory from specsolve._engine import coverage, indices -from specsolve._engine.queries import QueryBuilder +from specsolve._engine.queries import QueryBuilder, shared_expressions from specsolve._engine.scope import Scope, join_on from specsolve._engine.specialize import is_empty, specialized_on from specsolve._engine.terms import Term, presences_of @@ -171,13 +171,13 @@ def __init__(self, attached: AttachedSources, measured: Measured, lap: Lap) -> N self.variables: dict[str, indices.Indexed] = {} self.constraints: dict[str, indices.Indexed] = {} self.scope = Scope(self.program, attached, self.variables) - self.builder = QueryBuilder(self.scope, builds=True) + self.builder = QueryBuilder(self.scope, builds=True, shared=shared_expressions(self.program)) self.n_cols = 0 self.n_rows = 0 #: How many special-ordered sets have been numbered, contiguous ``0..n-1`` across the model. self.n_sets = 0 self._empty_tables = {} - self._where_coordinates: dict[tuple[tuple[str, ...], Mask], pl.DataFrame] = {} + self._admitted: dict[tuple[tuple[str, ...], Mask], pl.DataFrame] = {} def run(self) -> BuiltModel: """Build every entry, then freeze what they produced. @@ -416,12 +416,12 @@ def _build_sos(self, s: program.Sos, v: program.Variable) -> pl.DataFrame: self.n_sets = built.item(-1, 'set') + 1 return built - def _where_rows(self, dims: tuple[str, ...], where: program.Mask, start: int) -> pl.DataFrame: + def _admitted_rows(self, dims: tuple[str, ...], where: program.Mask, start: int) -> pl.DataFrame: """The coordinates over *dims* that *where* keeps, numbered from *start*, read once per build however many constraints share it.""" key = (dims, where) - if key not in self._where_coordinates: - self._where_coordinates[key] = indices.table(self.scope, dims, where, ROW, 0) - rows = self._where_coordinates[key] + if key not in self._admitted: + self._admitted[key] = indices.table(self.scope, dims, where, ROW, 0) + rows = self._admitted[key] return rows.with_columns((pl.col(ROW) + start).set_sorted()) if start else rows def _build_constraint(self, name: str, c: program.Constraint) -> _ConstraintShare: @@ -437,7 +437,7 @@ def _build_constraint(self, name: str, c: program.Constraint) -> _ConstraintShar start = self.n_rows if is_empty(c, self.attached): return self._without_a_row(name, c, self._empty_table(c.dims, ROW), start) - admitted = None if c.where is None else self._where_rows(c.dims, c.where, start) + admitted = None if c.where is None else self._admitted_rows(c.dims, c.where, start) if admitted is not None and not admitted.height: return self._without_a_row(name, c, admitted, start) linear, quadratic, constant = self._terms(name, c) diff --git a/src/specsolve/_engine/queries.py b/src/specsolve/_engine/queries.py index 182cbc489..d6aae7a57 100644 --- a/src/specsolve/_engine/queries.py +++ b/src/specsolve/_engine/queries.py @@ -59,7 +59,7 @@ from specsolve.errors import SpecsolveError if TYPE_CHECKING: - from collections.abc import Callable, Collection, Mapping, Sequence + from collections.abc import Callable, Mapping, Sequence from specsolve._engine.indices import Indexed @@ -73,34 +73,37 @@ def _totalled(p: Term) -> pl.LazyFrame: return p.table.group_by(p.dims).agg(total) if p.dims else p.table.select(total) -def _collected(terms: ExpressionTerms, kept: Collection[pl.LazyFrame]) -> ExpressionTerms: +def _held_in_memory(terms: ExpressionTerms) -> ExpressionTerms: """*terms* with every table they read collected in one pass: their own, their presences' and those presences' claims. - A table two places share is collected once and stays shared, and one in - *kept*, a variable's presence, stays as it is, since - [`Presence.identity`][specsolve._engine.terms.Presence.identity] tells two - presences apart by the table they hold. + A table two places share is collected once and stays shared. A presence + keeps its [`identity`][specsolve._engine.terms.Presence.identity], which + a collected table changes only for one compared by its table object. """ - skipped = {id(t) for t in kept} tables: dict[int, pl.LazyFrame] = {} for p in (*terms.linear, *terms.constant, *terms.quadratic): tables.setdefault(id(p.table), p.table) for x in p.presences: - if id(x.table) not in skipped: - tables.setdefault(id(x.table), x.table) + tables.setdefault(id(x.table), x.table) for u in x.unclaimed: tables.setdefault(id(u.table), u.table) held = dict(zip(tables, (frame.lazy() for frame in collected_all(list(tables.values()))), strict=True)) def presence(x: Presence) -> Presence: unclaimed = tuple(replace(u, table=held[id(u.table)]) for u in x.unclaimed) - return replace(x, table=held.get(id(x.table), x.table), unclaimed=unclaimed) + return replace(x, table=held[id(x.table)], unclaimed=unclaimed) return map_terms( terms, lambda p: replace(p, table=held[id(p.table)], presences=tuple(presence(x) for x in p.presences)) ) +def shared_expressions(compiled: program.Program) -> frozenset[str]: + """The named expressions *compiled* reads more than once, over every entry and nested reads included.""" + counts = Counter(n.name for n in walk(*compiled.roots) if isinstance(n, program.ExpressionReference)) + return frozenset(name for name, count in counts.items() if count > 1) + + def _one_coefficient(terms: tuple[Term, ...]) -> tuple[Term, ...]: """Constant *terms* over one set of dimensions added up to one term ([`_totalled`][]), else *terms* as they are. @@ -145,21 +148,19 @@ class QueryBuilder: on the builder of a build and on no other: a build places each term on an entry's rows by the term's own dimensions, so a term that holds nothing can be left out, where a read takes its dimensions from the terms it is given. + ``shared`` names the expressions a build holds in memory once built + ([`shared_expressions`][]). """ scope: Scope solution: Solution | None = None builds: bool = False - _presence_keys: dict[str, tuple[str, ...]] = field(default_factory=dict, compare=False, repr=False) - _variable_keys: dict[str, pl.DataFrame] = field(default_factory=dict, compare=False, repr=False) - _read_counts: dict[str, int] = field(default_factory=dict, compare=False, repr=False) - _named: dict[str, ExpressionTerms] = field(default_factory=dict, compare=False, repr=False) - _claims: dict[tuple[program.Mask, tuple[str, ...]], pl.DataFrame] = field( - default_factory=dict, compare=False, repr=False - ) - _variable_presence: dict[tuple[str, tuple[str, ...]], Presence] = field( + shared: frozenset[str] = frozenset() + _sparse_dims: dict[str, tuple[str, ...]] = field(default_factory=dict, compare=False, repr=False) + _held_coordinates: dict[tuple[program.Mask, tuple[str, ...]], pl.DataFrame] = field( default_factory=dict, compare=False, repr=False ) + _held_terms: dict[str, ExpressionTerms] = field(default_factory=dict, compare=False, repr=False) # ------------------------------------------------------------------ # bounds @@ -236,14 +237,19 @@ def expression( return _ExpressionWalk(self, context, admits_quadratic, reported).terms(expr) def _parameter_term(self, name: str) -> Term: - """A parameter as a constant term, keyed by its declared dimensions, present only at its rows under ``missing: absent``.""" + """A parameter as a constant term, keyed by its declared dimensions, present only at its rows under ``missing: absent``. + + Its presence is named by the parameter, so any two reads of it are one + to [`Presence.identity`][specsolve._engine.terms.Presence.identity]. + """ dims = self.scope.program.parameters[name].dims table = self.scope.attached.parameters[name].select(*dims, pl.col(VALUE).cast(pl.Float64).alias(CONSTANT)) present = table.select(*dims) if dims else table.select(pl.col(CONSTANT).is_not_null().alias(PRESENT)) presences = () if self.scope.absent(name): keys = self._sparse_along(name, dims, present) if dims else dims - presences = (Presence(present if keys == dims else present.select(*keys).unique(), keys),) + rows = present if keys == dims else present.select(*keys).unique() + presences = (Presence(rows, keys, of=('parameter', name)),) return Term(dims, table, 'constant', presences=presences, parameters=frozenset({name})) def _sparse_along(self, name: str, dims: tuple[str, ...], present: pl.LazyFrame) -> tuple[str, ...]: @@ -255,8 +261,8 @@ def _sparse_along(self, name: str, dims: tuple[str, ...], present: pl.LazyFrame) held twice, so rows that number the distinct keys of the other dimensions times the size of one cover that one completely. """ - if name in self._presence_keys: - return self._presence_keys[name] + if name in self._sparse_dims: + return self._sparse_dims[name] keys, rows = list(dims), self.scope.attached.parameter_rows[name] for d in reversed(dims): rest = [k for k in keys if k != d] @@ -265,69 +271,54 @@ def _sparse_along(self, name: str, dims: tuple[str, ...], present: pl.LazyFrame) distinct = present.select(rest).unique().select(pl.len()).pipe(collected).item() if distinct * self.scope.attached.dimensions[d].size == rows: keys, rows = rest, distinct - self._presence_keys[name] = tuple(keys) + self._sparse_dims[name] = tuple(keys) return tuple(keys) - def _named_terms(self, name: str, build: Callable[[], ExpressionTerms]) -> ExpressionTerms: - """The terms of the named expression *name*, built once per build where the program reads it more than once. + def _shared_terms(self, name: str, build: Callable[[], ExpressionTerms]) -> ExpressionTerms: + """The terms of the named expression *name*, built once and held in memory where it is [`shared`][]. A term is a query, so two entries reading one expression run it twice. - Where its read count is two or more, its tables, the tables that say - where its terms exist and the coordinates its cases claim are collected - once, together, and each reader joins what is in memory. Read once, it stays - a query, so the entry's own joins still push down into it. A read is - built every time: it reads at a solution. + A shared one's tables, the tables that say where its terms exist and + the coordinates its cases claim are collected once, together, and each + reader joins what is in memory. Read once, it stays a query, so the + entry's own joins still push down into it. """ - if not self.builds or self.solution is not None: - return build() - if not self._read_counts: - counts = Counter( - n.name for n in walk(*self.scope.program.roots) if isinstance(n, program.ExpressionReference) - ) - self._read_counts.update(counts) - if self._read_counts[name] < 2: + if name not in self.shared: return build() - if name not in self._named: - self._named[name] = _collected(build(), [x.table for x in self._variable_presence.values()]) - return self._named[name] + if name not in self._held_terms: + self._held_terms[name] = _held_in_memory(build()) + return self._held_terms[name] - def _claimed(self, when: program.Mask, on: tuple[str, ...]) -> pl.DataFrame: - """The coordinates over *on* where *when* holds, read once per build however many regions ask.""" + def _coordinates(self, when: program.Mask, on: tuple[str, ...]) -> pl.DataFrame: + """The coordinates over *on* where *when* holds, read once per build however many regions and variables ask.""" key = (when, on) - if key not in self._claims: - self._claims[key] = narrowed(self.scope, on, when).select(*on).pipe(collected) - return self._claims[key] + if key not in self._held_coordinates: + self._held_coordinates[key] = narrowed(self.scope, on, when).select(*on).pipe(collected) + return self._held_coordinates[key] def _variable_term(self, name: str) -> Term: """A variable as a linear term with unit coefficients.""" held = self.scope.variables[name] table = held.table.select(*held.dims, COL, pl.lit(1.0, dtype=pl.Float64).alias(COEFF)) - return Term(held.dims, table, 'linear', presences=self._variable_presences(name, held.dims)) + return Term(held.dims, table, 'linear', presences=self._variable_presences(name)) - def _variable_presences(self, name: str, dims: tuple[str, ...]) -> tuple[Presence, ...]: + def _variable_presences(self, name: str) -> tuple[Presence, ...]: """Presence only for a variable with a condition under ``missing: absent``, keyed explicitly as [`Presence`][] requires. A variable is its condition crossed with every dimension the condition does not read, so its presence is keyed by the dimensions it reads. Keyed by all of them, a ``cases:`` region over fewer widens it to - their full product. Built on the first reference over *dims* and - handed back on every later one, so that a presence two terms share - is the same object, which [`Presence.identity`][specsolve._engine.terms.Presence.identity] compares. + their full product. Named by the variable, so any two of its + presences are one to [`Presence.identity`][specsolve._engine.terms.Presence.identity]. """ entry = self.scope.program.variables[name] if entry.where is None or entry.missing != 'absent': return () - if (name, dims) not in self._variable_presence: - self._variable_presence[name, dims] = self._built_presence(name, dims, entry.where) - return (self._variable_presence[name, dims],) - - def _built_presence(self, name: str, dims: tuple[str, ...], where: program.Mask) -> Presence: - read = tuple(d for d in dims if d in where.dims) + dims = entry.dims + read = tuple(d for d in self.scope.program.dimensions if d in dims and d in entry.where.dims) if read and len(read) < len(dims): - if name not in self._variable_keys: - self._variable_keys[name] = narrowed(self.scope, read, where).select(*read).pipe(collected) - return Presence(self._variable_keys[name].lazy(), read) - return Presence(self.scope.variables[name].coordinates(), dims) + return (Presence(self._coordinates(entry.where, read).lazy(), read, of=('variable', name)),) + return (Presence(self.scope.variables[name].coordinates(), dims, of=('variable', name)),) def _solved_term(self, name: str) -> Term: """A variable at its primal — the constant term a read turns it into, carrying the presence its linear term would. @@ -345,7 +336,7 @@ def _solved_term(self, name: str) -> Term: rows = join_on(everywhere, rows, keys, 'left').with_columns( pl.col(CONSTANT).fill_null(float(entry.missing)) ) - return Term(dims, rows.select(*dims, CONSTANT), 'constant', presences=self._variable_presences(name, dims)) + return Term(dims, rows.select(*dims, CONSTANT), 'constant', presences=self._variable_presences(name)) def _dual_term(self, name: str) -> Term: """``dual(name)`` at the solve's row duals — one value per row the constraint built, and present exactly there. @@ -655,7 +646,7 @@ def terms(self, e: program.Expression) -> ExpressionTerms: if isinstance(e, program.Cases): return self._cases(e) if isinstance(e, program.ExpressionReference): - return self.builder._named_terms(e.name, lambda: self.terms(e.body)) + return self.builder._shared_terms(e.name, lambda: self.terms(e.body)) assert_never(e) def _product(self, a: ExpressionTerms, b: ExpressionTerms) -> ExpressionTerms: @@ -775,7 +766,7 @@ def _region(self, r: program.Region) -> ExpressionTerms: one over a dimension. """ on = tuple(d for d in self.scope.program.dimensions if d in r.when.dims) - truth = self.builder._claimed(r.when, on) if on else None + truth = self.builder._coordinates(r.when, on) if on else None if truth is not None and not truth.height and self.builder.builds: return ExpressionTerms((), ()) claimed = truth.lazy() if truth is not None else None @@ -815,7 +806,7 @@ def _relaxed( """ keys = x.keys(dims) if claimed is not None and on and keys: - return Presence(x.table, keys, (*x.unclaimed, Unclaimed(claimed, on))) + return replace(x, joined_on=keys, unclaimed=(*x.unclaimed, Unclaimed(claimed, on, when))) x = x.written_out(self.scope, dims) have = x.join_columns(dims) join_columns = tuple(dict.fromkeys((*have, *on))) diff --git a/src/specsolve/_engine/terms.py b/src/specsolve/_engine/terms.py index 94392387d..176b77245 100644 --- a/src/specsolve/_engine/terms.py +++ b/src/specsolve/_engine/terms.py @@ -48,11 +48,14 @@ class Unclaimed: A condition reads a missing row as false under a negation too ([`falsy_if_null`][specsolve._engine.conditions.falsy_if_null]), so the coordinates outside *table* are exactly the complement. One row per - coordinate, as the left join that reads it requires. + coordinate, as the left join that reads it requires. *when* is the + condition that claims them, so two regions under one condition claim the + same coordinates whatever table object holds them. """ table: pl.LazyFrame on: tuple[str, ...] + when: program.Mask @dataclass(frozen=True) @@ -67,12 +70,16 @@ class Presence: dimensions, implied columns that stay right as downstream operators rewrite them. A shift or window edge states narrower ones. A coordinate is also present outside each region in ``unclaimed``; a presence with one always - spells out ``joined_on``. + spells out ``joined_on``. ``of`` names the variable whose condition, or + the parameter whose rows, *table* holds, where that is all it holds: any + two presences of one of them hold the same coordinates. Every other + presence is itself only. """ table: pl.LazyFrame joined_on: tuple[str, ...] | None = None unclaimed: tuple[Unclaimed, ...] = () + of: tuple[Literal['variable', 'parameter'], str] | None = None def keys(self, term_dims: tuple[str, ...]) -> tuple[str, ...]: """The columns *table* is keyed by, for a term over *term_dims*.""" @@ -84,8 +91,15 @@ def join_columns(self, term_dims: tuple[str, ...]) -> tuple[str, ...]: return tuple(dict.fromkeys((*keys, *(d for u in self.unclaimed for d in u.on)))) def identity(self, term_dims: tuple[str, ...]) -> tuple[object, ...]: - """What two presences that narrow a term over *term_dims* alike share: the same tables on the same columns.""" - return (id(self.table), self.keys(term_dims), tuple((id(u.table), u.on) for u in self.unclaimed)) + """What two presences that narrow a term over *term_dims* alike share: one variable's or parameter's, or one table, on the same columns, outside the same regions. + + Never equal for two presences that admit different rows: a presence + names what it is [`of`][specsolve._engine.terms.Presence] only where its + table holds that and nothing else, and a region is named by the + condition that claims it. + """ + held = self.of if self.of is not None else id(self.table) + return (held, self.keys(term_dims), tuple((u.when, u.on) for u in self.unclaimed)) def keyed(self, term_dims: tuple[str, ...]) -> Presence: """This presence with its keys spelled out, for a term that leaves *term_dims* behind.""" diff --git a/tests/internals/engine/test_queries.py b/tests/internals/engine/test_queries.py index 0f0fd1175..8bb52bb4e 100644 --- a/tests/internals/engine/test_queries.py +++ b/tests/internals/engine/test_queries.py @@ -13,9 +13,9 @@ from specsolve._attached import AttachedSources, Dimension from specsolve._engine.conditions import narrowed from specsolve._engine.indices import Indexed -from specsolve._engine.queries import QueryBuilder +from specsolve._engine.queries import QueryBuilder, shared_expressions from specsolve._engine.scope import Scope -from specsolve._engine.terms import ExpressionTerms, presences_of +from specsolve._engine.terms import ExpressionTerms, Presence, Term, Unclaimed, presences_of from specsolve._names import COEFF, COL, CONSTANT from specsolve.errors import SpecsolveError @@ -47,6 +47,15 @@ COST = program.ParameterReference('cost', dims=('generator',)) LOAD = program.ParameterReference('load', dims=('snapshot',)) +#: A parameter under `missing: absent`, for the builders [`_with_pu`][] makes. +PU = program.ParameterReference('pu', dims=('snapshot', 'generator')) + +#: A variable over `generator` alone, whose condition reads every dimension it has. +R = program.VariableReference('r', dims=('generator',)) + +#: A condition over `snapshot`, for a region its variable's condition does not read. +LOADED = program.Mask(program.ParameterComparison('load', '>', 0.0, ('snapshot',))) + #: The join every grouping case here reads: out of `generator`, into `bus`. GEN_BUS_JOIN = program.JoinColumns('gen_bus', GEN_BUS, joined=('generator',), grouped=('bus',)) @@ -161,10 +170,37 @@ def test_a_shared_expression_narrows_by_its_variables_presence_once(self, read) narrowed, scope=replace(narrowed.scope, program=replace(narrowed.scope.program, constraints=rows)), builds=True, + shared=shared_expressions(replace(narrowed.scope.program, constraints=rows)), ) terms = builder.expression(read(shared), 'test') assert len(presences_of(terms.linear)) == 1, 'one presence for p, however it was read' + @pytest.mark.parametrize( + ('builder', 'expression'), + [ + pytest.param( + lambda: narrowed_builder(), program.Add(P, P, dims=P.dims), id='a condition over some dimensions' + ), + pytest.param( + lambda: _wholly_conditioned(), program.Add(R, R, dims=R.dims), id='a condition over every dimension' + ), + pytest.param( + lambda: narrowed_builder(), + program.Cases((program.Region(LOADED, program.Add(P, P, dims=P.dims)),), dims=P.dims), + id='inside a region', + ), + pytest.param( + lambda: _with_pu(_EVERY_SNAPSHOT), + program.Add(program.Multiply(P, PU, dims=P.dims), program.Multiply(P, PU, dims=P.dims), dims=P.dims), + id='a parameter with no row at some coordinates', + ), + ], + ) + def test_a_variable_read_twice_narrows_by_one_presence(self, builder, expression) -> None: + """Each read of a variable or a parameter builds its presence again, and every one names it, so the rows are narrowed by it once (#2269).""" + terms = builder().expression(expression, 'test') + assert len(presences_of(terms.linear)) == 1, 'one presence for the variable, however often it is read' + def test_a_quadratic_product_in_an_affine_position_is_an_invariant_not_a_refusal(self): """A quadratic product in an affine position is the lane contradicting itself, and would drop a variable.""" with pytest.raises(AssertionError, match='quadratic product in an affine position'): @@ -189,6 +225,14 @@ def narrowed_builder() -> QueryBuilder: return QueryBuilder(Scope(masked, attached(), tables)) +def _wholly_conditioned() -> QueryBuilder: + """A query builder whose `r` has a condition over every dimension it has.""" + where = program.Mask(program.ParameterComparison('available', '>', 0.0, ('generator',))) + masked = replace(PROGRAM, variables={'r': program.Variable(('generator',), where=where)}) + held = Indexed(('generator',), pl.LazyFrame(schema={'generator': pl.String, COL: pl.Int64}), 0, 0) + return QueryBuilder(Scope(masked, attached(), {'r': held})) + + def _with_pu(rows: pl.DataFrame) -> QueryBuilder: """A query builder whose `pu` is over ``(snapshot, generator)`` under ``missing: absent``, holding *rows*.""" masked = replace( @@ -209,6 +253,9 @@ def _with_pu(rows: pl.DataFrame) -> QueryBuilder: ) +#: A condition over `generator`, for the cases that need one and read none of its rows. +AVAILABLE = program.Mask(program.ParameterComparison('available', '>', 0.0, ('generator',))) + #: A named expression, `cost * p`, for the cases that read it from one entry or two. COST_P = program.ExpressionReference('cost_p', program.Multiply(P, COST, dims=P.dims), dims=P.dims) @@ -217,7 +264,8 @@ def _reading_cost_p(entries: int) -> QueryBuilder: """A builder for a build whose *entries* constraints each read `cost_p` once.""" zero = program.Constant(0.0, dims=()) rows = {f'c{i}': program.Constraint(P.dims, COST_P, '>=', zero) for i in range(entries)} - return QueryBuilder(Scope(replace(PROGRAM, constraints=rows), attached(), VARIABLES), builds=True) + reading = replace(PROGRAM, constraints=rows) + return QueryBuilder(Scope(reading, attached(), VARIABLES), builds=True, shared=shared_expressions(reading)) class TestShapeOperators: @@ -318,10 +366,8 @@ def test_a_presence_outside_its_regions_admits_what_its_complement_written_out_w self, held: list[str], claims: list[dict[str, list]] ) -> None: """The claimed rows stand in for the region's complement, which is a product less those rows; a filter must not tell them apart.""" - from specsolve._engine.terms import Presence, Unclaimed - scope = builder().scope - unclaimed = tuple(Unclaimed(pl.LazyFrame(c), tuple(c)) for c in claims) + unclaimed = tuple(Unclaimed(pl.LazyFrame(c), tuple(c), AVAILABLE) for c in claims) presence = Presence( pl.LazyFrame({'generator': held}, schema={'generator': pl.String}), ('generator',), unclaimed ) @@ -350,21 +396,20 @@ def build() -> ExpressionTerms: calls.append(1) return ExpressionTerms((), ()) - first, second = builder._named_terms('cost_p', build), builder._named_terms('cost_p', build) + first, second = builder._shared_terms('cost_p', build), builder._shared_terms('cost_p', build) assert len(calls) == built, 'the expression is built once where the program reads it twice' assert (first is second) == (built == 1), 'and the second reader is handed what the first built' def test_a_named_expression_held_in_memory_has_the_tables_it_was_built_with(self) -> None: """Every table a shared expression's terms read comes back from collection beside the term, presence and region it belongs to.""" - from specsolve._engine.queries import _collected - from specsolve._engine.terms import Presence, Term, Unclaimed + from specsolve._engine.queries import _held_in_memory def table(column: str, *labels: str) -> pl.LazyFrame: return pl.LazyFrame({column: list(labels)}) claimed = ( - Unclaimed(table('snapshot', 'u0'), ('snapshot',)), - Unclaimed(table('generator', 'u1'), ('generator',)), + Unclaimed(table('snapshot', 'u0'), ('snapshot',), AVAILABLE), + Unclaimed(table('generator', 'u1'), ('generator',), ~AVAILABLE), ) terms = ExpressionTerms( linear=( @@ -398,13 +443,83 @@ def read(held: ExpressionTerms) -> list[tuple[str, dict[str, list]]]: ] ] - assert read(_collected(terms, ())) == read(terms), 'each collected table lands where its query stood' + assert read(_held_in_memory(terms)) == read(terms), 'each collected table lands where its query stood' + + @pytest.mark.parametrize( + ('pair', 'same'), + [ + pytest.param( + lambda t, u: ( + Presence(t, ('generator',), of=('variable', 'p')), + Presence(u, ('generator',), of=('variable', 'p')), + ), + True, + id="one variable's presence in two tables", + ), + pytest.param( + lambda t, u: ( + Presence(t, ('generator',), of=('variable', 'p')), + Presence(t, ('generator',), of=('variable', 'q')), + ), + False, + id='two variables in one table', + ), + pytest.param( + lambda t, u: ( + Presence(t, ('generator',), of=('variable', 'p')), + Presence(t, ('snapshot',), of=('variable', 'p')), + ), + False, + id='one variable on other columns', + ), + pytest.param( + lambda t, u: ( + Presence(t, ('generator',), of=('parameter', 'pu')), + Presence(u, ('generator',), of=('parameter', 'pu')), + ), + True, + id="one parameter's presence in two tables", + ), + pytest.param( + lambda t, u: ( + Presence(t, ('generator',), of=('variable', 'p')), + Presence(t, ('generator',), of=('parameter', 'p')), + ), + False, + id='a variable and a parameter of one name', + ), + pytest.param(lambda t, u: (Presence(t), Presence(t)), True, id='one table'), + pytest.param(lambda t, u: (Presence(t), Presence(u)), False, id='two tables with the same rows'), + pytest.param( + lambda t, u: ( + Presence(t, ('generator',), (Unclaimed(t, ('generator',), AVAILABLE),)), + Presence(t, ('generator',), (Unclaimed(u, ('generator',), AVAILABLE),)), + ), + True, + id="one condition's claim in two tables", + ), + pytest.param( + lambda t, u: ( + Presence(t, ('generator',), (Unclaimed(t, ('generator',), AVAILABLE),)), + Presence(t, ('generator',), (Unclaimed(t, ('generator',), ~AVAILABLE),)), + ), + False, + id="two conditions' claims in one table", + ), + ], + ) + def test_two_presences_are_one_only_where_they_admit_the_same_rows(self, pair, same: bool) -> None: + """A presence is one with another by the variable or condition it holds, never by a table that merely has the same rows (#2269).""" + rows = {'generator': ['g0', 'g1']} + a, b = pair(pl.LazyFrame(rows), pl.LazyFrame(rows)) + dims = ('generator', 'snapshot') + assert (a.identity(dims) == b.identity(dims)) == same, 'one presence where they must admit the same rows' def test_a_region_condition_is_read_once_per_build(self) -> None: """Regions in many entries test the same few conditions; each condition's coordinates are read once.""" builder = _reading_cost_p(1) when = program.Mask(program.ParameterComparison('available', '>', 0.0, ('generator',))) - assert builder._claimed(when, ('generator',)) is builder._claimed(when, ('generator',)), ( + assert builder._coordinates(when, ('generator',)) is builder._coordinates(when, ('generator',)), ( 'a second region testing the same condition reuses the first read' )