diff --git a/bom-reachability/README.md b/bom-reachability/README.md index 91bf73ec..7721af96 100644 --- a/bom-reachability/README.md +++ b/bom-reachability/README.md @@ -42,7 +42,7 @@ Built on RelationalAI's graph reasoner: **reachability** for transitive dependen ## What's included - **Ontology**: two concepts (`SKU` and `BillOfMaterials`) wired into a directed dependency graph, plus a derived `feeds` self-relationship on `SKU` and a persisted `assembly_depth` property. -- **Model**: the concepts, data, graph, and rules in the `model/` package (`schema.py` declares the concepts, `source.py` loads the sample data, `reasoning.py` states the graph and rules), which `rai models deploy --path model` deploys to your Snowflake account. +- **Model**: the concepts, data, graph, and rules in the `model/` package (`schema.py` declares the concepts, `source.py` loads the sample data, `dependency_graph.py` states the reachability, betweenness, and dependency counts, `assembly_chains.py` states the assembly chains), which `rai models deploy --path model` deploys to your Snowflake account. - **Query**: `queries/dependency_report.py` — prints the reachability, betweenness centrality, and assembly-path report from the deployed model. - **Runbook**: `runbook.md` — a paste-testable walkthrough that reproduces the template step by step with the RAI skills; as important a reference as the script itself. - **Sample data**: `data/skus.csv` (9 SKUs across 3 tiers) and `data/bill_of_materials.csv` (14 BOM entries with site-specific assembly). See *Sample data* below. @@ -164,7 +164,8 @@ Run these steps from a terminal: │ ├── __init__.py # exports of the deployed model │ ├── schema.py # SKU and BillOfMaterials concepts │ ├── source.py # loads the sample CSVs -│ └── reasoning.py # graph and rules (reachability + betweenness + assembly paths) +│ ├── dependency_graph.py # graph, reachability, dependency counts, betweenness, bottleneck rank +│ └── assembly_chains.py # assembly paths, maximal chains, assembly depth ├── queries/ │ └── dependency_report.py # report printed from the deployed model └── data/ @@ -218,7 +219,7 @@ Betweenness centrality ranks components by how many shortest dependency paths pa Where reachability returns dependency *pairs*, path enumeration returns the actual *build sequences*. It walks the derived `feeds` edge to enumerate every assembly path; because the BOM is acyclic, this yields exactly the simple paths with no cycle risk. The model marks the maximal (non-extendable) chains, which the report prints with sub-paths suppressed, and persists the longest maximal chain ending at each SKU as `SKU.assembly_depth`. -See `model/reasoning.py` for the implementation, `queries/dependency_report.py` for the report, and `runbook.md` for the skill-driven reproduction. +See `model/dependency_graph.py` and `model/assembly_chains.py` for the implementation, `queries/dependency_report.py` for the report, and `runbook.md` for the skill-driven reproduction. ## Customize this template diff --git a/bom-reachability/model/__init__.py b/bom-reachability/model/__init__.py index 80d05dc0..1e97d796 100644 --- a/bom-reachability/model/__init__.py +++ b/bom-reachability/model/__init__.py @@ -18,22 +18,23 @@ persists the longest maximal chain ending at each SKU as its assembly depth, flagging instead a finished SKU reached by a chain longer than MAX_ASSEMBLY_HOPS. +The model has two rule modules: `dependency_graph.py` (reachability, +dependency counts, betweenness, bottleneck rank) and `assembly_chains.py` (chain +enumeration, maximal chains, chain counts, assembly depth). + Deploy: `rai models deploy --path model` deploys this package to the schemas in raiconfig.yaml and waits for its first refresh; `python -m queries.dependency_report` then prints the report from the deployed model. """ -from .reasoning import ( +from .assembly_chains import ( MAX_ASSEMBLY_HOPS, AssemblyStep, + ChainLength, MaximalChain, - betweenness, - graph, - num_edges, - num_nodes, - reachable, ) +from .dependency_graph import betweenness, graph, num_edges, num_nodes, reachable from .schema import SKU, BillOfMaterials, model from .source import DATA_DIR @@ -41,6 +42,7 @@ "DATA_DIR", "MAX_ASSEMBLY_HOPS", "AssemblyStep", + "ChainLength", "MaximalChain", "SKU", "BillOfMaterials", diff --git a/bom-reachability/model/reasoning.py b/bom-reachability/model/assembly_chains.py similarity index 67% rename from bom-reachability/model/reasoning.py rename to bom-reachability/model/assembly_chains.py index 40dea7fc..5e3fd6b9 100644 --- a/bom-reachability/model/reasoning.py +++ b/bom-reachability/model/assembly_chains.py @@ -1,51 +1,11 @@ -"""Dependency graph, bottleneck scores, and assembly chains over the BOM.""" +"""Assembly chains: every bottom-up chain that builds each finished good, which chains are maximal, +each chain's length, and each SKU's assembly depth.""" from relationalai.semantics import Hash, Integer, not_ -from relationalai.semantics.reasoners.graph import Graph from relationalai.semantics.std import aggregates as aggs from .schema import SKU, BillOfMaterials, model -# -------------------------------------------------- -# Build graph: SKU nodes, BOM edges (directed) -# Edge: output_sku -> input_sku ("depends on") -# -------------------------------------------------- - -graph = Graph( - model, - name="bom_graph", - directed=True, - weighted=False, - node_concept=SKU, - edge_concept=BillOfMaterials, - edge_src_relationship=BillOfMaterials.output_sku, - edge_dst_relationship=BillOfMaterials.input_sku, -) - -# Graph size, which the deployed model publishes for the queries. -node_count, edge_count = Integer.ref(), Integer.ref() -num_nodes = model.Relationship(f"the BOM graph has {Integer:num_nodes} nodes") -num_edges = model.Relationship(f"the BOM graph has {Integer:num_edges} edges") -model.where(graph.num_nodes()(node_count)).define(num_nodes(node_count)) -model.where(graph.num_edges()(edge_count)).define(num_edges(edge_count)) - -# Reachability: all transitive dependency pairs. -reachable = graph.reachable(full=True) - -# Betweenness centrality: structural bottlenecks. -betweenness = graph.betweenness_centrality() - -# Attach both results to SKU, so the deployed model publishes them for the queries. -SKU.reaches = reachable -SKU.betweenness = betweenness - -# How many other SKUs transitively depend on each SKU. -dependent = SKU.ref() -SKU.depended_on_by = model.Property(f"{SKU} is depended on by {Integer:depended_on_by} SKUs") -model.where(dependent.reaches(SKU), dependent != SKU).define( - SKU.depended_on_by(aggs.count(dependent).per(SKU)) -) - # -------------------------------------------------- # Assembly path enumeration # PREVIEW capability; requires relationalai>=1.15. @@ -113,3 +73,7 @@ model.where(MaximalChain(p), p.nodes(p.length) == end, not_(end.exceeds_hop_bound())).define( end.assembly_depth(aggs.max(p.length).per(end)) ) + +# Each chain's length in hops. +ChainLength = model.Relationship(f"assembly chain {Hash:path} has {Integer:hops} hops") +model.where(p).define(ChainLength(p, p.length)) diff --git a/bom-reachability/model/dependency_graph.py b/bom-reachability/model/dependency_graph.py new file mode 100644 index 00000000..1a3a0de7 --- /dev/null +++ b/bom-reachability/model/dependency_graph.py @@ -0,0 +1,65 @@ +"""Dependency graph: the directed SKU graph over the BOM, each SKU's transitive dependencies and +dependents, and its betweenness-centrality bottleneck score and rank.""" + +from relationalai.semantics import Integer, String +from relationalai.semantics.reasoners.graph import Graph +from relationalai.semantics.std import aggregates as aggs + +from .schema import SKU, BillOfMaterials, model + +# -------------------------------------------------- +# Build graph: SKU nodes, BOM edges (directed) +# Edge: output_sku -> input_sku ("depends on") +# -------------------------------------------------- + +graph = Graph( + model, + name="bom_graph", + directed=True, + weighted=False, + node_concept=SKU, + edge_concept=BillOfMaterials, + edge_src_relationship=BillOfMaterials.output_sku, + edge_dst_relationship=BillOfMaterials.input_sku, +) + +# Graph size, which the deployed model publishes for the queries. +node_count, edge_count = Integer.ref(), Integer.ref() +num_nodes = model.Relationship(f"the BOM graph has {Integer:num_nodes} nodes") +num_edges = model.Relationship(f"the BOM graph has {Integer:num_edges} edges") +model.where(graph.num_nodes()(node_count)).define(num_nodes(node_count)) +model.where(graph.num_edges()(edge_count)).define(num_edges(edge_count)) + +# Reachability: all transitive dependency pairs. +reachable = graph.reachable(full=True) + +# Betweenness centrality: structural bottlenecks. +betweenness = graph.betweenness_centrality() + +# Attach both results to SKU, so the deployed model publishes them for the queries. +SKU.reaches = reachable +SKU.betweenness = betweenness + +# How many other SKUs transitively depend on each SKU. +dependent = SKU.ref() +SKU.depended_on_by = model.Property(f"{SKU} is depended on by {Integer:depended_on_by} SKUs") +model.where(dependent.reaches(SKU), dependent != SKU).define( + SKU.depended_on_by(aggs.count(dependent).per(SKU)) +) + +# How many other SKUs each SKU transitively depends on, in total and of each type. +dependency, dep_type = SKU.ref(), String.ref() +SKU.n_dependencies = model.Property(f"{SKU} depends on {Integer:n_dependencies} SKUs") +SKU.n_dependencies_by_type = model.Relationship( + f"{SKU} depends on {Integer:n_dependencies} SKUs of type {String:dep_type}" +) +model.where(SKU.reaches(dependency), dependency != SKU).define( + SKU.n_dependencies(aggs.count(dependency).per(SKU)) +) +model.where(SKU.reaches(dependency), dependency != SKU, dependency.type == dep_type).define( + SKU.n_dependencies_by_type(aggs.count(dependency).per(SKU, dep_type), dep_type) +) + +# The bottlenecks: SKUs with a positive betweenness, ranked highest first, ties by SKU id. +SKU.bottleneck_rank = model.Property(f"{SKU} has bottleneck rank {Integer:bottleneck_rank}") +model.where(SKU.betweenness > 0).define(SKU.bottleneck_rank(aggs.rank(-SKU.betweenness, SKU.id))) diff --git a/bom-reachability/queries/dependency_report.py b/bom-reachability/queries/dependency_report.py index b8ab52f6..c39b44e9 100644 --- a/bom-reachability/queries/dependency_report.py +++ b/bom-reachability/queries/dependency_report.py @@ -4,8 +4,17 @@ python -m queries.dependency_report """ -from model import MAX_ASSEMBLY_HOPS, SKU, AssemblyStep, MaximalChain, model, num_edges, num_nodes -from relationalai.semantics import Hash, Integer, where +from model import ( + MAX_ASSEMBLY_HOPS, + SKU, + AssemblyStep, + ChainLength, + MaximalChain, + model, + num_edges, + num_nodes, +) +from relationalai.semantics import Hash, Integer, String, where if __name__ == "__main__": print("=== BOM Dependency Graph ===") @@ -32,17 +41,31 @@ # Dependencies of each finished good # -------------------------------------------------- + # Dependency counts, in total and by type, as the model publishes them. + n_deps = ( + model.select(SKU.id.alias("sku_id"), SKU.n_dependencies.alias("n")) + .to_df() + .set_index("sku_id")["n"] + ) + n_type, type_ref = Integer.ref(), String.ref() + n_deps_by_type = ( + model.where(SKU.n_dependencies_by_type(n_type, type_ref)) + .select(SKU.id.alias("sku_id"), type_ref.alias("dep_type"), n_type.alias("n")) + .to_df() + .set_index(["sku_id", "dep_type"])["n"] + ) + finished = all_deps_df[all_deps_df["product_type"] == "FINISHED_GOOD"] for product_id in sorted(finished["product_id"].unique()): deps = finished[(finished["product_id"] == product_id) & (finished["dep_id"] != product_id)] if len(deps) > 0: product_name = deps["product_name"].iloc[0] print(f"\n--- Dependencies of '{product_name}' ({product_id}) ---") - print(f" {len(deps)} transitive dependencies:") + print(f" {n_deps[product_id]} transitive dependencies:") for dep_type in ["COMPONENT", "RAW_MATERIAL"]: type_deps = deps[deps["dep_type"] == dep_type] if len(type_deps) > 0: - print(f"\n {dep_type}s ({len(type_deps)}):") + print(f"\n {dep_type}s ({n_deps_by_type[product_id, dep_type]}):") for _, row in type_deps.sort_values("dep_name").iterrows(): print(f" - {row['dep_name']} ({row['dep_id']})") @@ -86,9 +109,13 @@ print("\n=== Betweenness Centrality (bottleneck components) ===") print(btw_df.to_string(index=False)) - bottlenecks = btw_df[btw_df["betweenness"] > 0] - if len(bottlenecks) > 0: - top = bottlenecks.iloc[0] + top_df = ( + where(SKU.bottleneck_rank == 1) + .select(SKU.name.alias("sku_name"), SKU.betweenness.alias("betweenness")) + .to_df() + ) + if len(top_df) > 0: + top = top_df.iloc[0] print(f"\nTop bottleneck: {top['sku_name']} (betweenness={top['betweenness']:.4f})") print(" Sits on the most shortest dependency paths between other SKUs.") @@ -98,12 +125,13 @@ print("\n=== Assembly Path Enumeration (PREVIEW) ===") - path, step = Hash.ref(), Integer.ref() + path, step, hops = Hash.ref(), Integer.ref(), Integer.ref() assembly_df = ( - model.where(AssemblyStep(path, SKU, step)) + model.where(AssemblyStep(path, SKU, step), ChainLength(path, hops)) .select( path.alias("path"), step.alias("step"), + hops.alias("hops"), SKU.name.alias("sku_name"), ) .to_df() @@ -114,7 +142,7 @@ paths = [] for path_id, grp in assembly_df.groupby("path"): names = grp.sort_values("step")["sku_name"].tolist() - paths.append({"names": names, "length": len(names) - 1, "maximal": path_id in maximal_ids}) + paths.append({"names": names, "length": int(grp["hops"].iloc[0]), "maximal": path_id in maximal_ids}) print(f"\n Enumerated {len(paths)} assembly path(s) (<= {MAX_ASSEMBLY_HOPS} hops).") diff --git a/book_slate_recommendation/README.md b/book_slate_recommendation/README.md index 3bea7de5..18e2edbc 100644 --- a/book_slate_recommendation/README.md +++ b/book_slate_recommendation/README.md @@ -42,7 +42,7 @@ This template composes the slate as a single optimization decision rather than a ## What's included - **Ontology**: a three-stage pipeline (knowledge-graph path walks, then graph analysis, then prescriptive optimization) on a single shared ontology, wired to the bundled CSVs. -- **Model**: the `model/` package — the three-stage pipeline (`schema.py` declares the concepts, `source.py` loads the sample data and checks it, `reasoning.py` states the path walks, graph analysis, and slot-selection problem), which `rai models deploy --path model` deploys to your Snowflake account, where each refresh runs the solve. +- **Model**: the `model/` package — the three-stage pipeline (`schema.py` declares the concepts, `source.py` loads the sample data and checks it, `candidate_paths.py` states the path walks and the candidates they reach, `book_embeddedness.py` the graph analysis, and `slate_selection.py` the slot-selection problem and each user's slate), which `rai models deploy --path model` deploys to your Snowflake account, where each refresh runs the solve. - **Query**: `queries/slate_report.py` — prints the report from the deployed model. - **Runbook**: `runbook.md` — a paste-testable walkthrough that reproduces the template step by step with the RAI skills; as important a reference as the code in `model/`. - **Sample data**: a deterministic Open Library (CC0 public domain) slice of roughly 59 books, 52 authors, and 12 subjects, with synthetic users and read events layered on top. See *Sample data* below. @@ -200,7 +200,9 @@ book_slate_recommendation/ │ ├── __init__.py # exports of the deployed model │ ├── schema.py # concepts, properties, and edges │ ├── source.py # loads the CSVs and checks them -│ └── reasoning.py # paths walk + graph + prescriptive slot selection +│ ├── candidate_paths.py # KG path walks, candidates, explanation counts +│ ├── book_embeddedness.py # similarity-graph triangle counts +│ └── slate_selection.py # prescriptive slot selection and each user's slate ├── queries/ │ └── slate_report.py # report from the deployed model ├── runbook.md # paste-testable walkthrough (RAI skills) @@ -237,8 +239,8 @@ The bibliographic data is a deterministic slice of [Open Library](https://openli One shared ontology threads all three stages. The path-walk stage derives candidates and their evidence, the graph stage adds a structural measure, and the prescriptive stage reads both to compose the slate. -- **Key entities**: `User` — a reader; `Book` — a catalog title (an `Item` sub-concept); `Author` and `Subject` — a book's authors and topics; `Slot` — one of the K ordered recommendation positions in a user's slate; the derived `Candidate` — a (user, book) pair the knowledge-graph walks reach, scored by its explanation paths; a book the user already read is held at the unpicked sentinel slot. -- **Primary identifiers**: integer `id` on `User`, `Book`, `Author`, `Subject`; `pos` on `Slot`; composite `(user_id, book_id)` on `Candidate`. +- **Key entities**: `User` — a reader; `Book` — a catalog title (an `Item` sub-concept); `Author` and `Subject` — a book's authors and topics; `Slot` — one of the K ordered recommendation positions in a user's slate; the derived `Candidate` — a (user, book) pair the knowledge-graph walks reach, scored by its explanation paths, and flagged when its user has read it (`is_read`), where a read book is held at the unpicked sentinel slot; the derived `Slate` — a user's picks (the candidates in slots `1..K`) and their picks per subject. +- **Primary identifiers**: integer `id` on `User`, `Book`, `Author`, `Subject`; `pos` on `Slot`; `user_id` on `Slate`; composite `(user_id, book_id)` on `Candidate`. - **Important invariants**: `Book.in_house` is a 0/1 flag; `Book.age_days` is non-negative; similarity edges are unique on `(src_book_id, dst_book_id)`; every foreign key resolves; slot decisions take values in `1..K+1`, where slot 1 is the hero position and slot K+1 is the unpicked sentinel. The typed edges (`read`, `written_by`, `about`, `similar_to`) carry the graph structure; the unified `Item.connected_to` super-edge is their symmetric union, so the path walker can traverse one 2-arity relationship across the heterogeneous graph. Each `Candidate` carries typed evidence counts (`path_count_via_author`, `path_count_via_subject`, `path_count_via_kg_walk`, summed into `path_count_total`) and a `slot` decision. @@ -253,9 +255,9 @@ The pipeline runs in three stages over the shared ontology. Its architectural ce **Stage 2 — Graph analysis (hero-slot embeddedness).** A `Graph` is built from `Book.similar_to`, and triangle count returns the per-book count of similarity triangles each book participates in, stored as `Book.triangle_count`. Triangle count is graph-derived: it depends on the topology of the similarity graph, not on a per-book scalar that could be supplied externally. Stage 3 uses it to pin the hero slot to a densely embedded book. -**Stage 3 — Prescriptive constraint program (slot assignment).** Each candidate's slot is a decision in `1..K+1`, where slots `1..K` are slate positions (1 = hero, K = bottom of row) and slot K+1 is the unpicked sentinel. The K+1 encoding lets the position weight `(K + 1 - slot)` be zero for unpicked candidates, so no auxiliary picked/unpicked indicator is needed. The model enforces ten constraints — cardinality (exactly K picks per user), slot uniqueness, already-read exclusion, author uniqueness, subject-concentration cap, freshness floor, originals-exposure floor, cold-start cap, hero pin, and explanation-path floor — under a position-weighted engagement-decay objective. The objective weights each pick by `(K + 1 - slot) * path_count_total`, largest at slot 1, so the solver places the highest-path-support candidates at the top of the row — the canonical position-decay engagement model. After the deploy's refresh runs the solve, the report prints the status and objective, the chosen slate, subject distribution, and per-pick explanation support. It does not re-check the chosen slate against the ten constraints; it relies on the solver's status. +**Stage 3 — Prescriptive constraint program (slot assignment).** Each candidate's slot is a decision in `1..K+1`, where slots `1..K` are slate positions (1 = hero, K = bottom of row) and slot K+1 is the unpicked sentinel. The K+1 encoding lets the position weight `(K + 1 - slot)` be zero for unpicked candidates, so no auxiliary picked/unpicked indicator is needed. The model enforces ten constraints — cardinality (exactly K picks per user), slot uniqueness, already-read exclusion, author uniqueness, subject-concentration cap, freshness floor, originals-exposure floor, cold-start cap, hero pin, and explanation-path floor — under a position-weighted engagement-decay objective. The objective weights each pick by `(K + 1 - slot) * path_count_total`, largest at slot 1, so the solver places the highest-path-support candidates at the top of the row — the canonical position-decay engagement model. After the deploy's refresh runs the solve, rules over the solved slots publish each user's picks and picks per subject (`Slate.picks`, `Slate.picks_by_subject`), and the report prints the status and objective, the chosen slate, subject distribution, and per-pick explanation support. It does not re-check the chosen slate against the ten constraints; it relies on the solver's status. -See `model/reasoning.py` for the implementation and `runbook.md` for the skill-driven reproduction. +See `model/candidate_paths.py`, `model/book_embeddedness.py`, and `model/slate_selection.py` for the implementation and `runbook.md` for the skill-driven reproduction. **Where this fits in production.** Production recommender systems run a multi-stage funnel: catalog, then retrieval, then pre-ranking, then ranking, then slate optimization. This template implements the final slate-optimization stage — where business rules, diversity, exposure floors, and explainability constraints land — with the upstream graph and path-walk signals in the same declarative model. The per-typed evidence counts the report prints for each pick (`paths_via_author`, `paths_via_subject`, `paths_via_kg_walk`) are a decomposable, graph-grounded justification suitable for transparency workflows. @@ -276,7 +278,7 @@ Focus on the first changes most users will make. ### Tune parameters -The constraint dials are constants in `model/reasoning.py`, except `SLATE_SIZE_K`, which is in `model/source.py` because the slot rows use it: +Each dial is a constant at the top of the module that uses it under `# Configure inputs`: `MAX_HOPS` in `model/candidate_paths.py` and the rest in `model/slate_selection.py`: - **Slate size** — `SLATE_SIZE_K` (default `3`), the K of "row of K things". - **Walk depth** — `MAX_HOPS` (default `2`); bumping to 3 or more saturates fast on a heterogeneous graph. @@ -318,7 +320,7 @@ The model enforces ten constraints. If the data is too sparse or too clustered, 5. **Missing edges.** Every picked book must have at least one `Book.about(Subject)` and one `Book.written_by(Author)` row, or the diversity and uniqueness caps silently exempt it. 6. **Hero pin.** Each user needs at least one candidate whose book has `triangle_count >= HERO_EMBEDDEDNESS_THRESHOLD`, or there is no eligible book for slot 1. The report's per-user candidate floor check names users with no hero-eligible candidate; either lower `HERO_EMBEDDEDNESS_THRESHOLD` or densify the similarity input. -The report first runs a Python-level check that reads the candidate set and the read history from the deployed model, anti-joins them, and stops with an error naming the affected users per shortfall, with a strategy block keyed by which condition fired. It also prints an unread-candidate-count table before the solve result. +The report first runs a Python-level check that reads the unread candidates (those without `Candidate.is_read`) from the deployed model and stops with an error naming the affected users per shortfall, with a strategy block keyed by which condition fired. It also prints an unread-candidate-count table before the solve result. diff --git a/book_slate_recommendation/model/__init__.py b/book_slate_recommendation/model/__init__.py index 73f53524..9f8e4468 100644 --- a/book_slate_recommendation/model/__init__.py +++ b/book_slate_recommendation/model/__init__.py @@ -42,6 +42,16 @@ ~52 authors, 12 subjects) pulled by ``data/fetch_open_library_slice.py``. Customers fetch larger slices by re-running with ``--size md``/``--size lg``. +Modules, one per stage (each module imports the modules whose +declarations it reads): + +- ``candidate_paths.py``: the bounded KG walks, the candidates they reach, + their explanation path counts, and which candidates are already read. +- ``book_embeddedness.py``: the triangle count of each book over the + similarity graph. +- ``slate_selection.py``: the slot constraint program, its status and + objective, and each user's slate of picks. + Run: `rai models deploy --path model` deploys this package to the schemas in raiconfig.yaml and waits for its first refresh, which runs the solve. @@ -49,23 +59,24 @@ model. """ -from .reasoning import ( +from .candidate_paths import MAX_HOPS, Candidate +from .schema import Author, Book, Subject, User, model +from .slate_selection import ( COLD_START_CAP, EXPLANATION_FLOOR, FRESH_WINDOW_DAYS, FRESHNESS_FLOOR, HERO_EMBEDDEDNESS_THRESHOLD, - MAX_HOPS, MAX_PER_SUBJECT, ORIGINALS_FLOOR, + SLATE_SIZE_K, WEAK_EXPLANATION_THRESHOLD, - Candidate, + Slate, SolveStatus, TotalSupport, problem, ) -from .schema import Author, Book, Subject, User, model -from .source import DATA_DIR, SLATE_SIZE_K +from .source import DATA_DIR __all__ = [ "COLD_START_CAP", @@ -82,6 +93,7 @@ "Author", "Book", "Candidate", + "Slate", "SolveStatus", "Subject", "TotalSupport", diff --git a/book_slate_recommendation/model/book_embeddedness.py b/book_slate_recommendation/model/book_embeddedness.py new file mode 100644 index 00000000..76f21b2e --- /dev/null +++ b/book_slate_recommendation/model/book_embeddedness.py @@ -0,0 +1,45 @@ +"""Book structural embeddedness: the triangle count of each book over the similarity graph.""" + +from relationalai.semantics import Integer +from relationalai.semantics.reasoners.graph import Graph + +from .schema import Book, model + +# -------------------------------------------------- +# Stage 2: Graph reasoner -- structural embeddedness over book-similarity +# +# Per-Book triangle count over the similarity graph, which the hero pin +# (``hero_pin_ic`` in slate_selection.py) uses to keep slot 1, the +# highest-engagement position, for a structurally central pick. The count +# depends on the graph's topology, so unlike a per-Book popularity scalar it +# cannot be supplied as a data-layer input. +# -------------------------------------------------- + +# Book-Book similarity graph derived from shared authors / subjects. +# ``node_concept=Book`` makes graph-algorithm output bind directly to +# Book without DataFrame round-trips. Aggregator "sum" collapses +# multi-edges so two paths of similarity between the same pair count +# once. +sim_graph = Graph( + model, + directed=False, + weighted=False, + node_concept=Book, + aggregator="sum", + name="book_similarity_graph", +) +src_g, dst_g = Book.ref(), Book.ref() +model.define(sim_graph.Edge.new(src=src_g, dst=dst_g)).where( + Book.similar_to(src_g, dst_g), +) + +# Triangle count: per-Book count of similar_to triangles the book +# participates in, which distinguishes books central to dense neighborhoods +# from books on isolated edges of the similarity graph. +Book.triangle_count = model.Property(f"{Book} has structural embeddedness {Integer:triangle_count}") +triangle_rel = sim_graph.triangle_count() +b_tc = Book.ref() +tc = Integer.ref() +model.define(b_tc.triangle_count(tc)).where( + triangle_rel(b_tc, tc), +) diff --git a/book_slate_recommendation/model/candidate_paths.py b/book_slate_recommendation/model/candidate_paths.py new file mode 100644 index 00000000..2e171454 --- /dev/null +++ b/book_slate_recommendation/model/candidate_paths.py @@ -0,0 +1,181 @@ +"""Candidate set: bounded knowledge-graph walks from each reader, the explanation path counts of each +candidate, and which candidates the reader has already read.""" + +from relationalai.semantics import Integer, count + +from .schema import Author, Book, Item, Subject, User, model + +# -------------------------------------------------- +# Configure inputs +# -------------------------------------------------- + +# Bounded path depth for the KG walk. MAX_HOPS = 2 enumerates +# ``User -> read_Book`` (length 1, pruned by exclude_read_ic) and +# ``User -> read_Book -> similar_Book`` (length 2). Bumping to 3+ +# saturates fast on a heterogeneous KG (most users reach most books). +MAX_HOPS = 2 + +# Unified KG edge: a single 2-arity Item.connected_to relationship +# the path walker traverses, because a path() call walks one 2-arity +# relationship at a time. Each define() below contributes one direction +# of one typed edge to this symmetric union; the walker treats them all +# as the same generic hop. The typed-evidence +# properties below join candidate books directly against the user's +# read history via Book.written_by / Book.about rather than +# introspecting walker paths -- simpler and faster. +Item.connected_to = model.Relationship( + f"{Item:src} connected to {Item:dst}", + short_name="connected_to", +) + +# User <-> Book via read (both directions; user-anchor walks). +u_e, b_e = User.ref(), Book.ref() +rating_e = Integer.ref() +model.define(Item.connected_to(u_e, b_e)).where( + User.read(u_e, b_e, rating_e), +) +model.define(Item.connected_to(b_e, u_e)).where( + User.read(u_e, b_e, rating_e), +) + +# Book <-> Author. +b_a, a_e = Book.ref(), Author.ref() +model.define(Item.connected_to(b_a, a_e)).where(Book.written_by(b_a, a_e)) +model.define(Item.connected_to(a_e, b_a)).where(Book.written_by(b_a, a_e)) + +# Book <-> Subject. +b_s, s_e = Book.ref(), Subject.ref() +model.define(Item.connected_to(b_s, s_e)).where(Book.about(b_s, s_e)) +model.define(Item.connected_to(s_e, b_s)).where(Book.about(b_s, s_e)) + +# Book <-> Book via similar_to (both directions; the similarity graph +# is conceptually undirected for traversal purposes). +b_s1, b_s2 = Book.ref(), Book.ref() +model.define(Item.connected_to(b_s1, b_s2)).where(Book.similar_to(b_s1, b_s2)) +model.define(Item.connected_to(b_s2, b_s1)).where(Book.similar_to(b_s1, b_s2)) + +# -------------------------------------------------- +# Stage 1: Bounded KG walks via the paths library (architectural centerpiece) +# +# This is the load-bearing stage. The Candidate concept is derived +# from the path walker; without paths there are no candidates and no +# CSP variables. The per-typed counts produced here feed the +# engagement-weighted explanation floor, the cold-start cap, and the +# objective. +# -------------------------------------------------- + +# Walk the unified ``Item.connected_to`` edge from each User up to +# MAX_HOPS hops. The path pattern bounds the walk to MAX_HOPS, so the +# candidate set is the bounded reachable set under the KG. Naming the +# endpoints as a User and a Book lets the same pattern answer both +# "is this book reachable from this user" (``exists``, no +# enumeration) and "how many walks reach it" (``count``). +walk_user, walk_book = User.ref(), Book.ref() +kg_walks = model.path( + walk_user, + Item.connected_to.repeat(1, MAX_HOPS), + walk_book, +) + +# Candidate set: any (user, book) joined by a bounded KG walk. Books the +# user already read stay candidates; the already-read exclusion below +# forces them to the unpicked slot K+1. +Candidate = model.Concept( + "Candidate", + identify_by={"user_id": Integer, "book_id": Integer}, +) +model.define(Candidate.new(user_id=walk_user.id, book_id=walk_book.id)).where( + kg_walks.exists(), +) + +# Per-(user, candidate) explanation features: counts of distinct +# typed connections between the candidate and the user's read +# history. +# +# The author and subject ``count`` expressions are followed by ``| 0`` +# so the property is defined for *every* Candidate (not only those +# with at least one match). PyRel aggregates over an empty group produce no row, and +# the position-weighted explanation IC would silently drop Candidates +# whose property is undefined. +# +# Arithmetic ``a + s + w`` (not ``sum(model.union(a, s, w))``) -- +# union inside an aggregate body strips keys and deduplicates on +# projected values, undercounting whenever two of the three typed +# counts share a value. +Candidate.path_count_via_author = model.Property(f"{Candidate} has author connections {Integer:n}") +Candidate.path_count_via_subject = model.Property( + f"{Candidate} has subject connections {Integer:n}" +) +Candidate.path_count_via_kg_walk = model.Property(f"{Candidate} has KG-walk paths {Integer:n}") +Candidate.path_count_total = model.Property(f"{Candidate} has total connections {Integer:n}") + +c = Candidate.ref() +n = Integer.ref() +u_c, b_c = User.ref(), Book.ref() + +# via-author: the number of distinct authors the candidate shares +# with the user's read books. count(a_ref) counts each shared author +# once, however many of the user's read books it appears on. +b_read_a = Book.ref() +a_ref = Author.ref() +model.define(Candidate.path_count_via_author(c, n)).where( + Candidate(c), + n + == count(a_ref) + .per(c) + .where( + c.user_id == u_c.id, + c.book_id == b_c.id, + User.read(u_c, b_read_a, Integer.ref()), + Book.written_by(b_read_a, a_ref), + Book.written_by(b_c, a_ref), + ) + | 0, +) + +# via-subject: the number of distinct subjects the candidate shares +# with the user's read books, counted like via-author. +b_read_s = Book.ref() +s_ref = Subject.ref() +model.define(Candidate.path_count_via_subject(c, n)).where( + Candidate(c), + n + == count(s_ref) + .per(c) + .where( + c.user_id == u_c.id, + c.book_id == b_c.id, + User.read(u_c, b_read_s, Integer.ref()), + Book.about(b_read_s, s_ref), + Book.about(b_c, s_ref), + ) + | 0, +) + +# via-walk: number of bounded heterogeneous KG paths from this user +# to the candidate (the actual paths-walk count -- the headline +# explanation-strength signal). Every Candidate has at least one walk, +# so this count is always defined. +model.define(Candidate.path_count_via_kg_walk(c, n)).where( + Candidate(c), + c.user_id == walk_user.id, + c.book_id == walk_book.id, + n == kg_walks.all().count().per(walk_user, walk_book), +) + +# Total: sum across types as a single integer feature for cold-start +# threshold checks and explanation/objective weighting. +model.define(Candidate.path_count_total(c, n)).where( + Candidate(c), + n == c.path_count_via_author + c.path_count_via_subject + c.path_count_via_kg_walk, +) + +# Already-read candidates: the user has read the book. Only a candidate the user +# has not read can be picked for the slate. +Candidate.is_read = model.Relationship(f"{Candidate} is a book its user has read") +u_read, b_read = User.ref(), Book.ref() +model.where( + User.read(u_read, b_read, Integer.ref()), + Candidate.user_id == u_read.id, + Candidate.book_id == b_read.id, +).define(Candidate.is_read()) diff --git a/book_slate_recommendation/model/schema.py b/book_slate_recommendation/model/schema.py index 762eb1b6..f3c43a3e 100644 --- a/book_slate_recommendation/model/schema.py +++ b/book_slate_recommendation/model/schema.py @@ -6,7 +6,7 @@ # Item super-concept: heterogeneous-KG node base for User/Book/Author/ # Subject. The path walker traverses a single 2-arity edge relationship -# (Item.connected_to, defined in reasoning.py) across the whole KG. The +# (Item.connected_to, defined in candidate_paths.py) across the whole KG. The # unified-edge layer is needed because a path() call walks one 2-arity # relationship at a time, so the symmetric union of typed edges is # pre-materialised onto Item.connected_to. diff --git a/book_slate_recommendation/model/reasoning.py b/book_slate_recommendation/model/slate_selection.py similarity index 50% rename from book_slate_recommendation/model/reasoning.py rename to book_slate_recommendation/model/slate_selection.py index c16cf9f3..8d7ced04 100644 --- a/book_slate_recommendation/model/reasoning.py +++ b/book_slate_recommendation/model/slate_selection.py @@ -1,26 +1,20 @@ -"""Slate recommendation: bounded knowledge-graph walks, structural embeddedness, and the slate-selection CSP.""" +"""Slate selection: the constraint program that assigns each candidate a slot, the solve's status and +objective, and each reader's resulting slate.""" -from relationalai.semantics import ( - Integer, - String, - count, - sum, -) -from relationalai.semantics.reasoners.graph import Graph +from relationalai.semantics import Integer, String, count, std, sum from relationalai.semantics.reasoners.prescriptive import Problem -from .schema import Author, Book, Item, Slot, Subject, User, model -from .source import SLATE_SIZE_K +# Declares Book.triangle_count, the structural-embeddedness measure the hero pin reads. +from . import book_embeddedness # noqa: F401 +from .candidate_paths import Candidate +from .schema import Author, Book, Slot, Subject, User, model # -------------------------------------------------- # Configure inputs # -------------------------------------------------- -# Bounded path depth for the KG walk. MAX_HOPS = 2 enumerates -# ``User -> read_Book`` (length 1, pruned by exclude_read_ic) and -# ``User -> read_Book -> similar_Book`` (length 2). Bumping to 3+ -# saturates fast on a heterogeneous KG (most users reach most books). -MAX_HOPS = 2 +# Slate size: the K of "row of K things". Tune to taste. +SLATE_SIZE_K = 3 # Topic-span cap: at most this many picks per (user, subject). With # K=3 picks and MAX_PER_SUBJECT=2, no subject dominates the slate -- @@ -59,210 +53,8 @@ # distribution after rescaling. HERO_EMBEDDEDNESS_THRESHOLD = 4 -# Unified KG edge: a single 2-arity Item.connected_to relationship -# the path walker traverses, because a path() call walks one 2-arity -# relationship at a time. Each define() below contributes one direction -# of one typed edge to this symmetric union; the walker treats them all -# as the same generic hop. The typed-evidence -# properties below join candidate books directly against the user's -# read history via Book.written_by / Book.about rather than -# introspecting walker paths -- simpler and faster. -Item.connected_to = model.Relationship( - f"{Item:src} connected to {Item:dst}", - short_name="connected_to", -) - -# User <-> Book via read (both directions; user-anchor walks). -u_e, b_e = User.ref(), Book.ref() -rating_e = Integer.ref() -model.define(Item.connected_to(u_e, b_e)).where( - User.read(u_e, b_e, rating_e), -) -model.define(Item.connected_to(b_e, u_e)).where( - User.read(u_e, b_e, rating_e), -) - -# Book <-> Author. -b_a, a_e = Book.ref(), Author.ref() -model.define(Item.connected_to(b_a, a_e)).where(Book.written_by(b_a, a_e)) -model.define(Item.connected_to(a_e, b_a)).where(Book.written_by(b_a, a_e)) - -# Book <-> Subject. -b_s, s_e = Book.ref(), Subject.ref() -model.define(Item.connected_to(b_s, s_e)).where(Book.about(b_s, s_e)) -model.define(Item.connected_to(s_e, b_s)).where(Book.about(b_s, s_e)) - -# Book <-> Book via similar_to (both directions; the similarity graph -# is conceptually undirected for traversal purposes). -b_s1, b_s2 = Book.ref(), Book.ref() -model.define(Item.connected_to(b_s1, b_s2)).where(Book.similar_to(b_s1, b_s2)) -model.define(Item.connected_to(b_s2, b_s1)).where(Book.similar_to(b_s1, b_s2)) - -# -------------------------------------------------- -# Bounded KG walks via the paths library (architectural centerpiece) -# -# This is the load-bearing stage. The Candidate concept is derived -# from the path walker; without paths there are no candidates and no -# CSP variables. The per-typed counts produced here feed the -# engagement-weighted explanation floor, the cold-start cap, and the -# objective. -# -------------------------------------------------- - -# Walk the unified ``Item.connected_to`` edge from each User up to -# MAX_HOPS hops. The path pattern bounds the walk to MAX_HOPS, so the -# candidate set is the bounded reachable set under the KG. Naming the -# endpoints as a User and a Book lets the same pattern answer both -# "is this book reachable from this user" (``exists``, no -# enumeration) and "how many walks reach it" (``count``). -walk_user, walk_book = User.ref(), Book.ref() -kg_walks = model.path( - walk_user, - Item.connected_to.repeat(1, MAX_HOPS), - walk_book, -) - -# Candidate set: any (user, book) joined by a bounded KG walk. Books the -# user already read stay candidates; the already-read exclusion below -# forces them to the unpicked slot K+1. -Candidate = model.Concept( - "Candidate", - identify_by={"user_id": Integer, "book_id": Integer}, -) -model.define(Candidate.new(user_id=walk_user.id, book_id=walk_book.id)).where( - kg_walks.exists(), -) - -# Per-(user, candidate) explanation features: counts of distinct -# typed connections between the candidate and the user's read -# history. -# -# The author and subject ``count`` expressions are followed by ``| 0`` -# so the property is defined for *every* Candidate (not only those -# with at least one match). PyRel aggregates over an empty group produce no row, and -# the position-weighted explanation IC would silently drop Candidates -# whose property is undefined. -# -# Arithmetic ``a + s + w`` (not ``sum(model.union(a, s, w))``) -- -# union inside an aggregate body strips keys and deduplicates on -# projected values, undercounting whenever two of the three typed -# counts share a value. -Candidate.path_count_via_author = model.Property(f"{Candidate} has author connections {Integer:n}") -Candidate.path_count_via_subject = model.Property( - f"{Candidate} has subject connections {Integer:n}" -) -Candidate.path_count_via_kg_walk = model.Property(f"{Candidate} has KG-walk paths {Integer:n}") -Candidate.path_count_total = model.Property(f"{Candidate} has total connections {Integer:n}") - -c = Candidate.ref() -n = Integer.ref() -u_c, b_c = User.ref(), Book.ref() - -# via-author: the number of distinct authors the candidate shares -# with the user's read books. count(a_ref) counts each shared author -# once, however many of the user's read books it appears on. -b_read_a = Book.ref() -a_ref = Author.ref() -model.define(Candidate.path_count_via_author(c, n)).where( - Candidate(c), - n - == count(a_ref) - .per(c) - .where( - c.user_id == u_c.id, - c.book_id == b_c.id, - User.read(u_c, b_read_a, Integer.ref()), - Book.written_by(b_read_a, a_ref), - Book.written_by(b_c, a_ref), - ) - | 0, -) - -# via-subject: the number of distinct subjects the candidate shares -# with the user's read books, counted like via-author. -b_read_s = Book.ref() -s_ref = Subject.ref() -model.define(Candidate.path_count_via_subject(c, n)).where( - Candidate(c), - n - == count(s_ref) - .per(c) - .where( - c.user_id == u_c.id, - c.book_id == b_c.id, - User.read(u_c, b_read_s, Integer.ref()), - Book.about(b_read_s, s_ref), - Book.about(b_c, s_ref), - ) - | 0, -) - -# via-walk: number of bounded heterogeneous KG paths from this user -# to the candidate (the actual paths-walk count -- the headline -# explanation-strength signal). Every Candidate has at least one walk, -# so this count is always defined. -model.define(Candidate.path_count_via_kg_walk(c, n)).where( - Candidate(c), - c.user_id == walk_user.id, - c.book_id == walk_book.id, - n == kg_walks.all().count().per(walk_user, walk_book), -) - -# Total: sum across types as a single integer feature for cold-start -# threshold checks and explanation/objective weighting. -model.define(Candidate.path_count_total(c, n)).where( - Candidate(c), - n == c.path_count_via_author + c.path_count_via_subject + c.path_count_via_kg_walk, -) - # -------------------------------------------------- -# Stage 1: Graph reasoner -- structural embeddedness over book-similarity -# -# Per-Book triangle count over the similarity graph, used by -# ``hero_pin_ic`` to pin slot 1 (the highest-engagement position) to -# a structurally-central pick. The triangle-count signal is graph- -# derived (it depends on the similarity-graph topology), so unlike a -# per-Book popularity scalar, it cannot be supplied externally -# without reconstructing the graph -- which is what makes this an -# irreducible Graph-reasoner contribution, not just a data-layer -# input. -# -------------------------------------------------- - -# Book-Book similarity graph derived from shared authors / subjects. -# ``node_concept=Book`` makes graph-algorithm output bind directly to -# Book without DataFrame round-trips. Aggregator "sum" collapses -# multi-edges so two paths of similarity between the same pair count -# once. -sim_graph = Graph( - model, - directed=False, - weighted=False, - node_concept=Book, - aggregator="sum", - name="book_similarity_graph", -) -src_g, dst_g = Book.ref(), Book.ref() -model.define(sim_graph.Edge.new(src=src_g, dst=dst_g)).where( - Book.similar_to(src_g, dst_g), -) - -# Triangle count: per-Book count of similar_to triangles the book -# participates in -- a structural-embeddedness measure. Used by -# ``hero_pin_ic`` below to pin the hero slot (slot 1) to a densely- -# embedded book, distinguishing books central to dense neighborhoods -# from books that sit on isolated edges of the similarity graph. -# Triangle count is graph-derived: it depends on the topology of -# ``Book.similar_to``, not on a per-book scalar that could be -# supplied externally. -Book.triangle_count = model.Property(f"{Book} has structural embeddedness {Integer:triangle_count}") -triangle_rel = sim_graph.triangle_count() -b_tc = Book.ref() -tc = Integer.ref() -model.define(b_tc.triangle_count(tc)).where( - triangle_rel(b_tc, tc), -) - -# -------------------------------------------------- -# Stage 2: Prescriptive reasoner -- CSP slate selection (MiniZinc) +# Stage 3: Prescriptive reasoner -- CSP slate selection (MiniZinc) # # Decision: ``Candidate.slot`` ∈ {1, 2, ..., K, K+1}. Slot 1..K are # slate positions (1 = top of row); slot K+1 is the unpicked sentinel. @@ -296,6 +88,13 @@ ) problem.satisfy(slate_size_ic) +# Slot positions 1..K. The Slot concept exists so the slot-uniqueness IC +# counts distinct slot Concept values (the social_golfer idiom) rather +# than distinct anonymous Integer values. K+1 is the unpicked sentinel +# and is intentionally not a Slot row -- only filled positions are +# counted. +model.define(Slot.new(pos=std.common.range(1, SLATE_SIZE_K + 1))) + # Slot uniqueness: at most one Candidate per (user, slot position). # Counts Candidates whose slot decision equals each Slot's pos, per # (user, Slot). Combined with slate_size_ic (K picks per user) and @@ -311,18 +110,9 @@ # Already-read exclusion: any (user, book) where the user has already # read the book must have ``slot == K+1`` (unpicked). Lands at the # prescriptive layer rather than as a pre-pruning filter on Candidate -# derivation; the alternative would need a positive complement of -# ``User.read`` (a Cartesian-minus-existing-tuples relation with no -# scalar comparator to lean on). The ``slot == K+1`` IC keeps the -# rule pipeline pure-positive at minor CSP cost (a few wasted integer -# variables forced to the unpicked sentinel). -u_excl, b_excl = User.ref(), Book.ref() -rating_excl_ic = Integer.ref() -exclude_read_ic = model.where( - User.read(u_excl, b_excl, rating_excl_ic), - Candidate.user_id == u_excl.id, - Candidate.book_id == b_excl.id, -).require(Candidate.slot == SLATE_SIZE_K + 1) +# derivation: Candidate stays the full reachable set, and the cost is a +# few wasted integer variables forced to the unpicked sentinel. +exclude_read_ic = model.where(Candidate.is_read()).require(Candidate.slot == SLATE_SIZE_K + 1) problem.satisfy(exclude_read_ic) # Author uniqueness: at most one picked Candidate per (user, Author). @@ -428,3 +218,29 @@ SolveStatus = model.Relationship(f"slate solve status is {String:status}") TotalSupport = model.Relationship(f"slate total position-weighted path support is {Integer:support}") model.define(SolveStatus(problem.termination_status()), TotalSupport(problem.objective_value())) + +# -------------------------------------------------- +# The slate: each user's picked candidates and the subjects they cover +# -------------------------------------------------- + +# Values computed from the solution live on Slate, not Candidate: such a +# property on the concept the solve reads fails the deploy. A user's picks are the +# candidates in slots 1..K. +Slate = model.Concept("Slate", identify_by={"user_id": Integer}) +Slate.picks = model.Relationship(f"{Slate} picks {Candidate}") +model.define(Slate.new(user_id=User.id)) +model.where( + Slate.user_id == Candidate.user_id, + Candidate.slot <= SLATE_SIZE_K, +).define(Slate.picks(Candidate)) + +# Picks per subject: a book counts toward every subject it is about. +Slate.picks_by_subject = model.Relationship( + f"{Slate} has {Integer:n_picked} picks on subject {Subject:subject}" +) +picked_subject = Subject.ref() +model.where( + Slate.picks(Candidate), + Book.id == Candidate.book_id, + Book.about(Book, picked_subject), +).define(Slate.picks_by_subject(count(Candidate).per(Slate, picked_subject), picked_subject)) diff --git a/book_slate_recommendation/model/source.py b/book_slate_recommendation/model/source.py index 07582b4a..f0062047 100644 --- a/book_slate_recommendation/model/source.py +++ b/book_slate_recommendation/model/source.py @@ -2,13 +2,10 @@ from pathlib import Path -from pandas import DataFrame, read_csv +from pandas import read_csv from relationalai.semantics import Integer -from .schema import Author, Book, Slot, Subject, User, model - -# Slate size: the K of "row of K things". Tune to taste. -SLATE_SIZE_K = 3 +from .schema import Author, Book, Subject, User, model DATA_DIR = Path(__file__).resolve().parents[1] / "data" @@ -26,13 +23,6 @@ book_subjects_csv = read_csv(DATA_DIR / "book_subject.csv") book_similarities_csv = read_csv(DATA_DIR / "book_similar.csv") -# Slot positions 1..K. The Slot concept exists so the slot-uniqueness -# IC counts distinct slot Concept values (the social_golfer idiom) -# rather than distinct anonymous Integer values. K+1 is the unpicked -# sentinel and is intentionally not a Slot row -- only filled -# positions are counted. -slots_df = DataFrame({"pos": list(range(1, SLATE_SIZE_K + 1))}) - # -------------------------------------------------- # Pre-solve invariants # @@ -131,7 +121,6 @@ def _assert_in_set(df, col, allowed, source): model.define(Book.new(model.data(books_csv).to_schema())) model.define(Author.new(model.data(authors_csv).to_schema())) model.define(Subject.new(model.data(subjects_csv).to_schema())) -model.define(Slot.new(model.data(slots_df).to_schema())) read_data = model.data(reads_csv) rating_ref = Integer.ref() diff --git a/book_slate_recommendation/queries/slate_report.py b/book_slate_recommendation/queries/slate_report.py index c49a4ab8..27a28837 100644 --- a/book_slate_recommendation/queries/slate_report.py +++ b/book_slate_recommendation/queries/slate_report.py @@ -21,13 +21,14 @@ Author, Book, Candidate, + Slate, SolveStatus, Subject, TotalSupport, User, model, ) -from relationalai.semantics import Integer, count +from relationalai.semantics import Integer # explanation_ic requires sum((K+1-slot)*path_count_total) >= EXPLANATION_FLOOR. @@ -48,25 +49,17 @@ def _max_explanation_score(group): # user explicitly and refuse to report if any user fails any of the per-IC # feasibility necessary conditions below, so sparse customer reach hits a # clear Python-level error. - candidate_df = model.select( - Candidate.user_id.alias("user_id"), - Candidate.book_id.alias("book_id"), - Candidate.path_count_total.alias("path_count_total"), - ).to_df() - # The read history, book attributes, authorship, subjects and users all - # come from the deployed model. - rating = Integer.ref() - reads_df = model.select( - User.id.alias("user_id"), - Book.id.alias("book_id"), - ).where(User.read(User, Book, rating)).to_df() - unread = candidate_df.merge( - reads_df, - on=["user_id", "book_id"], - how="left", - indicator=True, + unread = ( + model.select( + Candidate.user_id.alias("user_id"), + Candidate.book_id.alias("book_id"), + Candidate.path_count_total.alias("path_count_total"), + ) + .where(model.not_(Candidate.is_read())) + .to_df() ) - unread = unread[unread["_merge"] == "left_only"][["user_id", "book_id", "path_count_total"]] + # The book attributes, authorship, subjects and users all come from the + # deployed model. # Pull triangle counts so the hero-eligible feasibility check can # count books meeting HERO_EMBEDDEDNESS_THRESHOLD per user. triangle_df = model.select( @@ -214,7 +207,7 @@ def _max_explanation_score(group): tc_pick.alias("triangle_count"), ) .where( - Candidate.slot <= SLATE_SIZE_K, + Slate.picks(Candidate), b_pick.id == Candidate.book_id, b_pick.triangle_count == tc_pick, ) @@ -223,20 +216,14 @@ def _max_explanation_score(group): print(slate_df.sort_values(["user_id", "slot"]).to_string(index=False)) print("\nSubject distribution per user's slate:") - u_disp = User.ref() - b_disp = Book.ref() - s_disp = Subject.ref() - # Only subjects with at least one pick are listed. - model.where( - Candidate.user_id == u_disp.id, - Candidate.book_id == b_disp.id, - Book.about(b_disp, s_disp), - Candidate.slot <= SLATE_SIZE_K, - ).select( - u_disp.id.alias("user_id"), - s_disp.name.alias("subject"), - count(Candidate).per(u_disp, s_disp).alias("n_picked"), - ).inspect() + slate = Slate.ref() + subject = Subject.ref() + n_picked = Integer.ref() + model.select( + slate.user_id.alias("user_id"), + subject.name.alias("subject"), + n_picked.alias("n_picked"), + ).where(slate.picks_by_subject(n_picked, subject)).inspect() print("\nExplanation-path support per picked item (ordered by slot):") expl_df = ( @@ -248,7 +235,7 @@ def _max_explanation_score(group): Candidate.path_count_via_author.alias("paths_via_author"), Candidate.path_count_via_subject.alias("paths_via_subject"), ) - .where(Candidate.slot <= SLATE_SIZE_K) + .where(Slate.picks(Candidate)) .to_df() ) print(expl_df.sort_values(["user_id", "slot"]).to_string(index=False)) diff --git a/campaign_roi/README.md b/campaign_roi/README.md index 7b33098b..41d52f12 100644 --- a/campaign_roi/README.md +++ b/campaign_roi/README.md @@ -36,7 +36,7 @@ Every marketing team eventually faces the same question: the portfolio of campai ## What's included -- **Model**: a continuous LP over a single `Campaign` concept, with per-campaign floor and cap bounds, a total-budget constraint, a paused-region share cap, and a conversion-maximizing objective — in the `model/` package (`schema.py` declares the concept, `source.py` loads the sample data, `reasoning.py` states the decision problem). +- **Model**: a continuous LP over a `Campaign` concept, with per-campaign floor and cap bounds, a total-budget constraint, a paused-region share cap, and a conversion-maximizing objective, and the optimized plan's comparison with the current budgets — in the `model/` package (`schema.py` declares the concept, `source.py` loads the sample data, `budget_plan.py` states the decision problem and compares the optimized plan with the current budgets). - **Deployment**: `rai models deploy --path model` deploys the package to your Snowflake account, where each refresh runs the solve. - **Query**: `queries/budget_reallocation.py` prints the report from the deployed model. - **Runbook**: `runbook.md` — a paste-testable walkthrough that reproduces the template step by step with the RAI skills; as important a reference as the script itself. @@ -195,7 +195,7 @@ Use this sequence to deploy the model and query it: │ ├── __init__.py # exports of the deployed model │ ├── schema.py # the Campaign concept │ ├── source.py # loads the sample campaigns -│ └── reasoning.py # constants, decision variable, constraints, objective, solve +│ └── budget_plan.py # constants, decision variable, constraints, objective, solve, plan comparison ├── queries/ │ └── budget_reallocation.py # report from the deployed model └── data/ @@ -220,17 +220,18 @@ Total current budget across all campaigns: $1,130K. WEST has the two highest-rat ## Model overview -The model is a single concept: one `Campaign` per row of `campaigns.csv`, enriched with a decision-variable property after the solve. +The model has one source concept: one `Campaign` per row of `campaigns.csv`, enriched with a decision-variable property after the solve. Two further concepts summarize the solved plan. - **Key entities**: `Campaign` — a marketing campaign with a current budget, region tag, and empirical conversion rate; its optimized budget is the decision variable populated after the solve. +- **Plan summaries**: `CampaignPlan` — each campaign's change from its current budget; `RegionSpend` — each region's current and optimized spend and the optimized share of `TOTAL_BUDGET`. A nullary relationship publishes the expected conversions at the current budgets. - **Primary identifiers**: integer `id` on `Campaign`, loaded from `data/campaigns.csv`. - **Important invariants**: `current_budget` and `conversion_rate` are non-negative; the optimized budget `x_budget` stays between the per-campaign floor and cap; total spend does not exceed `TOTAL_BUDGET`; and the paused region's spend does not exceed its share cap. -For the full concept and property definitions, see `model/schema.py` (the decision variable `Campaign.x_budget` is declared in `model/reasoning.py`); `runbook.md` builds them step by step with the RAI skills. +For the full concept and property definitions, see `model/schema.py` (the decision variable `Campaign.x_budget` is declared in `model/budget_plan.py`); `runbook.md` builds them step by step with the RAI skills. ## How it works -The model loads the campaigns into a single `Campaign` concept, defines one continuous decision variable per campaign, adds the floor, cap, total-budget, and regional-cap constraints, and maximizes conversions; the report prints the reallocation. +The model loads the campaigns into a `Campaign` concept, defines one continuous decision variable per campaign, adds the floor, cap, total-budget, and regional-cap constraints, and maximizes conversions. It then compares the optimized plan with the current budgets by campaign and by region; the report prints the reallocation. ### 1. Decision variable @@ -244,7 +245,11 @@ The per-campaign floor and cap are derived from each campaign's current spend: t The objective maximizes total expected conversions — the sum over campaigns of budget times conversion rate. -See `model/reasoning.py` for the implementation and `runbook.md` for the skill-driven reproduction. +### 4. Plan comparison + +Rules publish the expected conversions at the current budgets and, from the solved budgets, each campaign's change and each region's current and optimized spend. The solution-derived values sit on `CampaignPlan` and `RegionSpend`, not on `Campaign`, which the solve reads. The report divides by the current figures for the lift and each campaign's multiple, so a campaign with a zero current budget keeps its row with a missing multiple. + +See `model/budget_plan.py` for the implementation and `runbook.md` for the skill-driven reproduction. ## Customize this template @@ -254,7 +259,7 @@ Replace `data/campaigns.csv` with your own. Required columns: `id`, `name`, `reg ### Tune parameters -All parameters live at the top of `model/reasoning.py` under `# Configure inputs`: +All parameters live at the top of `model/budget_plan.py` under `# Configure inputs`: | Parameter | Default | Effect | |---|---|---| diff --git a/campaign_roi/model/__init__.py b/campaign_roi/model/__init__.py index da6dc83b..183d2b60 100644 --- a/campaign_roi/model/__init__.py +++ b/campaign_roi/model/__init__.py @@ -11,6 +11,8 @@ cannot exceed PAUSED_CAP_FRACTION of TOTAL_BUDGET. - Enforce a total budget constraint. - Maximize total expected conversions = sum(budget * conversion_rate). +- Compare the optimized plan with the current budgets: conversions, each + campaign's change, and spend per region (`budget_plan.py`). Run: `rai models deploy --path model` deploys this package to the schemas in @@ -18,12 +20,16 @@ `python -m queries.budget_reallocation` then prints the report from the deployed model. """ -from .reasoning import ( +from .budget_plan import ( CAP_MULTIPLIER, FLOOR_FRACTION, + PAUSED_CAP, PAUSED_CAP_FRACTION, PAUSED_REGION, TOTAL_BUDGET, + CampaignPlan, + CurrentConversions, + RegionSpend, SolveStatus, TotalConversions, problem, @@ -35,10 +41,14 @@ "CAP_MULTIPLIER", "DATA_DIR", "FLOOR_FRACTION", + "PAUSED_CAP", "PAUSED_CAP_FRACTION", "PAUSED_REGION", "TOTAL_BUDGET", "Campaign", + "CampaignPlan", + "CurrentConversions", + "RegionSpend", "SolveStatus", "TotalConversions", "model", diff --git a/campaign_roi/model/budget_plan.py b/campaign_roi/model/budget_plan.py new file mode 100644 index 00000000..fe26692c --- /dev/null +++ b/campaign_roi/model/budget_plan.py @@ -0,0 +1,107 @@ +"""Campaign budget plan: the reallocation problem that maximizes expected conversions under floors +and caps, and how the optimized plan compares with the current budgets.""" + +from relationalai.semantics import Float, String, sum +from relationalai.semantics.reasoners.prescriptive import Problem +from relationalai.semantics.std import aggregates as aggs + +from .schema import Campaign, model + +# -------------------------------------------------- +# Configure inputs +# -------------------------------------------------- + +TOTAL_BUDGET = 1130.0 # $K — same as current total; pure reallocation, no budget cut +FLOOR_FRACTION = 0.1 # no campaign drops below 10% of current spend +CAP_MULTIPLIER = 3.0 # no campaign exceeds 3x current spend +PAUSED_REGION = "WEST" +PAUSED_CAP_FRACTION = 0.5 # paused-region total cannot exceed 50% of TOTAL_BUDGET +PAUSED_CAP = PAUSED_CAP_FRACTION * TOTAL_BUDGET # $K cap on the paused region's total spend + +# -------------------------------------------------- +# Model the decision problem +# -------------------------------------------------- + +# Decision variable: optimized budget per campaign (continuous, $K). +Campaign.x_budget = model.Property(f"{Campaign} has new budget {Float:budget}") + +problem = Problem(model, Float, name="campaign_roi") + +problem.solve_for( + Campaign.x_budget, + lower=0, + name=["budget", Campaign.name], +) + +# Constraint: per-campaign floor and cap, derived from each campaign's +# current spend. +problem.satisfy(model.where(Campaign).require( + Campaign.x_budget >= FLOOR_FRACTION * Campaign.current_budget, + Campaign.x_budget <= CAP_MULTIPLIER * Campaign.current_budget, +)) + +# Constraint: total spend across all campaigns cannot exceed TOTAL_BUDGET. +problem.satisfy(model.require(sum(Campaign.x_budget) <= TOTAL_BUDGET)) + +# Constraint: paused-region total spend cannot exceed PAUSED_CAP. Without this +# constraint the optimizer would pour budget into the paused region whenever its +# conversion rates are competitive. +problem.satisfy(model.require( + sum(Campaign.x_budget).where(Campaign.region == PAUSED_REGION) <= PAUSED_CAP +)) + +# Objective: maximize total expected conversions. +problem.maximize(sum(Campaign.x_budget * Campaign.conversion_rate)) + +# -------------------------------------------------- +# Solve +# -------------------------------------------------- + +# Each refresh of the deployed model runs this solve. +problem.configure("highs", time_limit_sec=60) + +# The solve's status and objective, which the deployed model publishes for the queries. +SolveStatus = model.Relationship(f"campaign roi solve status is {String:status}") +TotalConversions = model.Relationship(f"campaign roi total conversions is {Float:conversions}") +model.define(SolveStatus(problem.termination_status()), TotalConversions(problem.objective_value())) + +# -------------------------------------------------- +# Compare the optimized plan with the current budgets +# -------------------------------------------------- + +# Expected conversions at the current budgets. +CurrentConversions = model.Relationship( + f"campaign roi current conversions is {Float:current_conversions}" +) +model.define(CurrentConversions(sum(Campaign, Campaign.current_budget * Campaign.conversion_rate))) + +# Each campaign's change from its current budget. It is computed from the solution, so +# it lives on CampaignPlan, not Campaign: such a property on the concept the solve reads +# fails the deploy. +CampaignPlan = model.Concept("CampaignPlan", identify_by={"campaign": Campaign}) +CampaignPlan.delta = model.Property(f"{CampaignPlan} changes its budget by {Float:delta}") +model.define(CampaignPlan.new(campaign=Campaign)) +model.where(CampaignPlan.campaign == Campaign).define( + CampaignPlan.delta(Campaign.x_budget - Campaign.current_budget) +) + +# Spend per region: current, optimized, and the optimized share of TOTAL_BUDGET. +RegionSpend = model.Concept("RegionSpend", identify_by={"region": String}) +RegionSpend.current_spend = model.Property(f"{RegionSpend} has current spend {Float:current_spend}") +RegionSpend.optimized_spend = model.Property( + f"{RegionSpend} has optimized spend {Float:optimized_spend}" +) +RegionSpend.share_of_total = model.Property( + f"{RegionSpend} has {Float:share_of_total} of the total budget" +) +model.define(RegionSpend.new(region=Campaign.region)) +_in_region = Campaign.region == RegionSpend.region +model.define( + RegionSpend.current_spend( + aggs.sum(Campaign, Campaign.current_budget).per(RegionSpend).where(_in_region) + ), + RegionSpend.optimized_spend( + aggs.sum(Campaign, Campaign.x_budget).per(RegionSpend).where(_in_region) + ), +) +model.define(RegionSpend.share_of_total(RegionSpend.optimized_spend / TOTAL_BUDGET)) diff --git a/campaign_roi/model/reasoning.py b/campaign_roi/model/reasoning.py deleted file mode 100644 index 42928d78..00000000 --- a/campaign_roi/model/reasoning.py +++ /dev/null @@ -1,65 +0,0 @@ -"""Campaign budget reallocation problem: maximize expected conversions under floors and caps.""" - -from relationalai.semantics import Float, String, sum -from relationalai.semantics.reasoners.prescriptive import Problem - -from .schema import Campaign, model - -# -------------------------------------------------- -# Configure inputs -# -------------------------------------------------- - -TOTAL_BUDGET = 1130.0 # $K — same as current total; pure reallocation, no budget cut -FLOOR_FRACTION = 0.1 # no campaign drops below 10% of current spend -CAP_MULTIPLIER = 3.0 # no campaign exceeds 3x current spend -PAUSED_REGION = "WEST" -PAUSED_CAP_FRACTION = 0.5 # paused-region total cannot exceed 50% of TOTAL_BUDGET - -# -------------------------------------------------- -# Model the decision problem -# -------------------------------------------------- - -# Decision variable: optimized budget per campaign (continuous, $K). -Campaign.x_budget = model.Property(f"{Campaign} has new budget {Float:budget}") - -problem = Problem(model, Float, name="campaign_roi") - -problem.solve_for( - Campaign.x_budget, - lower=0, - name=["budget", Campaign.name], -) - -# Constraint: per-campaign floor and cap, derived from each campaign's -# current spend. -problem.satisfy(model.where(Campaign).require( - Campaign.x_budget >= FLOOR_FRACTION * Campaign.current_budget, - Campaign.x_budget <= CAP_MULTIPLIER * Campaign.current_budget, -)) - -# Constraint: total spend across all campaigns cannot exceed TOTAL_BUDGET. -problem.satisfy(model.require(sum(Campaign.x_budget) <= TOTAL_BUDGET)) - -# Constraint: paused-region total spend cannot exceed -# PAUSED_CAP_FRACTION * TOTAL_BUDGET. Without this constraint the optimizer -# would pour budget into the paused region whenever its conversion rates -# are competitive. -problem.satisfy(model.require( - sum(Campaign.x_budget).where(Campaign.region == PAUSED_REGION) - <= PAUSED_CAP_FRACTION * TOTAL_BUDGET -)) - -# Objective: maximize total expected conversions. -problem.maximize(sum(Campaign.x_budget * Campaign.conversion_rate)) - -# -------------------------------------------------- -# Solve -# -------------------------------------------------- - -# Each refresh of the deployed model runs this solve. -problem.configure("highs", time_limit_sec=60) - -# The solve's status and objective, which the deployed model publishes for the queries. -SolveStatus = model.Relationship(f"campaign roi solve status is {String:status}") -TotalConversions = model.Relationship(f"campaign roi total conversions is {Float:conversions}") -model.define(SolveStatus(problem.termination_status()), TotalConversions(problem.objective_value())) diff --git a/campaign_roi/queries/budget_reallocation.py b/campaign_roi/queries/budget_reallocation.py index 52888e9e..0b0d83bb 100644 --- a/campaign_roi/queries/budget_reallocation.py +++ b/campaign_roi/queries/budget_reallocation.py @@ -7,10 +7,14 @@ """ from model import ( + PAUSED_CAP, PAUSED_CAP_FRACTION, PAUSED_REGION, TOTAL_BUDGET, Campaign, + CampaignPlan, + CurrentConversions, + RegionSpend, SolveStatus, TotalConversions, model, @@ -30,7 +34,12 @@ objective_value = conversions[0] print(f"Total expected conversions (optimized): {objective_value:,.1f}") + current_total = model.select(CurrentConversions).to_df().iloc[0, 0] + print(f"Total expected conversions (current): {current_total:,.1f}") + print(f"Lift: {(objective_value - current_total) / current_total * 100:+.1f}%") + # The id keeps campaigns that share every displayed value as separate rows. + plan = CampaignPlan.ref() results_df = model.select( Campaign.id.alias("id"), Campaign.name.alias("campaign"), @@ -38,28 +47,27 @@ Campaign.current_budget.alias("current"), Campaign.x_budget.alias("optimized"), Campaign.conversion_rate.alias("rate"), - ).to_df() - - current_total = (results_df["current"] * results_df["rate"]).sum() - print(f"Total expected conversions (current): {current_total:,.1f}") - print(f"Lift: {(objective_value - current_total) / current_total * 100:+.1f}%") + plan.delta.alias("delta"), + ).where(plan.campaign == Campaign).to_df() print("\nBudget reallocation per campaign (sorted by largest absolute change):") - results_df["delta"] = results_df["optimized"] - results_df["current"] results_df["multiple"] = results_df["optimized"] / results_df["current"] results_df = results_df.sort_values("delta", key=abs, ascending=False).reset_index(drop=True) print(results_df.drop(columns="id").to_string(index=False)) print("\nRegional spend (optimized):") regional = ( - results_df.groupby("region")[["current", "optimized"]] - .sum() - .reset_index() + model.select( + RegionSpend.region.alias("region"), + RegionSpend.current_spend.alias("current"), + RegionSpend.optimized_spend.alias("optimized"), + RegionSpend.share_of_total.alias("share_of_total"), + ) + .to_df() .sort_values("optimized", ascending=False) ) - regional["share_of_total"] = regional["optimized"] / TOTAL_BUDGET print(regional.to_string(index=False)) print( f"\nPaused region '{PAUSED_REGION}' cap: " - f"{PAUSED_CAP_FRACTION * TOTAL_BUDGET:.1f} ({PAUSED_CAP_FRACTION:.0%} of ${TOTAL_BUDGET:,.0f}K total)" + f"{PAUSED_CAP:.1f} ({PAUSED_CAP_FRACTION:.0%} of ${TOTAL_BUDGET:,.0f}K total)" ) diff --git a/campaign_roi/runbook.md b/campaign_roi/runbook.md index bbf3b288..bcd431e1 100644 --- a/campaign_roi/runbook.md +++ b/campaign_roi/runbook.md @@ -49,4 +49,4 @@ Each prompt is pasted into a fresh agent session loaded with the named `/rai-*` ## Data -Bundled CSV in `data/`: 12 campaigns with region, current budget, and conversion rate. The budget bounds (10%–300%), total-spend cap, and WEST regional cap are constants in `model/reasoning.py`. Full model in `model/`; the report in `queries/budget_reallocation.py`. +Bundled CSV in `data/`: 12 campaigns with region, current budget, and conversion rate. The budget bounds (10%–300%), total-spend cap, and WEST regional cap are constants in `model/budget_plan.py`. Full model in `model/`; the report in `queries/budget_reallocation.py`. diff --git a/cell_tower_coverage/README.md b/cell_tower_coverage/README.md index 4c9e3357..d7d3adec 100644 --- a/cell_tower_coverage/README.md +++ b/cell_tower_coverage/README.md @@ -38,7 +38,7 @@ Telecommunications and infrastructure teams routinely have to decide where to bu ## What's included -- **Model**: the `model/` package builds the semantic model (three concepts, two coverage relationships), the mixed-integer optimization problem (three binary variable families, five constraint families, one objective), and the solve (`schema.py` declares the concepts, `source.py` loads the sample data, `reasoning.py` states the decision problem); `rai models deploy --path model` deploys it to your Snowflake account, where each refresh runs the solve. +- **Model**: the `model/` package builds the semantic model (three concepts, two coverage relationships), the mixed-integer optimization problem (three binary variable families, five constraint families, one objective), and the solve (`schema.py` declares the concepts, `source.py` loads the sample data, `site_selection.py` states the decision problem, `coverage_summary.py` publishes the plan totals, tower loads, and coverage rate); `rai models deploy --path model` deploys it to your Snowflake account, where each refresh runs the solve. - **Query**: `queries/coverage_report.py` prints the report from the deployed model and writes `data/coverage_solution.csv`. - **Runbook**: `runbook.md` — a paste-testable walkthrough that reproduces the template step by step with the RAI skills; as important a reference as the script itself. - **Sample data**: 6 candidate tower sites, 10 demand zones, and 19 feasible tower-zone coverage pairs. See *Sample data* below. @@ -205,7 +205,8 @@ cell_tower_coverage/ __init__.py # exports of the deployed model schema.py # concepts and properties source.py # loads the CSVs, checks them, sets the build budget and tower cap - reasoning.py # decision variables, constraints, objective, solve + site_selection.py # decision variables, constraints, objective, solve + coverage_summary.py # plan totals, tower loads, zone assignments, coverage rate queries/ coverage_report.py # report from the deployed model data/ @@ -275,9 +276,9 @@ Two portfolio constraints bound the plan: total build cost stays at or under `BU ### 7. Maximize covered population -The objective rewards covering high-population zones, weighting each covered zone by its population. Because each zone has a single binary covered variable and each covered zone has exactly one assignment, the model handles overlapping tower coverage without double-counting population or overloading selected towers. After the solve, the model publishes the plan totals (selected build cost, total population, and each selected tower's assigned population) along with the budget and tower cap it solved with; the query reads them to print the report tables (selected sites with utilization, assigned zones, uncovered zones, coverage summary) and writes the per-zone assignments to `data/coverage_solution.csv`. +The objective rewards covering high-population zones, weighting each covered zone by its population. Because each zone has a single binary covered variable and each covered zone has exactly one assignment, the model handles overlapping tower coverage without double-counting population or overloading selected towers. After the solve, the model publishes the plan totals (selected build cost, total population, each tower's assigned population and utilization, the tower serving each covered zone, and the coverage rate and uncovered population) along with the budget and tower cap it solved with; the query reads them to print the report tables (selected sites with utilization, assigned zones, uncovered zones, coverage summary) and writes the per-zone assignments to `data/coverage_solution.csv`. -See `model/reasoning.py` for the implementation and `runbook.md` for the skill-driven reproduction. +See `model/site_selection.py` and `model/coverage_summary.py` for the implementation and `runbook.md` for the skill-driven reproduction. ## Customize this template diff --git a/cell_tower_coverage/model/__init__.py b/cell_tower_coverage/model/__init__.py index eb1de977..0fe634e7 100644 --- a/cell_tower_coverage/model/__init__.py +++ b/cell_tower_coverage/model/__init__.py @@ -10,7 +10,10 @@ - Report selected sites, assigned demand zones, tower utilization, and uncovered population. -The optimization is modeled as a mixed-integer linear problem. +The optimization is modeled as a mixed-integer linear problem. `site_selection.py` states the +decision problem and its solve; `coverage_summary.py` publishes the plan totals, each tower's load +and utilization, the tower serving each zone, and the coverage rate. Each module imports the modules +whose declarations it reads. Run: `rai models deploy --path model` deploys this package to the schemas in @@ -18,20 +21,17 @@ `python -m queries.coverage_report` then prints the report from the deployed model. """ -from .reasoning import ( +from .coverage_summary import ( BuildBudget, - CoveredPopulation, + CoverageRate, MaxNewTowers, SelectedBuildCost, - SolveStatus, TotalPopulation, - TowerLoad, - assigned, - covered, - problem, - selected, + UncoveredPopulation, + ZoneAssignment, ) from .schema import CoveragePair, DemandZone, TowerSite, model +from .site_selection import CoveredPopulation, SolveStatus, assigned, covered, problem, selected from .source import BUILD_BUDGET, DATA_DIR, MAX_NEW_TOWERS __all__ = [ @@ -40,14 +40,16 @@ "MAX_NEW_TOWERS", "BuildBudget", "CoveragePair", + "CoverageRate", "CoveredPopulation", "DemandZone", "MaxNewTowers", "SelectedBuildCost", "SolveStatus", "TotalPopulation", - "TowerLoad", "TowerSite", + "UncoveredPopulation", + "ZoneAssignment", "assigned", "covered", "model", diff --git a/cell_tower_coverage/model/coverage_summary.py b/cell_tower_coverage/model/coverage_summary.py new file mode 100644 index 00000000..7db926c1 --- /dev/null +++ b/cell_tower_coverage/model/coverage_summary.py @@ -0,0 +1,77 @@ +"""Coverage summary: the policy limits and plan totals, each tower's load and utilization, the tower +serving each covered zone, and the coverage rate and uncovered population.""" + +from relationalai.semantics import Float, Integer, String, sum +from relationalai.semantics.std import floats + +from .schema import CoveragePair, DemandZone, TowerSite, model + +# Declares the solution values the totals and loads read, and the covered population. +from .site_selection import CoveredPopulation, assigned, selected +from .source import BUILD_BUDGET, MAX_NEW_TOWERS + +# Policy limits and plan totals, which the deployed model publishes for the report. +BuildBudget = model.Relationship(f"cell tower coverage build budget is {Float:budget}") +MaxNewTowers = model.Relationship(f"cell tower coverage tower cap is {Integer:max_towers}") +TotalPopulation = model.Relationship(f"cell tower coverage total population is {Integer:population}") +SelectedBuildCost = model.Relationship(f"cell tower coverage selected build cost is {Float:cost}") +model.define( + BuildBudget(float(BUILD_BUDGET)), + MaxNewTowers(MAX_NEW_TOWERS), + TotalPopulation(sum(DemandZone, DemandZone.population)), + SelectedBuildCost( + sum(TowerSite, TowerSite.build_cost).where(TowerSite.x_selected(selected), selected > 0.5) + ), +) + +# The share of the population the plan covers (zero when there is no population) and the +# population it leaves uncovered. +CoverageRate = model.Relationship(f"cell tower coverage rate is {Float:coverage_rate}") +UncoveredPopulation = model.Relationship( + f"cell tower coverage uncovered population is {Float:uncovered_population}" +) +_population, _covered = Integer.ref(), Float.ref() +model.where(TotalPopulation(_population), CoveredPopulation(_covered), _population > 0).define( + CoverageRate(_covered / floats.float(_population)) +) +model.where(TotalPopulation(0)).define(CoverageRate(0.0)) +model.where(TotalPopulation(_population), CoveredPopulation(_covered)).define( + UncoveredPopulation(floats.float(_population) - _covered) +) + +# Each tower's load: the population of the zones assigned to it (zero for a tower with none) and +# that load as a share of its capacity (zero for a tower without capacity). They are +# relationships, not properties: a property is stored with its concept, and one computed from +# the solution on a concept the solve reads fails the deploy. +TowerSite.assigned_population = model.Relationship( + f"{TowerSite} serves assigned population {Integer:assigned_population}" +) +TowerSite.utilization = model.Relationship(f"{TowerSite} has utilization {Float:utilization}") +model.define( + TowerSite.assigned_population( + sum(CoveragePair, DemandZone.population) + .per(TowerSite) + .where( + CoveragePair.site(TowerSite), + CoveragePair.zone(DemandZone), + CoveragePair.z_assigned(assigned), + assigned > 0.5, + ) + | 0 + ) +) +model.where(TowerSite.capacity > 0).define( + TowerSite.utilization( + floats.float(TowerSite.assigned_population) / floats.float(TowerSite.capacity) + ) +) +model.where(TowerSite.capacity <= 0).define(TowerSite.utilization(0.0)) + +# The tower each covered zone is assigned to. +ZoneAssignment = model.Relationship( + f"cell tower coverage assigns zone {String:zone_id} to site {String:site_id} " + f"named {String:site_name}" +) +model.where(CoveragePair.z_assigned(assigned), assigned > 0.5, CoveragePair.site(TowerSite)).define( + ZoneAssignment(CoveragePair.zone_id, CoveragePair.site_id, TowerSite.name) +) diff --git a/cell_tower_coverage/model/reasoning.py b/cell_tower_coverage/model/site_selection.py similarity index 66% rename from cell_tower_coverage/model/reasoning.py rename to cell_tower_coverage/model/site_selection.py index 3e045b84..7e9164b0 100644 --- a/cell_tower_coverage/model/reasoning.py +++ b/cell_tower_coverage/model/site_selection.py @@ -1,6 +1,7 @@ -"""Cell tower coverage decision problem: choose sites and assign demand zones to maximize covered population.""" +"""Site selection: the decision problem that chooses tower sites and assigns demand zones to them to +maximize covered population, and its solve status and objective.""" -from relationalai.semantics import Float, Integer, String, sum +from relationalai.semantics import Float, String, sum from relationalai.semantics.reasoners.prescriptive import Problem from .schema import CoveragePair, DemandZone, TowerSite, model @@ -105,37 +106,3 @@ f"cell tower coverage covered population is {Float:covered_population}" ) model.define(SolveStatus(problem.termination_status()), CoveredPopulation(problem.objective_value())) - -# Policy limits and plan totals, which the deployed model publishes for the report. -BuildBudget = model.Relationship(f"cell tower coverage build budget is {Float:budget}") -MaxNewTowers = model.Relationship(f"cell tower coverage tower cap is {Integer:max_towers}") -TotalPopulation = model.Relationship(f"cell tower coverage total population is {Integer:population}") -SelectedBuildCost = model.Relationship(f"cell tower coverage selected build cost is {Float:cost}") -model.define( - BuildBudget(float(BUILD_BUDGET)), - MaxNewTowers(MAX_NEW_TOWERS), - TotalPopulation(sum(DemandZone, DemandZone.population)), - SelectedBuildCost( - sum(TowerSite, TowerSite.build_cost).where(TowerSite.x_selected(selected), selected > 0.5) - ), -) - -# Population each tower serves through its assigned zones. It lives on TowerLoad, not TowerSite: -# a property computed from the solution on a concept the solve reads fails the deploy. -TowerLoad = model.Concept("TowerLoad", identify_by={"site_id": String}) -TowerLoad.assigned_population = model.Property( - f"{TowerLoad} serves assigned population {Integer:assigned_population}" -) -model.define(TowerLoad.new(site_id=TowerSite.site_id)) -model.define( - TowerLoad.assigned_population( - sum(CoveragePair, DemandZone.population) - .per(TowerLoad) - .where( - CoveragePair.site_id == TowerLoad.site_id, - CoveragePair.zone(DemandZone), - CoveragePair.z_assigned(assigned), - assigned > 0.5, - ) - ) -) diff --git a/cell_tower_coverage/queries/coverage_report.py b/cell_tower_coverage/queries/coverage_report.py index 49aee7e0..b8d96693 100644 --- a/cell_tower_coverage/queries/coverage_report.py +++ b/cell_tower_coverage/queries/coverage_report.py @@ -11,20 +11,21 @@ DATA_DIR, BuildBudget, CoveragePair, + CoverageRate, CoveredPopulation, DemandZone, MaxNewTowers, SelectedBuildCost, SolveStatus, TotalPopulation, - TowerLoad, TowerSite, - assigned, + UncoveredPopulation, + ZoneAssignment, covered, model, selected, ) -from relationalai.semantics import count +from relationalai.semantics import String, count def _scalar(relationship, default=None): @@ -76,8 +77,9 @@ def _scalar(relationship, default=None): ) selected_sites_df["build_cost"] = pd.to_numeric(selected_sites_df["build_cost"]) tower_load_df = model.select( - TowerLoad.site_id.alias("site_id"), - TowerLoad.assigned_population.alias("assigned_population"), + TowerSite.site_id.alias("site_id"), + TowerSite.assigned_population.alias("assigned_population"), + TowerSite.utilization.alias("utilization"), ).to_df() zone_solution_df = ( @@ -98,17 +100,14 @@ def _scalar(relationship, default=None): ["covered", "population"], ascending=[False, False] ) + zone_id, site_id, site_name = String.ref(), String.ref(), String.ref() assignment_df = ( model.select( - CoveragePair.site_id.alias("assigned_site_id"), - TowerSite.name.alias("assigned_site"), - CoveragePair.zone_id.alias("zone_id"), - ) - .where( - CoveragePair.z_assigned(assigned), - CoveragePair.site(TowerSite), - assigned > 0.5, + site_id.alias("assigned_site_id"), + site_name.alias("assigned_site"), + zone_id.alias("zone_id"), ) + .where(ZoneAssignment(zone_id, site_id, site_name)) .to_df() ) @@ -116,15 +115,7 @@ def _scalar(relationship, default=None): zone_solution_df["assigned_site_id"] = zone_solution_df["assigned_site_id"].fillna("") zone_solution_df["assigned_site"] = zone_solution_df["assigned_site"].fillna("") - # A selected tower with no assigned zone has no published load; it serves zero people. selected_sites_df = selected_sites_df.merge(tower_load_df, on="site_id", how="left") - selected_sites_df["assigned_population"] = ( - selected_sites_df["assigned_population"].fillna(0).astype(int) - ) - capacity = selected_sites_df["capacity"] - selected_sites_df["utilization"] = ( - selected_sites_df["assigned_population"] / capacity.where(capacity > 0) - ).fillna(0.0) print("\n=== Selected Tower Sites ===") print( @@ -175,12 +166,11 @@ def _scalar(relationship, default=None): ) total_population = _scalar(TotalPopulation) - coverage_rate = covered_population / total_population if total_population else 0.0 print("\n=== Coverage Summary ===") print(f"Selected build cost: ${_scalar(SelectedBuildCost, 0):,.0f} of ${build_budget:,.0f}") print(f"Covered population: {covered_population:,.0f} of {total_population:,.0f}") - print(f"Coverage rate: {coverage_rate:.2%}") - print(f"Uncovered population: {total_population - covered_population:,.0f}") + print(f"Coverage rate: {_scalar(CoverageRate):.2%}") + print(f"Uncovered population: {_scalar(UncoveredPopulation):,.0f}") coverage_solution_csv = DATA_DIR / "coverage_solution.csv" zone_solution_df[ diff --git a/cell_tower_coverage/runbook.md b/cell_tower_coverage/runbook.md index cca7df55..41ad23c1 100644 --- a/cell_tower_coverage/runbook.md +++ b/cell_tower_coverage/runbook.md @@ -39,7 +39,7 @@ Each prompt is pasted into a fresh agent session loaded with the named `/rai-*` **Prompt:** /rai-prescriptive-problem Which sites should we build and which tower should serve each zone to cover the most people, building at most 3 towers within a $650,000 budget? Use a binary build decision per site, a binary covered decision per zone, and a binary serve decision per feasible site-zone pair. A zone counts as covered only if it's assigned to exactly one built tower, a tower can only serve zones if it's built, and the population a tower serves can't exceed its capacity. Maximize total covered population and persist the decisions to the ontology. -**Response:** OPTIMAL (HiGHS), covered population **90,000 of 102,900** (relative gap 0.0). The model has 3 binary decision families and 5 constraint families; build, cover, and serve decisions are written back as `TowerSite.x_selected`, `DemandZone.y_covered`, and `CoveragePair.z_assigned`. In `model/reasoning.py` the solve is declared with `problem.configure(...)`, so each refresh of the deployed model runs it. +**Response:** OPTIMAL (HiGHS), covered population **90,000 of 102,900** (relative gap 0.0). The model has 3 binary decision families and 5 constraint families; build, cover, and serve decisions are written back as `TowerSite.x_selected`, `DemandZone.y_covered`, and `CoveragePair.z_assigned`. In `model/site_selection.py` the solve is declared with `problem.configure(...)`, so each refresh of the deployed model runs it. ## 4. Read the build plan diff --git a/cicd_runner_allocation/README.md b/cicd_runner_allocation/README.md index f5f50fde..bc381eeb 100644 --- a/cicd_runner_allocation/README.md +++ b/cicd_runner_allocation/README.md @@ -37,7 +37,7 @@ Every merge kicks off a pipeline of build, test, and deploy jobs, and each job c ## What's included -- **Model**: three source concepts (`Runner`, `Workflow`, `Compatibility`) plus an `Assignment` decision concept, with a binary assignment variable, an assign-one-runner rule, a per-runner concurrency rule, and a cost-minimizing objective, in the `model/` package (`schema.py` declares the concepts, `source.py` loads the sample data and checks it, `reasoning.py` states one decision problem per concurrency scenario and one for the maintenance outage), which `rai models deploy --path model` deploys to your Snowflake account, where each refresh runs the solves. +- **Model**: three source concepts (`Runner`, `Workflow`, `Compatibility`) plus an `Assignment` decision concept, with a binary assignment variable, an assign-one-runner rule, a per-runner concurrency rule, and a cost-minimizing objective, in the `model/` package (`schema.py` declares the concepts, `source.py` loads the sample data and checks it, `runner_allocation.py` states one decision problem per concurrency scenario and one for the maintenance outage), which `rai models deploy --path model` deploys to your Snowflake account, where each refresh runs the solves. - **Query**: `queries/allocation_report.py`, which prints the report from the deployed model. - **Runbook**: `runbook.md` — a paste-testable walkthrough that reproduces the template step by step with the RAI skills; as important a reference as the model itself. - **Sample data**: 8 runner types, 20 workflow jobs, and their pre-computed compatibility pairs. See *Sample data* below. @@ -266,7 +266,7 @@ Use this sequence to deploy the model and query it: │ ├── __init__.py # exports of the deployed model │ ├── schema.py # concepts and properties │ ├── source.py # sample data and the outage's runner check -│ └── reasoning.py # one solve per scenario, the outage solve and its conflict +│ └── runner_allocation.py # one solve per scenario, the outage solve and its conflict ├── queries/ │ └── allocation_report.py # report from the deployed model └── data/ @@ -325,7 +325,7 @@ Each constraint's declared key gives it an entity back-pointer (`assign_one.work Any six of the seven high-CPU jobs already exceed the cap of five, so a minimal IIS needs six of them plus the `ubuntu-xlarge` concurrency rule. `in_conflict` also counts the constraint instances the solver marks as possibly in the conflict, so the stranded list can name all seven, as in the sample output above. To restore feasibility, relax one member — bring a runner back online or raise the cap. Because all seven jobs share the one survivor, lift the cap enough for all of them (or restore a runner) and redeploy to confirm; clearing a single job only resolves that one row of the conflict. -See `model/reasoning.py` and `queries/allocation_report.py` for the implementation and `runbook.md` for the skill-driven reproduction. +See `model/runner_allocation.py` and `queries/allocation_report.py` for the implementation and `runbook.md` for the skill-driven reproduction. > [!NOTE] > Conflict analysis works for mixed-integer models like this one (unlike sensitivity analysis, which needs a linear or quadratic program). It requires no objective — it diagnoses feasibility. Pass `conflict=True` to the `configure(...)` of the Problem whose infeasibility you want to explain. @@ -344,7 +344,7 @@ Focus on the first changes most users will make. - **Concurrency scenarios** — `SCENARIO_VALUES` (default `[0.5, 1.0, 1.5]`) is the list of concurrency multipliers swept; each scales every runner's `max_concurrent`. - **Per-runner caps** — change `max_concurrent` in `runners.csv` to model a different fleet size or capacity policy. -- **Solve budget** — each `problem.configure(...)` in `model/reasoning.py` uses `time_limit_sec=60`; raise it for larger fleets. +- **Solve budget** — each `problem.configure(...)` in `model/runner_allocation.py` uses `time_limit_sec=60`; raise it for larger fleets. ### Extend the model diff --git a/cicd_runner_allocation/model/__init__.py b/cicd_runner_allocation/model/__init__.py index 7dd73081..6133093b 100644 --- a/cicd_runner_allocation/model/__init__.py +++ b/cicd_runner_allocation/model/__init__.py @@ -28,7 +28,7 @@ `python -m queries.allocation_report` then prints the report from the deployed model. """ -from .reasoning import ( +from .runner_allocation import ( SCENARIO_PARAM, SCENARIO_VALUES, Assigned, diff --git a/cicd_runner_allocation/model/reasoning.py b/cicd_runner_allocation/model/runner_allocation.py similarity index 100% rename from cicd_runner_allocation/model/reasoning.py rename to cicd_runner_allocation/model/runner_allocation.py diff --git a/commercial_underwriting/README.md b/commercial_underwriting/README.md index 9212ba8e..8a9f74de 100644 --- a/commercial_underwriting/README.md +++ b/commercial_underwriting/README.md @@ -40,7 +40,7 @@ This template shows how to express that rulebook as declarative logic on a four- ## What's included - **Model**: the four-level `InsuredEntity` / `Policy` / `Location` / `Coverage` ontology, eight lower-level eligibility rules, two entity-level rollup rules (decline factors, marginal factors), and four mutually exclusive risk-tier subtype concepts — all as declarative derived Relationships. -- **Model**: the `model/` package (`schema.py` declares the concepts, `source.py` loads the sample data, `reasoning.py` states the rules and risk tiers) that `rai models deploy --path model` deploys to your Snowflake account. +- **Model**: the `model/` package (`schema.py` declares the concepts, `source.py` loads the sample data, `eligibility_flags.py` states the location and coverage flags, `underwriting_factors.py` rolls them up to each insured, and `risk_tiers.py` classifies each insured into a risk tier and totals premium by tier) that `rai models deploy --path model` deploys to your Snowflake account. - **Query**: `queries/underwriting_report.py` — prints the eligibility flags, flag matrix, tier classification, and premium by tier from the deployed model. - **Runbook**: `runbook.md` — a paste-testable walkthrough that reproduces the template step by step with the RAI skills; as important a reference as the script itself. - **Sample data**: four CSVs under `data/` — 8 insured businesses across 6 industries (`insured_entities.csv`), 8 commercial property policies one per insured (`policies.csv`), 11 scheduled locations (`locations.csv`), and 33 coverage lines, three per location (`coverages.csv`). @@ -195,7 +195,9 @@ Run these steps from a terminal: │ ├── __init__.py # exports of the deployed model │ ├── schema.py # hierarchy of concepts and properties │ ├── source.py # loads the CSVs -│ └── reasoning.py # thresholds, rules, and risk tiers +│ ├── eligibility_flags.py # location and coverage flags +│ ├── underwriting_factors.py # entity decline and marginal factors +│ └── risk_tiers.py # risk tiers and premium by tier ├── queries/ │ └── underwriting_report.py # report printed from the deployed model └── data/ @@ -232,15 +234,15 @@ For the full concept and property definitions, see `model/schema.py`; `runbook.m ## How it works -Rules run at three altitudes on the hierarchy and feed each other. A coverage is checked for insurance-to-value (ITV) adequacy; a location for fire-protection class, year-built, and occupancy class; an insured entity for industry and operating history. Each check is a declarative flag: a single `where(...).define(...)`, defined once per member for list-based checks (industry, occupancy) so PyRel unions the matches, and joining across concept levels in one clause for the ITV check. +Rules run at three altitudes on the hierarchy and feed each other. A coverage is checked for insurance-to-value (ITV) adequacy; a location for fire-protection class, year-built, and occupancy class; an insured entity for industry and operating history. Each check is a declarative flag: a single `where(...).define(...)`, defined once per member for list-based checks (industry, occupancy) so PyRel unions the matches, and joining across concept levels in one clause for the ITV check. The report's ITV percentage reads `Coverage.insurance_to_value`, the limit as a fraction of the replacement value. -Those lower-level flags then roll up. Entity-level rollup rules traverse the `InsuredEntity → Policy → Location → Coverage` chain to raise a flag on the entity if any descendant matches, and an OR-style aggregator (`has_decline_factor`, `has_marginal_factor`) unions the contributing flags via PyRel's set-union semantics. The tiers themselves are typed sub-concepts that extend `InsuredEntity`: any decline factor pushes the entity to **Decline**, marginal factors to **Non-Standard**, clean entities are **Standard**, and clean long-tenured entities with the highest fire-protection grades are **Preferred**. The tier conditions are written with explicit exclusions so the four sets partition the `InsuredEntity` set — Preferred being a tightened subset of "no decline, no marginal." Everything is declarative: lower-level rules feed entity-level rollups, which feed the tier classification, and PyRel resolves the ordering. +Those lower-level flags then roll up. Entity-level rollup rules traverse the `InsuredEntity → Policy → Location → Coverage` chain to raise a flag on the entity if any descendant matches, and an OR-style aggregator (`has_decline_factor`, `has_marginal_factor`) unions the contributing flags via PyRel's set-union semantics. The tiers themselves are typed sub-concepts that extend `InsuredEntity`: any decline factor pushes the entity to **Decline**, marginal factors to **Non-Standard**, clean entities are **Standard**, and clean long-tenured entities with the highest fire-protection grades are **Preferred**. The tier conditions are written with explicit exclusions so the four sets partition the `InsuredEntity` set — Preferred being a tightened subset of "no decline, no marginal." Each insured's tier label (`InsuredEntity.tier`) and each tier's insured count and premium (`TierPremium`) are rules too, so the report only formats them. Everything is declarative: lower-level rules feed entity-level rollups, which feed the tier classification, and PyRel resolves the ordering. ```text InsuredEntity -> Policy -> Location -> Coverage ``` -See `model/reasoning.py` for the implementation, `queries/underwriting_report.py` for the report, and `runbook.md` to reproduce it step by step with the RAI skills. +See `model/eligibility_flags.py`, `model/underwriting_factors.py`, and `model/risk_tiers.py` for the implementation, `queries/underwriting_report.py` for the report, and `runbook.md` to reproduce it step by step with the RAI skills. ## Customize this template @@ -250,19 +252,19 @@ Replace the four CSVs with your own underwriting submissions, keeping the header ### Tune parameters -All thresholds are at the top of `model/reasoning.py` under `# Configure inputs`: +Each threshold is at the top of the module that uses it, under `# Configure inputs`: -| Parameter | Default | Effect | -|---|---|---| -| `MIN_YEARS_IN_BUSINESS` | 3 | Below this → decline | -| `MAX_FP_CLASS_FOR_ELIGIBILITY` | 6 | Above this → decline | -| `MIN_YEAR_BUILT` | 1950 | Older → decline | -| `ITV_THRESHOLD` | 0.80 | Building coverage limit must reach this fraction of replacement value | -| `RESTRICTED_INDUSTRIES` | tuple | Industries that decline outright | -| `MARGINAL_INDUSTRIES` | tuple | Industries that flag the entity as marginal but acceptable | -| `HIGH_RISK_OCCUPANCIES` | tuple | Occupancy classes that flag the location as marginal | -| `PREFERRED_MIN_YEARS` | 15 | Years-in-business floor for the Preferred tier | -| `PREFERRED_MAX_FP_CLASS` | 3 | All locations must be at this FP class or better | +| Parameter | Module | Default | Effect | +|---|---|---|---| +| `MIN_YEARS_IN_BUSINESS` | `underwriting_factors.py` | 3 | Below this → decline | +| `MAX_FP_CLASS_FOR_ELIGIBILITY` | `eligibility_flags.py` | 6 | Above this → decline | +| `MIN_YEAR_BUILT` | `eligibility_flags.py` | 1950 | Older → decline | +| `ITV_THRESHOLD` | `eligibility_flags.py` | 0.80 | Building coverage limit must reach this fraction of replacement value | +| `RESTRICTED_INDUSTRIES` | `underwriting_factors.py` | tuple | Industries that decline outright | +| `MARGINAL_INDUSTRIES` | `underwriting_factors.py` | tuple | Industries that flag the entity as marginal but acceptable | +| `HIGH_RISK_OCCUPANCIES` | `eligibility_flags.py` | tuple | Occupancy classes that flag the location as marginal | +| `PREFERRED_MIN_YEARS` | `risk_tiers.py` | 15 | Years-in-business floor for the Preferred tier | +| `PREFERRED_MAX_FP_CLASS` | `risk_tiers.py` | 3 | All locations must be at this FP class or better | ### Extend the model @@ -275,7 +277,7 @@ All thresholds are at the top of `model/reasoning.py` under `# Configure inputs` - **Point at Snowflake tables.** Swap the CSV `model.data(...)` calls for `model.Table(...)` references to your submission tables; the ontology, rules, and tier classification are unchanged. Size the RAI engine to the submission volume — rules-based classification is lightweight, so a small engine handles large books. - **Schedule triage runs.** With table-backed sources, refresh the deployed model so every new account is scored as it arrives: set `interval_s` on the `standard` schedule in `raiconfig.yaml` for a periodic refresh, or call `.COMMERCIAL_UNDERWRITING_META._INTERNAL_REFRESH_MODEL('standard', NULL)` from your submission-intake pipeline. Redeploy only when the rules or declarations change. Persist the per-entity tier and flag matrix for downstream underwriting review. -- **Pin dependencies for reproducibility.** Keep the `relationalai` version pinned in `pyproject.toml` so rule outcomes stay stable across runs, and version-control your threshold constants (top of `model/reasoning.py`) as auditable underwriting parameters. +- **Pin dependencies for reproducibility.** Keep the `relationalai` version pinned in `pyproject.toml` so rule outcomes stay stable across runs, and version-control your threshold constants (top of each module in `model/`) as auditable underwriting parameters. ## Troubleshooting diff --git a/commercial_underwriting/model/__init__.py b/commercial_underwriting/model/__init__.py index 0ec3146c..ecf3c10b 100644 --- a/commercial_underwriting/model/__init__.py +++ b/commercial_underwriting/model/__init__.py @@ -6,15 +6,17 @@ InsuredEntity -> Policy -> Location -> Coverage - Load sample CSVs describing insured entities, policies, locations, and - coverages. + coverages (`source.py`). - Define declarative rules as derived Relationships using `define()` + `where()`: - - Eligibility flags at the entity level (restricted industry, insufficient - history) and the location level (old construction, poor fire protection, - high-risk occupancy). - - Building-coverage adequacy flag (insurance-to-value < 80%). -- Roll those flags up into entity-level decline and marginal indicators. + - Eligibility flags at the location level (old construction, poor fire + protection, high-risk occupancy) and the building-coverage adequacy flag + (insurance-to-value < 80%) (`eligibility_flags.py`). + - Entity-level flags (restricted industry, insufficient history) and the + roll-up of every flag into entity-level decline and marginal indicators + (`underwriting_factors.py`). - Classify each insured entity into a risk tier (Decline / NonStandard / - Standard / Preferred) using mutually exclusive subtype concepts. + Standard / Preferred) using mutually exclusive subtype concepts, label it, + and total the premium per tier (`risk_tiers.py`). The whole pipeline is declarative — there are no procedural rule chains. PyRel resolves dependencies automatically. @@ -25,14 +27,13 @@ queries.underwriting_report` then prints the report from the deployed model. """ -from .reasoning import ( - ITV_THRESHOLD, - MAX_FP_CLASS_FOR_ELIGIBILITY, - MIN_YEAR_BUILT, +from .eligibility_flags import ITV_THRESHOLD, MAX_FP_CLASS_FOR_ELIGIBILITY, MIN_YEAR_BUILT +from .risk_tiers import ( RiskTier_Decline, RiskTier_NonStandard, RiskTier_Preferred, RiskTier_Standard, + TierPremium, ) from .schema import Coverage, InsuredEntity, Location, Policy, model from .source import DATA_DIR @@ -50,5 +51,6 @@ "RiskTier_NonStandard", "RiskTier_Preferred", "RiskTier_Standard", + "TierPremium", "model", ] diff --git a/commercial_underwriting/model/eligibility_flags.py b/commercial_underwriting/model/eligibility_flags.py new file mode 100644 index 00000000..1ab53a33 --- /dev/null +++ b/commercial_underwriting/model/eligibility_flags.py @@ -0,0 +1,65 @@ +"""Location- and coverage-level eligibility flags: fire protection, construction age, occupancy, +and insurance-to-value adequacy of building coverages.""" + +from relationalai.semantics import Float + +from .schema import Coverage, Location, model + +# -------------------------------------------------- +# Configure inputs +# -------------------------------------------------- + +# Eligibility thresholds (typical commercial-lines underwriting guardrails). +MAX_FP_CLASS_FOR_ELIGIBILITY = 6 # ISO Public Protection Class 1=best, 10=worst +MIN_YEAR_BUILT = 1950 # construction older than this -> decline +ITV_THRESHOLD = 0.80 # building coverage limit must reach 80% of replacement value + +HIGH_RISK_OCCUPANCIES = ("GAS_STATION", "CANNABIS_RETAIL", "RESTAURANT_FAST_FOOD", "HABITATIONAL") + +# -------------------------------------------------- +# Stage 1: location- and coverage-level eligibility flags +# -------------------------------------------------- + +# Rule (eligibility flag): a location has poor fire protection if its ISO +# Public Protection Class exceeds the eligibility ceiling. +Location.has_poor_fire_protection = model.Relationship( + f"{Location} has poor fire protection" +) +model.where( + Location.fire_protection_class > MAX_FP_CLASS_FOR_ELIGIBILITY, +).define(Location.has_poor_fire_protection()) + +# Rule (eligibility flag): a location has old construction if its build year +# predates the eligibility floor. +Location.has_old_construction = model.Relationship(f"{Location} has old construction") +model.where( + Location.year_built < MIN_YEAR_BUILT, +).define(Location.has_old_construction()) + +# Rule (marginal flag): a location has a high-risk occupancy class. +Location.has_high_risk_occupancy = model.Relationship( + f"{Location} has high-risk occupancy" +) +for occ in HIGH_RISK_OCCUPANCIES: + model.where(Location.occupancy_class == occ).define( + Location.has_high_risk_occupancy() + ) + +# Rule (marginal flag): a building coverage is underinsured if its limit is +# below the insurance-to-value (ITV) threshold of the location's replacement +# value. Only applies to BUILDING coverages. +Coverage.is_underinsured = model.Relationship(f"{Coverage} is underinsured") +model.where( + Coverage.coverage_type == "BUILDING", + Coverage.coverage_limit < ITV_THRESHOLD * Coverage.location.replacement_value, +).define(Coverage.is_underinsured()) + +# Insurance to value (ITV) of a BUILDING coverage, as the report shows it: its +# limit as a fraction of the location's replacement value. +Coverage.insurance_to_value = model.Property(f"{Coverage} has {Float:insurance_to_value}") +model.where( + Coverage.coverage_type == "BUILDING", + Coverage.location.replacement_value > 0, +).define( + Coverage.insurance_to_value(Coverage.coverage_limit / Coverage.location.replacement_value) +) diff --git a/commercial_underwriting/model/reasoning.py b/commercial_underwriting/model/reasoning.py deleted file mode 100644 index 36ca7425..00000000 --- a/commercial_underwriting/model/reasoning.py +++ /dev/null @@ -1,211 +0,0 @@ -"""Underwriting rules: eligibility flags, decline and marginal rollups, and risk tiers.""" - -from .schema import Coverage, InsuredEntity, Location, Policy, model - -# -------------------------------------------------- -# Configure inputs -# -------------------------------------------------- - -# Eligibility thresholds (typical commercial-lines underwriting guardrails). -MIN_YEARS_IN_BUSINESS = 3 # below this -> insufficient history -> decline -MAX_FP_CLASS_FOR_ELIGIBILITY = 6 # ISO Public Protection Class 1=best, 10=worst -MIN_YEAR_BUILT = 1950 # construction older than this -> decline -ITV_THRESHOLD = 0.80 # building coverage limit must reach 80% of replacement value - -# Industry classifications. -RESTRICTED_INDUSTRIES = ("CANNABIS", "NUCLEAR", "EXPLOSIVES", "ASBESTOS_REMEDIATION") -MARGINAL_INDUSTRIES = ("MANUFACTURING_HEAVY", "AUTO_REPAIR") -HIGH_RISK_OCCUPANCIES = ("GAS_STATION", "CANNABIS_RETAIL", "RESTAURANT_FAST_FOOD", "HABITATIONAL") - -# Preferred-tier criteria. -PREFERRED_MIN_YEARS = 15 # must have at least this many years in business -PREFERRED_MAX_FP_CLASS = 3 # all locations must be at FP class 3 or better - -# -------------------------------------------------- -# Stage 1: location- and coverage-level eligibility flags -# -------------------------------------------------- - -# Rule (eligibility flag): a location has poor fire protection if its ISO -# Public Protection Class exceeds the eligibility ceiling. -Location.has_poor_fire_protection = model.Relationship( - f"{Location} has poor fire protection" -) -model.where( - Location.fire_protection_class > MAX_FP_CLASS_FOR_ELIGIBILITY, -).define(Location.has_poor_fire_protection()) - -# Rule (eligibility flag): a location has old construction if its build year -# predates the eligibility floor. -Location.has_old_construction = model.Relationship(f"{Location} has old construction") -model.where( - Location.year_built < MIN_YEAR_BUILT, -).define(Location.has_old_construction()) - -# Rule (marginal flag): a location has a high-risk occupancy class. -Location.has_high_risk_occupancy = model.Relationship( - f"{Location} has high-risk occupancy" -) -for occ in HIGH_RISK_OCCUPANCIES: - model.where(Location.occupancy_class == occ).define( - Location.has_high_risk_occupancy() - ) - -# Rule (marginal flag): a building coverage is underinsured if its limit is -# below the insurance-to-value (ITV) threshold of the location's replacement -# value. Only applies to BUILDING coverages. -Coverage.is_underinsured = model.Relationship(f"{Coverage} is underinsured") -model.where( - Coverage.coverage_type == "BUILDING", - Coverage.coverage_limit < ITV_THRESHOLD * Coverage.location.replacement_value, -).define(Coverage.is_underinsured()) - -# -------------------------------------------------- -# Stage 2: roll flags up to insured-entity decline and marginal indicators -# -------------------------------------------------- - -# Rule (decline factor): restricted industry. -InsuredEntity.has_restricted_industry = model.Relationship( - f"{InsuredEntity} has restricted industry" -) -for industry in RESTRICTED_INDUSTRIES: - model.where(InsuredEntity.industry_code == industry).define( - InsuredEntity.has_restricted_industry() - ) - -# Rule (decline factor): insufficient operating history. -InsuredEntity.has_insufficient_history = model.Relationship( - f"{InsuredEntity} has insufficient history" -) -model.where( - InsuredEntity.years_in_business < MIN_YEARS_IN_BUSINESS, -).define(InsuredEntity.has_insufficient_history()) - -# Rule (decline factor): any scheduled location has poor fire protection. -InsuredEntity.has_unprotected_location = model.Relationship( - f"{InsuredEntity} has unprotected location" -) -model.where( - Policy.insured_entity(InsuredEntity), - Location.policy(Policy), - Location.has_poor_fire_protection(), -).define(InsuredEntity.has_unprotected_location()) - -# Rule (decline factor): any scheduled location has old construction. -InsuredEntity.has_old_construction_location = model.Relationship( - f"{InsuredEntity} has old construction location" -) -model.where( - Policy.insured_entity(InsuredEntity), - Location.policy(Policy), - Location.has_old_construction(), -).define(InsuredEntity.has_old_construction_location()) - -# Rule (rollup): any decline factor. -InsuredEntity.has_decline_factor = model.Relationship( - f"{InsuredEntity} has any decline factor" -) -model.where(InsuredEntity.has_restricted_industry()).define( - InsuredEntity.has_decline_factor() -) -model.where(InsuredEntity.has_insufficient_history()).define( - InsuredEntity.has_decline_factor() -) -model.where(InsuredEntity.has_unprotected_location()).define( - InsuredEntity.has_decline_factor() -) -model.where(InsuredEntity.has_old_construction_location()).define( - InsuredEntity.has_decline_factor() -) - -# Rule (marginal factor): industry on the marginal-but-acceptable list. -InsuredEntity.has_marginal_industry = model.Relationship( - f"{InsuredEntity} has marginal industry" -) -for industry in MARGINAL_INDUSTRIES: - model.where(InsuredEntity.industry_code == industry).define( - InsuredEntity.has_marginal_industry() - ) - -# Rule (marginal factor): any scheduled location has a high-risk occupancy. -InsuredEntity.has_high_risk_occupancy_location = model.Relationship( - f"{InsuredEntity} has high-risk occupancy location" -) -model.where( - Policy.insured_entity(InsuredEntity), - Location.policy(Policy), - Location.has_high_risk_occupancy(), -).define(InsuredEntity.has_high_risk_occupancy_location()) - -# Rule (marginal factor): any building coverage is underinsured. -InsuredEntity.has_underinsured_coverage = model.Relationship( - f"{InsuredEntity} has underinsured coverage" -) -model.where( - Policy.insured_entity(InsuredEntity), - Location.policy(Policy), - Coverage.location(Location), - Coverage.is_underinsured(), -).define(InsuredEntity.has_underinsured_coverage()) - -# Rule (rollup): any marginal factor. -InsuredEntity.has_marginal_factor = model.Relationship( - f"{InsuredEntity} has any marginal factor" -) -model.where(InsuredEntity.has_marginal_industry()).define( - InsuredEntity.has_marginal_factor() -) -model.where(InsuredEntity.has_high_risk_occupancy_location()).define( - InsuredEntity.has_marginal_factor() -) -model.where(InsuredEntity.has_underinsured_coverage()).define( - InsuredEntity.has_marginal_factor() -) - -# -------------------------------------------------- -# Stage 3: risk-tier classification (mutually exclusive subtypes) -# -------------------------------------------------- -# An InsuredEntity always falls into exactly one of these four tiers. -# Conditions are written so the four sets partition the InsuredEntity set. - -RiskTier_Decline = model.Concept("RiskTier_Decline", extends=[InsuredEntity]) -RiskTier_NonStandard = model.Concept("RiskTier_NonStandard", extends=[InsuredEntity]) -RiskTier_Standard = model.Concept("RiskTier_Standard", extends=[InsuredEntity]) -RiskTier_Preferred = model.Concept("RiskTier_Preferred", extends=[InsuredEntity]) - -# Decline: any decline factor. -model.where( - InsuredEntity.has_decline_factor(), -).define(RiskTier_Decline(InsuredEntity)) - -# NonStandard: no decline factor AND has at least one marginal factor. -model.where( - model.not_(InsuredEntity.has_decline_factor()), - InsuredEntity.has_marginal_factor(), -).define(RiskTier_NonStandard(InsuredEntity)) - -# Preferred eligibility: no decline factor, no marginal factor, long history, -# and every scheduled location at FP class <= PREFERRED_MAX_FP_CLASS. -# Encoded as: NOT (entity has any location whose FP class exceeds the cap). -InsuredEntity.has_non_preferred_location = model.Relationship( - f"{InsuredEntity} has non-preferred location" -) -model.where( - Policy.insured_entity(InsuredEntity), - Location.policy(Policy), - Location.fire_protection_class > PREFERRED_MAX_FP_CLASS, -).define(InsuredEntity.has_non_preferred_location()) - -# Preferred: meets all preferred criteria. -model.where( - model.not_(InsuredEntity.has_decline_factor()), - model.not_(InsuredEntity.has_marginal_factor()), - model.not_(InsuredEntity.has_non_preferred_location()), - InsuredEntity.years_in_business >= PREFERRED_MIN_YEARS, -).define(RiskTier_Preferred(InsuredEntity)) - -# Standard: not Decline, not NonStandard, not Preferred (the residual). -model.where( - model.not_(InsuredEntity.has_decline_factor()), - model.not_(InsuredEntity.has_marginal_factor()), - model.not_(RiskTier_Preferred(InsuredEntity)), -).define(RiskTier_Standard(InsuredEntity)) diff --git a/commercial_underwriting/model/risk_tiers.py b/commercial_underwriting/model/risk_tiers.py new file mode 100644 index 00000000..f10c12f4 --- /dev/null +++ b/commercial_underwriting/model/risk_tiers.py @@ -0,0 +1,114 @@ +"""Risk tiers: the four mutually exclusive tier subtypes of an insured, each insured's tier label, +and the premium each tier carries.""" + +from relationalai.semantics import Float, Integer, String +from relationalai.semantics.std import aggregates as aggs + +# Declares the decline and marginal rollups the tiers read. +from . import underwriting_factors # noqa: F401 +from .schema import InsuredEntity, Location, Policy, model + +# -------------------------------------------------- +# Configure inputs +# -------------------------------------------------- + +# Preferred-tier criteria. +PREFERRED_MIN_YEARS = 15 # must have at least this many years in business +PREFERRED_MAX_FP_CLASS = 3 # all locations must be at FP class 3 or better + +# -------------------------------------------------- +# Stage 3: risk-tier classification (mutually exclusive subtypes) +# -------------------------------------------------- +# An InsuredEntity always falls into exactly one of these four tiers. +# Conditions are written so the four sets partition the InsuredEntity set. + +RiskTier_Decline = model.Concept("RiskTier_Decline", extends=[InsuredEntity]) +RiskTier_NonStandard = model.Concept("RiskTier_NonStandard", extends=[InsuredEntity]) +RiskTier_Standard = model.Concept("RiskTier_Standard", extends=[InsuredEntity]) +RiskTier_Preferred = model.Concept("RiskTier_Preferred", extends=[InsuredEntity]) + +# Decline: any decline factor. +model.where( + InsuredEntity.has_decline_factor(), +).define(RiskTier_Decline(InsuredEntity)) + +# NonStandard: no decline factor AND has at least one marginal factor. +model.where( + model.not_(InsuredEntity.has_decline_factor()), + InsuredEntity.has_marginal_factor(), +).define(RiskTier_NonStandard(InsuredEntity)) + +# Preferred eligibility: no decline factor, no marginal factor, long history, +# and every scheduled location at FP class <= PREFERRED_MAX_FP_CLASS. +# Encoded as: NOT (entity has any location whose FP class exceeds the cap). +InsuredEntity.has_non_preferred_location = model.Relationship( + f"{InsuredEntity} has non-preferred location" +) +model.where( + Policy.insured_entity(InsuredEntity), + Location.policy(Policy), + Location.fire_protection_class > PREFERRED_MAX_FP_CLASS, +).define(InsuredEntity.has_non_preferred_location()) + +# Preferred: meets all preferred criteria. +model.where( + model.not_(InsuredEntity.has_decline_factor()), + model.not_(InsuredEntity.has_marginal_factor()), + model.not_(InsuredEntity.has_non_preferred_location()), + InsuredEntity.years_in_business >= PREFERRED_MIN_YEARS, +).define(RiskTier_Preferred(InsuredEntity)) + +# Standard: not Decline, not NonStandard, not Preferred (the residual). +model.where( + model.not_(InsuredEntity.has_decline_factor()), + model.not_(InsuredEntity.has_marginal_factor()), + model.not_(RiskTier_Preferred(InsuredEntity)), +).define(RiskTier_Standard(InsuredEntity)) + +# Tier label: the first tier, in this priority order, that the insured is in; +# an insured in no tier is UNCLASSIFIED. +TIER_LABELS = ( + (RiskTier_Decline, "DECLINE"), + (RiskTier_NonStandard, "NON-STANDARD"), + (RiskTier_Preferred, "PREFERRED"), + (RiskTier_Standard, "STANDARD"), +) +InsuredEntity.tier = model.Property(f"{InsuredEntity} has risk tier {String:tier}") +for priority, (tier, label) in enumerate(TIER_LABELS): + model.where( + tier(InsuredEntity), + *(model.not_(higher(InsuredEntity)) for higher, _ in TIER_LABELS[:priority]), + ).define(InsuredEntity.tier(label)) +model.where( + *(model.not_(tier(InsuredEntity)) for tier, _ in TIER_LABELS), +).define(InsuredEntity.tier("UNCLASSIFIED")) + +# -------------------------------------------------- +# Premium by tier +# -------------------------------------------------- + +# Premium per insured: the sum of its policies' premiums, zero without a policy. +InsuredEntity.premium = model.Property(f"{InsuredEntity} has total premium {Float:premium}") +model.define(InsuredEntity.premium( + aggs.sum(Policy, Policy.total_premium) + .per(InsuredEntity) + .where(Policy.insured_entity(InsuredEntity)) + | 0.0 +)) + +# Each tier's insured count, total premium, and mean premium per insured. +TierPremium = model.Concept("TierPremium", identify_by={"tier": String}) +TierPremium.n_insureds = model.Property(f"{TierPremium} has {Integer:n_insureds} insureds") +TierPremium.total_premium = model.Property(f"{TierPremium} has {Float:total_premium}") +TierPremium.mean_premium = model.Property(f"{TierPremium} has {Float:mean_premium}") +model.define(TierPremium.new(tier=InsuredEntity.tier)) +_in_tier = InsuredEntity.tier == TierPremium.tier +model.define( + TierPremium.n_insureds(aggs.count(InsuredEntity).per(TierPremium).where(_in_tier)), + TierPremium.total_premium( + aggs.sum(InsuredEntity, InsuredEntity.premium).per(TierPremium).where(_in_tier) + ), + TierPremium.mean_premium( + aggs.avg(InsuredEntity, InsuredEntity.premium).per(TierPremium).where(_in_tier) + ), +) diff --git a/commercial_underwriting/model/underwriting_factors.py b/commercial_underwriting/model/underwriting_factors.py new file mode 100644 index 00000000..3d09c8fe --- /dev/null +++ b/commercial_underwriting/model/underwriting_factors.py @@ -0,0 +1,118 @@ +"""Insured-entity underwriting factors: entity-level decline and marginal flags, the location and +coverage flags rolled up to the insured, and the any-decline and any-marginal rollups.""" + +# Declares the location and coverage flags rolled up here. +from . import eligibility_flags # noqa: F401 +from .schema import Coverage, InsuredEntity, Location, Policy, model + +# -------------------------------------------------- +# Configure inputs +# -------------------------------------------------- + +MIN_YEARS_IN_BUSINESS = 3 # below this -> insufficient history -> decline + +# Industry classifications. +RESTRICTED_INDUSTRIES = ("CANNABIS", "NUCLEAR", "EXPLOSIVES", "ASBESTOS_REMEDIATION") +MARGINAL_INDUSTRIES = ("MANUFACTURING_HEAVY", "AUTO_REPAIR") + +# -------------------------------------------------- +# Stage 2: roll flags up to insured-entity decline and marginal indicators +# -------------------------------------------------- + +# Rule (decline factor): restricted industry. +InsuredEntity.has_restricted_industry = model.Relationship( + f"{InsuredEntity} has restricted industry" +) +for industry in RESTRICTED_INDUSTRIES: + model.where(InsuredEntity.industry_code == industry).define( + InsuredEntity.has_restricted_industry() + ) + +# Rule (decline factor): insufficient operating history. +InsuredEntity.has_insufficient_history = model.Relationship( + f"{InsuredEntity} has insufficient history" +) +model.where( + InsuredEntity.years_in_business < MIN_YEARS_IN_BUSINESS, +).define(InsuredEntity.has_insufficient_history()) + +# Rule (decline factor): any scheduled location has poor fire protection. +InsuredEntity.has_unprotected_location = model.Relationship( + f"{InsuredEntity} has unprotected location" +) +model.where( + Policy.insured_entity(InsuredEntity), + Location.policy(Policy), + Location.has_poor_fire_protection(), +).define(InsuredEntity.has_unprotected_location()) + +# Rule (decline factor): any scheduled location has old construction. +InsuredEntity.has_old_construction_location = model.Relationship( + f"{InsuredEntity} has old construction location" +) +model.where( + Policy.insured_entity(InsuredEntity), + Location.policy(Policy), + Location.has_old_construction(), +).define(InsuredEntity.has_old_construction_location()) + +# Rule (rollup): any decline factor. +InsuredEntity.has_decline_factor = model.Relationship( + f"{InsuredEntity} has any decline factor" +) +model.where(InsuredEntity.has_restricted_industry()).define( + InsuredEntity.has_decline_factor() +) +model.where(InsuredEntity.has_insufficient_history()).define( + InsuredEntity.has_decline_factor() +) +model.where(InsuredEntity.has_unprotected_location()).define( + InsuredEntity.has_decline_factor() +) +model.where(InsuredEntity.has_old_construction_location()).define( + InsuredEntity.has_decline_factor() +) + +# Rule (marginal factor): industry on the marginal-but-acceptable list. +InsuredEntity.has_marginal_industry = model.Relationship( + f"{InsuredEntity} has marginal industry" +) +for industry in MARGINAL_INDUSTRIES: + model.where(InsuredEntity.industry_code == industry).define( + InsuredEntity.has_marginal_industry() + ) + +# Rule (marginal factor): any scheduled location has a high-risk occupancy. +InsuredEntity.has_high_risk_occupancy_location = model.Relationship( + f"{InsuredEntity} has high-risk occupancy location" +) +model.where( + Policy.insured_entity(InsuredEntity), + Location.policy(Policy), + Location.has_high_risk_occupancy(), +).define(InsuredEntity.has_high_risk_occupancy_location()) + +# Rule (marginal factor): any building coverage is underinsured. +InsuredEntity.has_underinsured_coverage = model.Relationship( + f"{InsuredEntity} has underinsured coverage" +) +model.where( + Policy.insured_entity(InsuredEntity), + Location.policy(Policy), + Coverage.location(Location), + Coverage.is_underinsured(), +).define(InsuredEntity.has_underinsured_coverage()) + +# Rule (rollup): any marginal factor. +InsuredEntity.has_marginal_factor = model.Relationship( + f"{InsuredEntity} has any marginal factor" +) +model.where(InsuredEntity.has_marginal_industry()).define( + InsuredEntity.has_marginal_factor() +) +model.where(InsuredEntity.has_high_risk_occupancy_location()).define( + InsuredEntity.has_marginal_factor() +) +model.where(InsuredEntity.has_underinsured_coverage()).define( + InsuredEntity.has_marginal_factor() +) diff --git a/commercial_underwriting/queries/underwriting_report.py b/commercial_underwriting/queries/underwriting_report.py index d38a4c8b..9d413f07 100644 --- a/commercial_underwriting/queries/underwriting_report.py +++ b/commercial_underwriting/queries/underwriting_report.py @@ -15,14 +15,14 @@ Coverage, InsuredEntity, Location, - Policy, RiskTier_Decline, RiskTier_NonStandard, RiskTier_Preferred, RiskTier_Standard, + TierPremium, model, ) -from relationalai.semantics import sum +from pandas import Index if __name__ == "__main__": print("=" * 70) @@ -61,10 +61,9 @@ Coverage.location.address.alias("location_address"), Coverage.coverage_limit.alias("limit"), Coverage.location.replacement_value.alias("replacement_value"), + Coverage.insurance_to_value.alias("itv"), ).to_df() - underinsured["itv_pct"] = ( - underinsured["limit"] / underinsured["replacement_value"] * 100 - ).round(1) + underinsured["itv_pct"] = (underinsured.pop("itv") * 100).round(1) print(f"\nUnderinsured BUILDING coverages (ITV < {int(ITV_THRESHOLD * 100)}%): {len(underinsured)}") if not underinsured.empty: print(underinsured.to_string(index=False)) @@ -122,27 +121,29 @@ def query_flag(rel): model.where(RiskTier_Standard(InsuredEntity)).select(InsuredEntity.id.alias("id")).to_df()["id"] ) - - def classify(entity_id): - if entity_id in decline_ids: - return "DECLINE" - if entity_id in nonstandard_ids: - return "NON-STANDARD" - if entity_id in preferred_ids: - return "PREFERRED" - if entity_id in standard_ids: - return "STANDARD" - return "UNCLASSIFIED" - - - tier_df = ie_df[["id", "name", "industry", "years"]].copy() - tier_df["tier"] = tier_df["id"].apply(classify) + tier_labels = model.select( + InsuredEntity.id.alias("id"), InsuredEntity.tier.alias("tier") + ).to_df() + tier_df = ie_df[["id", "name", "industry", "years"]].merge(tier_labels, on="id", how="left") print("\nFinal risk tiers:") print(tier_df.to_string(index=False)) + # Per-tier insured counts and premium, as the model publishes them. + tier_premium = model.select( + TierPremium.tier.alias("tier"), + TierPremium.n_insureds.alias("count"), + TierPremium.total_premium.alias("sum"), + TierPremium.mean_premium.alias("mean"), + ).to_df().set_index("tier").sort_index() + # Sanity check: every entity must land in exactly one tier (mutual exclusivity). + # Most insureds first; equal counts keep the order the tiers first appear above. print("\nTier counts:") - print(tier_df["tier"].value_counts().to_string()) + first_seen = Index(tier_df["tier"].drop_duplicates(), name="tier") + print( + tier_premium["count"].reindex(first_seen).sort_values(ascending=False, kind="stable") + .to_string() + ) unclassified = tier_df[tier_df["tier"] == "UNCLASSIFIED"] if not unclassified.empty: @@ -154,12 +155,7 @@ def classify(entity_id): if overlap: print(f"\nWARNING: {len(overlap)} entities classified into multiple tiers: {sorted(overlap)}") - # Aggregate premium by tier — the underwriting business view. Premium is per insured, - # summed over its policies; an insured without a policy counts in its tier with zero premium. - premium_df = model.where(Policy.insured_entity(InsuredEntity)).select( - InsuredEntity.id.alias("id"), - sum(Policy, Policy.total_premium).per(InsuredEntity).alias("premium"), - ).to_df() - tier_df = tier_df.merge(premium_df, on="id", how="left").fillna({"premium": 0.0}) + # Premium by tier — the underwriting business view. Premium is per insured, summed + # over its policies; an insured without a policy counts in its tier with zero premium. print("\nPremium by tier:") - print(tier_df.groupby("tier")["premium"].agg(["count", "sum", "mean"]).to_string()) + print(tier_premium.to_string()) diff --git a/commercial_underwriting/runbook.md b/commercial_underwriting/runbook.md index 028fbd66..9d21dd30 100644 --- a/commercial_underwriting/runbook.md +++ b/commercial_underwriting/runbook.md @@ -34,7 +34,7 @@ Each prompt is pasted into a fresh agent session loaded with the named `/rai-*` **Prompt:** /rai-pyrel Encode the underwriting guardrails as layered flags. At the location level: poor fire protection (fire protection class above 6), old construction (built before 1950), high-risk occupancy (gas station, cannabis retail, fast-food, or habitational). At the coverage level: underinsured (a building coverage limit below 80% of the location's replacement value). Roll these up to each insured: a **decline factor** is a restricted industry (cannabis, nuclear, explosives, or asbestos remediation), fewer than 3 years in business, or any unprotected/old-construction location; a **marginal factor** is a marginal industry (heavy manufacturing or auto repair), a high-risk-occupancy location, or an underinsured coverage. Then classify each insured into exactly one risk tier: **Decline** if it has any decline factor; otherwise **Non-Standard** if it has any marginal factor; otherwise **Preferred** if it's well-established (15+ years) with every location well-protected; otherwise **Standard**. How many insured entities fall in each tier, and what premium does each tier represent? -**Response:** Authors the location flags (`has_poor_fire_protection`, `has_old_construction`, `has_high_risk_occupancy`), the coverage flag (`is_underinsured`), the entity rollups (`has_decline_factor`, `has_marginal_factor`), and four mutually-exclusive risk-tier subtype concepts. The rules are declarative, so the reasoner resolves their dependency order automatically and every insured lands in exactly one tier. The 8 insureds partition cleanly: **3 Decline** (a cannabis business, one under 3 years old, one with pre-1950 construction), **3 Non-Standard** (marginal industries or a high-risk-occupancy/underinsured location), **1 Standard**, and **1 Preferred** (15+ years, every location well-protected). Premium concentrates in Non-Standard (~$236k across 3) versus Decline (~$150k) — so the book's exposure is mostly in the marginal tier, exactly the segment underwriting should price and monitor most closely. +**Response:** Authors the location flags (`has_poor_fire_protection`, `has_old_construction`, `has_high_risk_occupancy`), the coverage flag (`is_underinsured`), the entity rollups (`has_decline_factor`, `has_marginal_factor`), four mutually-exclusive risk-tier subtype concepts, each insured's tier label, and the insured count and premium of each tier. The rules are declarative, so the reasoner resolves their dependency order automatically and every insured lands in exactly one tier. The 8 insureds partition cleanly: **3 Decline** (a cannabis business, one under 3 years old, one with pre-1950 construction), **3 Non-Standard** (marginal industries or a high-risk-occupancy/underinsured location), **1 Standard**, and **1 Preferred** (15+ years, every location well-protected). Premium concentrates in Non-Standard (~$236k across 3) versus Decline (~$150k) — so the book's exposure is mostly in the marginal tier, exactly the segment underwriting should price and monitor most closely. ## Data diff --git a/cybersecurity-attack-paths/README.md b/cybersecurity-attack-paths/README.md index c9bfb977..ebf205db 100644 --- a/cybersecurity-attack-paths/README.md +++ b/cybersecurity-attack-paths/README.md @@ -39,7 +39,7 @@ This template enumerates multi-step attack paths across an enterprise asset grap ## What's included -- **Model**: the `model/` package (`schema.py` declares the concepts, `source.py` loads the sample data, `reasoning.py` states the path patterns and rules) — the asset graph, technique edges, path patterns, and rules that `rai models deploy --path model` deploys to your Snowflake account. +- **Model**: the `model/` package (`schema.py` declares the concepts, `source.py` loads the sample data, `kill_chains.py` states the kill-chain paths, their exposure and remediation priority, and the on-attack-path flag, and `entry_to_target_routes.py` states the point query's routes) — the asset graph, technique edges, path patterns, and rules that `rai models deploy --path model` deploys to your Snowflake account. - **Query**: `queries/attack_path_report.py` — prints the kill-chains, point-query routes, exposure ranking, and flagged assets from the deployed model. - **Runbook**: `runbook.md` — a paste-testable walkthrough that reproduces the template step by step with the RAI skills; as important a reference as the script itself. - **Data**: `data/assets.csv` (12 assets) and `data/attack_steps.csv` (16 technique-tagged edges) @@ -157,8 +157,9 @@ cybersecurity-attack-paths/ ├── model/ │ ├── __init__.py # exports of the deployed model │ ├── schema.py # assets and technique edges -│ ├── source.py # loads the CSVs -│ └── reasoning.py # path patterns and rules +│ ├── source.py # loads the CSVs and the technique edges +│ ├── kill_chains.py # kill-chain paths, exposure, priority, on-attack-path flag +│ └── entry_to_target_routes.py # routes between the entry and the crown jewel ├── queries/ │ └── attack_path_report.py # report printed from the deployed model └── data/ @@ -193,9 +194,9 @@ The analysis starts by modeling each attacker technique as its own directed rela The centerpiece is a multi-edge path pattern (a preview capability) that composes the techniques in series: an exploit first, then credential reuse, then one or more lateral pivots, ending at an explicit destination. Filtering the source to an internet-facing asset and the destination to a crown jewel pins the threat model. Enforcing edge order is the whole point — a single union edge or a flat join cannot express "exploit first, then credentials, then pivots," which is exactly the kill-chain signature analysts care about, and each hop records the technique it used. -A separate point query pins both endpoints by id to enumerate every route between a chosen entry point and a chosen crown jewel over the union edge. The kill-chains are then ranked by the exposure summed along each one. Finally, the assets lying on any crown-jewel chain are flagged back onto the ontology as `Asset.on_attack_path`, so a later query can pull them without re-enumerating paths. +A separate point query pins both endpoints by id to enumerate every route between a chosen entry point and a chosen crown jewel over the union edge. The kill-chains are then ranked by the exposure summed along each one, and the model publishes each chain's remediation priority along with the counts of chains, routes, and flagged assets that the report prints. Finally, the assets lying on any crown-jewel chain are flagged back onto the ontology as `Asset.on_attack_path`, so a later query can pull them without re-enumerating paths. -See `model/reasoning.py` for the implementation, `queries/attack_path_report.py` for the report, and `runbook.md` to reproduce it step by step with the RAI skills. +See `model/kill_chains.py` and `model/entry_to_target_routes.py` for the implementation, `queries/attack_path_report.py` for the report, and `runbook.md` to reproduce it step by step with the RAI skills. ## Customize this template @@ -207,7 +208,7 @@ See `model/reasoning.py` for the implementation, `queries/attack_path_report.py` ### Tune parameters -- Raise `MAX_PIVOTS` or `MAX_ROUTE_HOPS` for larger estates with deeper lateral movement (these bound the kill-chain pivot repeat and the point-query hop count). +- Raise `MAX_PIVOTS` (`model/kill_chains.py`) or `MAX_ROUTE_HOPS` (`model/entry_to_target_routes.py`) for larger estates with deeper lateral movement (these bound the kill-chain pivot repeat and the point-query hop count). - Adjust how `Asset.exposure_score` is weighted in the ranking so the chains that surface first match your prioritization (raw sum, per-hop average, or a max along the path). ### Extend the model diff --git a/cybersecurity-attack-paths/model/__init__.py b/cybersecurity-attack-paths/model/__init__.py index c4c9aefe..7ddb193c 100644 --- a/cybersecurity-attack-paths/model/__init__.py +++ b/cybersecurity-attack-paths/model/__init__.py @@ -15,9 +15,12 @@ pivots". ``p.relationships`` labels the technique used at each hop. - Runs a point query between one named internet-facing entry and one named crown jewel over a derived ``can_reach`` edge, enumerating every route between them. -- Scores each kill-chain by the asset exposure summed along it, and persists - ``Asset.on_attack_path`` back to the ontology for the assets that lie on a - crown-jewel-reaching chain. +- Scores each kill-chain by the asset exposure summed along it, ranks the chains + for remediation, and persists ``Asset.on_attack_path`` back to the ontology for + the assets that lie on a crown-jewel-reaching chain. + +The kill-chain paths and their scores live in ``kill_chains.py``; the point query's +routes live in ``entry_to_target_routes.py``. Run: `rai models deploy --path model` deploys this package to the schemas in @@ -25,15 +28,21 @@ queries.attack_path_report` then prints the report from the deployed model. """ -from .reasoning import ( +from .entry_to_target_routes import ( ENTRY_ASSET, - MAX_PIVOTS, MAX_ROUTE_HOPS, TARGET_ASSET, + RouteCount, + RouteStep, +) +from .kill_chains import ( + MAX_PIVOTS, + AssetCoverage, + KillChainCount, KillChainExposure, KillChainHop, + KillChainPriority, KillChainStep, - RouteStep, ) from .schema import Asset, model from .source import DATA_DIR @@ -45,9 +54,13 @@ "MAX_ROUTE_HOPS", "TARGET_ASSET", "Asset", + "AssetCoverage", + "KillChainCount", "KillChainExposure", "KillChainHop", + "KillChainPriority", "KillChainStep", + "RouteCount", "RouteStep", "model", ] diff --git a/cybersecurity-attack-paths/model/entry_to_target_routes.py b/cybersecurity-attack-paths/model/entry_to_target_routes.py new file mode 100644 index 00000000..e35955ba --- /dev/null +++ b/cybersecurity-attack-paths/model/entry_to_target_routes.py @@ -0,0 +1,48 @@ +"""Entry-to-target routes: every simple route over any technique from one internet-facing entry +asset to one crown jewel, each route's assets, and how many routes there are.""" + +from relationalai.semantics import Hash, Integer, not_, where +from relationalai.semantics.std import aggregates as aggs + +from .schema import Asset, model + +# -------------------------------------------------- +# Configure inputs +# -------------------------------------------------- + +# Maximum length (in edges) of a route in the point query between two named assets. +MAX_ROUTE_HOPS = 6 +# The point query's endpoints: a specific internet-facing entry and a crown jewel. +ENTRY_ASSET = "web-01" +TARGET_ASSET = "db-01" + +# -------------------------------------------------- +# Paths: routes between two named assets +# -------------------------------------------------- +# The point query's pattern: routes over the technique-agnostic can_reach edge from +# a pinned entry asset to a pinned crown jewel, 1..MAX_ROUTE_HOPS hops. +src_pt, dst_pt = Asset.ref(), Asset.ref() +route = model.path(src_pt.can_reach.repeat(1, MAX_ROUTE_HOPS), dst_pt).all().paths() + +# Keep only SIMPLE routes (no asset revisited). .all().paths() has WALK semantics and no +# native simple-path mode, so drop node-repeating walks with a negated existential over +# positions -- expressed natively in the route's where() (no pandas). +i, j = Integer.ref(), Integer.ref() +simple_route = [ + route, + src_pt.id == ENTRY_ASSET, + dst_pt.id == TARGET_ASSET, + not_(where(i < j, route.nodes(i) == route.nodes(j))), +] + +# The deployed model publishes the routes the report reads, keyed by each route's id: the +# assets in order, and how many routes there are. +RouteStep = model.Relationship( + f"entry-to-target route {Hash:path} has {Asset:asset} at step {Integer:step}" +) +model.where(*simple_route).define(RouteStep(route, Asset(route.nodes), route.nodes["index"])) +RouteCount = model.Relationship(f"there are {Integer:n_routes} entry-to-target routes") +counted_route, route_asset, route_step = Hash.ref(), Asset.ref(), Integer.ref() +model.define(RouteCount( + aggs.count(counted_route).where(RouteStep(counted_route, route_asset, route_step)) | 0 +)) diff --git a/cybersecurity-attack-paths/model/reasoning.py b/cybersecurity-attack-paths/model/kill_chains.py similarity index 68% rename from cybersecurity-attack-paths/model/reasoning.py rename to cybersecurity-attack-paths/model/kill_chains.py index f863ce27..23469eef 100644 --- a/cybersecurity-attack-paths/model/reasoning.py +++ b/cybersecurity-attack-paths/model/kill_chains.py @@ -1,6 +1,8 @@ -"""Kill-chain attack paths, the entry-to-crown-jewel route query, and the on-attack-path flag.""" +"""Kill-chain attack paths: the exploit, credential-reuse, and pivot chains from an internet-facing +asset into a crown jewel, each chain's steps, techniques, exposure, and remediation priority, how +many chains there are, and the assets that lie on a chain.""" -from relationalai.semantics import Hash, Integer, String, not_, where +from relationalai.semantics import Hash, Integer, String from relationalai.semantics.std import aggregates as aggs from .schema import Asset, model @@ -12,11 +14,6 @@ # Lateral-movement depth: how many pivot_to hops the kill-chain may take after the # initial exploit + credential reuse. The estate is small, so a low cap suffices. MAX_PIVOTS = 2 -# Maximum length (in edges) of a route in the point query between two named assets. -MAX_ROUTE_HOPS = 6 -# The point query's endpoints: a specific internet-facing entry and a crown jewel. -ENTRY_ASSET = "web-01" -TARGET_ASSET = "db-01" # -------------------------------------------------- # Paths: kill-chain attack paths (multi-relationship sequence) @@ -32,11 +29,6 @@ a, b, c, dst = Asset.ref(), Asset.ref(), Asset.ref(), Asset.ref() kill = model.path(a.exploit_to, b.cred_to, c.pivot_to.repeat(1, MAX_PIVOTS), dst).all().paths() -# The point query's pattern: routes over the technique-agnostic can_reach edge from -# a pinned entry asset to a pinned crown jewel, 1..MAX_ROUTE_HOPS hops. -src_pt, dst_pt = Asset.ref(), Asset.ref() -route = model.path(src_pt.can_reach.repeat(1, MAX_ROUTE_HOPS), dst_pt).all().paths() - # The crown-jewel kill-chains: an internet-facing foothold that ends on a crown jewel. crown_kill = [kill, a.internet_facing == "yes", dst.crown_jewel == "yes"] @@ -51,8 +43,7 @@ # Published paths # -------------------------------------------------- # The deployed model publishes the paths the report reads, keyed by each path's id: the -# crown-jewel kill-chains' assets, techniques, and total exposure, and the point query's -# simple routes. +# crown-jewel kill-chains' assets, techniques, and total exposure, and how many chains there are. KillChainStep = model.Relationship( f"kill chain {Hash:path} has {Asset:asset} at step {Integer:step}" ) @@ -66,6 +57,13 @@ KillChainHop(kill, kill.relationships["relationship"], kill.relationships["index"]) ) +# How many kill-chains there are. +KillChainCount = model.Relationship(f"there are {Integer:n_chains} kill chains") +chain, chain_asset, chain_step = Hash.ref(), Asset.ref(), Integer.ref() +model.define(KillChainCount( + aggs.count(chain).where(KillChainStep(chain, chain_asset, chain_step)) | 0 +)) + # Exposure is a per-asset score (a stand-in for a CVSS / attack-surface metric) summed ALONG # each kill-chain IN PYREL: aggregates.sum(Asset(kill.nodes).exposure_score).per(kill) sums # the per-node value over each path's node sequence -- the core paths-only aggregation. This @@ -78,16 +76,23 @@ KillChainExposure(kill, total) ) -# Keep only SIMPLE routes (no asset revisited). .all().paths() has WALK semantics and no -# native simple-path mode, so drop node-repeating walks with a negated existential over -# positions -- expressed natively in the route's where() (no pandas). -i, j = Integer.ref(), Integer.ref() -RouteStep = model.Relationship( - f"entry-to-target route {Hash:path} has {Asset:asset} at step {Integer:step}" +# Remediation priority: 1 for the kill-chain with the most total exposure. Ties go to the +# lower path id. The exposure is negated so both keys sort ascending. +KillChainPriority = model.Relationship( + f"kill chain {Hash:path} has remediation priority {Integer:priority}" ) +exposed_chain, chain_exposure = Hash.ref(), Integer.ref() model.where( - route, - src_pt.id == ENTRY_ASSET, - dst_pt.id == TARGET_ASSET, - not_(where(i < j, route.nodes(i) == route.nodes(j))), -).define(RouteStep(route, Asset(route.nodes), route.nodes["index"])) + KillChainExposure(exposed_chain, chain_exposure), + priority := aggs.rank(-chain_exposure, exposed_chain), +).define(KillChainPriority(exposed_chain, priority)) + +# How many assets there are, and how many of them lie on a crown-jewel kill-chain. +AssetCoverage = model.Relationship( + f"the estate has {Integer:n_assets} assets, {Integer:n_on_attack_path} on an attack path" +) +flagged_asset = Asset.ref() +model.define(AssetCoverage( + aggs.count(Asset), + aggs.count(flagged_asset).where(flagged_asset.on_attack_path == "yes") | 0, +)) diff --git a/cybersecurity-attack-paths/model/source.py b/cybersecurity-attack-paths/model/source.py index 3e4bd49d..2166344a 100644 --- a/cybersecurity-attack-paths/model/source.py +++ b/cybersecurity-attack-paths/model/source.py @@ -24,20 +24,12 @@ def load_csv(filename): Asset.exposure_score(asset_data["exposure_score"]), ) -# Load attack steps. Each row is one technique-specific edge; split by technique to -# populate the three typed edges, and load every row into the can_reach union. -steps_df = load_csv("attack_steps.csv") -for technique, rel in [("exploit", "exploit_to"), ("cred", "cred_to"), ("pivot", "pivot_to")]: - sub = model.data(steps_df[steps_df["technique"] == technique][["src", "dst"]]) - u, v = Asset.ref(), Asset.ref() - model.where( - u.id == sub["src"], - v.id == sub["dst"], - ).define(getattr(u, rel)(v)) - -all_steps = model.data(steps_df[["src", "dst"]]) -ru, rv = Asset.ref(), Asset.ref() -model.where( - ru.id == all_steps["src"], - rv.id == all_steps["dst"], -).define(ru.can_reach(rv)) +# Load attack steps. Each row is one technique-specific edge: its technique picks the +# typed edge it populates, and every row populates the can_reach union. +steps = model.data(load_csv("attack_steps.csv")) +u, v = Asset.ref(), Asset.ref() +step_ends = (u.id == steps["src"], v.id == steps["dst"]) +model.where(*step_ends, steps["technique"] == "exploit").define(u.exploit_to(v)) +model.where(*step_ends, steps["technique"] == "cred").define(u.cred_to(v)) +model.where(*step_ends, steps["technique"] == "pivot").define(u.pivot_to(v)) +model.where(*step_ends).define(u.can_reach(v)) diff --git a/cybersecurity-attack-paths/queries/attack_path_report.py b/cybersecurity-attack-paths/queries/attack_path_report.py index cf07e2de..42440b1b 100644 --- a/cybersecurity-attack-paths/queries/attack_path_report.py +++ b/cybersecurity-attack-paths/queries/attack_path_report.py @@ -15,9 +15,13 @@ MAX_ROUTE_HOPS, TARGET_ASSET, Asset, + AssetCoverage, + KillChainCount, KillChainExposure, KillChainHop, + KillChainPriority, KillChainStep, + RouteCount, RouteStep, model, ) @@ -45,6 +49,7 @@ kill_df = kill_df.drop_duplicates(["path_id", "step"]).sort_values(["path_id", "step"]) hop_df = hop_df.drop_duplicates(["path_id", "hop"]).sort_values(["path_id", "hop"]) + n_chains = int(model.select(KillChainCount).to_df().iloc[0, 0]) # Reassemble each kill-chain: ordered asset names + the technique used at each hop. # The technique is the relationship label as-is -- the dotted relationship name, @@ -58,7 +63,7 @@ labelled += f" --[{tech}]--> {nm}" chains.append({"path_id": pid, "hops": len(assets) - 1, "labelled": labelled}) - print(f"\n{len(chains)} kill-chain attack path(s) reach a crown jewel " + print(f"\n{n_chains} kill-chain attack path(s) reach a crown jewel " f"(exploit -> cred -> 1-{MAX_PIVOTS} pivots, from an internet-facing asset):") for ch in sorted(chains, key=lambda c: c["hops"]): print(f" [{ch['hops']} hops] {ch['labelled']}") @@ -68,7 +73,7 @@ # -------------------------------------------------- # The model pins both endpoints by id and enumerates all simple routes between them # over the technique-agnostic can_reach edge (any technique, 1..MAX_ROUTE_HOPS); see - # model/reasoning.py. + # model/entry_to_target_routes.py. route_df = ( model.where(RouteStep(path, Asset, step)) .select(path.alias("path_id"), step.alias("step"), Asset.id.alias("asset_id")) @@ -76,13 +81,14 @@ ) route_df = route_df.drop_duplicates(["path_id", "step"]).sort_values(["path_id", "step"]) routes = sorted( - {tuple(g["asset_id"]) for _, g in route_df.groupby("path_id")}, + (tuple(g["asset_id"]) for _, g in route_df.groupby("path_id")), key=lambda seq: (len(seq), seq), ) + n_routes = int(model.select(RouteCount).to_df().iloc[0, 0]) print(f"\n=== Point query: all routes from {ENTRY_ASSET} to {TARGET_ASSET} " f"(any technique, <= {MAX_ROUTE_HOPS} hops, simple) ===") - print(f" {len(routes)} route(s):") + print(f" {n_routes} route(s):") for seq in routes: print(" " + " -> ".join(seq)) @@ -91,29 +97,37 @@ # -------------------------------------------------- # The riskiest chain is the one whose assets carry the most exposure overall -- the # first remediation target. The model sums each kill-chain's per-asset exposure along - # its node sequence (see model/reasoning.py). - total = Integer.ref() - totals = ( - model.where(KillChainExposure(path, total)) - .select(path.alias("path_id"), total.alias("total_exposure")) + # its node sequence and ranks the chains by it (see model/kill_chains.py). + total, priority = Integer.ref(), Integer.ref() + ranking = ( + model.where(KillChainExposure(path, total), KillChainPriority(path, priority)) + .select(path.alias("path_id"), total.alias("total_exposure"), priority.alias("priority")) .to_df() ) - # Join total_exposure onto the assembled chains by path id (label string-join is pandas). + # Join total_exposure and priority onto the assembled chains by path id. exposure_by_path = dict( - totals[["path_id", "total_exposure"]].itertuples(index=False, name=None) + ranking[["path_id", "total_exposure"]].itertuples(index=False, name=None) ) + priority_by_path = dict(ranking[["path_id", "priority"]].itertuples(index=False, name=None)) for ch in chains: ch["total_exposure"] = int(exposure_by_path[ch["path_id"]]) + ch["priority"] = int(priority_by_path[ch["path_id"]]) print("\n=== Kill-chains ranked by total asset exposure (highest = remediate first) ===") - for ch in sorted(chains, key=lambda c: c["total_exposure"], reverse=True): + for ch in sorted(chains, key=lambda c: c["priority"]): print(f" exposure {ch['total_exposure']:>3} ({ch['hops']} hops) {ch['labelled']}") # -------------------------------------------------- # Assets on a crown-jewel attack path # -------------------------------------------------- - total_assets = len(model.select(Asset.id.alias("id")).to_df()) + n_assets, n_flagged = Integer.ref(), Integer.ref() + coverage = ( + model.where(AssetCoverage(n_assets, n_flagged)) + .select(n_assets.alias("n_assets"), n_flagged.alias("n_flagged")) + .to_df() + .iloc[0] + ) x = Asset.ref() flagged = ( model.where( @@ -124,6 +138,6 @@ ) print("\n=== Assets on a crown-jewel attack path (Asset.on_attack_path persisted) ===") - print(f" {len(flagged)} of {total_assets} assets:") + print(f" {int(coverage['n_flagged'])} of {int(coverage['n_assets'])} assets:") for _, r in flagged.sort_values("id").iterrows(): print(f" {r['id']:<8} {r['name']:<24} ({r['zone']})") diff --git a/datacenter_compute_allocation/README.md b/datacenter_compute_allocation/README.md index 15aaa380..c07dc80c 100644 --- a/datacenter_compute_allocation/README.md +++ b/datacenter_compute_allocation/README.md @@ -53,7 +53,7 @@ This template models that allocation as a scenario sweep across three axes (powe ## What's included -- `model/` — the deployed model: `schema.py` declares the concepts and the GNN task relationships, `source.py` loads the bundled CSVs, `reasoning.py` states the GNN, the rules, the PageRank, the 24-cell allocation MIP, and the rules that summarize its solution +- `model/` — the deployed model: `schema.py` declares the concepts and the GNN task relationships, `source.py` loads the bundled CSVs, and five modules state the reasoning: `utilization_forecast.py` (the GNN and its forecasts), `workload_eligibility.py` (priority tiers and hardware compatibility), `gating_scores.py` (the dependency PageRank), `compute_allocation.py` (the 24-cell allocation MIP), and `allocation_outcomes.py` (the rules that summarize its solution) - `train.py` — trains the utilization GNN over the deployed splits and registers its version - `queries/allocation_report.py` — prints the per-stage diagnostics, the per-cell summary, the Pareto frontiers, the plan, and the demand overlay from the deployed model - `data/data_centers.csv` — 5 DCs (snapshot of the upstream $300M-approved set) @@ -172,7 +172,7 @@ Use this sequence to deploy the model, train the GNN, and query the allocation p predictive: name: workload_utilization_gnn # created on first use if it doesn't exist gnns: - workload_utilization: # the GNN's name in model/reasoning.py + workload_utilization: # the GNN's name in model/utilization_forecast.py registry: .DATACENTER_COMPUTE_ALLOCATION model: WORKLOAD_UTILIZATION version: V1 # train.py registers this version @@ -266,7 +266,7 @@ Use this sequence to deploy the model, train the GNN, and query the allocation p frontier_loss 0.50 24,611,119.95 666,690.99 2.64 ``` - The report prints all four stages and the demand overlay; the lines above are trimmed. The GNN is stochastic, so the utilization probabilities shift from one training run to the next; the dependency PageRank is deterministic, so the frontier pretrains rank first by gating score on every run. In the run shown, the baseline cell assigns all 110 workloads; because the solve stops at its time limit with its best solution so far, the cells and workload counts can differ from one refresh to the next. The solve above is the open-source HiGHS default, which returns a feasible solution at its `SOLVER_TIME_LIMIT_SEC` of 240 seconds and reports `TIME_LIMIT` (signal, not failure), so each refresh takes about that long and the cells are labelled FEASIBLE or UNSOLVED. With Gurobi, the solve reaches `OPTIMAL` in seconds and the cells are labelled OPTIMAL or INFEASIBLE; set `SOLVER` in `model/reasoning.py` to switch. The full printout and a step-by-step walkthrough are in `runbook.md`. + The report prints all four stages and the demand overlay; the lines above are trimmed. The GNN is stochastic, so the utilization probabilities shift from one training run to the next; the dependency PageRank is deterministic, so the frontier pretrains rank first by gating score on every run. In the run shown, the baseline cell assigns all 110 workloads; because the solve stops at its time limit with its best solution so far, the cells and workload counts can differ from one refresh to the next. The solve above is the open-source HiGHS default, which returns a feasible solution at its `SOLVER_TIME_LIMIT_SEC` of 240 seconds and reports `TIME_LIMIT` (signal, not failure), so each refresh takes about that long and the cells are labelled FEASIBLE or UNSOLVED. With Gurobi, the solve reaches `OPTIMAL` in seconds and the cells are labelled OPTIMAL or INFEASIBLE; set `SOLVER` in `model/compute_allocation.py` to switch. The full printout and a step-by-step walkthrough are in `runbook.md`. To predict and solve again without changing the model, refresh the deployed model, then run the query again: @@ -293,7 +293,11 @@ datacenter_compute_allocation/ __init__.py # exports for train.py and the query schema.py # concepts, GNN task relationships source.py # bundled CSVs, demand scenarios, base facts - reasoning.py # GNN, rules, PageRank, allocation MIP, cell outcomes, plan + utilization_forecast.py # Stage 1: GNN, utilization forecasts and their split + workload_eligibility.py # Stage 2: priority tiers, hardware compatibility + gating_scores.py # Stage 3: dependency PageRank (gating score) + compute_allocation.py # Stage 4: allocation MIP and its solve status + allocation_outcomes.py # cell outcomes, plan, chosen assignments, demand overlay train.py # trains the GNN and registers its version queries/ allocation_report.py # per-stage diagnostics, per-cell summary, frontiers, plan, overlay @@ -340,7 +344,7 @@ One shared ontology threads all four stages: each stage reads concepts and prope - **Primary identifiers**: string ids on `DataCenterRequest`, `GpuPool`, `AILab`, and `Workload`; the scenario concepts are identified by `name`; `WorkloadForecast` by workload id; `WorkloadGpuCompat`, `WorkloadDependency`, `Compatibility`, `Assignment`, and `ScenarioCell` carry composite keys. - **Important invariants**: `envelope_multiplier`, `fraction`, and `anchor_max_share` are fractions; a negative sentinel on `MarginFloor.fraction` / `DiversityCap.anchor_max_share` marks the unconstrained row (its constraint is skipped); the `is_high_utilization` label is binary; `Assignment.x_assign` decision variables are binary; power / cost / GPU counts are non-negative. -For the full concept and property definitions — the entity concepts and the three scenario concepts in `model/schema.py`, and the derived `WorkloadForecast` / `Compatibility` / `Assignment` / `ScenarioCell` / `AllocationPlan` / `DemandScenarioOutlook` concepts each stage writes in `model/reasoning.py` — `runbook.md` builds them step by step with the RAI skills. +For the full concept and property definitions — the entity concepts and the three scenario concepts in `model/schema.py`, and the derived `WorkloadForecast` / `Compatibility` / `Assignment` / `ScenarioCell` / `AllocationPlan` / `DemandScenarioOutlook` concepts each stage writes in `model/` — `runbook.md` builds them step by step with the RAI skills. ## How it works @@ -375,7 +379,7 @@ The objective is what makes this a real chain rather than four disjoint reasoner Finally, a `DemandScenario` overlay replays the locked-in plan under four risk scenarios. Anchor (P0) revenue is treated as contractual (factor 1.0) — the operator gets paid for the seat regardless of utilization — while opportunistic (P1/P2) seats realize only the scenario factor of their assigned revenue. The overlay reports realized and stranded revenue per scenario and persists each as a `DemandScenarioOutlook(scenario)` concept row, so the stranded-capacity exposure of the chosen plan is queryable as ontology, not just printed. -See `model/reasoning.py` for the implementation and `runbook.md` to reproduce each stage step by step with the RAI skills. +See the modules in `model/` for the implementation and `runbook.md` to reproduce each stage step by step with the RAI skills. ## Customize this template @@ -387,7 +391,7 @@ See `model/reasoning.py` for the implementation and `runbook.md` to reproduce ea ### Tune parameters - Tune the scenario axes: edit `power_envelope_levels.csv`, `margin_floors.csv`, and `diversity_caps.csv`. Adding rows scales the cell count multiplicatively. -- Change the priority spread by editing the weights in the Stage 2 rules of `model/reasoning.py` (default 100 / 10 / 1). +- Change the priority spread by editing the weights in the Stage 2 rules of `model/workload_eligibility.py` (default 100 / 10 / 1). ### Extend the model @@ -395,7 +399,7 @@ See `model/reasoning.py` for the implementation and `runbook.md` to reproduce ea ### Scale up / productionize -- Tune the Stage 4 solve by adjusting `SOLVER` or `SOLVER_TIME_LIMIT_SEC` in `model/reasoning.py`. The default works on any prescriptive engine; faster commercial solvers (when licensed) can reach OPTIMAL in a fraction of the time. +- Tune the Stage 4 solve by adjusting `SOLVER` or `SOLVER_TIME_LIMIT_SEC` in `model/compute_allocation.py`. The default works on any prescriptive engine; faster commercial solvers (when licensed) can reach OPTIMAL in a fraction of the time. - Replace the bundled CSVs with CDC ingestion from the operator's inventory, telemetry, and contract systems; the ontology shape is independent of the load pipeline. ## Troubleshooting @@ -433,7 +437,7 @@ The shipped constraints admit an empty allocation in every cell: C1 is a soft `<
Solver returns TIME_LIMIT with sensible per-cell results -Expected at the default `time_limit_sec=240`. Per-cell numbers remain valid with `TIME_LIMIT` (`rai-prescriptive-results`: `TIME_LIMIT` is signal, not error). Raise `SOLVER_TIME_LIMIT_SEC` or switch to a faster solver in `model/reasoning.py` if you need a tighter MIP gap. +Expected at the default `time_limit_sec=240`. Per-cell numbers remain valid with `TIME_LIMIT` (`rai-prescriptive-results`: `TIME_LIMIT` is signal, not error). Raise `SOLVER_TIME_LIMIT_SEC` or switch to a faster solver in `model/compute_allocation.py` if you need a tighter MIP gap.
@@ -445,7 +449,7 @@ Likely an upstream constraint (C5 / C6 / C7) firing at unintended cells. Check t
Per-workload utilization probabilities do not match the README's distribution -The GNN is stochastic, so the probabilities shift from one training run to the next, and a different `seed` or `n_epochs` in `model/reasoning.py` changes them too. The structural outcome (frontier pretrains near the top, evals near the bottom) reproduces. +The GNN is stochastic, so the probabilities shift from one training run to the next, and a different `seed` or `n_epochs` in `model/utilization_forecast.py` changes them too. The structural outcome (frontier pretrains near the top, evals near the bottom) reproduces.
## What this template abstracts diff --git a/datacenter_compute_allocation/model/__init__.py b/datacenter_compute_allocation/model/__init__.py index cec85eda..b8cfe07f 100644 --- a/datacenter_compute_allocation/model/__init__.py +++ b/datacenter_compute_allocation/model/__init__.py @@ -7,29 +7,33 @@ of that approved campus set at a $300M investment level; this template demonstrates the operator-side allocation decision that picks up after. -Four reasoner stages on a shared ontology: +Four reasoner stages on a shared ontology, in five modules, each of which +imports the modules whose declarations it reads: Stage 1 -- Predictive: heterogeneous-graph GNN binary-classifies per-workload utilization probability (will this workload actually use its - allocated capacity at high duty cycle, or stall / be repaced?). + allocated capacity at high duty cycle, or stall / be repaced?) + (`utilization_forecast.py`). Stage 2 -- Rules: hardware compatibility (memory + GPU type allowlist) + priority-tier classification (P0/P1/P2 from contract_tier). - Populates Compatibility(workload, gpu_pool). + Populates Compatibility(workload, gpu_pool) + (`workload_eligibility.py`). Stage 3 -- Graph: reverse-PageRank on the WorkloadDependency.blocks DAG writes Workload.gating_score (frontier pretrains gating long - chains land high; isolated inference workloads land at baseline). + chains land high; isolated inference workloads land at baseline) + (`gating_scores.py`). Stage 4 -- Prescriptive MIP: assigns workloads under power, GPU-count, gross-margin-floor, and anchor-concentration-cap constraints, across a scenario sweep (PowerEnvelopeLevel x MarginFloor x DiversityCap = 2 x 3 x 4 = 24 cells). Maximizes a four-factor strategic value: priority * gating * utilization_probability * strategic_value_usd, amplified by (1 + under_provisioning_penalty) for asymmetric - failure-mode pricing. + failure-mode pricing (`compute_allocation.py`). The headline plan persists as an AllocationPlan singleton plus an Assignment.is_chosen unary Relationship over the chosen-cell decision rows, the 24 cells as ScenarioCell rows, and the demand overlay as a DemandScenarioOutlook -per scenario -- all queryable as ontology. +per scenario -- all queryable as ontology (`allocation_outcomes.py`). Run: `rai models deploy --path model` deploys this package to the schemas in @@ -38,21 +42,21 @@ diagnostics, the per-cell summary, two Pareto frontiers, and the demand overlay. """ -from .reasoning import ( +from .allocation_outcomes import ( CHOSEN_DIVERSITY, CHOSEN_ENVELOPE, CHOSEN_MARGIN, - WORKLOAD_TYPES, AllocationPlan, - Assignment, - Compatibility, + CellStatusCount, DemandScenarioOutlook, ScenarioCell, +) +from .compute_allocation import ( + WORKLOAD_TYPES, + Assignment, SolveObjective, SolveStatus, SolveTime, - WorkloadForecast, - gnn, problem, ) from .schema import ( @@ -68,16 +72,21 @@ model, ) from .source import DATA_DIR +from .utilization_forecast import HIGH_UTILIZATION, UtilizationSplit, WorkloadForecast, gnn +from .workload_eligibility import PRIORITY_TIERS, Compatibility, PriorityTierCount __all__ = [ "CHOSEN_DIVERSITY", "CHOSEN_ENVELOPE", "CHOSEN_MARGIN", "DATA_DIR", + "HIGH_UTILIZATION", + "PRIORITY_TIERS", "WORKLOAD_TYPES", "AILab", "AllocationPlan", "Assignment", + "CellStatusCount", "Compatibility", "DataCenterRequest", "DemandScenario", @@ -86,10 +95,12 @@ "GpuPool", "MarginFloor", "PowerEnvelopeLevel", + "PriorityTierCount", "ScenarioCell", "SolveObjective", "SolveStatus", "SolveTime", + "UtilizationSplit", "Workload", "WorkloadDependency", "WorkloadForecast", diff --git a/datacenter_compute_allocation/model/allocation_outcomes.py b/datacenter_compute_allocation/model/allocation_outcomes.py new file mode 100644 index 00000000..09cb4a40 --- /dev/null +++ b/datacenter_compute_allocation/model/allocation_outcomes.py @@ -0,0 +1,274 @@ +"""Allocation outcomes: each scenario cell's results from the solved assignments, the headline plan +and its chosen assignments, and the plan replayed under demand-risk scenarios.""" + +from relationalai.semantics import Float, Integer, String, not_, sum +from relationalai.semantics.std import aggregates as aggs +from relationalai.semantics.std import math, strings + +from .compute_allocation import Assignment, SolveStatus +from .schema import DemandScenario, DiversityCap, MarginFloor, PowerEnvelopeLevel, model + +# -------------------------------------------------- +# Configure inputs +# -------------------------------------------------- + +# Headline plan cell. The AllocationPlan singleton + Assignment.is_chosen +# flag persist this cell's outcome; tighter cells in the 24-cell sweep +# remain queryable via Assignment.x_assign but are diagnostic overlays +# rather than the operator-facing plan. +CHOSEN_ENVELOPE = "100pct" +CHOSEN_MARGIN = "unconstrained" +CHOSEN_DIVERSITY = "none" +PLAN_ID = "DCCA_BASELINE" + +# -------------------------------------------------- +# Stage 4 (cont.): Per-cell outcomes + headline-plan persistence +# One ScenarioCell per (env, mar, div). Its aggregates are computed from the +# solved Assignment.x_assign values (mirrors energy_grid_planning's +# InvestmentPortfolio). A cell with no assignments has a zero n_assigned, +# revenue and cost. The chosen baseline cell is persisted as an +# AllocationPlan singleton + Assignment.is_chosen flag + DemandScenario +# overlay so the plan is queryable as ontology. +# -------------------------------------------------- + +ScenarioCell = model.Concept( + "ScenarioCell", + identify_by={"envelope": PowerEnvelopeLevel, "margin": MarginFloor, "diversity": DiversityCap}, +) +ScenarioCell.n_assigned = model.Property(f"{ScenarioCell} has {Integer:n_assigned}") +ScenarioCell.revenue_usd = model.Property(f"{ScenarioCell} has {Float:revenue_usd}") +ScenarioCell.anchor_revenue_usd = model.Property(f"{ScenarioCell} has {Float:anchor_revenue_usd}") +ScenarioCell.energy_cost_usd = model.Property(f"{ScenarioCell} has {Float:energy_cost_usd}") +ScenarioCell.dep_cost_usd = model.Property(f"{ScenarioCell} has {Float:dep_cost_usd}") +ScenarioCell.total_cost_usd = model.Property(f"{ScenarioCell} has {Float:total_cost_usd}") +ScenarioCell.realized_margin = model.Property(f"{ScenarioCell} has {Float:realized_margin}") +ScenarioCell.anchor_share = model.Property(f"{ScenarioCell} has {Float:anchor_share}") +ScenarioCell.n_by_type = model.Relationship( + f"{ScenarioCell} has {String:workload_type} workload count {Integer:n}" +) +ScenarioCell.n_by_tier = model.Relationship( + f"{ScenarioCell} has {String:priority_tier} workload count {Integer:n}" +) +ScenarioCell.status = model.Property(f"{ScenarioCell} has status {String:status}") + +model.define(ScenarioCell.new( + envelope=PowerEnvelopeLevel, margin=MarginFloor, diversity=DiversityCap, +)) + +xq = Float.ref("xq") + + +def _assigned_in_cell(): + """Conditions selecting the Assignments the solve placed in ScenarioCell.""" + return ( + Assignment.x_assign(ScenarioCell.envelope, ScenarioCell.margin, ScenarioCell.diversity, xq), + xq > 0.5, + ) + + +model.define(ScenarioCell.n_assigned( + aggs.count(Assignment).where(*_assigned_in_cell()).per(ScenarioCell) | 0 +)) +model.define(ScenarioCell.revenue_usd( + sum(Assignment, Assignment.workload.strategic_value_usd) + .where(*_assigned_in_cell()).per(ScenarioCell) | 0.0 +)) +model.define(ScenarioCell.anchor_revenue_usd( + sum(Assignment, Assignment.workload.strategic_value_usd) + .where(*_assigned_in_cell(), Assignment.workload.lab.is_strategic_anchor == True) + .per(ScenarioCell) | 0.0 +)) +model.define(ScenarioCell.energy_cost_usd( + sum(Assignment, + Assignment.workload.gpu_count_required + * Assignment.workload.duration_hours + * Assignment.gpu_pool.power_per_gpu_kw + * Assignment.gpu_pool.data_center.pue + * Assignment.gpu_pool.data_center.dollars_per_mwh / 1000.0) + .where(*_assigned_in_cell()).per(ScenarioCell) | 0.0 +)) +model.define(ScenarioCell.dep_cost_usd( + sum(Assignment, + Assignment.workload.gpu_count_required + * Assignment.workload.duration_hours + * Assignment.gpu_pool.hourly_depreciation_rate) + .where(*_assigned_in_cell()).per(ScenarioCell) | 0.0 +)) +model.define(ScenarioCell.total_cost_usd(ScenarioCell.energy_cost_usd + ScenarioCell.dep_cost_usd)) +# A cell with no revenue has no margin or anchor share. +model.where(ScenarioCell.revenue_usd > 0).define( + ScenarioCell.realized_margin( + (ScenarioCell.revenue_usd - ScenarioCell.total_cost_usd) / ScenarioCell.revenue_usd + ), + ScenarioCell.anchor_share(ScenarioCell.anchor_revenue_usd / ScenarioCell.revenue_usd), +) + +# Per-(cell, workload_type) and per-(cell, priority_tier) counts; a kind with no assignment +# in the cell has no row. +wtype = String.ref() +model.define(ScenarioCell.n_by_type( + wtype, + aggs.count(Assignment) + .where(*_assigned_in_cell(), Assignment.workload.workload_type == wtype) + .per(ScenarioCell, wtype), +)) +tier = String.ref() +model.define(ScenarioCell.n_by_tier( + tier, + aggs.count(Assignment) + .where(*_assigned_in_cell(), Assignment.workload.priority_tier == tier) + .per(ScenarioCell, tier), +)) + +# Per-cell status, set by the cell's assignment count: when the global solve +# proved optimality, cells with assignments are OPTIMAL and cells with none +# are INFEASIBLE, a label for an empty optimum rather than a proof (an empty +# allocation satisfies every cell's constraints). When the wall-clock ran out +# first, they are FEASIBLE and UNSOLVED. +solve_status = String.ref() +model.where( + SolveStatus(solve_status), solve_status == "OPTIMAL", ScenarioCell.n_assigned > 0 +).define(ScenarioCell.status("OPTIMAL")) +model.where( + SolveStatus(solve_status), solve_status == "OPTIMAL", not_(ScenarioCell.n_assigned > 0) +).define(ScenarioCell.status("INFEASIBLE")) +model.where( + SolveStatus(solve_status), solve_status != "OPTIMAL", ScenarioCell.n_assigned > 0 +).define(ScenarioCell.status("FEASIBLE")) +model.where( + SolveStatus(solve_status), solve_status != "OPTIMAL", not_(ScenarioCell.n_assigned > 0) +).define(ScenarioCell.status("UNSOLVED")) + +# Cells per status label. +CellStatusCount = model.Relationship( + f"{Integer:n_cells} scenario cells have status {String:status}" +) +_status = String.ref() +model.where(ScenarioCell.status == _status).define( + CellStatusCount(aggs.count(ScenarioCell).per(_status), _status) +) + +# The two one-axis sweeps through the headline plan's power envelope: the cells that vary the +# margin floor at the headline diversity cap, and the cells that vary the diversity cap at the +# headline margin floor. +ScenarioCell.in_margin_sweep = model.Relationship(f"{ScenarioCell} is in the margin-floor sweep") +ScenarioCell.in_diversity_sweep = model.Relationship( + f"{ScenarioCell} is in the diversity-cap sweep" +) +model.where( + ScenarioCell.envelope.name == CHOSEN_ENVELOPE, + ScenarioCell.diversity.name == CHOSEN_DIVERSITY, +).define(ScenarioCell.in_margin_sweep()) +model.where( + ScenarioCell.envelope.name == CHOSEN_ENVELOPE, + ScenarioCell.margin.name == CHOSEN_MARGIN, +).define(ScenarioCell.in_diversity_sweep()) + +# AllocationPlan is a singleton holding the operator-facing summary +# (revenue, cost, anchor share, n_assigned, status, binding axis) for +# the chosen cell; Assignment.is_chosen narrows the per-cell decision +# rows to the chosen scenario. Mirrors the telco_network_recovery +# RestorePlan / is_selected_upgrade pattern. +AllocationPlan = model.Concept("AllocationPlan", identify_by={"id": String}) +AllocationPlan.chosen_envelope = model.Property( + f"{AllocationPlan} has chosen envelope {String:chosen_envelope}" +) +AllocationPlan.chosen_margin = model.Property( + f"{AllocationPlan} has chosen margin {String:chosen_margin}" +) +AllocationPlan.chosen_diversity = model.Property( + f"{AllocationPlan} has chosen diversity {String:chosen_diversity}" +) +AllocationPlan.n_assigned = model.Property(f"{AllocationPlan} has {Integer:n_assigned}") +AllocationPlan.revenue_usd = model.Property(f"{AllocationPlan} has {Float:revenue_usd}") +AllocationPlan.total_cost_usd = model.Property( + f"{AllocationPlan} has {Float:total_cost_usd}" +) +AllocationPlan.realized_margin = model.Property( + f"{AllocationPlan} has {Float:realized_margin}" +) +AllocationPlan.anchor_share = model.Property(f"{AllocationPlan} has {Float:anchor_share}") +AllocationPlan.status = model.Property(f"{AllocationPlan} has status {String:status}") +AllocationPlan.binding_axis = model.Property( + f"{AllocationPlan} has binding axis {String:binding_axis}" +) + +model.define(AllocationPlan.new(id=PLAN_ID)) +chosen_cell = ( + AllocationPlan.id == PLAN_ID, + ScenarioCell.envelope.name == CHOSEN_ENVELOPE, + ScenarioCell.margin.name == CHOSEN_MARGIN, + ScenarioCell.diversity.name == CHOSEN_DIVERSITY, +) +model.where(*chosen_cell).define( + AllocationPlan.chosen_envelope(CHOSEN_ENVELOPE), + AllocationPlan.chosen_margin(CHOSEN_MARGIN), + AllocationPlan.chosen_diversity(CHOSEN_DIVERSITY), +) +model.where(*chosen_cell).define(AllocationPlan.n_assigned(ScenarioCell.n_assigned)) +model.where(*chosen_cell).define(AllocationPlan.revenue_usd(ScenarioCell.revenue_usd)) +model.where(*chosen_cell).define(AllocationPlan.total_cost_usd(ScenarioCell.total_cost_usd)) +model.where(*chosen_cell).define(AllocationPlan.realized_margin(ScenarioCell.realized_margin)) +model.where(*chosen_cell).define(AllocationPlan.anchor_share(ScenarioCell.anchor_share)) +model.where(*chosen_cell).define(AllocationPlan.status(ScenarioCell.status)) +model.where(*chosen_cell, ScenarioCell.n_assigned > 0).define( + AllocationPlan.binding_axis("power_envelope") +) +model.where(*chosen_cell, not_(ScenarioCell.n_assigned > 0)).define( + AllocationPlan.binding_axis(strings.lower(ScenarioCell.status)) +) + +Assignment.is_chosen = model.Relationship(f"{Assignment} is in chosen cell") +xc = Float.ref("xc") +chosen_env_c = PowerEnvelopeLevel.lookup(name=CHOSEN_ENVELOPE) +chosen_mar_c = MarginFloor.lookup(name=CHOSEN_MARGIN) +chosen_div_c = DiversityCap.lookup(name=CHOSEN_DIVERSITY) +model.where( + Assignment.x_assign(chosen_env_c, chosen_mar_c, chosen_div_c, xc), + xc > 0.5, +).define(Assignment.is_chosen()) + +# DemandScenario overlay: stranded-capacity exposure under risk. +# The chosen plan is locked in, but lab-side demand for the assigned +# workloads can soften from the GNN's point forecast. P0 revenue is +# contractual (factor = 1.0); P1/P2 realize only `factor`. The delta +# is stranded capacity: GPUs powered, depreciation accruing, no workload. +DemandScenarioOutlook = model.Concept( + "DemandScenarioOutlook", + identify_by={"scenario": DemandScenario}, +) +DemandScenarioOutlook.realized_revenue_usd = model.Property( + f"{DemandScenarioOutlook} has {Float:realized_revenue_usd}" +) +DemandScenarioOutlook.stranded_revenue_usd = model.Property( + f"{DemandScenarioOutlook} has {Float:stranded_revenue_usd}" +) +DemandScenarioOutlook.stranded_share = model.Property( + f"{DemandScenarioOutlook} has {Float:stranded_share}" +) +model.define(DemandScenarioOutlook.new(scenario=DemandScenario)) + +p0_revenue = sum(Assignment, Assignment.workload.strategic_value_usd).where( + Assignment.is_chosen(), Assignment.workload.priority_tier == "P0" +) | 0.0 +other_revenue = sum(Assignment, Assignment.workload.strategic_value_usd).where( + Assignment.is_chosen(), Assignment.workload.priority_tier != "P0" +) | 0.0 +model.where(DemandScenarioOutlook.scenario == DemandScenario).define( + DemandScenarioOutlook.realized_revenue_usd(p0_revenue + other_revenue * DemandScenario.factor) +) +model.where(AllocationPlan.id == PLAN_ID).define( + DemandScenarioOutlook.stranded_revenue_usd( + math.maximum(AllocationPlan.revenue_usd - DemandScenarioOutlook.realized_revenue_usd, 0.0) + ) +) + +# The stranded share of the chosen plan's revenue, zero for a plan without revenue. +model.where(AllocationPlan.id == PLAN_ID, AllocationPlan.revenue_usd > 0).define( + DemandScenarioOutlook.stranded_share( + DemandScenarioOutlook.stranded_revenue_usd / AllocationPlan.revenue_usd + ) +) +model.where(AllocationPlan.id == PLAN_ID, not_(AllocationPlan.revenue_usd > 0)).define( + DemandScenarioOutlook.stranded_share(0.0) +) diff --git a/datacenter_compute_allocation/model/compute_allocation.py b/datacenter_compute_allocation/model/compute_allocation.py new file mode 100644 index 00000000..a6ff4c88 --- /dev/null +++ b/datacenter_compute_allocation/model/compute_allocation.py @@ -0,0 +1,202 @@ +"""Compute allocation: the allocation MIP that assigns workloads to GPU pools across the 24-cell +scenario sweep, and the solve's status, time and objective.""" + +from relationalai.semantics import Float, String, sum +from relationalai.semantics.reasoners.prescriptive import Problem + +# Declares Workload.gating_score, the gating scores the objective reads. +from . import gating_scores # noqa: F401 +from .schema import ( + DataCenterRequest, + DiversityCap, + GpuPool, + MarginFloor, + PowerEnvelopeLevel, + Workload, + model, +) +from .utilization_forecast import WorkloadForecast +from .workload_eligibility import Compatibility + +# -------------------------------------------------- +# Configure inputs +# -------------------------------------------------- + +# Solver. HiGHS is the open-source default that ships with the +# prescriptive engine; switch to "gurobi" if your engine has a Gurobi +# license (faster convergence, tighter MIP gaps on the 24-cell sweep). +SOLVER = "highs" +SOLVER_TIME_LIMIT_SEC = 240 + +# The workload types the per-type floor (C7) and the per-cell type counts range over. +WORKLOAD_TYPES = ("pretrain", "finetune", "inference", "eval") + +# -------------------------------------------------- +# Stage 4: Prescriptive -- compute allocation MIP (24-cell sweep) +# Decision variable: Assignment.x_assign(PowerEnvelopeLevel, MarginFloor, +# DiversityCap), binary. One per (Workload, GpuPool) +# in Compatibility, per scenario cell. +# +# Constraints: +# C1+C2 -- At most one assignment per workload per cell, P0 included: +# priority_weight=100 in the objective weights P0 workloads +# heavily but does not force them in, so a P0 workload left +# unassigned in a cell is a diagnostic signal. +# C3 -- Per-pool GPU-count capacity. +# C4 -- Per-DC power envelope: gpu_count * power_per_gpu * pue <= +# approved_mw * 1000 * envelope_multiplier. +# C5 -- Gross-margin floor (linearized; skipped when fraction < 0). +# C6 -- Anchor concentration cap (skipped when share < 0). +# C7 -- Workload-type floor (one per type; skipped when floor < 0). +# +# Objective: maximize sum over assignments of +# priority_weight * gating_score * utilization_probability * +# strategic_value_usd * (1 + under_provisioning_penalty) +# -------------------------------------------------- + +# Decision variable: Assignment indexed by the three scenario axes. A +# workload is assignable once it has a utilization forecast. +Assignment = model.Concept( + "Assignment", + identify_by={"workload": Workload, "gpu_pool": GpuPool}, +) +model.define( + Assignment.new(workload=Compatibility.workload, gpu_pool=Compatibility.gpu_pool) +).where(WorkloadForecast.workload_id == Compatibility.workload.id) + +Assignment.x_assign = model.Property( + f"{Assignment} per {PowerEnvelopeLevel} per {MarginFloor} per {DiversityCap} " + f"assigned {Float:x_assign}" +) + +problem = Problem(model, Float, name="datacenter_compute_allocation") + +# Bind the decision variable. The Float ref pattern (mirrors upstream +# energy_grid_planning's x_a / x_u) lets constraints and objective +# reference the variable's value via the bound Float ref inside arithmetic. +x = Float.ref("x") +problem.solve_for( + Assignment.x_assign(PowerEnvelopeLevel, MarginFloor, DiversityCap, x), + type="bin", + name=["assign", PowerEnvelopeLevel.name, MarginFloor.name, DiversityCap.name, + Assignment.workload.id, Assignment.gpu_pool.id], +) + +# C1+C2: at most one assignment per workload per cell +x2 = Float.ref() +Wany = Workload.ref() +problem.satisfy(model.where( + Assignment.x_assign(PowerEnvelopeLevel, MarginFloor, DiversityCap, x2), + Assignment.workload == Wany, +).require( + sum(Assignment, x2).per(Wany, PowerEnvelopeLevel, MarginFloor, DiversityCap) <= 1.0 +)) + +# C3: per-pool GPU count capacity +x3 = Float.ref() +G = GpuPool.ref() +problem.satisfy(model.where( + Assignment.x_assign(PowerEnvelopeLevel, MarginFloor, DiversityCap, x3), + Assignment.gpu_pool == G, +).require( + sum(x3 * Assignment.workload.gpu_count_required) + .per(G, PowerEnvelopeLevel, MarginFloor, DiversityCap) + <= G.available_gpu_count +)) + +# C4: per-DC power envelope +x4 = Float.ref() +DC = DataCenterRequest.ref() +problem.satisfy(model.where( + Assignment.x_assign(PowerEnvelopeLevel, MarginFloor, DiversityCap, x4), + Assignment.gpu_pool.data_center == DC, +).require( + sum(x4 + * Assignment.workload.gpu_count_required + * Assignment.gpu_pool.power_per_gpu_kw + * DC.pue) + .per(DC, PowerEnvelopeLevel, MarginFloor, DiversityCap) + <= DC.approved_mw * 1000.0 * PowerEnvelopeLevel.envelope_multiplier +)) + +# C5: gross-margin floor (linearized; skipped when fraction < 0) +# revenue * (1 - fraction) >= total_cost +# total_cost = energy_cost + depreciation_cost (per workload, per duration) +# Energy alone clears at ~99% margin; depreciation is the SemiAnalysis +# 14-16% net BMaaS pressure source. +x5 = Float.ref() +problem.satisfy(model.where( + Assignment.x_assign(PowerEnvelopeLevel, MarginFloor, DiversityCap, x5), + MarginFloor.fraction >= 0.0, +).require( + sum(x5 * Assignment.workload.strategic_value_usd + * (1.0 - MarginFloor.fraction)) + .per(PowerEnvelopeLevel, MarginFloor, DiversityCap) + >= sum(x5 * Assignment.workload.gpu_count_required + * Assignment.workload.duration_hours + * (Assignment.gpu_pool.power_per_gpu_kw + * Assignment.gpu_pool.data_center.pue + * Assignment.gpu_pool.data_center.dollars_per_mwh / 1000.0 + + Assignment.gpu_pool.hourly_depreciation_rate)) + .per(PowerEnvelopeLevel, MarginFloor, DiversityCap) +)) + +# C6: anchor concentration cap (skipped when share < 0) +x6 = Float.ref() +problem.satisfy(model.where( + Assignment.x_assign(PowerEnvelopeLevel, MarginFloor, DiversityCap, x6), + DiversityCap.anchor_max_share >= 0.0, +).require( + sum(x6 * Assignment.workload.strategic_value_usd) + .where(Assignment.workload.lab.is_strategic_anchor == True) + .per(PowerEnvelopeLevel, MarginFloor, DiversityCap) + <= DiversityCap.anchor_max_share + * sum(x6 * Assignment.workload.strategic_value_usd) + .per(PowerEnvelopeLevel, MarginFloor, DiversityCap) +)) + +# C7: workload-type floor (one constraint per type; skipped when floor < 0) +for wt in WORKLOAD_TYPES: + x7 = Float.ref() + problem.satisfy(model.where( + Assignment.x_assign(PowerEnvelopeLevel, MarginFloor, DiversityCap, x7), + DiversityCap.workload_type_floor >= 0.0, + ).require( + sum(Assignment, x7) + .where(Assignment.workload.workload_type == wt) + .per(PowerEnvelopeLevel, MarginFloor, DiversityCap) + >= DiversityCap.workload_type_floor + * sum(Assignment, x7).per(PowerEnvelopeLevel, MarginFloor, DiversityCap) + )) + +# Objective: four-factor strategic value, amplified by under-provisioning penalty +# The (1 + under_provisioning_penalty) multiplier captures asymmetric failure modes: +# an unfilled anchor seat (P0) costs more than the foregone revenue, while an +# unfilled research eval costs only the revenue. P0 = 1.0 (2x amp), P1 = 0.3, P2 = 0.0. +x_obj = Float.ref() +problem.maximize( + sum(PowerEnvelopeLevel, MarginFloor, DiversityCap, + x_obj + * Assignment.workload.priority_weight + * Assignment.workload.gating_score + * WorkloadForecast.utilization_probability + * Assignment.workload.strategic_value_usd + * (1.0 + Assignment.workload.under_provisioning_penalty)) + .where( + Assignment.x_assign(PowerEnvelopeLevel, MarginFloor, DiversityCap, x_obj), + WorkloadForecast.workload_id == Assignment.workload.id, + ) +) + +# Each refresh of the deployed model runs this solve. +problem.configure(SOLVER, time_limit_sec=SOLVER_TIME_LIMIT_SEC) + +# The solve's status, time and objective, which the deployed model publishes for the queries. +SolveStatus = model.Relationship(f"datacenter allocation solve status is {String:status}") +SolveTime = model.Relationship(f"datacenter allocation solve time is {Float:seconds}") +SolveObjective = model.Relationship(f"datacenter allocation objective is {Float:objective}") +model.define( + SolveStatus(problem.termination_status()), + SolveTime(problem.solve_time_sec()), + SolveObjective(problem.objective_value()), +) diff --git a/datacenter_compute_allocation/model/gating_scores.py b/datacenter_compute_allocation/model/gating_scores.py new file mode 100644 index 00000000..ccf4ee14 --- /dev/null +++ b/datacenter_compute_allocation/model/gating_scores.py @@ -0,0 +1,35 @@ +"""Gating scores: each workload's gating score, from reverse PageRank on the workload-dependency DAG.""" + +from relationalai.semantics import Float +from relationalai.semantics.reasoners.graph import Graph + +# The GNN takes as features the Workload properties declared before its predictions, so it is +# declared first: the gating score is a graph result, not a feature. +from . import utilization_forecast # noqa: F401 +from .schema import Workload, WorkloadDependency, model + +# -------------------------------------------------- +# Stage 3: Graph -- workload-dependency PageRank (gating score) +# Reverse-PageRank on the WorkloadDependency.blocks DAG: a high +# `gating_score` means many downstream workloads are gated by this +# one (frontier pretrain that gates 14 fine-tunes + evals lands at +# the top). +# -------------------------------------------------- + +dag = Graph(model, name="dependency_dag", directed=True, weighted=False, node_concept=Workload) + +# Edge reversal: PageRank flows toward upstream gating workloads. +# We define edges as (successor -> predecessor) so a node's PageRank +# accumulates incoming flow from everything it gates. +dep_ref = WorkloadDependency.ref() +model.define( + dag.Edge.new(src=dep_ref.successor, dst=dep_ref.predecessor) +).where(dep_ref.dependency_type == "blocks") + +pagerank = dag.pagerank() +Workload.gating_score = model.Property( + f"{Workload} has {Float:gating_score} gating score" +) +score_ref = Float.ref("g") +wl_ref = Workload.ref() +model.define(wl_ref.gating_score(score_ref)).where(pagerank(wl_ref, score_ref)) diff --git a/datacenter_compute_allocation/model/reasoning.py b/datacenter_compute_allocation/model/reasoning.py deleted file mode 100644 index 6d1ffe6c..00000000 --- a/datacenter_compute_allocation/model/reasoning.py +++ /dev/null @@ -1,627 +0,0 @@ -"""Datacenter compute allocation reasoning: GNN, eligibility rules, gating PageRank, the allocation MIP, and its outcome rules.""" - -from relationalai.semantics import Float, Integer, String, not_, sum -from relationalai.semantics.reasoners.graph import Graph -from relationalai.semantics.reasoners.predictive import GNN, PropertyTransformer -from relationalai.semantics.reasoners.prescriptive import Problem -from relationalai.semantics.std import aggregates as aggs -from relationalai.semantics.std import math, strings - -from .schema import ( - DataCenterRequest, - DemandScenario, - DiversityCap, - GpuPool, - LabMetric, - MarginFloor, - PowerEnvelopeLevel, - Test, - Train, - Val, - Workload, - WorkloadDependency, - WorkloadGpuCompat, - model, -) - -SEED = 42 -GNN_EPOCHS = 80 -GNN_LR = 0.002 - -# Headline plan cell. The AllocationPlan singleton + Assignment.is_chosen -# flag persist this cell's outcome; tighter cells in the 24-cell sweep -# remain queryable via Assignment.x_assign but are diagnostic overlays -# rather than the operator-facing plan. -CHOSEN_ENVELOPE = "100pct" -CHOSEN_MARGIN = "unconstrained" -CHOSEN_DIVERSITY = "none" -PLAN_ID = "DCCA_BASELINE" - -# Stage 4 solver. HiGHS is the open-source default that ships with the -# prescriptive engine; switch to "gurobi" if your engine has a Gurobi -# license (faster convergence, tighter MIP gaps on the 24-cell sweep). -SOLVER = "highs" -SOLVER_TIME_LIMIT_SEC = 240 - -WORKLOAD_TYPES = ("pretrain", "finetune", "inference", "eval") - -# -------------------------------------------------- -# Stage 1: Predictive -- per-workload utilization-probability GNN -# Binary node classification: for each Workload, predict the probability -# that the workload will be high-utilization next period. Stranded -# capacity (depreciation accruing without offsetting revenue) is the -# operator's biggest economic exposure, so this is the load-bearing -# forward-looking signal. -# -# Heterogeneous graph with three cross-concept edge types: -# 1. lab_workloads: LabMetric -> Workload owned by the same lab -# 2. WorkloadDependency.blocks DAG (shared with Stage 3) -# 3. co_dated: LabMetric -> LabMetric on the same date when their -# labs share a workload_type (cross-lab industry co-movement) -# -------------------------------------------------- - -# Heterogeneous graph over LabMetric and Workload with three edge types. -gnn_graph = Graph(model, name="gnn_graph", directed=False, weighted=False) - -# Edge 1: LabMetric -> Workload owned by the same lab. -model.define(gnn_graph.Edge.new(src=LabMetric, dst=Workload)).where( - LabMetric.lab == Workload.lab.name, -) - -# Edge 2: WorkloadDependency.blocks DAG -- shared with Stage 3 PageRank. -dep_ref = WorkloadDependency.ref() -model.define( - gnn_graph.Edge.new(src=dep_ref.predecessor, dst=dep_ref.successor) -).where(dep_ref.dependency_type == "blocks") - -# Edge 3: LabMetric -> LabMetric, cross-lab same-date pairs whose labs -# share a workload_type. They carry the cross-lab co-movement signal that -# a per-workload tabular model cannot see. -LM_a = LabMetric.ref() -LM_b = LabMetric.ref() -Wl_a = Workload.ref() -Wl_b = Workload.ref() -model.define(gnn_graph.Edge.new(src=LM_a, dst=LM_b)).where( - LM_a.metric_date == LM_b.metric_date, - LM_a.lab != LM_b.lab, - Wl_a.lab.name == LM_a.lab, - Wl_b.lab.name == LM_b.lab, - Wl_a.workload_type == Wl_b.workload_type, -) - -# Feature configuration -- drop PKs/identifiers; type the rest. -# LabMetric.metric_date is the time_col -- it must also appear in -# datetime= per the rai-predictive-training triple-coupling rule. -pt = PropertyTransformer( - drop=[ - LabMetric.metric_id, - Workload.id, Workload.name, - ], - category=[ - LabMetric.lab, - Workload.lab, Workload.workload_type, Workload.gpu_type_preferred, - Workload.reservation_model, - ], - continuous=[ - LabMetric.active_training_runs, LabMetric.gpu_hours_consumed, - LabMetric.tokens_trained, LabMetric.inference_qps, - LabMetric.eval_runs_launched, LabMetric.paper_submissions, - LabMetric.funding_announced_usd, LabMetric.model_release_events, - LabMetric.prev_day_growth, LabMetric.prev_week_growth, - LabMetric.growth_7d_mean, - Workload.gpu_count_required, Workload.mem_required_gb, - Workload.strategic_value_usd, Workload.duration_hours, - ], - datetime=[LabMetric.metric_date], - time_col=[LabMetric.metric_date], -) - -# `name` ties this GNN to the registered model and version that -# `reasoners.predictive.gnns.workload_utilization` names in raiconfig.yaml: -# train.py registers the trained run there, and every refresh scores the -# test split with it. -gnn = GNN( - name="workload_utilization", - graph=gnn_graph, - property_transformer=pt, - train=Train, - validation=Val, - task_type="binary_classification", - eval_metric="roc_auc", - has_time_column=True, - stream_logs=False, - seed=SEED, - n_epochs=GNN_EPOCHS, - lr=GNN_LR, -) -Workload.predictions = gnn.predictions(domain=Test) - -# The probability is a property of its own concept, not of Workload: the GNN -# reads the Workload table, so a Workload property derived from the -# predictions would make the predictions depend on themselves. -WorkloadForecast = model.Concept("WorkloadForecast", identify_by={"workload_id": String}) -WorkloadForecast.utilization_probability = model.Property( - f"{WorkloadForecast} has {Float:utilization_probability} utilization probability" -) -model.define(WorkloadForecast.new(workload_id=Workload.id)).where(Workload.predictions) -model.define(WorkloadForecast.utilization_probability(Workload.predictions.probs)).where( - Workload.predictions, - Workload.id == WorkloadForecast.workload_id, -) - -# -------------------------------------------------- -# Stage 2: Rules -- eligibility + priority classification -# Hardware compatibility (memory + GPU-type allowlist) + priority tier -# from contract_tier. Asymmetric failure-mode pricing: under-provisioning -# an anchor (P0) carries an SLA / contract / reputational penalty that is -# a multiple of the raw foregone revenue; Stage 4 multiplies the -# assignment reward by (1 + under_provisioning_penalty). -# -------------------------------------------------- - -# Rule family 1: hardware compatibility -# `is_eligible` is defined with positive conditions directly (PyRel -# does not support `~` negation on relationship-application expressions). -# Failure flags are still derived for reporting/queryability: -Workload.fails_memory = model.Relationship( - f"{Workload} fails memory check on {GpuPool}" -) -model.where( - Workload.mem_required_gb > GpuPool.mem_per_gpu_gb, -).define(Workload.fails_memory(GpuPool)) - -# Rule family 2: priority tier + numeric weight (lex-emulating spread) -Workload.priority_tier = model.Property( - f"{Workload} has priority tier {String:priority_tier}" -) -Workload.priority_weight = model.Property( - f"{Workload} has {Float:priority_weight} priority weight" -) -model.where(Workload.lab.contract_tier == "anchor_reserved").define( - Workload.priority_tier("P0")) -model.where(Workload.lab.contract_tier == "committed").define( - Workload.priority_tier("P1")) -model.where(Workload.lab.contract_tier == "on_demand").define( - Workload.priority_tier("P2")) - -model.where(Workload.priority_tier == "P0").define(Workload.priority_weight(100.0)) -model.where(Workload.priority_tier == "P1").define(Workload.priority_weight(10.0)) -model.where(Workload.priority_tier == "P2").define(Workload.priority_weight(1.0)) - -# Asymmetric failure mode: unfilled P0 seats hurt more than unfilled P2. -Workload.under_provisioning_penalty = model.Property( - f"{Workload} has {Float:under_provisioning_penalty} under-provisioning penalty" -) -model.where(Workload.priority_tier == "P0").define( - Workload.under_provisioning_penalty(1.0)) -model.where(Workload.priority_tier == "P1").define( - Workload.under_provisioning_penalty(0.3)) -model.where(Workload.priority_tier == "P2").define( - Workload.under_provisioning_penalty(0.0)) - -# Composite eligibility: positive form of (passes_gpu_type AND passes_memory). -Workload.is_eligible = model.Relationship( - f"{Workload} is eligible on {GpuPool}" -) -model.where( - WorkloadGpuCompat.workload == Workload, - WorkloadGpuCompat.gpu_type == GpuPool.gpu_type, - Workload.mem_required_gb <= GpuPool.mem_per_gpu_gb, -).define(Workload.is_eligible(GpuPool)) - -# Compatibility precompute -- keeps the Stage 4 MIP linear and small. -Compatibility = model.Concept( - "Compatibility", - identify_by={"workload": Workload, "gpu_pool": GpuPool}, -) -model.where( - Workload.is_eligible(GpuPool), -).define( - Compatibility.new(workload=Workload, gpu_pool=GpuPool) -) - -# -------------------------------------------------- -# Stage 3: Graph -- workload-dependency PageRank (gating score) -# Reverse-PageRank on the WorkloadDependency.blocks DAG: a high -# `gating_score` means many downstream workloads are gated by this -# one (frontier pretrain that gates 14 fine-tunes + evals lands at -# the top). -# -------------------------------------------------- - -dag = Graph(model, name="dependency_dag", directed=True, weighted=False, node_concept=Workload) - -# Edge reversal: PageRank flows toward upstream gating workloads. -# We define edges as (successor -> predecessor) so a node's PageRank -# accumulates incoming flow from everything it gates. -dep_ref = WorkloadDependency.ref() -model.define( - dag.Edge.new(src=dep_ref.successor, dst=dep_ref.predecessor) -).where(dep_ref.dependency_type == "blocks") - -pagerank = dag.pagerank() -Workload.gating_score = model.Property( - f"{Workload} has {Float:gating_score} gating score" -) -score_ref = Float.ref("g") -wl_ref = Workload.ref() -model.define(wl_ref.gating_score(score_ref)).where(pagerank(wl_ref, score_ref)) - -# -------------------------------------------------- -# Stage 4: Prescriptive -- compute allocation MIP (24-cell sweep) -# Decision variable: Assignment.x_assign(PowerEnvelopeLevel, MarginFloor, -# DiversityCap), binary. One per (Workload, GpuPool) -# in Compatibility, per scenario cell. -# -# Constraints: -# C1+C2 -- At most one assignment per workload per cell, P0 included: -# priority_weight=100 in the objective weights P0 workloads -# heavily but does not force them in, so a P0 workload left -# unassigned in a cell is a diagnostic signal. -# C3 -- Per-pool GPU-count capacity. -# C4 -- Per-DC power envelope: gpu_count * power_per_gpu * pue <= -# approved_mw * 1000 * envelope_multiplier. -# C5 -- Gross-margin floor (linearized; skipped when fraction < 0). -# C6 -- Anchor concentration cap (skipped when share < 0). -# C7 -- Workload-type floor (one per type; skipped when floor < 0). -# -# Objective: maximize sum over assignments of -# priority_weight * gating_score * utilization_probability * -# strategic_value_usd * (1 + under_provisioning_penalty) -# -------------------------------------------------- - -# Decision variable: Assignment indexed by the three scenario axes. A -# workload is assignable once it has a utilization forecast. -Assignment = model.Concept( - "Assignment", - identify_by={"workload": Workload, "gpu_pool": GpuPool}, -) -model.define( - Assignment.new(workload=Compatibility.workload, gpu_pool=Compatibility.gpu_pool) -).where(WorkloadForecast.workload_id == Compatibility.workload.id) - -Assignment.x_assign = model.Property( - f"{Assignment} per {PowerEnvelopeLevel} per {MarginFloor} per {DiversityCap} " - f"assigned {Float:x_assign}" -) - -problem = Problem(model, Float, name="datacenter_compute_allocation") - -# Bind the decision variable. The Float ref pattern (mirrors upstream -# energy_grid_planning's x_a / x_u) lets constraints and objective -# reference the variable's value via the bound Float ref inside arithmetic. -x = Float.ref("x") -problem.solve_for( - Assignment.x_assign(PowerEnvelopeLevel, MarginFloor, DiversityCap, x), - type="bin", - name=["assign", PowerEnvelopeLevel.name, MarginFloor.name, DiversityCap.name, - Assignment.workload.id, Assignment.gpu_pool.id], -) - -# C1+C2: at most one assignment per workload per cell -x2 = Float.ref() -Wany = Workload.ref() -problem.satisfy(model.where( - Assignment.x_assign(PowerEnvelopeLevel, MarginFloor, DiversityCap, x2), - Assignment.workload == Wany, -).require( - sum(Assignment, x2).per(Wany, PowerEnvelopeLevel, MarginFloor, DiversityCap) <= 1.0 -)) - -# C3: per-pool GPU count capacity -x3 = Float.ref() -G = GpuPool.ref() -problem.satisfy(model.where( - Assignment.x_assign(PowerEnvelopeLevel, MarginFloor, DiversityCap, x3), - Assignment.gpu_pool == G, -).require( - sum(x3 * Assignment.workload.gpu_count_required) - .per(G, PowerEnvelopeLevel, MarginFloor, DiversityCap) - <= G.available_gpu_count -)) - -# C4: per-DC power envelope -x4 = Float.ref() -DC = DataCenterRequest.ref() -problem.satisfy(model.where( - Assignment.x_assign(PowerEnvelopeLevel, MarginFloor, DiversityCap, x4), - Assignment.gpu_pool.data_center == DC, -).require( - sum(x4 - * Assignment.workload.gpu_count_required - * Assignment.gpu_pool.power_per_gpu_kw - * DC.pue) - .per(DC, PowerEnvelopeLevel, MarginFloor, DiversityCap) - <= DC.approved_mw * 1000.0 * PowerEnvelopeLevel.envelope_multiplier -)) - -# C5: gross-margin floor (linearized; skipped when fraction < 0) -# revenue * (1 - fraction) >= total_cost -# total_cost = energy_cost + depreciation_cost (per workload, per duration) -# Energy alone clears at ~99% margin; depreciation is the SemiAnalysis -# 14-16% net BMaaS pressure source. -x5 = Float.ref() -problem.satisfy(model.where( - Assignment.x_assign(PowerEnvelopeLevel, MarginFloor, DiversityCap, x5), - MarginFloor.fraction >= 0.0, -).require( - sum(x5 * Assignment.workload.strategic_value_usd - * (1.0 - MarginFloor.fraction)) - .per(PowerEnvelopeLevel, MarginFloor, DiversityCap) - >= sum(x5 * Assignment.workload.gpu_count_required - * Assignment.workload.duration_hours - * (Assignment.gpu_pool.power_per_gpu_kw - * Assignment.gpu_pool.data_center.pue - * Assignment.gpu_pool.data_center.dollars_per_mwh / 1000.0 - + Assignment.gpu_pool.hourly_depreciation_rate)) - .per(PowerEnvelopeLevel, MarginFloor, DiversityCap) -)) - -# C6: anchor concentration cap (skipped when share < 0) -x6 = Float.ref() -problem.satisfy(model.where( - Assignment.x_assign(PowerEnvelopeLevel, MarginFloor, DiversityCap, x6), - DiversityCap.anchor_max_share >= 0.0, -).require( - sum(x6 * Assignment.workload.strategic_value_usd) - .where(Assignment.workload.lab.is_strategic_anchor == True) - .per(PowerEnvelopeLevel, MarginFloor, DiversityCap) - <= DiversityCap.anchor_max_share - * sum(x6 * Assignment.workload.strategic_value_usd) - .per(PowerEnvelopeLevel, MarginFloor, DiversityCap) -)) - -# C7: workload-type floor (one constraint per type; skipped when floor < 0) -for wt in WORKLOAD_TYPES: - x7 = Float.ref() - problem.satisfy(model.where( - Assignment.x_assign(PowerEnvelopeLevel, MarginFloor, DiversityCap, x7), - DiversityCap.workload_type_floor >= 0.0, - ).require( - sum(Assignment, x7) - .where(Assignment.workload.workload_type == wt) - .per(PowerEnvelopeLevel, MarginFloor, DiversityCap) - >= DiversityCap.workload_type_floor - * sum(Assignment, x7).per(PowerEnvelopeLevel, MarginFloor, DiversityCap) - )) - -# Objective: four-factor strategic value, amplified by under-provisioning penalty -# The (1 + under_provisioning_penalty) multiplier captures asymmetric failure modes: -# an unfilled anchor seat (P0) costs more than the foregone revenue, while an -# unfilled research eval costs only the revenue. P0 = 1.0 (2x amp), P1 = 0.3, P2 = 0.0. -x_obj = Float.ref() -problem.maximize( - sum(PowerEnvelopeLevel, MarginFloor, DiversityCap, - x_obj - * Assignment.workload.priority_weight - * Assignment.workload.gating_score - * WorkloadForecast.utilization_probability - * Assignment.workload.strategic_value_usd - * (1.0 + Assignment.workload.under_provisioning_penalty)) - .where( - Assignment.x_assign(PowerEnvelopeLevel, MarginFloor, DiversityCap, x_obj), - WorkloadForecast.workload_id == Assignment.workload.id, - ) -) - -# Each refresh of the deployed model runs this solve. -problem.configure(SOLVER, time_limit_sec=SOLVER_TIME_LIMIT_SEC) - -# The solve's status, time and objective, which the deployed model publishes for the queries. -SolveStatus = model.Relationship(f"datacenter allocation solve status is {String:status}") -SolveTime = model.Relationship(f"datacenter allocation solve time is {Float:seconds}") -SolveObjective = model.Relationship(f"datacenter allocation objective is {Float:objective}") -model.define( - SolveStatus(problem.termination_status()), - SolveTime(problem.solve_time_sec()), - SolveObjective(problem.objective_value()), -) - -# -------------------------------------------------- -# Stage 4 (cont.): Per-cell outcomes + headline-plan persistence -# One ScenarioCell per (env, mar, div). Its aggregates are computed from the -# solved Assignment.x_assign values (mirrors energy_grid_planning's -# InvestmentPortfolio). An infeasible cell has no assignments, so its -# aggregates have no value. The chosen baseline cell is persisted as an -# AllocationPlan singleton + Assignment.is_chosen flag + DemandScenario -# overlay so the plan is queryable as ontology. -# -------------------------------------------------- - -ScenarioCell = model.Concept( - "ScenarioCell", - identify_by={"envelope": PowerEnvelopeLevel, "margin": MarginFloor, "diversity": DiversityCap}, -) -ScenarioCell.n_assigned = model.Property(f"{ScenarioCell} has {Integer:n_assigned}") -ScenarioCell.revenue_usd = model.Property(f"{ScenarioCell} has {Float:revenue_usd}") -ScenarioCell.anchor_revenue_usd = model.Property(f"{ScenarioCell} has {Float:anchor_revenue_usd}") -ScenarioCell.energy_cost_usd = model.Property(f"{ScenarioCell} has {Float:energy_cost_usd}") -ScenarioCell.dep_cost_usd = model.Property(f"{ScenarioCell} has {Float:dep_cost_usd}") -ScenarioCell.total_cost_usd = model.Property(f"{ScenarioCell} has {Float:total_cost_usd}") -ScenarioCell.realized_margin = model.Property(f"{ScenarioCell} has {Float:realized_margin}") -ScenarioCell.anchor_share = model.Property(f"{ScenarioCell} has {Float:anchor_share}") -ScenarioCell.n_by_type = model.Relationship( - f"{ScenarioCell} has {String:workload_type} workload count {Integer:n}" -) -ScenarioCell.n_by_tier = model.Relationship( - f"{ScenarioCell} has {String:priority_tier} workload count {Integer:n}" -) -ScenarioCell.status = model.Property(f"{ScenarioCell} has status {String:status}") - -model.define(ScenarioCell.new( - envelope=PowerEnvelopeLevel, margin=MarginFloor, diversity=DiversityCap, -)) - -xq = Float.ref("xq") - - -def _assigned_in_cell(): - """Conditions selecting the Assignments the solve placed in ScenarioCell.""" - return ( - Assignment.x_assign(ScenarioCell.envelope, ScenarioCell.margin, ScenarioCell.diversity, xq), - xq > 0.5, - ) - - -model.define(ScenarioCell.n_assigned( - aggs.count(Assignment).where(*_assigned_in_cell()).per(ScenarioCell) | 0 -)) -model.define(ScenarioCell.revenue_usd( - sum(Assignment, Assignment.workload.strategic_value_usd) - .where(*_assigned_in_cell()).per(ScenarioCell) | 0.0 -)) -model.define(ScenarioCell.anchor_revenue_usd( - sum(Assignment, Assignment.workload.strategic_value_usd) - .where(*_assigned_in_cell(), Assignment.workload.lab.is_strategic_anchor == True) - .per(ScenarioCell) | 0.0 -)) -model.define(ScenarioCell.energy_cost_usd( - sum(Assignment, - Assignment.workload.gpu_count_required - * Assignment.workload.duration_hours - * Assignment.gpu_pool.power_per_gpu_kw - * Assignment.gpu_pool.data_center.pue - * Assignment.gpu_pool.data_center.dollars_per_mwh / 1000.0) - .where(*_assigned_in_cell()).per(ScenarioCell) | 0.0 -)) -model.define(ScenarioCell.dep_cost_usd( - sum(Assignment, - Assignment.workload.gpu_count_required - * Assignment.workload.duration_hours - * Assignment.gpu_pool.hourly_depreciation_rate) - .where(*_assigned_in_cell()).per(ScenarioCell) | 0.0 -)) -model.define(ScenarioCell.total_cost_usd(ScenarioCell.energy_cost_usd + ScenarioCell.dep_cost_usd)) -# A cell with no revenue has no margin or anchor share. -model.where(ScenarioCell.revenue_usd > 0).define( - ScenarioCell.realized_margin( - (ScenarioCell.revenue_usd - ScenarioCell.total_cost_usd) / ScenarioCell.revenue_usd - ), - ScenarioCell.anchor_share(ScenarioCell.anchor_revenue_usd / ScenarioCell.revenue_usd), -) - -# Per-(cell, workload_type) and per-(cell, priority_tier) counts. -wtype = String.ref() -model.define(ScenarioCell.n_by_type( - wtype, - aggs.count(Assignment) - .where(*_assigned_in_cell(), Assignment.workload.workload_type == wtype) - .per(ScenarioCell, wtype), -)) -tier = String.ref() -model.define(ScenarioCell.n_by_tier( - tier, - aggs.count(Assignment) - .where(*_assigned_in_cell(), Assignment.workload.priority_tier == tier) - .per(ScenarioCell, tier), -)) - -# Per-cell status: when the global solve proved optimality, cells with -# assignments are OPTIMAL and cells with none are INFEASIBLE. When the -# wall-clock ran out first, they are FEASIBLE and UNSOLVED. -solve_status = String.ref() -model.where( - SolveStatus(solve_status), solve_status == "OPTIMAL", ScenarioCell.n_assigned > 0 -).define(ScenarioCell.status("OPTIMAL")) -model.where( - SolveStatus(solve_status), solve_status == "OPTIMAL", not_(ScenarioCell.n_assigned > 0) -).define(ScenarioCell.status("INFEASIBLE")) -model.where( - SolveStatus(solve_status), solve_status != "OPTIMAL", ScenarioCell.n_assigned > 0 -).define(ScenarioCell.status("FEASIBLE")) -model.where( - SolveStatus(solve_status), solve_status != "OPTIMAL", not_(ScenarioCell.n_assigned > 0) -).define(ScenarioCell.status("UNSOLVED")) - -# AllocationPlan is a singleton holding the operator-facing summary -# (revenue, cost, anchor share, n_assigned, status, binding axis) for -# the chosen cell; Assignment.is_chosen narrows the per-cell decision -# rows to the chosen scenario. Mirrors the telco_network_recovery -# RestorePlan / is_selected_upgrade pattern. -AllocationPlan = model.Concept("AllocationPlan", identify_by={"id": String}) -AllocationPlan.chosen_envelope = model.Property( - f"{AllocationPlan} has chosen envelope {String:chosen_envelope}" -) -AllocationPlan.chosen_margin = model.Property( - f"{AllocationPlan} has chosen margin {String:chosen_margin}" -) -AllocationPlan.chosen_diversity = model.Property( - f"{AllocationPlan} has chosen diversity {String:chosen_diversity}" -) -AllocationPlan.n_assigned = model.Property(f"{AllocationPlan} has {Integer:n_assigned}") -AllocationPlan.revenue_usd = model.Property(f"{AllocationPlan} has {Float:revenue_usd}") -AllocationPlan.total_cost_usd = model.Property( - f"{AllocationPlan} has {Float:total_cost_usd}" -) -AllocationPlan.realized_margin = model.Property( - f"{AllocationPlan} has {Float:realized_margin}" -) -AllocationPlan.anchor_share = model.Property(f"{AllocationPlan} has {Float:anchor_share}") -AllocationPlan.status = model.Property(f"{AllocationPlan} has status {String:status}") -AllocationPlan.binding_axis = model.Property( - f"{AllocationPlan} has binding axis {String:binding_axis}" -) - -model.define(AllocationPlan.new(id=PLAN_ID)) -chosen_cell = ( - AllocationPlan.id == PLAN_ID, - ScenarioCell.envelope.name == CHOSEN_ENVELOPE, - ScenarioCell.margin.name == CHOSEN_MARGIN, - ScenarioCell.diversity.name == CHOSEN_DIVERSITY, -) -model.where(*chosen_cell).define( - AllocationPlan.chosen_envelope(CHOSEN_ENVELOPE), - AllocationPlan.chosen_margin(CHOSEN_MARGIN), - AllocationPlan.chosen_diversity(CHOSEN_DIVERSITY), -) -model.where(*chosen_cell).define(AllocationPlan.n_assigned(ScenarioCell.n_assigned)) -model.where(*chosen_cell).define(AllocationPlan.revenue_usd(ScenarioCell.revenue_usd)) -model.where(*chosen_cell).define(AllocationPlan.total_cost_usd(ScenarioCell.total_cost_usd)) -model.where(*chosen_cell).define(AllocationPlan.realized_margin(ScenarioCell.realized_margin)) -model.where(*chosen_cell).define(AllocationPlan.anchor_share(ScenarioCell.anchor_share)) -model.where(*chosen_cell).define(AllocationPlan.status(ScenarioCell.status)) -model.where(*chosen_cell, ScenarioCell.n_assigned > 0).define( - AllocationPlan.binding_axis("power_envelope") -) -model.where(*chosen_cell, not_(ScenarioCell.n_assigned > 0)).define( - AllocationPlan.binding_axis(strings.lower(ScenarioCell.status)) -) - -Assignment.is_chosen = model.Relationship(f"{Assignment} is in chosen cell") -xc = Float.ref("xc") -chosen_env_c = PowerEnvelopeLevel.lookup(name=CHOSEN_ENVELOPE) -chosen_mar_c = MarginFloor.lookup(name=CHOSEN_MARGIN) -chosen_div_c = DiversityCap.lookup(name=CHOSEN_DIVERSITY) -model.where( - Assignment.x_assign(chosen_env_c, chosen_mar_c, chosen_div_c, xc), - xc > 0.5, -).define(Assignment.is_chosen()) - -# DemandScenario overlay: stranded-capacity exposure under risk. -# The chosen plan is locked in, but lab-side demand for the assigned -# workloads can soften from the GNN's point forecast. P0 revenue is -# contractual (factor = 1.0); P1/P2 realize only `factor`. The delta -# is stranded capacity: GPUs powered, depreciation accruing, no workload. -DemandScenarioOutlook = model.Concept( - "DemandScenarioOutlook", - identify_by={"scenario": DemandScenario}, -) -DemandScenarioOutlook.realized_revenue_usd = model.Property( - f"{DemandScenarioOutlook} has {Float:realized_revenue_usd}" -) -DemandScenarioOutlook.stranded_revenue_usd = model.Property( - f"{DemandScenarioOutlook} has {Float:stranded_revenue_usd}" -) -model.define(DemandScenarioOutlook.new(scenario=DemandScenario)) - -p0_revenue = sum(Assignment, Assignment.workload.strategic_value_usd).where( - Assignment.is_chosen(), Assignment.workload.priority_tier == "P0" -) | 0.0 -other_revenue = sum(Assignment, Assignment.workload.strategic_value_usd).where( - Assignment.is_chosen(), Assignment.workload.priority_tier != "P0" -) | 0.0 -model.where(DemandScenarioOutlook.scenario == DemandScenario).define( - DemandScenarioOutlook.realized_revenue_usd(p0_revenue + other_revenue * DemandScenario.factor) -) -model.where(AllocationPlan.id == PLAN_ID).define( - DemandScenarioOutlook.stranded_revenue_usd( - math.maximum(AllocationPlan.revenue_usd - DemandScenarioOutlook.realized_revenue_usd, 0.0) - ) -) diff --git a/datacenter_compute_allocation/model/utilization_forecast.py b/datacenter_compute_allocation/model/utilization_forecast.py new file mode 100644 index 00000000..ec5634c4 --- /dev/null +++ b/datacenter_compute_allocation/model/utilization_forecast.py @@ -0,0 +1,138 @@ +"""Utilization forecast: the per-workload utilization-probability GNN, each workload's forecast +probability, and the split of workloads at the high-utilization cutoff.""" + +from relationalai.semantics import Float, Integer, String +from relationalai.semantics.reasoners.graph import Graph +from relationalai.semantics.reasoners.predictive import GNN, PropertyTransformer +from relationalai.semantics.std import aggregates as aggs + +from .schema import LabMetric, Test, Train, Val, Workload, WorkloadDependency, model + +# -------------------------------------------------- +# Configure inputs +# -------------------------------------------------- + +SEED = 42 +GNN_EPOCHS = 80 +GNN_LR = 0.002 + +# A workload forecast at or above this probability is expected to run at high utilization. +HIGH_UTILIZATION = 0.5 + +# -------------------------------------------------- +# Stage 1: Predictive -- per-workload utilization-probability GNN +# Binary node classification: for each Workload, predict the probability +# that the workload will be high-utilization next period. Stranded +# capacity (depreciation accruing without offsetting revenue) is the +# operator's biggest economic exposure, so this is the load-bearing +# forward-looking signal. +# +# Heterogeneous graph with three cross-concept edge types: +# 1. lab_workloads: LabMetric -> Workload owned by the same lab +# 2. WorkloadDependency.blocks DAG (shared with Stage 3) +# 3. co_dated: LabMetric -> LabMetric on the same date when their +# labs share a workload_type (cross-lab industry co-movement) +# -------------------------------------------------- + +# Heterogeneous graph over LabMetric and Workload with three edge types. +gnn_graph = Graph(model, name="gnn_graph", directed=False, weighted=False) + +# Edge 1: LabMetric -> Workload owned by the same lab. +model.define(gnn_graph.Edge.new(src=LabMetric, dst=Workload)).where( + LabMetric.lab == Workload.lab.name, +) + +# Edge 2: WorkloadDependency.blocks DAG -- shared with Stage 3 PageRank. +dep_ref = WorkloadDependency.ref() +model.define( + gnn_graph.Edge.new(src=dep_ref.predecessor, dst=dep_ref.successor) +).where(dep_ref.dependency_type == "blocks") + +# Edge 3: LabMetric -> LabMetric, cross-lab same-date pairs whose labs +# share a workload_type. They carry the cross-lab co-movement signal that +# a per-workload tabular model cannot see. +LM_a = LabMetric.ref() +LM_b = LabMetric.ref() +Wl_a = Workload.ref() +Wl_b = Workload.ref() +model.define(gnn_graph.Edge.new(src=LM_a, dst=LM_b)).where( + LM_a.metric_date == LM_b.metric_date, + LM_a.lab != LM_b.lab, + Wl_a.lab.name == LM_a.lab, + Wl_b.lab.name == LM_b.lab, + Wl_a.workload_type == Wl_b.workload_type, +) + +# Feature configuration -- drop PKs/identifiers; type the rest. +# LabMetric.metric_date is the time_col -- it must also appear in +# datetime= per the rai-predictive-training triple-coupling rule. +pt = PropertyTransformer( + drop=[ + LabMetric.metric_id, + Workload.id, Workload.name, + ], + category=[ + LabMetric.lab, + Workload.lab, Workload.workload_type, Workload.gpu_type_preferred, + Workload.reservation_model, + ], + continuous=[ + LabMetric.active_training_runs, LabMetric.gpu_hours_consumed, + LabMetric.tokens_trained, LabMetric.inference_qps, + LabMetric.eval_runs_launched, LabMetric.paper_submissions, + LabMetric.funding_announced_usd, LabMetric.model_release_events, + LabMetric.prev_day_growth, LabMetric.prev_week_growth, + LabMetric.growth_7d_mean, + Workload.gpu_count_required, Workload.mem_required_gb, + Workload.strategic_value_usd, Workload.duration_hours, + ], + datetime=[LabMetric.metric_date], + time_col=[LabMetric.metric_date], +) + +# `name` ties this GNN to the registered model and version that +# `reasoners.predictive.gnns.workload_utilization` names in raiconfig.yaml: +# train.py registers the trained run there, and every refresh scores the +# test split with it. +gnn = GNN( + name="workload_utilization", + graph=gnn_graph, + property_transformer=pt, + train=Train, + validation=Val, + task_type="binary_classification", + eval_metric="roc_auc", + has_time_column=True, + stream_logs=False, + seed=SEED, + n_epochs=GNN_EPOCHS, + lr=GNN_LR, +) +Workload.predictions = gnn.predictions(domain=Test) + +# The probability is a property of its own concept, not of Workload: the GNN +# reads the Workload table, so a Workload property derived from the +# predictions would make the predictions depend on themselves. +WorkloadForecast = model.Concept("WorkloadForecast", identify_by={"workload_id": String}) +WorkloadForecast.utilization_probability = model.Property( + f"{WorkloadForecast} has {Float:utilization_probability} utilization probability" +) +model.define(WorkloadForecast.new(workload_id=Workload.id)).where(Workload.predictions) +model.define(WorkloadForecast.utilization_probability(Workload.predictions.probs)).where( + Workload.predictions, + Workload.id == WorkloadForecast.workload_id, +) + +# How many workloads have a forecast, how many of them are at or above the +# high-utilization cutoff, and how many are below it. +UtilizationSplit = model.Relationship( + f"the forecast covers {Integer:n_total} workloads, {Integer:n_high} at high utilization " + f"and {Integer:n_low} below" +) +model.define(UtilizationSplit( + aggs.count(WorkloadForecast).where(WorkloadForecast.utilization_probability), + aggs.count(WorkloadForecast).where( + WorkloadForecast.utilization_probability >= HIGH_UTILIZATION) | 0, + aggs.count(WorkloadForecast).where( + WorkloadForecast.utilization_probability < HIGH_UTILIZATION) | 0, +)) diff --git a/datacenter_compute_allocation/model/workload_eligibility.py b/datacenter_compute_allocation/model/workload_eligibility.py new file mode 100644 index 00000000..d70839a5 --- /dev/null +++ b/datacenter_compute_allocation/model/workload_eligibility.py @@ -0,0 +1,89 @@ +"""Workload eligibility: each workload's priority tier and weights, the hardware compatibility of +workloads with GPU pools, and the workload count per priority tier.""" + +from relationalai.semantics import Float, Integer, String +from relationalai.semantics.std import aggregates as aggs + +from .schema import GpuPool, Workload, WorkloadGpuCompat, model + +# -------------------------------------------------- +# Stage 2: Rules -- eligibility + priority classification +# Hardware compatibility (memory + GPU-type allowlist) + priority tier +# from contract_tier. Asymmetric failure-mode pricing: under-provisioning +# an anchor (P0) carries an SLA / contract / reputational penalty that is +# a multiple of the raw foregone revenue; Stage 4 multiplies the +# assignment reward by (1 + under_provisioning_penalty). +# -------------------------------------------------- + +# The priority tiers assigned below. +PRIORITY_TIERS = ("P0", "P1", "P2") + +# Rule family 1: hardware compatibility +# `is_eligible` is defined with positive conditions directly (PyRel +# does not support `~` negation on relationship-application expressions). +# Failure flags are still derived for reporting/queryability: +Workload.fails_memory = model.Relationship( + f"{Workload} fails memory check on {GpuPool}" +) +model.where( + Workload.mem_required_gb > GpuPool.mem_per_gpu_gb, +).define(Workload.fails_memory(GpuPool)) + +# Rule family 2: priority tier + numeric weight (lex-emulating spread) +Workload.priority_tier = model.Property( + f"{Workload} has priority tier {String:priority_tier}" +) +Workload.priority_weight = model.Property( + f"{Workload} has {Float:priority_weight} priority weight" +) +model.where(Workload.lab.contract_tier == "anchor_reserved").define( + Workload.priority_tier("P0")) +model.where(Workload.lab.contract_tier == "committed").define( + Workload.priority_tier("P1")) +model.where(Workload.lab.contract_tier == "on_demand").define( + Workload.priority_tier("P2")) + +model.where(Workload.priority_tier == "P0").define(Workload.priority_weight(100.0)) +model.where(Workload.priority_tier == "P1").define(Workload.priority_weight(10.0)) +model.where(Workload.priority_tier == "P2").define(Workload.priority_weight(1.0)) + +# Asymmetric failure mode: unfilled P0 seats hurt more than unfilled P2. +Workload.under_provisioning_penalty = model.Property( + f"{Workload} has {Float:under_provisioning_penalty} under-provisioning penalty" +) +model.where(Workload.priority_tier == "P0").define( + Workload.under_provisioning_penalty(1.0)) +model.where(Workload.priority_tier == "P1").define( + Workload.under_provisioning_penalty(0.3)) +model.where(Workload.priority_tier == "P2").define( + Workload.under_provisioning_penalty(0.0)) + +# Workloads per priority tier; a tier without workloads has no row. +PriorityTierCount = model.Relationship( + f"{Integer:n_workloads} workloads have priority tier {String:priority_tier}" +) +_tier = String.ref() +model.where(Workload.priority_tier == _tier).define( + PriorityTierCount(aggs.count(Workload).per(_tier), _tier) +) + +# Composite eligibility: positive form of (passes_gpu_type AND passes_memory). +Workload.is_eligible = model.Relationship( + f"{Workload} is eligible on {GpuPool}" +) +model.where( + WorkloadGpuCompat.workload == Workload, + WorkloadGpuCompat.gpu_type == GpuPool.gpu_type, + Workload.mem_required_gb <= GpuPool.mem_per_gpu_gb, +).define(Workload.is_eligible(GpuPool)) + +# Compatibility precompute -- keeps the Stage 4 MIP linear and small. +Compatibility = model.Concept( + "Compatibility", + identify_by={"workload": Workload, "gpu_pool": GpuPool}, +) +model.where( + Workload.is_eligible(GpuPool), +).define( + Compatibility.new(workload=Workload, gpu_pool=GpuPool) +) diff --git a/datacenter_compute_allocation/queries/allocation_report.py b/datacenter_compute_allocation/queries/allocation_report.py index cd41a2eb..b866d47b 100644 --- a/datacenter_compute_allocation/queries/allocation_report.py +++ b/datacenter_compute_allocation/queries/allocation_report.py @@ -17,10 +17,16 @@ import pandas as pd from model import ( + CHOSEN_DIVERSITY, + CHOSEN_ENVELOPE, + CHOSEN_MARGIN, + HIGH_UTILIZATION, + PRIORITY_TIERS, WORKLOAD_TYPES, AILab, AllocationPlan, Assignment, + CellStatusCount, Compatibility, DataCenterRequest, DemandScenario, @@ -29,10 +35,12 @@ GpuPool, MarginFloor, PowerEnvelopeLevel, + PriorityTierCount, ScenarioCell, SolveObjective, SolveStatus, SolveTime, + UtilizationSplit, Workload, WorkloadDependency, WorkloadForecast, @@ -41,7 +49,13 @@ from relationalai.semantics import Integer, String, count, select CELL_KEYS = ["envelope", "margin", "diversity"] -PRIORITY_TIERS = ("P0", "P1", "P2") +CELL_KEY_COLUMNS = [ + ScenarioCell.envelope.name.alias("envelope"), + ScenarioCell.margin.name.alias("margin"), + ScenarioCell.diversity.name.alias("diversity"), +] +TOP_FORECASTS = 5 +TOP_GATING = 10 def banner(title: str) -> None: @@ -59,34 +73,41 @@ def stage_0_ontology() -> None: count(PowerEnvelopeLevel).alias("envelopes"), count(MarginFloor).alias("margins"), count(DiversityCap).alias("diversities"), + count(ScenarioCell).alias("cells"), ).to_df().iloc[0] print(f" Loaded {int(n['dcs'])} DataCenterRequest entries") - cells = int(n["envelopes"]) * int(n["margins"]) * int(n["diversities"]) print(f" Ontology loaded: {int(n['labs'])} labs, {int(n['pools'])} pools, " f"{int(n['workloads'])} workloads, {int(n['deps'])} dep edges, " - f"{int(n['envelopes'])}x{int(n['margins'])}x{int(n['diversities'])}={cells} scenario cells") + f"{int(n['envelopes'])}x{int(n['margins'])}x{int(n['diversities'])}={int(n['cells'])} " + f"scenario cells") def stage_1_predictive() -> bool: banner("STAGE 1: PREDICT -- per-workload utilization-probability GNN") + total_ref, high_ref, low_ref = Integer.ref(), Integer.ref(), Integer.ref() + split = ( + select(total_ref.alias("n_total"), high_ref.alias("n_high"), low_ref.alias("n_low")) + .where(UtilizationSplit(total_ref, high_ref, low_ref)) + .to_df() + ) + if split.empty: + print(" (no predictions returned) Run `python train.py`, then refresh the deployed model.") + return False + n_total, n_high, n_low = (int(split[c].iloc[0]) for c in ("n_total", "n_high", "n_low")) + print(f" Workload utilization-probability distribution: " + f"n_total={n_total}, n>={HIGH_UTILIZATION}: {n_high}, n<{HIGH_UTILIZATION}: {n_low}") probs_df = select( Workload.id.alias("id"), Workload.name.alias("name"), WorkloadForecast.utilization_probability.alias("p"), ).where(WorkloadForecast.workload_id == Workload.id).to_df() - if probs_df.empty: - print(" (no predictions returned) Run `python train.py`, then refresh the deployed model.") - return False probs_df["p"] = pd.to_numeric(probs_df["p"], errors="coerce") - n_high = int((probs_df["p"] >= 0.5).sum()) - n_total = int(probs_df["p"].notna().sum()) - print(f" Workload utilization-probability distribution: " - f"n_total={n_total}, n>=0.5: {n_high}, n<0.5: {n_total - n_high}") - print(" Top 5 (most likely to be high-utilization):") - for _, r in probs_df.sort_values("p", ascending=False).head(5).iterrows(): + print(f" Top {TOP_FORECASTS} (most likely to be high-utilization):") + # Ties on the probability list the lower workload id first. + for _, r in probs_df.sort_values(["p", "id"], ascending=[False, True]).head(TOP_FORECASTS).iterrows(): print(f" + {r['name']:<45} p={float(r['p']):.3f}") - print(" Bottom 5 (most likely to stall / be repaced):") - for _, r in probs_df.sort_values("p", ascending=True).head(5).iterrows(): + print(f" Bottom {TOP_FORECASTS} (most likely to stall / be repaced):") + for _, r in probs_df.sort_values(["p", "id"]).head(TOP_FORECASTS).iterrows(): print(f" - {r['name']:<45} p={float(r['p']):.3f}") return True @@ -94,8 +115,12 @@ def stage_1_predictive() -> bool: def stage_2_rules() -> None: banner("STAGE 2: RULES -- eligibility + priority classification") n_compat = int(select(count(Compatibility).alias("n")).to_df()["n"].iloc[0]) - tier_df = select(Workload.id.alias("id"), Workload.priority_tier.alias("tier")).to_df() - tier_counts = tier_df.groupby("tier").size().reset_index(name="n") + tier, n_workloads = String.ref(), Integer.ref() + tier_counts = ( + select(tier.alias("tier"), n_workloads.alias("n")) + .where(PriorityTierCount(n_workloads, tier)) + .to_df() + ) print(f" Compatibility table: {n_compat} eligible (Workload, GpuPool) pairs") print(" Priority tier counts:") for _, r in tier_counts.sort_values("tier").iterrows(): @@ -109,20 +134,20 @@ def stage_3_graph() -> None: Workload.name.alias("name"), Workload.gating_score.alias("gating_score"), ).to_df() - top = g_df.dropna(subset=["gating_score"]).sort_values("gating_score", ascending=False).head(10) - print(" Top-10 gating workloads (frontier pretrains expected to dominate):") + # Ties on the gating score list the lower workload id first. + top = ( + g_df.dropna(subset=["gating_score"]) + .sort_values(["gating_score", "id"], ascending=[False, True]) + .head(TOP_GATING) + ) + print(f" Top-{TOP_GATING} gating workloads (frontier pretrains expected to dominate):") for _, r in top.iterrows(): print(f" {r['name']:<45} score={float(r['gating_score']):.4f}") def cell_table() -> pd.DataFrame: """One row per scenario cell: status, aggregates (0 when the cell has no assignments), and counts.""" - keys = [ - ScenarioCell.envelope.name.alias("envelope"), - ScenarioCell.margin.name.alias("margin"), - ScenarioCell.diversity.name.alias("diversity"), - ] - cells_df = select(*keys, ScenarioCell.status.alias("status")).to_df() + cells_df = select(*CELL_KEY_COLUMNS, ScenarioCell.status.alias("status")).to_df() for col, prop in ( ("n_assigned", ScenarioCell.n_assigned), ("revenue_usd", ScenarioCell.revenue_usd), @@ -131,7 +156,7 @@ def cell_table() -> pd.DataFrame: ("realized_margin", ScenarioCell.realized_margin), ("anchor_share", ScenarioCell.anchor_share), ): - part = select(*keys, prop.alias(col)).to_df() + part = select(*CELL_KEY_COLUMNS, prop.alias(col)).to_df() cells_df = cells_df.merge(part, on=CELL_KEYS, how="left") for col in ("n_assigned", "revenue_usd", "anchor_revenue_usd", "total_cost_usd"): cells_df[col] = cells_df[col].fillna(0) @@ -141,7 +166,7 @@ def cell_table() -> pd.DataFrame: (ScenarioCell.n_by_type, WORKLOAD_TYPES), (ScenarioCell.n_by_tier, PRIORITY_TIERS), ): - part = select(*keys, kind.alias("kind"), count_ref.alias("n")).where( + part = select(*CELL_KEY_COLUMNS, kind.alias("kind"), count_ref.alias("n")).where( relationship(kind, count_ref) ).to_df() wide = part.pivot_table(index=CELL_KEYS, columns="kind", values="n", aggfunc="sum").reset_index() @@ -155,6 +180,26 @@ def cell_table() -> pd.DataFrame: return cells_df.sort_values(CELL_KEYS) +def status_counts(statuses: pd.Series) -> pd.Series: + """Cells per status label from the model, most first; ties keep the order in which their + labels first appear in `statuses`.""" + status, n_cells = String.ref(), Integer.ref() + by_status = ( + select(status.alias("status"), n_cells.alias("n")) + .where(CellStatusCount(n_cells, status)) + .to_df() + .set_index("status")["n"] + ) + order = pd.Index(statuses.drop_duplicates(), name="status") + return by_status.reindex(order).astype(int).sort_values(ascending=False, kind="stable") + + +def sweep_cells(cells_df: pd.DataFrame, in_sweep) -> pd.DataFrame: + """The rows of the cell table for the cells the model places in the sweep `in_sweep`.""" + members = select(*CELL_KEY_COLUMNS).where(in_sweep()).to_df() + return cells_df.merge(members, on=CELL_KEYS) + + def stage_4_prescriptive() -> None: banner("STAGE 4: PRESCRIPTIVE -- compute allocation MIP (24-cell sweep)") status = model.select(SolveStatus).to_df().iloc[:, 0].tolist() @@ -174,7 +219,7 @@ def stage_4_prescriptive() -> None: if cells_df.empty: print(" No scenario cells returned.") return - labels = cells_df["status"].value_counts() + labels = status_counts(cells_df["status"]) summary = ", ".join(f"{n} {label.lower()}" for label, n in labels.items()) print(f"\n Per-cell summary ({len(cells_df)} cells: {summary}):") display_cols = ( @@ -185,22 +230,17 @@ def stage_4_prescriptive() -> None: ) print(cells_df[display_cols].to_string(index=False, float_format=lambda v: f"{v:,.2f}")) - # Two headline Pareto frontiers, both at envelope=100pct. - headline_env = "100pct" - print(f"\n Pareto frontier 1: Margin floor <-> Revenue (envelope={headline_env}, " - f"diversity=none)") - p1 = cells_df[ - (cells_df["envelope"] == headline_env) & (cells_df["diversity"] == "none") - ].sort_values("margin") + # Two headline Pareto frontiers, both at the headline envelope. + print(f"\n Pareto frontier 1: Margin floor <-> Revenue (envelope={CHOSEN_ENVELOPE}, " + f"diversity={CHOSEN_DIVERSITY})") + p1 = sweep_cells(cells_df, ScenarioCell.in_margin_sweep).sort_values("margin") if len(p1): print(p1[["margin", "n_assigned", "revenue_usd", "realized_margin", "anchor_share"]].to_string(index=False, float_format=lambda v: f"{v:,.2f}")) - print(f"\n Pareto frontier 2: Diversity cap <-> Revenue (envelope={headline_env}, " - f"margin=unconstrained)") - p2 = cells_df[ - (cells_df["envelope"] == headline_env) & (cells_df["margin"] == "unconstrained") - ].sort_values("diversity") + print(f"\n Pareto frontier 2: Diversity cap <-> Revenue (envelope={CHOSEN_ENVELOPE}, " + f"margin={CHOSEN_MARGIN})") + p2 = sweep_cells(cells_df, ScenarioCell.in_diversity_sweep).sort_values("diversity") if len(p2): print(p2[["diversity", "n_assigned", "revenue_usd", "realized_margin", "anchor_share"] + [f"n_{wt}" for wt in WORKLOAD_TYPES] @@ -244,12 +284,10 @@ def stage_4_prescriptive() -> None: DemandScenario.factor.alias("factor"), DemandScenarioOutlook.realized_revenue_usd.alias("realized_revenue_usd"), DemandScenarioOutlook.stranded_revenue_usd.alias("stranded_revenue_usd"), + DemandScenarioOutlook.stranded_share.alias("stranded_pct"), ).where(DemandScenarioOutlook.scenario == DemandScenario).to_df() overlay_df = overlay_df.sort_values("factor", ascending=False).reset_index(drop=True) - expected_revenue = float(plan_df["revenue_usd"].iloc[0]) - overlay_df["stranded_pct"] = ( - overlay_df["stranded_revenue_usd"] / expected_revenue * 100.0 if expected_revenue else 0.0 - ) + overlay_df["stranded_pct"] = overlay_df["stranded_pct"] * 100.0 print("\n DemandScenario overlay (chosen plan replayed under risk):") print(overlay_df.to_string(index=False, float_format=lambda v: f"{v:,.2f}")) diff --git a/defect_root_cause/README.md b/defect_root_cause/README.md index 3efb2839..7f0ca6f7 100644 --- a/defect_root_cause/README.md +++ b/defect_root_cause/README.md @@ -45,7 +45,7 @@ At a high level, this exercises three RelationalAI capabilities on one shared mo ## What's included -- **Model** (`model/` package): the ontology and all three reasoning stages, which `rai models deploy --path model` deploys to your Snowflake account. `schema.py` declares the concepts, `source.py` loads the sample data, and `reasoning.py` states the three reasoning stages. +- **Model** (`model/` package): the ontology and all three reasoning stages, which `rai models deploy --path model` deploys to your Snowflake account. `schema.py` declares the concepts and `source.py` loads the sample data. `failure_timeline.py` rolls failures up by build week, `genealogy.py`, `contrast_scoring.py`, and `diagnosis.py` state the three reasoning stages, and `root_cause_evidence.py` derives each suspect's defect signature. - **Query** (`queries/root_cause_report.py`): prints the report from the deployed model. - **Runbook**: `runbook.md` — a paste-testable walkthrough that reproduces the template step by step with the RAI skills; as important a reference as the script itself. - **Data generator** (`generate_data.py`): rebuilds the sample corpus deterministically from a fixed seed. The generated files are already included, so you do not need to run it to use the template. @@ -197,7 +197,11 @@ defect_root_cause/ │ ├── __init__.py # exports of the deployed model │ ├── schema.py # concepts and properties │ ├── source.py # loads the CSVs -│ └── reasoning.py # genealogy graph, contrast scoring, and the diagnosis solve +│ ├── failure_timeline.py # failure rate by build week and the spike onset +│ ├── genealogy.py # genealogy graph and backward reachability +│ ├── contrast_scoring.py # baseline, lift, and suspects +│ ├── diagnosis.py # the diagnosis solve and its headline +│ └── root_cause_evidence.py # defect signature of each suspect ├── queries/ │ └── root_cause_report.py # report printed from the deployed model ├── generate_data.py # regenerates the corpus (CSVs already included) @@ -230,7 +234,7 @@ The genealogy is the backbone: a built `Lot` consumes its input lots, so followi - **Primary identifiers**: every concept carries a string `id` (for example `LOT::SP-0423` on `Factor`); the genealogy and process history are threaded by relationships (`Lot consumes Lot`, `Unit consumes Lot`, `Unit ran on Machine`) rather than shared keys. - **Important invariants**: `Unit.defective` is `0` or `1`; `Factor.lift` is the touched-unit defect rate over the plant baseline (≈ 1.0 for non-causal high-volume factors); the `is_root_cause` decision variable is binary; a defective unit is either explained by a named cause it touches or marked unexplained. -For the full concept and property definitions — including the relations the reasoning traces (`Lot consumes Lot`, `Unit consumes Lot`, `Unit ran on Machine`, and the derived `Factor touches Unit` incidence) — see `model/schema.py` and, for `Factor touches Unit` and the rest of the derived relations, `model/reasoning.py`; `runbook.md` builds them step by step with the RAI skills. +For the full concept and property definitions — including the relations the reasoning traces (`Lot consumes Lot`, `Unit consumes Lot`, `Unit ran on Machine`, and the derived `Factor touches Unit` incidence) — see `model/schema.py` and, for `Factor touches Unit` and the rest of the derived relations, the modules next to it; `runbook.md` builds them step by step with the RAI skills. ## How it works @@ -242,7 +246,7 @@ failure timeline -> genealogy graph -> contrast scoring -> minimal-diagnosis opt ### Locate the spike onset -A real investigation starts on the timeline rather than the genealogy. Rolling failures up by build week locates the onset — the first week whose rate runs well above the opening baseline — which tells the rest of the chain which window to interrogate. Here the rate steps from 1.9 percent in week one to 6.6 percent in week two, so the onset is week two. +A real investigation starts on the timeline rather than the genealogy. Rolling failures up by build week (`BuildWeek`) locates the onset (`SpikeOnset`) — the first week whose rate runs above twice the opening week's — which marks the window an investigator interrogates first. Here the rate steps from 1.9 percent in week one to 6.6 percent in week two, so the onset is week two. ### Trace the genealogy backward (Graph) @@ -256,7 +260,7 @@ Each candidate is scored by how concentrated defects are among the units it touc A binary decision variable names each suspect a root cause, and a binary slack lets a defective unit be left unexplained. The coverage constraint requires every defective unit to be explained by a named cause it touches or else marked unexplained. The objective trades off three things: a cost for each named cause (so the diagnosis stays small), a penalty for naming a cause that also touches many good units (so it stays specific), and a cost for leaving a defect unexplained. Together these make the optimizer prefer the single deep root over the several proximate sub-assemblies that merely carry it. The deployed model publishes the problem's structure counts, and the report's formulation audit checks them after the refresh has solved; a failed audit stops the report, not the refresh. -See `model/reasoning.py` for the implementation, `queries/root_cause_report.py` for the report, and `runbook.md` to reproduce each stage step by step with the RAI skills. +See `model/genealogy.py`, `model/contrast_scoring.py`, and `model/diagnosis.py` for the implementation, `queries/root_cause_report.py` for the report, and `runbook.md` to reproduce each stage step by step with the RAI skills. ## Sample output @@ -312,7 +316,7 @@ The diagnosis names a contaminated solder-paste lot (`SP-0423`) and a reflow ove ### Use your own data - Replace the CSVs in `data/` with your own genealogy, keeping the same column names. The genealogy can be any depth, because backward reachability handles arbitrary bill-of-materials tiers. -- To add another kind of candidate cause (an operator, a work order, or a supplier site), append rows to `factors.csv` with the new kind, add a matching back-pointer property, and add one `Factor.touches` rule, mirroring the existing lot, machine, and shift pattern. +- To add another kind of candidate cause (an operator, a work order, or a supplier site), append rows to `factors.csv` with the new kind, add a matching back-pointer property and its loader rule in `model/source.py`, one `Factor.touches` rule in `model/genealogy.py`, and one `Factor.evidence` rule in `model/root_cause_evidence.py`, mirroring the existing lot, machine, and shift pattern. ### Tune parameters diff --git a/defect_root_cause/model/__init__.py b/defect_root_cause/model/__init__.py index b3a46de8..ded77e18 100644 --- a/defect_root_cause/model/__init__.py +++ b/defect_root_cause/model/__init__.py @@ -30,27 +30,30 @@ Each stage enriches the shared ontology, and downstream stages consume those enrichments as first-class properties -- the accretive enrichment pattern. +Modules: `failure_timeline.py` (failure rate per build week and the spike +onset), `genealogy.py` (Stage 1), `contrast_scoring.py` (Stage 2), +`diagnosis.py` (Stage 3), and `root_cause_evidence.py` (each suspect's defect +signature). Each module imports the modules whose declarations it reads. + Run: `rai models deploy --path model` deploys this package to the schemas in raiconfig.yaml and waits for its first refresh, which runs the solve; `python -m queries.root_cause_report` then prints the report from the deployed model. """ -from .reasoning import ( - LIFT_THRESHOLD, - MIN_DEFECTS, - MIN_SUPPORT, +from . import root_cause_evidence +from .contrast_scoring import LIFT_THRESHOLD, MIN_DEFECTS, MIN_SUPPORT, PlantBaseline +from .diagnosis import ( DiagnosisCost, DiagnosisResult, - PlantBaseline, SolveStatus, num_cons, num_cover, - num_edges, num_min_objs, - num_nodes, num_vars, ) +from .failure_timeline import BuildWeek, SpikeOnset +from .genealogy import num_edges, num_incidence, num_nodes from .schema import Factor, Lot, Machine, Supplier, Unit, model from .source import DATA_DIR @@ -59,6 +62,7 @@ "LIFT_THRESHOLD", "MIN_DEFECTS", "MIN_SUPPORT", + "BuildWeek", "DiagnosisCost", "DiagnosisResult", "Factor", @@ -66,13 +70,16 @@ "Machine", "PlantBaseline", "SolveStatus", + "SpikeOnset", "Supplier", "Unit", "model", "num_cons", "num_cover", "num_edges", + "num_incidence", "num_min_objs", "num_nodes", "num_vars", + "root_cause_evidence", ] diff --git a/defect_root_cause/model/contrast_scoring.py b/defect_root_cause/model/contrast_scoring.py new file mode 100644 index 00000000..64fe970e --- /dev/null +++ b/defect_root_cause/model/contrast_scoring.py @@ -0,0 +1,72 @@ +"""Contrast scoring: the plant-wide failure rate, each candidate factor's defect counts, rate, and +lift over that baseline, and the suspects screened for the diagnosis.""" + +from relationalai.semantics import Float, Integer +from relationalai.semantics.std import aggregates as aggs +from relationalai.semantics.std import floats + +# Declares Factor.touches, the incidence the counts range over. +from . import genealogy # noqa: F401 +from .schema import Factor, Unit, model + +# -------------------------------------------------- +# Configure inputs +# -------------------------------------------------- + +# Stage 2 contrast-scoring thresholds. A factor is a suspect only if defects +# among the units it touches run materially above the plant-wide baseline +# (LIFT) and it touches enough units to trust the rate (SUPPORT) and enough +# defects to matter (MIN_DEFECTS). +LIFT_THRESHOLD = 1.5 +MIN_SUPPORT = 30 +MIN_DEFECTS = 5 + +# -------------------------------------------------- +# Stage 2 -- Rules: contrast scoring of candidate factors +# -------------------------------------------------- + +# Plant-wide failure rate: defective units over the distinct units in the model. +PlantBaseline = model.Concept("PlantBaseline", identify_by={"id": Integer}) +PlantBaseline.n_units = model.Property(f"{PlantBaseline} has {Integer:n_units}") +PlantBaseline.n_defective = model.Property(f"{PlantBaseline} has {Integer:n_defective}") +PlantBaseline.failure_rate = model.Property(f"{PlantBaseline} has {Float:failure_rate}") +model.define(PlantBaseline.new(id=1)) +model.define(PlantBaseline.n_units(aggs.count(Unit).per(PlantBaseline))) +model.define( + PlantBaseline.n_defective(aggs.count(Unit).per(PlantBaseline).where(Unit.is_defective())) +) +model.define( + PlantBaseline.failure_rate( + floats.float(PlantBaseline.n_defective) / floats.float(PlantBaseline.n_units) + ) +) + +# Per-factor incidence: how many units it touches, and how many of those failed. +Factor.touched_count = model.Property(f"{Factor} touches {Integer:touched_count}") +Factor.defect_count = model.Property(f"{Factor} has {Integer:defect_count}") +Factor.defect_rate = model.Property(f"{Factor} has {Float:defect_rate}") +Factor.lift = model.Property(f"{Factor} has {Float:lift}") +# is_suspect: defects are concentrated enough among the units this factor +# touches to warrant optimization -- the contrast screen before the MILP. +Factor.is_suspect = model.Relationship(f"{Factor} is suspect") + +model.define(Factor.touched_count(aggs.count(Unit).per(Factor).where(Factor.touches(Unit)))) +model.define(Factor.defect_count(aggs.count(Unit).per(Factor).where(Factor.touches(Unit), Unit.is_defective()))) +# defect_rate and lift each derive directly from the two counts (kept one +# level deep so the chain stays robust alongside the genealogy graph). +model.where(Factor.defect_count > 0).define( + Factor.defect_rate(floats.float(Factor.defect_count) / floats.float(Factor.touched_count)) +) +model.where(Factor.defect_count > 0).define( + Factor.lift( + (floats.float(Factor.defect_count) / floats.float(Factor.touched_count)) + / PlantBaseline.failure_rate + ) +) +# A factor is a suspect only when defect lift, support, and defect count all +# clear threshold -- screening out high-coverage, low-lift trunk factors. +model.where( + Factor.lift >= LIFT_THRESHOLD, + Factor.touched_count >= MIN_SUPPORT, + Factor.defect_count >= MIN_DEFECTS +).define(Factor.is_suspect(Factor)) diff --git a/defect_root_cause/model/reasoning.py b/defect_root_cause/model/diagnosis.py similarity index 51% rename from defect_root_cause/model/reasoning.py rename to defect_root_cause/model/diagnosis.py index 0771bc05..1df3473b 100644 --- a/defect_root_cause/model/reasoning.py +++ b/defect_root_cause/model/diagnosis.py @@ -1,121 +1,24 @@ -"""Root-cause diagnosis: lot genealogy graph, contrast scoring, and the minimal-diagnosis set cover.""" +"""Root-cause diagnosis: the minimal-diagnosis set-cover MILP over the suspect factors, its +formulation counts and solve status, and the DiagnosisResult headline.""" -from relationalai.semantics import ( - Float, - Integer, - String, -) -from relationalai.semantics.reasoners.graph import Graph +from relationalai.semantics import Float, Integer, String from relationalai.semantics.reasoners.prescriptive import Problem from relationalai.semantics.std import aggregates as aggs from relationalai.semantics.std import floats -from .schema import Factor, Lot, Unit, model +# Declares the suspect screen and the per-factor counts the solve reads. +from . import contrast_scoring # noqa: F401 +from .schema import Factor, Unit, model # -------------------------------------------------- # Configure inputs # -------------------------------------------------- -# Stage 2 contrast-scoring thresholds. A factor is a suspect only if defects -# among the units it touches run materially above the plant-wide baseline -# (LIFT) and it touches enough units to trust the rate (SUPPORT) and enough -# defects to matter (MIN_DEFECTS). -LIFT_THRESHOLD = 1.5 -MIN_SUPPORT = 30 -MIN_DEFECTS = 5 - # Stage 3 minimal-diagnosis objective weights. W_SELECT = 5.0 # parsimony: cost of naming one more factor a root cause W_GOOD = 0.02 # specificity: penalty per good unit a named factor also touches W_UNEXPLAINED = 1.0 # cost of leaving a defective unit unexplained (relief valve for scattered baseline failures) -# -------------------------------------------------- -# Stage 1 -- Graph: backward reachability over the lot genealogy -# -------------------------------------------------- - -# Directed parent -> child genealogy graph on Lot. Following edges from a -# top-tier lot reaches every lot consumed beneath it. -graph = Graph(model, directed=True, weighted=False, node_concept=Lot, name="lot_genealogy") -parent, child = Lot.ref(), Lot.ref() -model.where(parent.consumes(child)).define(graph.Edge.new(src=parent, dst=child)) - -# The graph's size, which the deployed model publishes for the queries. -node_count, edge_count = Integer.ref(), Integer.ref() -num_nodes = model.Relationship(f"the lot genealogy graph has {Integer:num_nodes} nodes") -num_edges = model.Relationship(f"the lot genealogy graph has {Integer:num_edges} edges") -model.where(graph.num_nodes()(node_count)).define(num_nodes(node_count)) -model.where(graph.num_edges()(edge_count)).define(num_edges(edge_count)) - -# Transitive closure: which lots each top-tier lot reaches. -reach = graph.reachable(full=True) - -# Unit.touches_lot: a unit touches the top-tier lots it consumes directly, -# plus every lot reachable beneath them. This backward closure is what lets a -# deep contaminated lot be attributed to the finished units that carry it. -Unit.touches_lot = model.Relationship(f"{Unit} touches {Lot:lot}") -model.where((u := Unit.ref()).consumes_lot(top := Lot.ref())).define(Unit.touches_lot(u, top)) -model.where( - (u := Unit.ref()).consumes_lot(top := Lot.ref()), - reach(top, deep := Lot.ref()) -).define(Unit.touches_lot(u, deep)) - -# Factor.touches: the unified incidence the diagnosis ranges over. Lot factors -# inherit the genealogy closure; machine and shift factors come from process. -Factor.touches = model.Relationship(f"{Factor} touches {Unit}") -model.where((u := Unit.ref()).touches_lot((f := Factor.ref()).lot)).define(Factor.touches(f, u)) -model.where((u := Unit.ref()).ran_on((f := Factor.ref()).machine)).define(Factor.touches(f, u)) -model.where((u := Unit.ref()).shift == (f := Factor.ref()).shift_name).define(Factor.touches(f, u)) - -# -------------------------------------------------- -# Stage 2 -- Rules: contrast scoring of candidate factors -# -------------------------------------------------- - -# Plant-wide failure rate: defective units over the distinct units in the model. -PlantBaseline = model.Concept("PlantBaseline", identify_by={"id": Integer}) -PlantBaseline.n_units = model.Property(f"{PlantBaseline} has {Integer:n_units}") -PlantBaseline.n_defective = model.Property(f"{PlantBaseline} has {Integer:n_defective}") -PlantBaseline.failure_rate = model.Property(f"{PlantBaseline} has {Float:failure_rate}") -model.define(PlantBaseline.new(id=1)) -model.define(PlantBaseline.n_units(aggs.count(Unit).per(PlantBaseline))) -model.define( - PlantBaseline.n_defective(aggs.count(Unit).per(PlantBaseline).where(Unit.is_defective())) -) -model.define( - PlantBaseline.failure_rate( - floats.float(PlantBaseline.n_defective) / floats.float(PlantBaseline.n_units) - ) -) - -# Per-factor incidence: how many units it touches, and how many of those failed. -Factor.touched_count = model.Property(f"{Factor} touches {Integer:touched_count}") -Factor.defect_count = model.Property(f"{Factor} has {Integer:defect_count}") -Factor.defect_rate = model.Property(f"{Factor} has {Float:defect_rate}") -Factor.lift = model.Property(f"{Factor} has {Float:lift}") -# is_suspect: defects are concentrated enough among the units this factor -# touches to warrant optimization -- the contrast screen before the MILP. -Factor.is_suspect = model.Relationship(f"{Factor} is suspect") - -model.define(Factor.touched_count(aggs.count(Unit).per(Factor).where(Factor.touches(Unit)))) -model.define(Factor.defect_count(aggs.count(Unit).per(Factor).where(Factor.touches(Unit), Unit.is_defective()))) -# defect_rate and lift each derive directly from the two counts (kept one -# level deep so the chain stays robust alongside the genealogy graph). -model.where(Factor.defect_count > 0).define( - Factor.defect_rate(floats.float(Factor.defect_count) / floats.float(Factor.touched_count)) -) -model.where(Factor.defect_count > 0).define( - Factor.lift( - (floats.float(Factor.defect_count) / floats.float(Factor.touched_count)) - / PlantBaseline.failure_rate - ) -) -# A factor is a suspect only when defect lift, support, and defect count all -# clear threshold -- screening out high-coverage, low-lift trunk factors. -model.where( - Factor.lift >= LIFT_THRESHOLD, - Factor.touched_count >= MIN_SUPPORT, - Factor.defect_count >= MIN_DEFECTS -).define(Factor.is_suspect(Factor)) - # -------------------------------------------------- # Stage 3 -- Prescriptive: minimal-diagnosis set-cover MILP # -------------------------------------------------- diff --git a/defect_root_cause/model/failure_timeline.py b/defect_root_cause/model/failure_timeline.py new file mode 100644 index 00000000..1f75c110 --- /dev/null +++ b/defect_root_cause/model/failure_timeline.py @@ -0,0 +1,40 @@ +"""Failure timeline: the units, defective units, and final-test failure rate of each build week, +and the build week in which the failure spike starts.""" + +from relationalai.semantics import Float, Integer +from relationalai.semantics.std import aggregates as aggs +from relationalai.semantics.std import floats + +from .schema import Unit, model + +# A week is part of the spike when its failure rate exceeds this multiple of +# the opening (earliest) week's rate. +SPIKE_RATE_FACTOR = 2.0 + +BuildWeek = model.Concept("BuildWeek", identify_by={"week": Integer}) +BuildWeek.n_units = model.Property(f"{BuildWeek} has {Integer:n_units}") +BuildWeek.n_defective = model.Property(f"{BuildWeek} has {Integer:n_defective}") +BuildWeek.failure_rate = model.Property(f"{BuildWeek} has {Float:failure_rate}") +model.define(BuildWeek.new(week=Unit.build_week)) +_built_that_week = Unit.build_week == BuildWeek.week +model.define( + BuildWeek.n_units(aggs.count(Unit).per(BuildWeek).where(_built_that_week)), + BuildWeek.n_defective( + aggs.count(Unit).per(BuildWeek).where(_built_that_week, Unit.is_defective()) | 0 + ), +) +model.define( + BuildWeek.failure_rate(floats.float(BuildWeek.n_defective) / floats.float(BuildWeek.n_units)) +) + +# Spiking weeks fail at more than SPIKE_RATE_FACTOR times the opening week's +# rate; the spike onset is the earliest of them (none when no week spikes). +BuildWeek.is_spiking = model.Relationship(f"{BuildWeek} fails well above the opening week") +_opening, _week, _any_week = BuildWeek.ref(), BuildWeek.ref(), BuildWeek.ref() +model.where( + _opening.week == aggs.min(_any_week.week), + _week.failure_rate > SPIKE_RATE_FACTOR * _opening.failure_rate, +).define(_week.is_spiking()) +SpikeOnset = model.Relationship(f"the failure spike starts in build week {Integer:week}") +_spiking = BuildWeek.ref() +model.define(SpikeOnset(aggs.min(_spiking.week).where(_spiking.is_spiking()))) diff --git a/defect_root_cause/model/genealogy.py b/defect_root_cause/model/genealogy.py new file mode 100644 index 00000000..b6d4aa4b --- /dev/null +++ b/defect_root_cause/model/genealogy.py @@ -0,0 +1,51 @@ +"""Lot genealogy: backward reachability over the lot genealogy graph, which links each unit to every +lot beneath it and each candidate factor to the units it touches.""" + +from relationalai.semantics import Integer +from relationalai.semantics.reasoners.graph import Graph +from relationalai.semantics.std import aggregates as aggs + +from .schema import Factor, Lot, Unit, model + +# -------------------------------------------------- +# Stage 1 -- Graph: backward reachability over the lot genealogy +# -------------------------------------------------- + +# Directed parent -> child genealogy graph on Lot. Following edges from a +# top-tier lot reaches every lot consumed beneath it. +graph = Graph(model, directed=True, weighted=False, node_concept=Lot, name="lot_genealogy") +parent, child = Lot.ref(), Lot.ref() +model.where(parent.consumes(child)).define(graph.Edge.new(src=parent, dst=child)) + +# The graph's size, which the deployed model publishes for the queries. +node_count, edge_count = Integer.ref(), Integer.ref() +num_nodes = model.Relationship(f"the lot genealogy graph has {Integer:num_nodes} nodes") +num_edges = model.Relationship(f"the lot genealogy graph has {Integer:num_edges} edges") +model.where(graph.num_nodes()(node_count)).define(num_nodes(node_count)) +model.where(graph.num_edges()(edge_count)).define(num_edges(edge_count)) + +# Transitive closure: which lots each top-tier lot reaches. +reach = graph.reachable(full=True) + +# Unit.touches_lot: a unit touches the top-tier lots it consumes directly, +# plus every lot reachable beneath them. This backward closure is what lets a +# deep contaminated lot be attributed to the finished units that carry it. +Unit.touches_lot = model.Relationship(f"{Unit} touches {Lot:lot}") +model.where((u := Unit.ref()).consumes_lot(top := Lot.ref())).define(Unit.touches_lot(u, top)) +model.where( + (u := Unit.ref()).consumes_lot(top := Lot.ref()), + reach(top, deep := Lot.ref()) +).define(Unit.touches_lot(u, deep)) + +# Factor.touches: the unified incidence the diagnosis ranges over. Lot factors +# inherit the genealogy closure; machine and shift factors come from process. +Factor.touches = model.Relationship(f"{Factor} touches {Unit}") +model.where((u := Unit.ref()).touches_lot((f := Factor.ref()).lot)).define(Factor.touches(f, u)) +model.where((u := Unit.ref()).ran_on((f := Factor.ref()).machine)).define(Factor.touches(f, u)) +model.where((u := Unit.ref()).shift == (f := Factor.ref()).shift_name).define(Factor.touches(f, u)) + +# The number of (factor, unit) incidence facts the closure yields. +num_incidence = model.Relationship( + f"backward reachability yields {Integer:num_incidence} factor-unit incidence facts" +) +model.define(num_incidence(aggs.count(Factor, Unit).where(Factor.touches(Unit)))) diff --git a/defect_root_cause/model/root_cause_evidence.py b/defect_root_cause/model/root_cause_evidence.py new file mode 100644 index 00000000..f5f704c3 --- /dev/null +++ b/defect_root_cause/model/root_cause_evidence.py @@ -0,0 +1,40 @@ +"""Root-cause evidence: for each suspect factor, the defect type its failures concentrate in and +that type's share of its defective units with a recorded type.""" + +from relationalai.semantics import Float, Integer, String +from relationalai.semantics.std import aggregates as aggs +from relationalai.semantics.std import floats + +# Declares the suspect screen. +from . import contrast_scoring # noqa: F401 +from .schema import Factor, Unit, model + +# Defect types of the defective units each suspect touches. +Factor.defect_type_count = model.Relationship( + f"{Factor} has {String:defect_type} on {Integer:n_units} defective units" +) +_type = String.ref() +model.where( + Factor.is_suspect(), + Factor.touches(Unit), + Unit.is_defective(), + Unit.defect_type == _type, +).define(Factor.defect_type_count(_type, aggs.count(Unit).per(Factor, _type))) + +# Defect signature: the most frequent type (ties broken by type name) and its +# share of the factor's defective units that have a type. +Factor.signature_type = model.Property(f"{Factor} has signature defect type {String:type}") +Factor.signature_share = model.Property(f"{Factor} has signature share {Float:share}") +_n_units, _any_type, _n_typed = Integer.ref(), String.ref(), Integer.ref() +# Most units first (negated count), ties broken by defect type name. +model.where( + Factor.defect_type_count(_type, _n_units), + aggs.rank(-_n_units, _type).per(Factor) == 1, +).define( + Factor.signature_type(_type), + Factor.signature_share(floats.float(_n_units) / floats.float( + aggs.sum(_any_type, _n_typed).per(Factor).where( + Factor.defect_type_count(_any_type, _n_typed) + ) + )), +) diff --git a/defect_root_cause/model/source.py b/defect_root_cause/model/source.py index 199f7322..12c2bf2a 100644 --- a/defect_root_cause/model/source.py +++ b/defect_root_cause/model/source.py @@ -61,11 +61,14 @@ ppd = model.data(read_csv(DATA_DIR / "unit_process.csv")) model.define(Unit.lookup(id=ppd.UNIT_ID).ran_on(Machine.lookup(id=ppd.MACHINE_ID))) -# Candidate factors, loaded per kind so each gets the right back-pointer. -fac = read_csv(DATA_DIR / "factors.csv") -lf = model.data(fac[fac.KIND == "LOT"]) -model.define(f := Factor.new(id=lf.FACTOR_ID), f.kind(lf.KIND), f.label(lf.LABEL), f.lot(Lot.lookup(id=lf.REF_ID))) -mf = model.data(fac[fac.KIND == "MACHINE"]) -model.define(f := Factor.new(id=mf.FACTOR_ID), f.kind(mf.KIND), f.label(mf.LABEL), f.machine(Machine.lookup(id=mf.REF_ID))) -sf = model.data(fac[fac.KIND == "SHIFT"]) -model.define(f := Factor.new(id=sf.FACTOR_ID), f.kind(sf.KIND), f.label(sf.LABEL), f.shift_name(sf.REF_ID)) +# Candidate factors. REF_ID names the factor's lot, machine, or shift, so each +# kind's rule binds the matching back-pointer. +fd = model.data(read_csv(DATA_DIR / "factors.csv")) +model.define(f := Factor.new(id=fd.FACTOR_ID), f.kind(fd.KIND), f.label(fd.LABEL)) +model.where(fd.KIND == "LOT").define( + Factor.lookup(id=fd.FACTOR_ID).lot(Lot.lookup(id=fd.REF_ID)) +) +model.where(fd.KIND == "MACHINE").define( + Factor.lookup(id=fd.FACTOR_ID).machine(Machine.lookup(id=fd.REF_ID)) +) +model.where(fd.KIND == "SHIFT").define(Factor.lookup(id=fd.FACTOR_ID).shift_name(fd.REF_ID)) diff --git a/defect_root_cause/queries/root_cause_report.py b/defect_root_cause/queries/root_cause_report.py index b5291b63..a4ad989e 100644 --- a/defect_root_cause/queries/root_cause_report.py +++ b/defect_root_cause/queries/root_cause_report.py @@ -13,21 +13,25 @@ LIFT_THRESHOLD, MIN_DEFECTS, MIN_SUPPORT, + BuildWeek, DiagnosisCost, DiagnosisResult, Factor, PlantBaseline, SolveStatus, - Unit, + SpikeOnset, model, num_cons, num_cover, num_edges, + num_incidence, num_min_objs, num_nodes, num_vars, ) +TOP_RAW_FACTORS = 6 + if __name__ == "__main__": baseline = model.select( PlantBaseline.n_units.alias("units"), @@ -45,15 +49,18 @@ # timeline -- failures by build week -- before touching genealogy. The onset is # the first week whose rate runs well above the opening week's baseline; it # tells the rest of the chain which window's changes to interrogate. - wk = model.select( - Unit.build_week.alias("week"), Unit.defective.alias("defective") - ).to_df() - timeline = wk.groupby("week").agg( - units=("defective", "size"), defects=("defective", "sum") + timeline = ( + model.select( + BuildWeek.week.alias("week"), + BuildWeek.n_units.alias("units"), + BuildWeek.failure_rate.alias("rate"), + ) + .to_df() + .set_index("week") + .sort_index() ) - timeline["rate"] = timeline["defects"] / timeline["units"] - opening = timeline["rate"].iloc[0] - onset = next((int(w) for w, r in timeline["rate"].items() if r > 2 * opening), None) + onset_weeks = model.select(SpikeOnset).to_df().iloc[:, 0].tolist() + onset = int(onset_weeks[0]) if onset_weeks else None print("\nWhen did the spike start? Final-test failure rate by build week:") for week, r in timeline.iterrows(): mark = " <- spike onset" if onset == int(week) else "" @@ -74,12 +81,7 @@ # everything. That is exactly the trap the contrast stage corrects. Genealogy # closure puts lots and machines on the same footing: a deep lot is "touched by" # every finished unit that carries it. - # One row per factor (selecting the count alone would merge factors with equal counts). - n_incidence = ( - model.select(Factor.id.alias("factor"), Factor.touched_count.alias("units")) - .to_df()["units"] - .sum() - ) + n_incidence = int(model.select(num_incidence).to_df().iloc[0, 0]) top_raw = ( model.select( Factor.id.alias("factor"), @@ -89,7 +91,7 @@ ) .to_df() .sort_values(["defects", "factor"], ascending=[False, True]) - .head(6) + .head(TOP_RAW_FACTORS) .reset_index(drop=True) ) print( @@ -184,24 +186,24 @@ # Corroborating evidence per named cause, the way a real RCA write-up reads: # the defect signature it concentrates (a paste fault should present as cold # solder, a reflow fault as solder bridging), plus a kind-specific tell -- - # supplier and receipt date for a lot, calibration age for a machine. All of it - # is read back from ontology already loaded; the diagnosis is the hypothesis, - # this is the supporting evidence an engineer would confirm physically. - sig = ( - model.where( - (f := Factor.ref()).is_root_cause > 0.5, - f.touches(u := Unit.ref()), - u.is_defective(), + # supplier and receipt date for a lot, calibration age for a machine. The model + # publishes the signature of every suspect factor; the diagnosis is the + # hypothesis, this is the supporting evidence an engineer would confirm physically. + signatures = ( + model.where((f := Factor.ref()).is_root_cause > 0.5) + .select( + f.id.alias("factor"), + f.signature_type.alias("signature_type"), + f.signature_share.alias("signature_share"), ) - .select(f.id.alias("factor"), u.defect_type.alias("defect_type")) .to_df() + .set_index("factor") ) print("\nCorroborating evidence per root cause:") for _, row in diagnosis.iterrows(): fid, kind, label = row["factor"], row["kind"], row["label"] - types = sig[sig["factor"] == fid]["defect_type"] - dom = types.value_counts() - signature = f"{dom.iloc[0] / len(types):.0%} {dom.index[0]}" + sig = signatures.loc[fid] + signature = f"{sig['signature_share']:.0%} {sig['signature_type']}" # Each kind's evidence is read through the factor's typed pointer to its lot, # machine, or shift. if kind == "LOT": diff --git a/demand_forecasting/README.md b/demand_forecasting/README.md index 548bfedb..0f87111d 100644 --- a/demand_forecasting/README.md +++ b/demand_forecasting/README.md @@ -35,12 +35,12 @@ Assumes familiarity with Python, basic ML concepts (regression, RMSE), and time- ## What's included -- **Model**: `model/` — the deployed model: concepts and splits (`schema.py`, `source.py`), the graph, the GNN and its predictions (`reasoning.py`) +- **Model**: `model/` — the deployed model: concepts and the CSV loaders (`schema.py`, `source.py`), the temporal split (`temporal_split.py`), the graph, the GNN and its predictions (`demand_forecast.py`), the weekly rollup and RMSEs (`forecast_accuracy.py`), and the data summary (`sales_summary.py`) - **Training**: `train.py` — trains the GNN over the deployed splits and registers its version - **Query**: `queries/forecast_report.py` — prints the weekly forecast and test-set RMSE from the deployed model - **Runbook**: `runbook.md` — a paste-testable walkthrough that reproduces the template step by step with the RAI skills; as important a reference as the code itself. - **Synthetic data generator**: `data/generate_favorita_mini.py` — reproducible Favorita-shaped data generator (run once if you need to regenerate; output is committed under `data/favorita_mini/`) -- **Model**: `Store`, `Item`, `ItemFamily`, `Sale`, plus three task-table concepts (`TrainTable`, `ValTable`, `TestTable`) carrying the unit-sales targets +- **Model**: `Store`, `Item`, `ItemFamily`, `Sale`, plus the `Train`, `Val`, and `Test` relationships carrying the sales of each temporal split - **Sample data**: bundled synthetic Favorita-shaped dataset (3 stores × 25 items × 365 days); see [Sample data](#sample-data) - **Outputs**: store/item counts, temporal split summary, GNN training/prediction metrics, weekly per-(city, family) forecast table, per-Sale and per-week RMSE @@ -126,7 +126,7 @@ Use this sequence to deploy the model, train the GNN, and query its forecast: predictive: name: demand_forecasting_gnn # created on first use if it doesn't exist gnns: - demand_forecast: # the GNN's name in model/reasoning.py + demand_forecast: # the GNN's name in model/demand_forecast.py registry: .DEMAND_FORECASTING model: DEMAND_FORECAST version: V1 # train.py registers this version @@ -219,8 +219,11 @@ Use this sequence to deploy the model, train the GNN, and query its forecast: ├── model/ │ ├── __init__.py # exports for train.py and the query │ ├── schema.py # concepts and the Train/Val/Test task relationships -│ ├── source.py # bundled CSVs and the temporal split -│ └── reasoning.py # graph, feature types, the GNN and its predictions +│ ├── source.py # bundled CSVs +│ ├── temporal_split.py # test and validation cutoffs, the Train/Val/Test split +│ ├── demand_forecast.py # graph, feature types, the GNN and its predictions +│ ├── forecast_accuracy.py # per-sale and weekly forecasts against actuals, RMSEs +│ └── sales_summary.py # record counts and the range of unit sales ├── train.py # trains the GNN and registers its version ├── queries/ │ └── forecast_report.py # weekly forecast and test-set RMSE @@ -255,7 +258,7 @@ Customers adapting this template would replace these CSVs with a real Favorita s The model is a small retail ontology whose only purpose is to give the graph neural network (GNN) a heterogeneous neighborhood: sales linked to their store and item, and items rolled up to a family. -- **Key entities**: `Store`, `Item`, `ItemFamily`, `Sale`, plus three task-table concepts (`TrainTable`, `ValTable`, `TestTable`) that carry the split targets into the trainer. +- **Key entities**: `Store`, `Item`, `ItemFamily`, `Sale`, plus the `Train`, `Val`, and `Test` relationships that carry the split targets into the trainer. - **Primary identifiers**: `Store.store_id`, `Item.item_id`, `Sale.sale_id` (all integers); `ItemFamily.family` (the family string). - **Important invariants**: `unit_sales` is a non-negative integer and is the regression target (dropped from features to prevent leakage); every `Sale` links to exactly one `Store` and one `Item`; every `Item` links to exactly one `ItemFamily`; `ItemFamily` is derived from the distinct `Item.family` values rather than loaded. @@ -264,7 +267,7 @@ For the full concept and property definitions — including the GNN edges (`Sale ```text Stores + Items + Sales (bundled CSVs) -> Build heterogeneous graph: Sale -> Store, Sale -> Item, Item -> ItemFamily - -> Temporal train/val/test split in pandas (last 60 days = test, previous 60 = val) + -> Temporal train/val/test split as rules over Sale.date (last 60 days = test, previous 60 = val) -> Predictive: GNN regression on Sale.unit_sales -> Reporting: aggregate per-Sale predictions to weekly per-(city, family) forecasts ``` @@ -277,13 +280,13 @@ The pipeline builds a heterogeneous graph, trains a regression GNN over it, and **Declare features and target.** Primary and foreign keys are dropped because the graph carries identity, and `Sale.unit_sales` is dropped from the features because it is the regression target — keeping it would leak the answer. The remaining columns are declared explicitly as categorical, continuous, integer, or datetime features. -**Split temporally.** Forecasting requires training on the past and evaluating on the future; a random split would leak future signal into training. The split is done in pandas before the task tables are built — the last 60 days become the test window and the 60 before that the validation window. +**Split temporally.** Forecasting requires training on the past and evaluating on the future; a random split would leak future signal into training. Rules over `Sale.date` derive the split from the latest sale date — the last 60 days become the test window and the 60 before that the validation window. **Train and predict.** The GNN runs a regression task with `has_time_column=True`: each Train, Val and Test row carries its sale date, and `Sale.date` is the property transformer's time column. Predictions are attached back to each Sale. -**Aggregate to a weekly forecast.** Two queries pull the per-Sale predictions and their store city and item family; pandas then rolls them up into weekly per-(city, family) buckets against the actuals, pooling stores that share a city. +**Aggregate to a weekly forecast.** Rules pair each per-Sale prediction with its store city and item family and roll them up into weekly per-(city, family) buckets against the actuals, pooling stores that share a city. The same module computes the per-Sale and per-week RMSE. -See `model/reasoning.py` for the graph and the GNN, `queries/forecast_report.py` for the rollup, and `runbook.md` to reproduce it step by step with the RAI skills. +See `model/demand_forecast.py` for the graph and the GNN, `model/forecast_accuracy.py` for the rollup, `queries/forecast_report.py` for the printed report, and `runbook.md` to reproduce it step by step with the RAI skills. ## Customize this template @@ -294,7 +297,7 @@ See `model/reasoning.py` for the graph and the GNN, `queries/forecast_report.py` ### Tune parameters -- **Change the forecast windows** — change `TEST_DAYS` / `VAL_DAYS` in `model/source.py` to set the lengths of the test and validation windows. Default is a 60-day test window after a 60-day val window; the report still aggregates by week. +- **Change the forecast windows** — change `TEST_DAYS` / `VAL_DAYS` in `model/temporal_split.py` to set the lengths of the test and validation windows. Default is a 60-day test window after a 60-day val window; the report still aggregates by week. ### Extend the model @@ -310,7 +313,7 @@ The bundled `favorita_mini` is intentionally tiny so the template runs in minute 1. Download the dataset from [Kaggle: Corporación Favorita Grocery Sales Forecasting](https://www.kaggle.com/c/favorita-grocery-sales-forecasting). License is "Subject to Competition Rules" — review before redistributing. 2. Load `stores.csv`, `items.csv`, and `train.csv` (the sales table) into Snowflake, and map their columns to the ones the model reads: the Kaggle files name the keys `store_nbr`, `item_nbr`, and `id` (the model reads `store_id`, `item_id`, and `sale_id`), and the store and item types `type` and `class` (the model reads `store_type` and `item_class`). Raw `unit_sales` includes returns (negative values) and fractional quantities for items sold by weight, while the model's target is a non-negative integer, so decide how to filter or round them. -3. Read the tables through `model.Table("..")` sources in `model/source.py` instead of pandas frames: the deployed model writes each pandas frame into its definition as inline rows, which does not scale to the full corpus. The temporal split in `model/source.py` works on pandas frames, so restate it as rules over `Sale.date`. +3. Read the tables through `model.Table("..
")` sources in `model/source.py` instead of pandas frames: the deployed model writes each pandas frame into its definition as inline rows, which does not scale to the full corpus. The temporal split in `model/temporal_split.py` is written over `Sale.date`, so it needs no change. 4. Size the predictive reasoner for the data with `reasoners.predictive.size` in `raiconfig.yaml` (a GPU size for the full corpus): a deployed GNN runs on the device that size provides. 5. Trim the date window in the tables you map if you don't need the full 5 years; `TEST_DAYS` / `VAL_DAYS` control the temporal split inside that window. 6. Real Favorita has additional tables (`oil.csv`, `holidays_events.csv`, `transactions.csv`) you may want to fold in as features — see [Customize this template](#customize-this-template) above for the pattern. diff --git a/demand_forecasting/model/__init__.py b/demand_forecasting/model/__init__.py index bc9f979f..64243b89 100644 --- a/demand_forecasting/model/__init__.py +++ b/demand_forecasting/model/__init__.py @@ -1,26 +1,36 @@ """Demand-forecasting model: Favorita-shaped sales data and a regression GNN. +Modules: `temporal_split.py` (the validation and test cutoffs from the latest sale date, and the +Train, Val, and Test relationships), `demand_forecast.py` (the graph, the GNN, and its +predictions), `forecast_accuracy.py` (each predicted sale's forecast against its actual sales, +the weekly rollup per store city and item family, and the RMSEs), and `sales_summary.py` (the +record counts and the range of unit sales). Each module imports the modules whose declarations +it reads. + `rai models deploy --path model` deploys everything this package declares. """ -from .schema import Item, ItemFamily, Sale, Store, TestTable, TrainTable, ValTable, model -from .source import DATA_DIR, TEST_START, VAL_START - -# isort: split -# The reasoning declares the graph and the GNN over the facts loaded above. -from .reasoning import gnn +from .demand_forecast import gnn +from .forecast_accuracy import SaleForecast, SaleRmse, WeeklyForecast, WeeklyRmse +from .sales_summary import SalesCounts, UnitSales +from .schema import Item, ItemFamily, Sale, Store, model +from .source import DATA_DIR +from .temporal_split import TestStart, ValStart __all__ = [ "DATA_DIR", "Item", "ItemFamily", "Sale", + "SaleForecast", + "SaleRmse", + "SalesCounts", "Store", - "TEST_START", - "TestTable", - "TrainTable", - "VAL_START", - "ValTable", + "TestStart", + "UnitSales", + "ValStart", + "WeeklyForecast", + "WeeklyRmse", "gnn", "model", ] diff --git a/demand_forecasting/model/reasoning.py b/demand_forecasting/model/demand_forecast.py similarity index 89% rename from demand_forecasting/model/reasoning.py rename to demand_forecasting/model/demand_forecast.py index c67f8a3f..2c70b995 100644 --- a/demand_forecasting/model/reasoning.py +++ b/demand_forecasting/model/demand_forecast.py @@ -1,8 +1,11 @@ -"""The GNN graph, the regression GNN, and the per-Sale predictions it declares.""" +"""Demand forecast: the GNN graph, the regression GNN, and the per-Sale predictions it declares.""" from relationalai.semantics.reasoners.graph import Graph from relationalai.semantics.reasoners.predictive import GNN, PropertyTransformer +# Declare the loaded Sale, Store, and Item properties, and derive the Train, Val, and Test +# relationships the GNN trains and predicts over. +from . import source, temporal_split # noqa: F401 from .schema import Item, ItemFamily, Sale, Store, Test, Train, Val, model SEED = 42 diff --git a/demand_forecasting/model/forecast_accuracy.py b/demand_forecasting/model/forecast_accuracy.py new file mode 100644 index 00000000..353b7295 --- /dev/null +++ b/demand_forecasting/model/forecast_accuracy.py @@ -0,0 +1,87 @@ +"""Forecast accuracy: each predicted sale's forecast against its actual sales, the weekly rollup per +store city and item family, and the test-set RMSE per sale and per weekly rollup.""" + +from relationalai.semantics import DateTime, Float, Integer, String +from relationalai.semantics.std import aggregates as aggs +from relationalai.semantics.std import datetime, floats, math + +# Declare Sale.predictions, the GNN forecasts, and the loaded Sale, Store, and Item properties. +from . import demand_forecast, source # noqa: F401 +from .schema import Item, Sale, Store, model + +# -------------------------------------------------- +# Forecast of each predicted sale +# -------------------------------------------------- +# One row per predicted sale, kept apart from Sale: the GNN reads Sale, so a Sale +# property derived from the predictions would make the predictions depend on +# themselves. A sale whose store or item is missing has no city or family. +SaleForecast = model.Concept("SaleForecast", identify_by={"sale_id": Integer}) +SaleForecast.actual = model.Property(f"{SaleForecast} has actual sales {Float:actual}") +SaleForecast.predicted = model.Property(f"{SaleForecast} has forecast sales {Float:predicted}") +SaleForecast.error = model.Property(f"{SaleForecast} has forecast error {Float:error}") +SaleForecast.week_start = model.Property( + f"{SaleForecast} is in the week starting {DateTime:week_start}" +) +SaleForecast.city = model.Property(f"{SaleForecast} is in the city {String:city}") +SaleForecast.family = model.Property(f"{SaleForecast} is of the family {String:family}") +model.define(SaleForecast.new(sale_id=Sale.sale_id)).where(Sale.predictions) +_of_sale = Sale.sale_id == SaleForecast.sale_id +model.define(SaleForecast.actual(floats.float(Sale.unit_sales))).where(_of_sale) +# The forecast is clipped at zero. +model.define(SaleForecast.predicted(math.maximum(Sale.predictions.predicted_value, 0.0))).where( + Sale.predictions, _of_sale +) +model.define(SaleForecast.error(SaleForecast.predicted - SaleForecast.actual)) +# The week starts at midnight on the Monday on or before the sale date, whatever the sale's time. +_sale_day = datetime.datetime.to_date(Sale.date) +model.define( + SaleForecast.week_start( + datetime.date.to_datetime( + datetime.date.subtract(_sale_day, datetime.days(datetime.date.weekday(_sale_day))) + ) + ) +).where(_of_sale) +model.define(SaleForecast.city(Store.city)).where(_of_sale, Sale.store_id == Store.store_id) +model.define(SaleForecast.family(Item.family)).where(_of_sale, Sale.item_id == Item.item_id) + +# -------------------------------------------------- +# Weekly forecast per (city, item family) +# -------------------------------------------------- +# Forecasts without a city or family are left out of the weekly rollup. +WeeklyForecast = model.Concept( + "WeeklyForecast", identify_by={"city": String, "family": String, "week_start": DateTime} +) +WeeklyForecast.actual = model.Property(f"{WeeklyForecast} has actual sales {Float:actual}") +WeeklyForecast.predicted = model.Property(f"{WeeklyForecast} has forecast sales {Float:predicted}") +WeeklyForecast.error = model.Property(f"{WeeklyForecast} has forecast error {Float:error}") +WeeklyForecast.abs_err = model.Property(f"{WeeklyForecast} has absolute error {Float:abs_err}") +model.define( + WeeklyForecast.new( + city=SaleForecast.city, family=SaleForecast.family, week_start=SaleForecast.week_start + ) +) +_in_week = ( + SaleForecast.city == WeeklyForecast.city, + SaleForecast.family == WeeklyForecast.family, + SaleForecast.week_start == WeeklyForecast.week_start, +) +model.define( + WeeklyForecast.actual( + aggs.sum(SaleForecast, SaleForecast.actual).per(WeeklyForecast).where(*_in_week) + ), + WeeklyForecast.predicted( + aggs.sum(SaleForecast, SaleForecast.predicted).per(WeeklyForecast).where(*_in_week) + ), +) +model.define(WeeklyForecast.error(WeeklyForecast.predicted - WeeklyForecast.actual)) +model.define(WeeklyForecast.abs_err(math.abs(WeeklyForecast.error))) + +# -------------------------------------------------- +# Test-set RMSE +# -------------------------------------------------- +SaleRmse = model.Relationship(f"the test-set RMSE per sale is {Float:rmse}") +WeeklyRmse = model.Relationship(f"the test-set RMSE per (city, family, week) is {Float:rmse}") +model.define(SaleRmse(math.sqrt(aggs.avg(SaleForecast, SaleForecast.error * SaleForecast.error)))) +model.define( + WeeklyRmse(math.sqrt(aggs.avg(WeeklyForecast, WeeklyForecast.error * WeeklyForecast.error))) +) diff --git a/demand_forecasting/model/sales_summary.py b/demand_forecasting/model/sales_summary.py new file mode 100644 index 00000000..98b1e8d0 --- /dev/null +++ b/demand_forecasting/model/sales_summary.py @@ -0,0 +1,37 @@ +"""Sales summary: the number of stores, items, and sales, the number of sales in each temporal +split, and the range and mean of unit sales.""" + +from relationalai.semantics import DateTime, Float, Integer +from relationalai.semantics.std import aggregates as aggs +from relationalai.semantics.std import floats + +# Declares Sale.unit_sales, a column of the loaded sales. +from . import source # noqa: F401 +from .schema import Item, Sale, Store, Test, Train, Val, model + +SalesCounts = model.Relationship( + f"the data has {Integer:stores} stores, {Integer:items} items and {Integer:sales} sales, " + f"split into {Integer:train} train, {Integer:val} validation and {Integer:test} test sales" +) +_timestamp, _target = DateTime.ref(), Integer.ref() +model.define( + SalesCounts( + aggs.count(Store), + aggs.count(Item), + aggs.count(Sale), + aggs.count(Sale).where(Train(Sale, _timestamp, _target)) | 0, + aggs.count(Sale).where(Val(Sale, _timestamp, _target)) | 0, + aggs.count(Sale).where(Test(Sale, _timestamp)) | 0, + ) +) + +UnitSales = model.Relationship( + f"unit sales range from {Integer:min_sales} to {Integer:max_sales} with mean {Float:mean_sales}" +) +model.define( + UnitSales( + aggs.min(Sale.unit_sales), + aggs.max(Sale.unit_sales), + aggs.avg(Sale, floats.float(Sale.unit_sales)), + ) +) diff --git a/demand_forecasting/model/schema.py b/demand_forecasting/model/schema.py index de6ed67c..2c158637 100644 --- a/demand_forecasting/model/schema.py +++ b/demand_forecasting/model/schema.py @@ -20,13 +20,8 @@ # onpromotion flag. The GNN target is Sale.unit_sales. Sale = Concept("Sale", identify_by={"sale_id": Integer}) -# Task tables: one row per Sale in each temporal split. -TrainTable = Concept("TrainTable") -ValTable = Concept("ValTable") -TestTable = Concept("TestTable") - -# Regression task relationships. Each carries the timestamp (Sale.date) -# since the GNN is trained with has_time_column=True. +# Regression task relationships: the Sales in each temporal split. Each carries +# the timestamp (Sale.date) since the GNN is trained with has_time_column=True. Train = Relationship(f"{Sale} at {DateTime:timestamp} has {Integer:value}") Val = Relationship(f"{Sale} at {DateTime:timestamp} has {Integer:value}") Test = Relationship(f"{Sale} at {DateTime:timestamp}") diff --git a/demand_forecasting/model/source.py b/demand_forecasting/model/source.py index 13950880..9c3749ff 100644 --- a/demand_forecasting/model/source.py +++ b/demand_forecasting/model/source.py @@ -1,28 +1,13 @@ -"""Bundled Favorita-shaped CSVs and the temporal train / validation / test split.""" +"""Bundled Favorita-shaped CSVs.""" from pathlib import Path import pandas as pd -from .schema import ( - Item, - ItemFamily, - Sale, - Store, - Test, - TestTable, - Train, - TrainTable, - Val, - ValTable, - model, -) +from .schema import Item, ItemFamily, Sale, Store, model DATA_DIR = Path(__file__).resolve().parents[1] / "data" / "favorita_mini" -TEST_DAYS = 60 # last 60 days as test window -VAL_DAYS = 60 # 60 days before test as validation - stores_df = pd.read_csv(DATA_DIR / "stores.csv") items_df = pd.read_csv(DATA_DIR / "items.csv") sales_df = pd.read_csv(DATA_DIR / "sales.csv", parse_dates=["date"]) @@ -31,38 +16,3 @@ model.define(Item.new(model.data(items_df).to_schema())) model.define(ItemFamily.new(family=Item.family)) model.define(Sale.new(model.data(sales_df).to_schema())) - -# -------------------------------------------------- -# Train / Val / Test split (temporal) -# -------------------------------------------------- -# Forecast use cases require temporal splits: training on the past, evaluating -# on the future. Random splits leak future signal into training. - -max_date = sales_df["date"].max() -TEST_START = max_date - pd.Timedelta(days=TEST_DAYS - 1) -VAL_START = TEST_START - pd.Timedelta(days=VAL_DAYS) - -train_mask = sales_df["date"] < VAL_START -val_mask = (sales_df["date"] >= VAL_START) & (sales_df["date"] < TEST_START) -test_mask = sales_df["date"] >= TEST_START - -train_df = sales_df.loc[train_mask, ["sale_id", "date", "unit_sales"]].reset_index(drop=True) -val_df = sales_df.loc[val_mask, ["sale_id", "date", "unit_sales"]].reset_index(drop=True) -test_df = sales_df.loc[test_mask, ["sale_id", "date"]].reset_index(drop=True) - -model.define(TrainTable.new(model.data(train_df).to_schema())) -model.define(ValTable.new(model.data(val_df).to_schema())) -model.define(TestTable.new(model.data(test_df).to_schema())) - -# The split was done temporally in pandas above (train < VAL_START, -# val < TEST_START, test >= TEST_START), so the GNN trains on the past and -# evaluates on the future. -model.define(Train(Sale, TrainTable.date, TrainTable.unit_sales)).where( - Sale.sale_id == TrainTable.sale_id, -) -model.define(Val(Sale, ValTable.date, ValTable.unit_sales)).where( - Sale.sale_id == ValTable.sale_id, -) -model.define(Test(Sale, TestTable.date)).where( - Sale.sale_id == TestTable.sale_id, -) diff --git a/demand_forecasting/model/temporal_split.py b/demand_forecasting/model/temporal_split.py new file mode 100644 index 00000000..3d6d60bc --- /dev/null +++ b/demand_forecasting/model/temporal_split.py @@ -0,0 +1,48 @@ +"""Temporal split: the test and validation cutoffs derived from the latest sale date, and the Train, +Val, and Test relationships of the sales on each side of them.""" + +from relationalai.semantics import DateTime +from relationalai.semantics.std import aggregates as aggs +from relationalai.semantics.std import datetime + +# Declares Sale.date and Sale.unit_sales, the columns of the loaded sales. +from . import source # noqa: F401 +from .schema import Sale, Test, Train, Val, model + +# -------------------------------------------------- +# Configure inputs +# -------------------------------------------------- + +TEST_DAYS = 60 # last 60 days as test window +VAL_DAYS = 60 # 60 days before test as validation + +# -------------------------------------------------- +# Train / Val / Test split (temporal) +# -------------------------------------------------- +# Forecast use cases require temporal splits: training on the past, evaluating +# on the future. Random splits leak future signal into training. + +# The test window is the last TEST_DAYS days of sales; the validation window is +# the VAL_DAYS days before it. +LatestSale = model.Relationship(f"the latest sale is on {DateTime:latest}") +TestStart = model.Relationship(f"the test window starts on {DateTime:test_start}") +ValStart = model.Relationship(f"the validation window starts on {DateTime:val_start}") +model.define(LatestSale(aggs.max(Sale.date))) +_latest, _test_start, _val_start = DateTime.ref(), DateTime.ref(), DateTime.ref() +model.where(LatestSale(_latest)).define( + TestStart(datetime.datetime.subtract(_latest, datetime.days(TEST_DAYS - 1))) +) +model.where(TestStart(_test_start)).define( + ValStart(datetime.datetime.subtract(_test_start, datetime.days(VAL_DAYS))) +) + +# Train: before the validation window. Val: from the validation window up to the +# test window. Test: from the test window on. The GNN trains on the past and +# evaluates on the future. +model.where(ValStart(_val_start), Sale.date < _val_start).define( + Train(Sale, Sale.date, Sale.unit_sales) +) +model.where( + ValStart(_val_start), TestStart(_test_start), Sale.date >= _val_start, Sale.date < _test_start +).define(Val(Sale, Sale.date, Sale.unit_sales)) +model.where(TestStart(_test_start), Sale.date >= _test_start).define(Test(Sale, Sale.date)) diff --git a/demand_forecasting/queries/forecast_report.py b/demand_forecasting/queries/forecast_report.py index e19318ea..c405f179 100644 --- a/demand_forecasting/queries/forecast_report.py +++ b/demand_forecasting/queries/forecast_report.py @@ -7,83 +7,98 @@ item family) over the test window, and the test-set RMSE. """ -import numpy as np import pandas as pd -from model import TEST_START, VAL_START, Item, Sale, Store, TestTable, TrainTable, ValTable, model -from relationalai.semantics import Float, count, select +from model import ( + SaleForecast, + SaleRmse, + SalesCounts, + TestStart, + UnitSales, + ValStart, + WeeklyForecast, + WeeklyRmse, + model, +) +from relationalai.semantics import Float, Integer + + +def published(relationship) -> float: + """The one figure a nullary relationship of the model publishes, NaN when it derives none.""" + values = model.select(relationship).to_df().iloc[:, 0] + return float(values.iloc[0]) if len(values) else float("nan") def main() -> None: + stores, items, sales, train, val, test = (Integer.ref() for _ in range(6)) counts = ( - select( - count(Store).alias("stores"), - count(Item).alias("items"), - count(Sale).alias("sales"), - (count(TrainTable) | 0).alias("train"), - (count(ValTable) | 0).alias("val"), - (count(TestTable) | 0).alias("test"), + model.where(SalesCounts(stores, items, sales, train, val, test)) + .select( + stores.alias("stores"), + items.alias("items"), + sales.alias("sales"), + train.alias("train"), + val.alias("val"), + test.alias("test"), ) .to_df() .iloc[0] ) - unit_sales = select(Sale.sale_id, Sale.unit_sales).to_df()["unit_sales"] + lowest, highest, mean = Integer.ref(), Integer.ref(), Float.ref() + unit_sales = ( + model.where(UnitSales(lowest, highest, mean)) + .select(lowest.alias("min"), highest.alias("max"), mean.alias("mean")) + .to_df() + ) print(f"Stores: {counts['stores']} Items: {counts['items']} Sales: {counts['sales']:,}") print( f"Splits (temporal): train={counts['train']:,} val={counts['val']:,} test={counts['test']:,}" ) - # The cutoffs that model/source.py split the sales on. - print(f"Train: < {VAL_START.date()}; Val: {VAL_START.date()} -- {TEST_START.date()}; " - f"Test: >= {TEST_START.date()}") - print(f"unit_sales: min={unit_sales.min()} mean={unit_sales.mean():.2f} max={unit_sales.max()}") + # The cutoffs that the model splits the sales on. + val_start = pd.Timestamp(model.select(ValStart).to_df().iloc[0, 0]) + test_start = pd.Timestamp(model.select(TestStart).to_df().iloc[0, 0]) + print(f"Train: < {val_start.date()}; Val: {val_start.date()} -- {test_start.date()}; " + f"Test: >= {test_start.date()}") + print(f"unit_sales: min={unit_sales['min'].iloc[0]} mean={unit_sales['mean'].iloc[0]:.2f} " + f"max={unit_sales['max'].iloc[0]}") print("\n" + "=" * 60) print("Forecast (test window) -- weekly aggregate per (city, item family)") print("=" * 60) - # Predictions and store/item metadata are read separately and left-joined, so a - # prediction whose store or item is missing still counts toward the per-Sale RMSE. - predicted_value_ref = Float.ref() - results_df = ( - model.where(Sale.predictions.predicted_value(predicted_value_ref)) - .select( - Sale.sale_id.alias("sale_id"), - Sale.date.alias("date"), - Sale.unit_sales.alias("actual"), - predicted_value_ref.alias("predicted"), - ) - .to_df() - ) - dimensions_df = select( - Sale.sale_id.alias("sale_id"), Store.city.alias("city"), Item.family.alias("family") - ).where(Sale.predictions, Sale.store_id == Store.store_id, Sale.item_id == Item.item_id).to_df() - results_df = results_df.merge(dimensions_df, on="sale_id", how="left") - - if results_df.empty: + # A prediction whose store or item is missing has no city or family: it counts toward + # the per-Sale RMSE but is left out of the weekly table. + n_predictions = len(model.select(SaleForecast.sale_id).to_df()) + if n_predictions == 0: print("(no predictions returned)") else: - results_df["date"] = pd.to_datetime(results_df["date"]) - results_df["predicted"] = results_df["predicted"].astype(float).clip(lower=0) - results_df["actual"] = results_df["actual"].astype(float) - results_df["week_start"] = results_df["date"].dt.to_period("W").dt.start_time - unlabeled = int((results_df["city"].isna() | results_df["family"].isna()).sum()) + labeled = model.select( + SaleForecast.sale_id.alias("sale_id"), + SaleForecast.city.alias("city"), + SaleForecast.family.alias("family"), + ).to_df() + unlabeled = n_predictions - len(labeled) if unlabeled: print(f"{unlabeled} predictions have no store city or item family: they count toward " "the per-Sale RMSE but not the weekly table.") weekly = ( - results_df.groupby(["city", "family", "week_start"])[["actual", "predicted"]] - .sum() - .reset_index() + model.select( + WeeklyForecast.city.alias("city"), + WeeklyForecast.family.alias("family"), + WeeklyForecast.week_start.alias("week_start"), + WeeklyForecast.actual.alias("actual"), + WeeklyForecast.predicted.alias("predicted"), + WeeklyForecast.abs_err.alias("abs_err"), + ) + .to_df() .sort_values(["city", "family", "week_start"]) ) - weekly["abs_err"] = (weekly["predicted"] - weekly["actual"]).abs() + weekly["week_start"] = pd.to_datetime(weekly["week_start"]) print(weekly.head(20).to_string(index=False)) - test_rmse = float(np.sqrt(((results_df["predicted"] - results_df["actual"]) ** 2).mean())) - weekly_rmse = float(np.sqrt(((weekly["predicted"] - weekly["actual"]) ** 2).mean())) - print(f"\nTest-set RMSE (per-Sale): {test_rmse:.4f}") - print(f"Test-set RMSE (per (city, family, week)): {weekly_rmse:.4f}") + print(f"\nTest-set RMSE (per-Sale): {published(SaleRmse):.4f}") + print(f"Test-set RMSE (per (city, family, week)): {published(WeeklyRmse):.4f}") if __name__ == "__main__": diff --git a/demand_forecasting/runbook.md b/demand_forecasting/runbook.md index c3ce1a02..bfe9bcc2 100644 --- a/demand_forecasting/runbook.md +++ b/demand_forecasting/runbook.md @@ -45,4 +45,4 @@ Each prompt is pasted into a fresh agent session loaded with the named `/rai-*` ## Data -Bundled CSVs in `data/favorita_mini/`: 3 stores, 25 items, ~27,375 daily sales (generated by `generate_favorita_mini.py`). The test-window length (60 days) is a constant in `model/source.py` and the training config is in `model/reasoning.py`. Full model in `model/`; training in `train.py`; the report in `queries/forecast_report.py`. +Bundled CSVs in `data/favorita_mini/`: 3 stores, 25 items, ~27,375 daily sales (generated by `generate_favorita_mini.py`). The test-window length (60 days) is a constant in `model/temporal_split.py` and the training config is in `model/demand_forecast.py`. The weekly rollup and RMSEs are rules in `model/forecast_accuracy.py`. Full model in `model/`; training in `train.py`; the report in `queries/forecast_report.py`. diff --git a/demand_planning_temporal/README.md b/demand_planning_temporal/README.md index f5efd271..7341dd99 100644 --- a/demand_planning_temporal/README.md +++ b/demand_planning_temporal/README.md @@ -29,7 +29,7 @@ Prescriptive reasoning makes this practical because the solver simultaneously ba - **Operations researchers** looking for a multi-period flow-conservation pattern in RelationalAI - A cost-minimizing weekly production plan per (site, SKU, week), produced by **prescriptive** decision variables and a HiGHS solve. -- A date-filtered planning horizon: each horizon's problem uses only the demand orders inside its window; `model/source.py` maps due dates to integer week numbers, and `std.common.range()` builds each horizon's weeks. +- A date-filtered planning horizon: each horizon's problem uses only the demand orders inside its window; `model/horizon_scope.py` maps due dates to integer week numbers and selects each horizon's orders, and `std.common.range()` builds each horizon's weeks. - An inventory schedule that satisfies flow conservation (`inv[t] = inv[t-1] + production[t] - demand[t]`) enforced as prescriptive constraints. - A service-level guarantee (a 95% minimum-fulfillment constraint) plus an unmet-demand report showing whether any demand went unserved. - A three-scenario what-if sweep that shows how total cost changes as the planning horizon extends, with each horizon solved as its own problem in one deployed model. @@ -38,7 +38,7 @@ Built using **prescriptive reasoning**: continuous decision variables for produc ## What's included -- **Model**: concepts for sites, SKUs, demand orders, production capacity, and weekly demand, time-indexed production and inventory variables, and one cost-minimizing problem per planning horizon, in the `model/` package (`schema.py` declares the concepts, `source.py` loads the sample data and scopes the orders to each horizon, `reasoning.py` states the decision problems), which `rai models deploy --path model` deploys to your Snowflake account, where each refresh runs the solves. +- **Model**: concepts for sites, SKUs, demand orders, production capacity, and weekly demand, time-indexed production and inventory variables, and one cost-minimizing problem per planning horizon, in the `model/` package (`schema.py` declares the concepts, `source.py` loads the sample data, `horizon_scope.py` maps due dates to weeks and scopes the orders to each horizon, `capacity_inputs.py` sets each site-SKU pair's starting inventory and holding cost, `weekly_demand.py` builds the weekly demand, `production_plans.py` states the decision problems), which `rai models deploy --path model` deploys to your Snowflake account, where each refresh runs the solves. - **Query**: `queries/demand_planning.py`, which prints the report from the deployed model. - **Runbook**: `runbook.md` — a paste-testable walkthrough that reproduces the template step by step with the RAI skills; as important a reference as the code in `model/`. - **Data**: `data/sites.csv`, `data/skus.csv`, `data/demand_orders.csv`, `data/production_capacity.csv`, `data/initial_inventory.csv` @@ -203,8 +203,11 @@ Use this sequence to deploy the model and query it: ├── model/ │ ├── __init__.py # exports of the deployed model │ ├── schema.py # concepts and properties -│ ├── source.py # sample data, planning horizons, and order scoping -│ └── reasoning.py # decision variables, constraints, objective, one problem per horizon +│ ├── source.py # sample data and planning horizons +│ ├── horizon_scope.py # order weeks, orders in each horizon, order counts +│ ├── capacity_inputs.py # starting inventory and holding cost per site-SKU pair +│ ├── weekly_demand.py # demand per site, SKU, and week in each horizon +│ └── production_plans.py # decision variables, constraints, objective, one problem per horizon ├── queries/ │ └── demand_planning.py # report from the deployed model └── data/ @@ -229,29 +232,29 @@ The bundled data is a small, illustrative multi-site production dataset covering ## Model overview -The model is a multi-period production and inventory ontology. Sites and SKUs are reference entities; demand orders are the dated event table that temporal filtering scopes; production capacity carries the pre-joined data the solver's decision variables attach to. +The model is a multi-period production and inventory ontology. Sites and SKUs are reference entities; demand orders are the dated event table that temporal filtering scopes; production capacity carries the data the solver's decision variables attach to, including each pair's starting inventory and holding cost. -- **Key entities**: `Site`, `SKU`, `DemandOrder`, `ProdCapacity`, and `WeeklyDemand` (pre-aggregated demand per planning horizon, site, SKU, and week, including zero-demand weeks). +- **Key entities**: `Site`, `SKU`, `DemandOrder`, `ProdCapacity`, and `InitialInventory` (starting inventory per site and SKU), and `WeeklyDemand` (demand per planning horizon, site, SKU, and week, including zero-demand weeks). - **Primary identifiers**: `Site.id` and `SKU.id` (integers); `DemandOrder.id` (integer); the composite key `ProdCapacity(site_id, sku_id)`; the composite key `WeeklyDemand(wk_planning_end, wk_site_id, wk_sku_id, wk_week_num)`. - **Important invariants**: quantities, costs, production, and inventory are non-negative; inventory obeys flow conservation (`inv[t] = inv[t-1] + production[t] - demand[t]`); week 0 inventory equals the initial inventory; unmet demand per order is bounded by the order quantity; total unmet demand is capped by the 95% service level. Unmet demand is not subtracted from the inventory withdrawal: inventory must cover all demand, and `x_unmet` counts only toward the service level and the penalty. -For the full concept and property definitions, see `model/schema.py`; the time-indexed `x_production` / `x_inventory` decision variables on `ProdCapacity` are declared in `model/reasoning.py`, and the relationships linking orders and capacity to their `Site` and `SKU` in `model/source.py`; `runbook.md` builds them step by step with the RAI skills. +For the full concept and property definitions, see `model/schema.py`; the time-indexed `x_production` / `x_inventory` decision variables on `ProdCapacity` are declared in `model/production_plans.py`, and the relationships linking orders and capacity to their `Site` and `SKU` in `model/source.py`; `runbook.md` builds them step by step with the RAI skills. ## How it works -**Sweep planning horizons.** `model/source.py` lists three `planning_end` dates to analyze how the horizon length affects cost. For each, it selects the demand orders inside the window (so each problem sees only relevant demand) and builds the weekly demand over the horizon's weeks. `model/reasoning.py` defines one problem per horizon, so an infeasible horizon never affects the others. +**Sweep planning horizons.** `model/source.py` lists three `planning_end` dates to analyze how the horizon length affects cost. For each, `model/horizon_scope.py` selects the demand orders inside the window (so each problem sees only relevant demand) and `model/weekly_demand.py` builds the weekly demand over the horizon's weeks. `model/production_plans.py` defines one problem per horizon, so an infeasible horizon never affects the others. **Map dates to integer weeks.** `std.common.range()` requires integer periods, so each order's due date is converted into a week number relative to the planning start, and the number of weeks is derived from the horizon length. The week count varies by scenario (14 weeks for January, 18 for February, 22 for March). **Index decision variables by time.** Production and inventory variables are indexed by both concept (site × SKU) and time period via a multi-arity property pattern, creating one continuous variable per (site, SKU, week) combination, bounded by the per-line weekly capacity. -**Enforce flow conservation.** The core multi-period constraint ties adjacent weeks together: inventory at the end of week `t` equals inventory at the end of week `t-1` plus production in week `t` minus demand in week `t`. A `WeeklyDemand` concept pre-aggregates orders into weekly buckets — including zero-demand weeks — so the constraint covers every period. +**Enforce flow conservation.** The core multi-period constraint ties adjacent weeks together: inventory at the end of week `t` equals inventory at the end of week `t-1` plus production in week `t` minus demand in week `t`. A `WeeklyDemand` concept sums orders into weekly buckets — including zero-demand weeks — so the constraint covers every period. **Minimize total cost.** The objective adds production cost, holding cost, and an unmet-demand penalty, each summed over its own concept, and the solver minimizes the total subject to the flow-conservation and service-level constraints. `model/source.py` also includes a commented-out Pattern B for data that carries Unix epoch-second timestamps instead of date strings: convert the horizon boundaries to epochs and filter identically. -See `model/reasoning.py` for the implementation and `runbook.md` to reproduce it step by step with the RAI skills. +See `model/production_plans.py` for the implementation and `runbook.md` to reproduce it step by step with the RAI skills. ## Customize this template @@ -263,8 +266,8 @@ See `model/reasoning.py` for the implementation and `runbook.md` to reproduce it ### Tune parameters - **Change the planning horizon**: Edit `planning_start` and the `SCENARIO_VALUES` list in `model/source.py` to shift the optimization window. Each value becomes its own problem, and the week count and date filter update automatically per scenario. -- **Adjust service level**: Change `min_service_level` in `model/reasoning.py` (default 0.95) to require higher or lower demand fulfillment. -- **Adjust safety stock**: The `safety_stock_weeks` parameter in `model/reasoning.py` (default 1) requires inventory at the end of each week to be at least `safety_stock_weeks × average weekly demand` per site-SKU pair. Set to 0 to disable, or increase for more conservative buffering. +- **Adjust service level**: Change `min_service_level` in `model/production_plans.py` (default 0.95) to require higher or lower demand fulfillment. +- **Adjust safety stock**: The `safety_stock_weeks` parameter in `model/production_plans.py` (default 1) requires inventory at the end of each week to be at least `safety_stock_weeks × average weekly demand` per site-SKU pair. Set to 0 to disable, or increase for more conservative buffering. ### Extend the model @@ -273,8 +276,8 @@ See `model/reasoning.py` for the implementation and `runbook.md` to reproduce it ### Scale up / productionize -- The scenario sweep shares one model across horizons; for production, read your Snowflake tables into DataFrames (for example with Snowpark's `to_pandas()`) in place of the CSV loads in `model/source.py`, so its week-number and weekly-demand preparation still runs. That preparation happens at deploy time, so new order data needs a redeploy, not only a refresh. -- Solve time is controlled by `time_limit_sec` on `problem.configure("highs", ...)` in `model/reasoning.py`; raise it if larger site/SKU/week grids need more time. +- The scenario sweep shares one model across horizons; for production, read your Snowflake tables into DataFrames (for example with Snowpark's `to_pandas()`) in place of the CSV loads in `model/source.py`. The frames are read at deploy time, so new order data needs a redeploy, not only a refresh. +- Solve time is controlled by `time_limit_sec` on `problem.configure("highs", ...)` in `model/production_plans.py`; raise it if larger site/SKU/week grids need more time. ## Troubleshooting diff --git a/demand_planning_temporal/model/__init__.py b/demand_planning_temporal/model/__init__.py index 971197ef..255bb5b2 100644 --- a/demand_planning_temporal/model/__init__.py +++ b/demand_planning_temporal/model/__init__.py @@ -14,6 +14,12 @@ - Solve one problem for each planning horizon, so the horizons are independent what-if scenarios. +Modules: `horizon_scope.py` (the week of each order and the orders in each +horizon), `capacity_inputs.py` (starting inventory and holding cost per site and +SKU), `weekly_demand.py` (demand per site, SKU, and week), and +`production_plans.py` (the decision problems). Each module imports the modules +whose declarations it reads. + Temporal filtering patterns demonstrated: - Pattern A (native date columns, used here): filter by due_date string comparisons, then map dates to integer week numbers for std.common.range() periods. @@ -27,7 +33,8 @@ `python -m queries.demand_planning` then prints the report from the deployed model. """ -from .reasoning import PLANS, Plan +from .horizon_scope import NumOrders, PlanOrderCount +from .production_plans import PLANS, Plan from .schema import DemandOrder, OrderInPlan, ProdCapacity, WeeklyDemand, model from .source import DATA_DIR, planning_start @@ -35,8 +42,10 @@ "DATA_DIR", "PLANS", "DemandOrder", + "NumOrders", "OrderInPlan", "Plan", + "PlanOrderCount", "ProdCapacity", "WeeklyDemand", "model", diff --git a/demand_planning_temporal/model/capacity_inputs.py b/demand_planning_temporal/model/capacity_inputs.py new file mode 100644 index 00000000..81320b51 --- /dev/null +++ b/demand_planning_temporal/model/capacity_inputs.py @@ -0,0 +1,25 @@ +"""Capacity inputs: each site-SKU pair's starting inventory and weekly holding cost.""" + +from relationalai.semantics.std import aggregates as aggs +from relationalai.semantics.std import floats + +from .schema import SKU, InitialInventory, ProdCapacity, model + +# Starting inventory of a pair: its recorded quantity, zero when the pair has no record. +model.define( + ProdCapacity.initial_inventory( + aggs.sum(InitialInventory, floats.float(InitialInventory.quantity)) + .per(ProdCapacity) + .where( + InitialInventory.site_id == ProdCapacity.site_id, + InitialInventory.sku_id == ProdCapacity.sku_id, + ) + | 0.0 + ) +) + +# Holding cost per week of a pair: its SKU's, so the solver expressions read a property of +# ProdCapacity rather than a traversal through SKU (which raises functional-dependency issues). +model.where(SKU.id == ProdCapacity.sku_id).define( + ProdCapacity.holding_cost_per_week(SKU.holding_cost_per_week) +) diff --git a/demand_planning_temporal/model/horizon_scope.py b/demand_planning_temporal/model/horizon_scope.py new file mode 100644 index 00000000..58880ce6 --- /dev/null +++ b/demand_planning_temporal/model/horizon_scope.py @@ -0,0 +1,43 @@ +"""Horizon scope: the week of each demand order, the orders inside each planning horizon, and the +order counts.""" + +from relationalai.semantics import Integer, String +from relationalai.semantics.std import aggregates as aggs +from relationalai.semantics.std import datetime + +from .schema import DemandOrder, OrderInPlan, model +from .source import SCENARIO_VALUES, planning_start + +# DATE-TO-PERIOD MAPPING: weeks since planning_start, so the week of planning_start itself is 1 +# and an order due before it falls in week 0 or earlier. +model.define( + DemandOrder.week_num( + datetime.date.diff( + "day", + datetime.date.fromisoformat(planning_start), + datetime.date.fromisoformat(DemandOrder.due_date), + ) + // 7 + + 1 + ) +) + +# DATE FILTERING: an order is in a horizon's plan when it is due from planning_start through that +# horizon's planning_end. ISO date strings compare as dates. +for planning_end in SCENARIO_VALUES: + model.where( + DemandOrder.due_date >= planning_start, DemandOrder.due_date <= planning_end + ).define(OrderInPlan(DemandOrder, planning_end)) + +# The number of orders, and the number inside each horizon's plan (zero for an empty horizon). +NumOrders = model.Relationship(f"there are {Integer:num_orders} demand orders") +PlanOrderCount = model.Relationship( + f"the plan ending {String:planning_end} has {Integer:n_orders} demand orders in scope" +) +model.define(NumOrders(aggs.count(DemandOrder))) +for planning_end in SCENARIO_VALUES: + model.define( + PlanOrderCount( + planning_end, aggs.count(DemandOrder).where(OrderInPlan(DemandOrder, planning_end)) | 0 + ) + ) diff --git a/demand_planning_temporal/model/reasoning.py b/demand_planning_temporal/model/production_plans.py similarity index 96% rename from demand_planning_temporal/model/reasoning.py rename to demand_planning_temporal/model/production_plans.py index 8f147ab0..569b861b 100644 --- a/demand_planning_temporal/model/reasoning.py +++ b/demand_planning_temporal/model/production_plans.py @@ -1,10 +1,13 @@ -"""Demand planning decision problems: a least-cost multi-week plan for each planning horizon.""" +"""Production plans: a least-cost multi-week production and inventory plan for each planning +horizon.""" from typing import Any, NamedTuple from relationalai.semantics import Float, Integer, String, std, sum from relationalai.semantics.reasoners.prescriptive import Problem +# Declare the orders in each horizon, the weekly demand, and the capacity inputs the problems read. +from . import capacity_inputs, horizon_scope, weekly_demand # noqa: F401 from .schema import DemandOrder, OrderInPlan, ProdCapacity, WeeklyDemand, model from .source import SCENARIO_VALUES, weeks_in_horizon diff --git a/demand_planning_temporal/model/schema.py b/demand_planning_temporal/model/schema.py index 9b073ec0..9b4d0a39 100644 --- a/demand_planning_temporal/model/schema.py +++ b/demand_planning_temporal/model/schema.py @@ -22,6 +22,8 @@ DemandOrder = Concept("DemandOrder", identify_by={"id": Integer}) DemandOrder.quantity = Property(f"{DemandOrder} has {Integer:quantity}") DemandOrder.due_date = Property(f"{DemandOrder} has {String:due_date}") +DemandOrder.site_id = Property(f"{DemandOrder} ships from site {Integer:site_id}") +DemandOrder.sku_id = Property(f"{DemandOrder} is for SKU {Integer:sku_id}") DemandOrder.week_num = Property(f"{DemandOrder} falls in week {Integer:week_num}") # The orders inside each planning horizon, keyed by the horizon's planning_end date. @@ -42,6 +44,12 @@ f"{ProdCapacity} has {Float:holding_cost_per_week}" ) +# Concept: starting inventory per site x SKU (REFERENCE TABLE - no filtering needed) +InitialInventory = Concept( + "InitialInventory", identify_by={"site_id": Integer, "sku_id": Integer} +) +InitialInventory.quantity = Property(f"{InitialInventory} has {Integer:quantity}") + # Concept: demand per site x SKU x week in each planning horizon (0 for weeks with no orders) WeeklyDemand = Concept( "WeeklyDemand", diff --git a/demand_planning_temporal/model/source.py b/demand_planning_temporal/model/source.py index 066243ad..904ac918 100644 --- a/demand_planning_temporal/model/source.py +++ b/demand_planning_temporal/model/source.py @@ -1,20 +1,11 @@ -"""Load the sample sites, SKUs, orders, and capacity into the demand planning model, scoped to each planning horizon.""" +"""Load the sample sites, SKUs, orders, capacity, and starting inventory into the demand planning model.""" -import itertools from datetime import datetime from pathlib import Path import pandas as pd -from .schema import ( - SKU, - DemandOrder, - OrderInPlan, - ProdCapacity, - Site, - WeeklyDemand, - model, -) +from .schema import SKU, DemandOrder, InitialInventory, ProdCapacity, Site, model DATA_DIR = Path(__file__).resolve().parents[1] / "data" @@ -23,12 +14,15 @@ planning_start = "2025-11-01" # Start of planning horizon # Scenarios (what-if analysis): each planning_end value is one planning horizon, -# solved by its own Problem in model/reasoning.py. +# solved by its own Problem in model/production_plans.py. SCENARIO_VALUES = ["2026-01-31", "2026-02-28", "2026-03-31"] def weeks_in_horizon(planning_end): - """Number of weekly periods from planning_start through planning_end.""" + """Number of weekly periods from planning_start through planning_end. + + A Python value because it sets the index ranges of the decision variables. + """ start_date = datetime.strptime(planning_start, "%Y-%m-%d") end_date = datetime.strptime(planning_end, "%Y-%m-%d") return int((end_date - start_date).days / 7) + 1 @@ -42,131 +36,46 @@ def weeks_in_horizon(planning_end): sku_csv = pd.read_csv(DATA_DIR / "skus.csv") model.define(SKU.new(model.data(sku_csv).to_schema())) -orders_df = pd.read_csv(DATA_DIR / "demand_orders.csv") -orders_df["due_date"] = pd.to_datetime(orders_df["due_date"]) - -# DATE-TO-PERIOD MAPPING: Convert due_date to integer week number -orders_df["week_num"] = ( - (orders_df["due_date"] - pd.Timestamp(planning_start)).dt.days // 7 + 1 -).astype(int) - # -------------------------------------------------- # EPOCH TIMESTAMP ALTERNATIVE (Pattern B): -# If DemandOrder had epoch integer timestamps instead of date strings, -# filtering would look like this: +# If DemandOrder had epoch integer timestamps instead of date strings, the rules in +# horizon_scope.py would compare them with epoch bounds: # # start_epoch = int(datetime.strptime(planning_start, "%Y-%m-%d").timestamp()) # end_epoch = int(datetime.strptime(planning_end, "%Y-%m-%d").timestamp()) + 86399 # -# # Filter in pandas before loading -# filtered_orders = orders_df[ -# (orders_df["created_at"] >= start_epoch) & -# (orders_df["created_at"] <= end_epoch) -# ].copy() -# -# # Or filter in .where() clauses on constraints -# problem.satisfy(model.require( -# sum(DemandOrder.x_unmet) <= (1 - min_service_level) * sum(DemandOrder.quantity) -# ).where( +# model.where( # DemandOrder.created_at >= start_epoch, DemandOrder.created_at <= end_epoch -# )) +# ).define(OrderInPlan(DemandOrder, planning_end)) # -# # Period mapping from epoch: week_num = (epoch - start_epoch) // (7 * 86400) + 1 +# # Period mapping from epoch: week_num = (created_at - start_epoch) // (7 * 86400) + 1 # -------------------------------------------------- -# Map demand orders data (all orders; each horizon below selects its own). -order_data = model.data( - orders_df.assign(due_date=orders_df["due_date"].dt.strftime("%Y-%m-%d")) -) +# Map demand orders data (all orders; horizon_scope.py selects each horizon's). Due dates are +# loaded as yyyy-mm-dd strings, the one form horizon_scope.py both parses and compares. +orders_df = pd.read_csv(DATA_DIR / "demand_orders.csv") +orders_df["due_date"] = pd.to_datetime(orders_df["due_date"]).dt.strftime("%Y-%m-%d") +order_data = model.data(orders_df) model.define( o := DemandOrder.new(id=order_data.id), o.quantity(order_data.quantity), o.due_date(order_data.due_date), - o.week_num(order_data.week_num), + o.site_id(order_data.site_id), + o.sku_id(order_data.sku_id), ) # Link demand orders to SKU and Site via foreign keys model.define(DemandOrder.sku(SKU)).where(DemandOrder.id == order_data.id, SKU.id == order_data.sku_id) model.define(DemandOrder.site(Site)).where(DemandOrder.id == order_data.id, Site.id == order_data.site_id) -# Map production capacity data from CSV. -pc_df = pd.read_csv(DATA_DIR / "production_capacity.csv") -inv_df = pd.read_csv(DATA_DIR / "initial_inventory.csv") - -# Pre-join: merge initial inventory and SKU holding cost into ProdCapacity -# This avoids relationship traversal FD issues in solver expressions -pc_df = pc_df.merge( - inv_df[["site_id", "sku_id", "quantity"]], on=["site_id", "sku_id"], how="left" +# Map production capacity and starting inventory data from CSV. +model.define( + ProdCapacity.new(model.data(pd.read_csv(DATA_DIR / "production_capacity.csv")).to_schema()) ) -pc_df = pc_df.rename(columns={"quantity": "initial_inventory"}).fillna(0) -pc_df = pc_df.merge( - sku_csv[["id", "holding_cost_per_week"]], - left_on="sku_id", - right_on="id", - how="left", - suffixes=("", "_sku"), +model.define( + InitialInventory.new(model.data(pd.read_csv(DATA_DIR / "initial_inventory.csv")).to_schema()) ) -pc_df = pc_df.drop(columns=["id"], errors="ignore") - -pc_data = model.data(pc_df) -model.define(ProdCapacity.new(pc_data.to_schema())) # Link to Site and SKU model.define(ProdCapacity.site(Site)).where(Site.id == ProdCapacity.site_id) model.define(ProdCapacity.sku(SKU)).where(SKU.id == ProdCapacity.sku_id) - -# Per planning horizon: the orders in scope and the weekly demand over its weeks. -scope_frames = [] -demand_frames = [] -for planning_end in SCENARIO_VALUES: - num_weeks = weeks_in_horizon(planning_end) - - # DATE FILTERING: Only orders within the planning horizon are in scope - filtered_orders = orders_df[ - (orders_df["due_date"] >= planning_start) - & (orders_df["due_date"] <= planning_end) - ] - scope_frames.append( - pd.DataFrame({"id": filtered_orders["id"], "planning_end": planning_end}) - ) - - # Pre-aggregate demand into weekly buckets per SKU per Site - weekly_demand = ( - filtered_orders.groupby(["week_num", "sku_id", "site_id"])["quantity"] - .sum() - .reset_index() - ) - - # Build complete demand matrix: every (site, sku, week) combo, 0 for missing weeks - all_combos = list( - itertools.product( - pc_df["site_id"].unique(), pc_df["sku_id"].unique(), range(1, num_weeks + 1) - ) - ) - full_demand = pd.DataFrame(all_combos, columns=["site_id", "sku_id", "week_num"]) - full_demand = full_demand.merge( - weekly_demand[["site_id", "sku_id", "week_num", "quantity"]], - on=["site_id", "sku_id", "week_num"], - how="left", - ).fillna(0.0) - full_demand["planning_end"] = planning_end - demand_frames.append(full_demand) - -scope_df = pd.concat(scope_frames, ignore_index=True) -# With no order inside any horizon there is nothing to scope. -if not scope_df.empty: - scope_data = model.data(scope_df) - model.define(OrderInPlan(DemandOrder, scope_data.planning_end)).where( - DemandOrder.id == scope_data.id - ) - -wd_data = model.data(pd.concat(demand_frames, ignore_index=True)) -model.define( - wd := WeeklyDemand.new( - wk_planning_end=wd_data.planning_end, - wk_site_id=wd_data.site_id, - wk_sku_id=wd_data.sku_id, - wk_week_num=wd_data.week_num, - ), - wd.wk_quantity(wd_data.quantity), -) diff --git a/demand_planning_temporal/model/weekly_demand.py b/demand_planning_temporal/model/weekly_demand.py new file mode 100644 index 00000000..15185731 --- /dev/null +++ b/demand_planning_temporal/model/weekly_demand.py @@ -0,0 +1,38 @@ +"""Weekly demand: the demand of each site and SKU in each week of each planning horizon, zero for +weeks without orders.""" + +from relationalai.semantics import Integer, std +from relationalai.semantics.std import aggregates as aggs +from relationalai.semantics.std import floats + +# Defines DemandOrder.week_num and OrderInPlan, the order scope the weekly demand sums. +from . import horizon_scope # noqa: F401 +from .schema import DemandOrder, OrderInPlan, ProdCapacity, WeeklyDemand, model +from .source import SCENARIO_VALUES, weeks_in_horizon + +# A row for each site-SKU pair with capacity, in each week of each horizon. +_week = Integer.ref() +for planning_end in SCENARIO_VALUES: + model.where(_week == std.common.range(1, weeks_in_horizon(planning_end) + 1)).define( + WeeklyDemand.new( + wk_planning_end=planning_end, + wk_site_id=ProdCapacity.site_id, + wk_sku_id=ProdCapacity.sku_id, + wk_week_num=_week, + ) + ) + +# The quantity ordered for the pair in the week by the horizon's orders, zero when none. +model.define( + WeeklyDemand.wk_quantity( + aggs.sum(DemandOrder, floats.float(DemandOrder.quantity)) + .per(WeeklyDemand) + .where( + OrderInPlan(DemandOrder, WeeklyDemand.wk_planning_end), + DemandOrder.week_num == WeeklyDemand.wk_week_num, + DemandOrder.site_id == WeeklyDemand.wk_site_id, + DemandOrder.sku_id == WeeklyDemand.wk_sku_id, + ) + | 0.0 + ) +) diff --git a/demand_planning_temporal/queries/demand_planning.py b/demand_planning_temporal/queries/demand_planning.py index 6234c4e7..1b4481d1 100644 --- a/demand_planning_temporal/queries/demand_planning.py +++ b/demand_planning_temporal/queries/demand_planning.py @@ -5,11 +5,11 @@ inventory levels, and unmet demand, then a summary of the horizons. """ -from model import PLANS, DemandOrder, OrderInPlan, model, planning_start -from relationalai.semantics import Float, Integer, count +from model import PLANS, NumOrders, PlanOrderCount, model, planning_start +from relationalai.semantics import Float, Integer if __name__ == "__main__": - total_orders = model.select(count(DemandOrder)).to_df().iloc[0, 0] + total_orders = int(model.select(NumOrders).to_df().iloc[0, 0]) scenario_results = [] for plan in PLANS: @@ -36,8 +36,12 @@ print( f" Planning horizon: {planning_start} to {plan.planning_end} ({plan.num_weeks} weeks)" ) - orders_in_scope = len( - model.select(DemandOrder.id).where(OrderInPlan(DemandOrder, plan.planning_end)).to_df() + n_orders_ref = Integer.ref() + orders_in_scope = int( + model.where(PlanOrderCount(plan.planning_end, n_orders_ref)) + .select(n_orders_ref) + .to_df() + .iloc[0, 0] ) print(f" Demand orders in scope: {orders_in_scope} (of {total_orders} total)") diff --git a/demand_planning_temporal/runbook.md b/demand_planning_temporal/runbook.md index 84832871..faeec279 100644 --- a/demand_planning_temporal/runbook.md +++ b/demand_planning_temporal/runbook.md @@ -39,7 +39,7 @@ Each prompt is pasted into a fresh agent session loaded with the named `/rai-*` **Prompt:** /rai-prescriptive-problem Map each order's due date to a week and build a weekly time grid, then decide weekly production, end-of-week inventory, and any unmet demand per site-SKU (all non-negative). Inventory must carry over week to week — end-of-week inventory equals last week's inventory plus this week's production minus this week's demand, starting from opening inventory — weekly production can't exceed capacity, at least 95% of total demand must be met, and end-of-week inventory must stay above one week of average demand (safety stock). Minimize total cost — production plus holding plus a penalty on unmet demand. Solve three planning horizons as separate problems — ending 2026-01-31, 2026-02-28, and 2026-03-31 — and persist the decisions to the ontology. -**Response:** OPTIMAL in all three horizons (HiGHS). Total cost **rises with the horizon** — a longer plan carries the same inventory for more weeks and pulls in more orders, so more holding cost accrues. (The absolute dollar totals depend on the planning-start date and how the weekly grid is anchored, so the reproducible result is the upward trend across horizons, not a specific figure.) Each horizon is its own problem in `model/reasoning.py`, configured with `problem.configure(...)` so each refresh of the deployed model runs all three. The production, inventory, and unmet decisions (`ProdCapacity.x_production`, `ProdCapacity.x_inventory`, `DemandOrder.x_unmet`) are published per horizon for the report. +**Response:** OPTIMAL in all three horizons (HiGHS). Total cost **rises with the horizon** — a longer plan carries the same inventory for more weeks and pulls in more orders, so more holding cost accrues. (The absolute dollar totals depend on the planning-start date and how the weekly grid is anchored, so the reproducible result is the upward trend across horizons, not a specific figure.) Each horizon is its own problem in `model/production_plans.py`, configured with `problem.configure(...)` so each refresh of the deployed model runs all three. The production, inventory, and unmet decisions (`ProdCapacity.x_production`, `ProdCapacity.x_inventory`, `DemandOrder.x_unmet`) are published per horizon for the report. ## 4. Read the plan across horizons diff --git a/disease-outbreak-prevention/README.md b/disease-outbreak-prevention/README.md index 4f5169e2..ba47e115 100644 --- a/disease-outbreak-prevention/README.md +++ b/disease-outbreak-prevention/README.md @@ -38,7 +38,7 @@ Built using **graph analysis** (a directed, weighted graph with `Facility` as th ## What's included -- **Model**: the `Facility` concept, the `FacilityConnection` edge concept (with `transfer_volume`, `contact_intensity`, and a derived `risk_weight`), the directed weighted `Graph` built from them, and the weighted degree centrality, indegree, and outdegree metrics, in the `model/` package (`schema.py` declares the concepts, `source.py` loads the sample data, `reasoning.py` states the graph and metrics). `rai models deploy --path model` deploys it to your Snowflake account, where each refresh computes the metrics. +- **Model**: the `Facility` concept, the `FacilityConnection` edge concept (with `transfer_volume`, `contact_intensity`, and a derived `risk_weight`), the directed weighted `Graph` built from them, the weighted degree centrality, indegree, and outdegree metrics, and each facility's priority rank, in the `model/` package (`schema.py` declares the concepts, `source.py` loads the sample data, `facility_network.py` states the graph, the metrics, the rank, and the network summary). `rai models deploy --path model` deploys it to your Snowflake account, where each refresh computes the metrics. - **Query**: `queries/facility_ranking.py` — prints the ranked report from the deployed model. - **App**: `app.py` — an optional Streamlit web app that queries the deployed model. - **Runbook**: `runbook.md` — a paste-testable walkthrough that reproduces the template step by step with the RAI skills; as important a reference as the script itself. @@ -194,7 +194,7 @@ disease-outbreak-prevention/ __init__.py # exports of the deployed model schema.py # Facility and FacilityConnection concepts source.py # loads the sample CSVs - reasoning.py # risk weight, graph, and metrics + facility_network.py # risk weight, graph, metrics, priority rank, network summary queries/ facility_ranking.py # report from the deployed model app.py # optional Streamlit app (queries the deployed model) @@ -227,7 +227,7 @@ For the full concept and property definitions, see `model/schema.py`; `runbook.m ## How it works -The deployed model computes weighted centrality on the graph; the report and the app query it and rank facilities: +The deployed model computes weighted centrality on the graph; it also ranks the facilities, and the report and the app query the result: ```text CSV files → model/ (deployed) → weighted centrality + degree metrics → rank facilities → display / export @@ -237,11 +237,11 @@ CSV files → model/ (deployed) → weighted centrality + degree metrics → ran 2. **Calculate graph metrics.** Each refresh of the deployed model runs the Graph API, which computes weighted degree centrality (summing risk-weighted edges and dividing by the number of other facilities, so the score reflects cumulative transmission risk rather than a raw connection count) alongside indegree and outdegree counts. -3. **Query and rank.** A single query, shared by the report and the app, pulls each facility's identity, type, region, published centrality score, and in/out and total connection counts, then sorts descending by centrality (ties by facility id) to produce the ranked shortlist. +3. **Query the ranking.** Each refresh also ranks the facilities by centrality, highest first with ties by facility id, and computes the network summary (facility count, mean centrality, mean connections). A single query, shared by the report and the app, pulls each facility's priority rank, identity, type, region, published centrality score, and in/out and total connection counts, and orders them by rank to produce the ranked shortlist. 4. **Present results.** `queries/facility_ranking.py` prints the ranked table, a top-priority breakdown, network summary statistics, and response recommendations from the deployed model. The optional Streamlit app queries the same deployed model and renders the ranking as an interactive network graph with a filterable table and CSV export. -See `model/reasoning.py` and `queries/facility_ranking.py` for the implementation and `runbook.md` for the skill-driven reproduction. +See `model/facility_network.py` and `queries/facility_ranking.py` for the implementation and `runbook.md` for the skill-driven reproduction. ## Customize this template @@ -255,7 +255,7 @@ Focus on the first changes most users will make. ### Tune parameters -- The risk formula is `risk_weight = transfer_volume x contact_intensity`, defined in `model/reasoning.py`. Change how the two factors combine (for example, a weighted average) to reweight what "risk" means. +- The risk formula is `risk_weight = transfer_volume x contact_intensity`, defined in `model/facility_network.py`. Change how the two factors combine (for example, a weighted average) to reweight what "risk" means. - Switch the graph's centrality metric if you want a different notion of importance (for example, betweenness or eigenvector centrality) in place of weighted degree. ### Extend the model diff --git a/disease-outbreak-prevention/model/__init__.py b/disease-outbreak-prevention/model/__init__.py index 0d62dabd..288c0ed6 100644 --- a/disease-outbreak-prevention/model/__init__.py +++ b/disease-outbreak-prevention/model/__init__.py @@ -6,6 +6,7 @@ - Load a network of healthcare facilities and their connections from CSV. - Calculate weighted degree centrality for each facility (considering connection weights). - Calculate each facility's incoming and outgoing connection counts. +- Rank the facilities by centrality and summarize the network (`facility_network.py`). Run: `rai models deploy --path model` deploys this package to the schemas in @@ -14,7 +15,7 @@ `streamlit run app.py` starts the interactive app, both from the deployed model. """ -from .reasoning import graph +from .facility_network import NetworkSummary, graph from .schema import Facility, FacilityConnection, model from .source import DATA_DIR @@ -22,6 +23,7 @@ "DATA_DIR", "Facility", "FacilityConnection", + "NetworkSummary", "graph", "model", ] diff --git a/disease-outbreak-prevention/model/reasoning.py b/disease-outbreak-prevention/model/facility_network.py similarity index 66% rename from disease-outbreak-prevention/model/reasoning.py rename to disease-outbreak-prevention/model/facility_network.py index 7e6037f6..3d5d228a 100644 --- a/disease-outbreak-prevention/model/reasoning.py +++ b/disease-outbreak-prevention/model/facility_network.py @@ -1,7 +1,10 @@ -"""Facility network graph: risk-weighted degree centrality and in/out connection counts.""" +"""Facility network: each connection's risk weight, the risk-weighted facility graph, each +facility's weighted degree centrality, connection counts and priority rank, and the network +summary.""" from relationalai.semantics import Float, Integer, define from relationalai.semantics.reasoners.graph import Graph +from relationalai.semantics.std import aggregates as aggs from .schema import Facility, FacilityConnection, model @@ -49,3 +52,21 @@ model.define( Facility.total_connections(Facility.incoming_connections + Facility.outgoing_connections) ) + +# Priority rank: 1 is the facility with the highest weighted degree centrality, ties broken by +# the lower facility id. The centrality is negated so both keys sort ascending: the Logic +# engine's rank does not mix ascending and descending keys. +Facility.priority_rank = model.Property(f"{Facility} has {Integer:priority_rank}") +model.define(Facility.priority_rank(aggs.rank(-Facility.degree_centrality, Facility.id))) + +# The network's facility count and its mean degree centrality and connections per facility. +NetworkSummary = model.Relationship( + f"the network has {Integer:n_facilities} facilities, a mean degree centrality of " + f"{Float:mean_centrality}, and a mean of {Float:mean_connections} connections per facility" +) +_scored = (Facility.degree_centrality, Facility.total_connections) +model.define(NetworkSummary( + aggs.count(Facility).where(*_scored), + aggs.avg(Facility, Facility.degree_centrality).where(*_scored), + aggs.avg(Facility, Facility.total_connections).where(*_scored), +)) diff --git a/disease-outbreak-prevention/queries/facility_ranking.py b/disease-outbreak-prevention/queries/facility_ranking.py index fa431274..20562bf0 100644 --- a/disease-outbreak-prevention/queries/facility_ranking.py +++ b/disease-outbreak-prevention/queries/facility_ranking.py @@ -5,29 +5,47 @@ receive priority for vaccines, testing stations, and emergency response teams. """ -from model import Facility, model +from model import Facility, NetworkSummary, model +from relationalai.semantics import Float, Integer def ranked_facilities(): - """Every facility's published metrics, ranked by weighted degree centrality. + """Every facility's published metrics, in priority-rank order (highest weighted degree + centrality first). - Shared by this report and the Streamlit app. Ties rank by facility id. + Shared by this report and the Streamlit app. """ - results = model.select( - Facility.id.alias("id"), - Facility.name.alias("name"), - Facility.type.alias("type"), - Facility.region.alias("region"), - Facility.degree_centrality.alias("degree_centrality"), - Facility.incoming_connections.alias("incoming_connections"), - Facility.outgoing_connections.alias("outgoing_connections"), - Facility.total_connections.alias("total_connections"), - ).to_df() - results = results.sort_values( - ["degree_centrality", "id"], ascending=[False, True] - ).reset_index(drop=True) - results.insert(0, "rank", range(1, len(results) + 1)) - return results + return ( + model.select( + Facility.priority_rank.alias("rank"), + Facility.id.alias("id"), + Facility.name.alias("name"), + Facility.type.alias("type"), + Facility.region.alias("region"), + Facility.degree_centrality.alias("degree_centrality"), + Facility.incoming_connections.alias("incoming_connections"), + Facility.outgoing_connections.alias("outgoing_connections"), + Facility.total_connections.alias("total_connections"), + ) + .to_df() + .sort_values("rank") + .reset_index(drop=True) + ) + + +def network_summary(): + """The facility count and the mean centrality and connections per facility, from the model.""" + n_ref, centrality_ref, connections_ref = Integer.ref(), Float.ref(), Float.ref() + return ( + model.where(NetworkSummary(n_ref, centrality_ref, connections_ref)) + .select( + n_ref.alias("n_facilities"), + centrality_ref.alias("mean_centrality"), + connections_ref.alias("mean_connections"), + ) + .to_df() + .iloc[0] + ) if __name__ == "__main__": @@ -71,10 +89,11 @@ def ranked_facilities(): print() # Summary statistics + summary = network_summary() print("\n📊 NETWORK SUMMARY:") - print(f" • Total facilities analyzed: {len(results)}") - print(f" • Average degree centrality: {results['degree_centrality'].mean():.4f}") - print(f" • Average connections per facility: {results['total_connections'].mean():.1f}") + print(f" • Total facilities analyzed: {int(summary['n_facilities'])}") + print(f" • Average degree centrality: {float(summary['mean_centrality']):.4f}") + print(f" • Average connections per facility: {float(summary['mean_connections']):.1f}") print(f" • Highest weighted centrality: {results.iloc[0]['name']} ({int(results.iloc[0]['total_connections'])} connections)") print("\n✅ Analysis complete!") diff --git a/energy_grid_planning/README.md b/energy_grid_planning/README.md index 7e31f1ff..3acc1d70 100644 --- a/energy_grid_planning/README.md +++ b/energy_grid_planning/README.md @@ -50,7 +50,7 @@ Texas is now the fastest-growing market for AI data center development. Hypersca ## What's included -- `model/` -- the deployed model: `schema.py` declares the concepts, `source.py` loads the sample data and the investment levels, and `reasoning.py` states the forecast, graph, rules, and decision problem +- `model/` -- the deployed model: `schema.py` declares the concepts, `source.py` loads the sample data and the investment levels, and one module per stage states the forecast (`load_forecast.py`), graph (`grid_topology.py`), corridors (`corridor_fragility.py`), rules (`interconnection_compliance.py`), and decision problem (`investment_solve.py`, with the per-level portfolios and knee point in `investment_frontier.py`) - `queries/energy_grid_report.py` -- Prints the five-stage report from the deployed model - `runbook.md` -- a paste-testable walkthrough that reproduces the template step by step with the RAI skills; as important a reference as the script itself - `data/substations.csv` -- 12 Texas substations with capacity, load, and coordinates @@ -217,7 +217,12 @@ energy_grid_planning/ __init__.py # Exports of the deployed model schema.py # Concepts and properties source.py # Sample data and investment levels - reasoning.py # Forecast, graph, corridors, rules, investment solve + load_forecast.py # Stage 1: predicted load, growth, capacity breach + grid_topology.py # Stage 2: components, communities, centrality, criticality + corridor_fragility.py # Stage 3: corridors, most fragile routes, contingency + interconnection_compliance.py # Stage 4: compliance rules and counts + investment_solve.py # Stage 5: the approval and upgrade solve + investment_frontier.py # Stage 5: portfolios, marginal value, knee point queries/ energy_grid_report.py # Five-stage report from the deployed model data/ @@ -274,7 +279,7 @@ One shared ontology threads all five stages. Each stage reads concepts and prope - **Primary identifiers**: string `id` on the base entities (e.g. `SUB-001`, `TL-001`); `name` on `InvestmentLevel` (e.g. `"$300M"`); `investment_level_name` on `InvestmentPortfolio`. - **Important invariants**: `predicted_load`, `max_capacity_mw`, `current_load_mw`, `requested_mw`, and `capacity_increase_mw` are non-negative MW; `low_carbon_requirement_pct` is a fraction of the substation's generation capacity (`0.60` means 60%); a generator is low-carbon when `emissions_rate == 0`; Stage 5 decision variables (`x_approve`, `x_upgrade`) are binary. -`Substation` is the hub: Stages 1-2 enrich it with forecast and topology properties that Stages 4-5 consume, and Stage 3 adds corridor fragility for the report. The Stage 3 paths analysis also derives two transient sub-concepts, `GeneratorSubstation` and `DCSubstation` (both `extends=[Substation]`), to type the corridor endpoints. For the full concept and property definitions, see `model/schema.py`; `runbook.md` builds them step by step with the RAI skills. +`Substation` is the hub: Stages 1-2 enrich it with forecast and topology properties that Stages 4-5 consume, and Stage 3 adds corridor fragility and the contingency routes. The Stage 3 paths analysis also derives two transient sub-concepts, `GeneratorSubstation` and `DCSubstation` (both `extends=[Substation]`), to type the corridor endpoints. For the full concept and property definitions, see `model/schema.py`; `runbook.md` builds them step by step with the RAI skills. ## How it works @@ -283,7 +288,7 @@ One shared ontology threads all five stages. Each stage reads properties earlier ```text demand forecasts → predicted_load ───────────────┬→ compliance rules (with generation mix) grid topology + centrality → structural flags ───┘ - └→ corridor fragility (reported) + └→ corridor fragility and contingency predicted_load + upgrade costs + revenue → one MIP across the budget levels → Pareto frontier ``` @@ -297,9 +302,9 @@ The Graph reasoner uses `Substation` directly as its node concept, with edges be ### Stage 3: Paths -- Transmission Corridors & Contingency -> PREVIEW capability; requires `relationalai>=1.15`. +> PREVIEW capability; requires `relationalai>=1.27`. -Where Stage 2 scores a *substation*, the paths capability scores the *corridor* feeding each data center. It derives a bidirectional substation-to-substation edge from active transmission lines, enumerates generator-substation to DC-substation routes, and ranks each by the Stage 2 betweenness summed along its hops — the most fragile corridor carries the greatest through-traffic exposure. A contingency pass removes the highest-betweenness substation and re-enumerates to show which data centers reroute; the most-fragile load is persisted as `Substation.fragility_load`. The report, not the model, picks each data center's winning corridor and runs the contingency, in pandas over the published corridor steps. On the bundled grid this enumerates 421 generator-to-DC corridors; the most fragile carries a betweenness-load of 99.833 through the Dallas-Fort Worth, Abilene Central, and Houston Ship Channel hubs. +Where Stage 2 scores a *substation*, the paths capability scores the *corridor* feeding each data center. It derives a bidirectional substation-to-substation edge from active transmission lines, enumerates generator-substation to DC-substation routes, and ranks each by the Stage 2 betweenness summed along its hops — the most fragile corridor carries the greatest through-traffic exposure. A contingency pass drops every corridor through the highest-betweenness substation, keeping the baseline betweenness, to show which data centers reroute; the model persists each data center substation's most fragile load (`Substation.fragility_load`), its rank, its most fragile route (`Substation.fragile_route`), and its route with the offline substation removed (`Substation.contingency_route`), with the corridor and reroute counts in `CorridorSummary`. On the bundled grid this enumerates 421 generator-to-DC corridors; the most fragile carries a betweenness-load of 99.833 through the Dallas-Fort Worth, Abilene Central, and Houston Ship Channel hubs. ### Stage 4: Rules -- Interconnection Queue Compliance @@ -315,7 +320,7 @@ An `InvestmentLevel` Scenario Concept holds 5 budget levels ($200M-$600M), each One solve produces the entire frontier. The knee point at $300M (6 DCs, 1,530 MW, $252M net value) is the budget level where the marginal net value per added $M falls the most from the step into it to the step out of it (on a tie, the smaller budget; if the marginal value never falls, the report names no knee): both DFW upgrades fit the budget, and Google Metroplex DC and Lambda Labs DFW join. At $200M, 4 DCs are approved (Microsoft, Amazon SA, Crusoe, Oracle); beyond the knee each additional $100M adds one more DC with diminishing returns ($1,013K/$M into the knee vs $439K/$M from $400M to $500M). Revenue is the objective, so where several upgrade sets earn the same revenue (as at $500M), the net value depends on which set the solver returns. xAI Colossus (500 MW) is never approved at any budget — DFW headroom goes to Google and Lambda. Per-level results (approvals, upgrades, MW) are all queried from the ontology via `model.select()` rather than parsed from solver output. -See `model/reasoning.py` for the implementation of the five stages and `runbook.md` for the skill-driven reproduction. +See the modules in `model/` for the implementation of the five stages and `runbook.md` for the skill-driven reproduction. ## Customize this template @@ -329,8 +334,8 @@ Focus on the first changes most users will make. ### Tune parameters - **Investment levels** — the budget scenarios (`$200M-$600M`) are `InvestmentLevel` rows; add rows for finer Pareto resolution or shift the budget caps to match your capex envelope. -- **Corridor hop bound** — `MAX_CORRIDOR_HOPS` in `model/reasoning.py` caps the Stage 3 path enumeration; raise it to trace longer generator-to-DC corridors. -- **Structural-criticality cutoff** — `CRITICAL_THRESHOLD` in `model/reasoning.py` sets how many substations Stage 2 flags critical, ranked by the sum of their betweenness, degree, and eigenvector centrality ranks, feeding Stage 4's structural rule. +- **Corridor hop bound** — `MAX_CORRIDOR_HOPS` in `model/corridor_fragility.py` caps the Stage 3 path enumeration; raise it to trace longer generator-to-DC corridors. +- **Structural-criticality cutoff** — `CRITICAL_THRESHOLD` in `model/grid_topology.py` sets how many substations Stage 2 flags critical, ranked by the sum of their betweenness, degree, and eigenvector centrality ranks, feeding Stage 4's structural rule. - **Objective weights** — Stage 5 maximizes annual interconnection revenue; adjust `annual_revenue_per_mw` to reweight which requests clear at each budget; the net-value amortization changes only the reported net value, marginal value per budget step and knee, not the approvals. ### Extend the model diff --git a/energy_grid_planning/model/__init__.py b/energy_grid_planning/model/__init__.py index efa1c3c8..6508928b 100644 --- a/energy_grid_planning/model/__init__.py +++ b/energy_grid_planning/model/__init__.py @@ -10,10 +10,11 @@ detection, and multi-metric centrality (betweenness, degree, eigenvector) on the transmission grid topology. Results are stored directly as Substation properties on the shared ontology. -- Stage 3 -- Paths (PREVIEW, relationalai>=1.15): enumerate generator-sub -> +- Stage 3 -- Paths (PREVIEW, relationalai>=1.27): enumerate generator-sub -> DC-sub transmission corridors, rank each by Stage 2 betweenness summed along - the route (most fragile = greatest through-traffic exposure), and re-enumerate - with the highest-betweenness substation offline. Persists Substation.fragility_load. + the route (most fragile = greatest through-traffic exposure), and drop every + corridor through the highest-betweenness substation. Persists each DC substation's + fragility load and most fragile route, with and without the offline substation. - Stage 4 -- Rules: declarative interconnection queue compliance checks (capacity, structural criticality, low-carbon mandate) that consume Stage 1 and 2 enrichments. @@ -21,6 +22,11 @@ InvestmentLevel as a Scenario Concept. One solve across 5 budget levels produces a Pareto frontier with results queryable directly from the ontology. +Modules: `load_forecast.py` (Stage 1), `grid_topology.py` (Stage 2), `corridor_fragility.py` +(Stage 3), `interconnection_compliance.py` (Stage 4), and `investment_solve.py` and +`investment_frontier.py` (Stage 5: the solve, then each level's portfolio, marginal value, and +knee point). Each module imports the modules whose declarations it reads. + Run: `rai models deploy --path model` deploys this package to the schemas in raiconfig.yaml and waits for its first refresh, which runs the graph analysis, @@ -28,13 +34,12 @@ prints the report from the deployed model. """ -from .reasoning import ( - CRITICAL_THRESHOLD, - MAX_CORRIDOR_HOPS, - CorridorStep, - SolveObjective, - SolveStatus, -) +from . import load_forecast +from .corridor_fragility import MAX_CORRIDOR_HOPS, CorridorSummary +from .grid_topology import CRITICAL_THRESHOLD, GridRegion, GridTopology +from .interconnection_compliance import ComplianceSummary +from .investment_frontier import InvestmentRange +from .investment_solve import SolveObjective, SolveStatus from .schema import ( DataCenterRequest, DemandForecast, @@ -50,14 +55,19 @@ "CRITICAL_THRESHOLD", "DATA_DIR", "MAX_CORRIDOR_HOPS", - "CorridorStep", + "ComplianceSummary", + "CorridorSummary", "DataCenterRequest", "DemandForecast", + "GridRegion", + "GridTopology", "InvestmentLevel", "InvestmentPortfolio", + "InvestmentRange", "SolveObjective", "SolveStatus", "Substation", "SubstationUpgrade", + "load_forecast", "model", ] diff --git a/energy_grid_planning/model/corridor_fragility.py b/energy_grid_planning/model/corridor_fragility.py new file mode 100644 index 00000000..b2b30273 --- /dev/null +++ b/energy_grid_planning/model/corridor_fragility.py @@ -0,0 +1,186 @@ +"""Corridor fragility: the simple generator-to-data-center corridors, each data center substation's most +fragile corridor, and the corridors that remain with the highest-betweenness substation offline.""" + +from relationalai.semantics import Float, Hash, Integer, String, not_, where +from relationalai.semantics.std import aggregates as aggs +from relationalai.semantics.std import math + +# Declares Substation.betweenness, the criticality each corridor sums. +from . import grid_topology # noqa: F401 +from .schema import ( + DataCenterRequest, + DCSubstation, + Generator, + GeneratorSubstation, + Substation, + TransmissionLine, + model, +) + +# -------------------------------------------------- +# Configure inputs +# -------------------------------------------------- + +MAX_CORRIDOR_HOPS = 6 +LOAD_DECIMALS = 6 # corridor loads that agree to this many decimals count as equal (absorbs summation noise) + +# -------------------------------------------------- +# Stage 3: Paths -- Transmission Corridors & Contingency +# PREVIEW capability; requires relationalai>=1.27 (ordered string_join). +# -------------------------------------------------- +# Composes on Stage 2's Substation.betweenness. Where Stage 2 scores a *node*, +# paths scores the *corridor* feeding each data center: enumerate generator-sub -> +# DC-sub transmission routes, rank each by total betweenness summed along its hops +# (most fragile = greatest through-traffic exposure), then drop every corridor through +# the highest-betweenness substation to see which DC substations reroute. + +# Bidirectional Substation<->Substation grid edge from active transmission lines. +Substation.connects_to = model.Relationship( + f"{Substation} connects to {Substation}", short_name="connects_to" +) +tl_fwd = TransmissionLine.ref() +s_from, s_to = Substation.ref(), Substation.ref() +model.where( + tl_fwd.from_substation(s_from), + tl_fwd.to_substation(s_to), + tl_fwd.is_active == True, +).define(s_from.connects_to(s_to)) +tl_rev = TransmissionLine.ref() +s_a, s_b = Substation.ref(), Substation.ref() +model.where( + tl_rev.from_substation(s_a), + tl_rev.to_substation(s_b), + tl_rev.is_active == True, +).define(s_b.connects_to(s_a)) + +# Typed endpoints: substations hosting a generator (source) and a DC request (sink). +gen_ref, gen_sub = Generator.ref(), Substation.ref() +model.where(gen_ref.substation(gen_sub)).define(GeneratorSubstation(gen_sub)) +dc_ref, dc_sub = DataCenterRequest.ref(), Substation.ref() +model.where(dc_ref.substation(dc_sub)).define(DCSubstation(dc_sub)) + +# Enumerate generator-sub -> DC-sub corridors (finite repeat; the grid is meshed/cyclic). +corridor_src, corridor_dst = GeneratorSubstation.ref(), DCSubstation.ref() +corridor = ( + model.path( + corridor_src, Substation.connects_to.repeat(1, MAX_CORRIDOR_HOPS), corridor_dst + ) + .all() + .paths() +) + +# Simple corridors: no substation appears twice. The grid is cyclic, so .all().paths() also yields walks +# that revisit a node; the negated existential drops them in the same where() as the sums below, so on +# every corridor that remains the position sum equals the distinct-substation sum. +def _simple_corridor(): + i, j = Integer.ref(), Integer.ref() + return not_(where(i < j, corridor.nodes(i) == corridor.nodes(j))) + + +SimpleCorridor = model.Relationship(f"{Hash:corridor} is a simple corridor") +model.where(corridor, _simple_corridor()).define(SimpleCorridor(corridor)) + +# Each DC substation's fragility load is the highest corridor score among the simple corridors ending +# at it, where a corridor's score sums Stage 2's betweenness over its nodes. +Substation.fragility_load = model.Property(f"{Substation} has {Float:fragility_load}") +model.where( + corridor, + _simple_corridor(), + total := aggs.sum(Substation(corridor.nodes).betweenness).per(corridor), + frag := aggs.max(total).per(corridor_dst), +).define(corridor_dst.fragility_load(frag)) + +# The DC substations ranked by fragility load, highest first, ties to the smaller id. Loads compare to +# LOAD_DECIMALS, so float noise from the order a sum adds its terms cannot reorder equal loads. The load +# is negated so both keys sort ascending. +Substation.fragility_rank = model.Property(f"{Substation} has fragility rank {Integer:fragility_rank}") +model.define( + Substation.fragility_rank(aggs.rank(-math.round(Substation.fragility_load, LOAD_DECIMALS), Substation.id)) +) + +# Each DC substation's most fragile route: the simple corridor with the highest load (to LOAD_DECIMALS), +# ties to the smaller joined substation ids (ids have a fixed width, so text order is id-list order). The +# route lists the substation names from generator to DC substation. +Substation.fragile_route = model.Property(f"{Substation} has most fragile route {String:fragile_route}") +model.where( + corridor, + _simple_corridor(), + total := aggs.sum(Substation(corridor.nodes).betweenness).per(corridor), + ids := aggs.string_join( + Substation(corridor.nodes).id, sep=",", index=corridor.nodes["index"] + ).per(corridor), + aggs.rank(-math.round(total, LOAD_DECIMALS), ids).per(corridor_dst) == 1, + route := aggs.string_join( + Substation(corridor.nodes).name, sep=" -> ", index=corridor.nodes["index"] + ).per(corridor), +).define(corridor_dst.fragile_route(route)) + +# Contingency: the substation with the highest betweenness (ties to the smaller id) goes offline, and every +# corridor through it is dropped. The remaining corridors keep their baseline betweenness. +Substation.is_offline = model.Relationship(f"{Substation} is offline in the contingency") +model.where(aggs.rank(-Substation.betweenness, Substation.id) == 1).define(Substation.is_offline()) + + +# Corridors that avoid the offline substation. The node is read at its own index, as in _simple_corridor, so +# the test applies to the whole corridor; a bare corridor.nodes would bind the node the sums below iterate +# over and only drop the offline substation from them. +def _avoids_offline(): + k, offline = Integer.ref(), Substation.ref() + return not_(where(offline.is_offline(), corridor.nodes(k) == offline)) + + +# Each DC substation's most fragile route with the offline substation removed; a DC substation with no +# corridor left has none. +Substation.contingency_route = model.Property( + f"{Substation} has contingency route {String:contingency_route}" +) +model.where( + corridor, + _simple_corridor(), + _avoids_offline(), + total := aggs.sum(Substation(corridor.nodes).betweenness).per(corridor), + ids := aggs.string_join( + Substation(corridor.nodes).id, sep=",", index=corridor.nodes["index"] + ).per(corridor), + aggs.rank(-math.round(total, LOAD_DECIMALS), ids).per(corridor_dst) == 1, + route := aggs.string_join( + Substation(corridor.nodes).name, sep=" -> ", index=corridor.nodes["index"] + ).per(corridor), +).define(corridor_dst.contingency_route(route)) + +# The corridor counts: simple corridors, DC substations with a corridor before and after the contingency, +# those whose most fragile route changes, and those left with none. +CorridorSummary = model.Concept("CorridorSummary", identify_by={"id": Integer}) +CorridorSummary.n_corridors = model.Property(f"{CorridorSummary} has {Integer:n_corridors} simple corridors") +CorridorSummary.n_served = model.Property(f"{CorridorSummary} serves {Integer:n_served} DC substations") +CorridorSummary.n_served_contingency = model.Property( + f"{CorridorSummary} serves {Integer:n_served_contingency} DC substations in the contingency" +) +CorridorSummary.n_rerouted = model.Property(f"{CorridorSummary} reroutes {Integer:n_rerouted} DC substations") +CorridorSummary.n_lost = model.Property(f"{CorridorSummary} loses {Integer:n_lost} DC substations") +model.define(CorridorSummary.new(id=1)) +_corridor, _dc = Hash.ref(), Substation.ref() +_route, _contingency_route = String.ref(), String.ref() +model.define( + CorridorSummary.n_corridors( + aggs.count(_corridor).per(CorridorSummary).where(SimpleCorridor(_corridor)) | 0 + ), + CorridorSummary.n_served( + aggs.count(_dc).per(CorridorSummary).where(_dc.fragile_route(_route)) | 0 + ), + CorridorSummary.n_served_contingency( + aggs.count(_dc).per(CorridorSummary).where(_dc.contingency_route(_contingency_route)) | 0 + ), + CorridorSummary.n_rerouted( + aggs.count(_dc).per(CorridorSummary).where( + _dc.fragile_route(_route), _dc.contingency_route(_contingency_route), _route != _contingency_route + ) + | 0 + ), + CorridorSummary.n_lost( + aggs.count(_dc).per(CorridorSummary).where( + _dc.fragile_route(_route), not_(_dc.contingency_route(_contingency_route)) + ) + | 0 + ), +) diff --git a/energy_grid_planning/model/grid_topology.py b/energy_grid_planning/model/grid_topology.py new file mode 100644 index 00000000..fb32edd4 --- /dev/null +++ b/energy_grid_planning/model/grid_topology.py @@ -0,0 +1,127 @@ +"""Grid topology: connected components, Louvain communities, and centrality of the transmission grid, the +structurally critical substations, and the grid's connectivity and regions.""" + +from relationalai.semantics import Float, Integer, String, distinct +from relationalai.semantics.reasoners.graph import Graph +from relationalai.semantics.std import aggregates as aggs + +from .schema import Substation, TransmissionLine, model + +# -------------------------------------------------- +# Configure inputs +# -------------------------------------------------- + +CRITICAL_THRESHOLD = 3 # top-N substations by combined centrality rank are "structurally critical" + +# -------------------------------------------------- +# Stage 2: Graph -- Grid Topology & Structural Vulnerability +# -------------------------------------------------- + +grid_graph = Graph( + model, + name="grid_graph", + directed=False, + weighted=False, + node_concept=Substation, + aggregator="sum", +) + +# Edges: active transmission lines between substations. +line_ref = TransmissionLine.ref() +model.define(grid_graph.Edge.new(src=line_ref.from_substation, dst=line_ref.to_substation)).where( + line_ref.is_active == True +) + +# a) Weakly Connected Components +wcc = grid_graph.weakly_connected_component() +Substation.component = model.Property(f"{Substation} in component {String:component}") +wcc_node, wcc_comp = Substation.ref(), Substation.ref() +model.define(wcc_node.component(wcc_comp.id)).where(wcc(wcc_node, wcc_comp)) + +# b) Community Detection (Louvain) +community = grid_graph.louvain() +comm_label = Integer.ref("comm") + +# c) Centrality Analysis (betweenness, degree, eigenvector) +betweenness = grid_graph.betweenness_centrality() +btwn_score = Float.ref("btwn") + +degree = grid_graph.degree_centrality() +deg_score = Float.ref("deg") + +eigenvector = grid_graph.eigenvector_centrality() +eig_score = Float.ref("eig") + +# Store graph results directly on Substation. +Substation.grid_community = model.Property( + f"{Substation} in grid community {Integer:grid_community}" +) +Substation.betweenness = model.Property(f"{Substation} has {Float:betweenness}") +Substation.degree_centrality = model.Property(f"{Substation} has {Float:degree_centrality}") +Substation.eigenvector_centrality = model.Property( + f"{Substation} has {Float:eigenvector_centrality}" +) + +sub_ref = Substation.ref() +model.define(sub_ref.grid_community(comm_label)).where(community(sub_ref, comm_label)) +model.define(sub_ref.betweenness(btwn_score)).where(betweenness(sub_ref, btwn_score)) +model.define(sub_ref.degree_centrality(deg_score)).where(degree(sub_ref, deg_score)) +model.define(sub_ref.eigenvector_centrality(eig_score)).where(eigenvector(sub_ref, eig_score)) + +# Composite critical rank from all three centrality metrics. +Substation.betweenness_rank = model.Property(f"{Substation} has {Integer:betweenness_rank}") +Substation.degree_rank = model.Property(f"{Substation} has {Integer:degree_rank}") +Substation.eigenvector_rank = model.Property(f"{Substation} has {Integer:eigenvector_rank}") +Substation.combined_rank = model.Property(f"{Substation} has {Integer:combined_rank}") +Substation.critical_rank = model.Property(f"{Substation} has {Integer:critical_rank}") + +model.define( + Substation.betweenness_rank(aggs.rank(aggs.desc(Substation.betweenness, Substation.id))) +) +model.define( + Substation.degree_rank(aggs.rank(aggs.desc(Substation.degree_centrality, Substation.id))) +) +model.define( + Substation.eigenvector_rank( + aggs.rank(aggs.desc(Substation.eigenvector_centrality, Substation.id)) + ) +) +model.define( + Substation.combined_rank( + Substation.betweenness_rank + Substation.degree_rank + Substation.eigenvector_rank + ) +) +model.define(Substation.critical_rank(aggs.rank(Substation.combined_rank, Substation.id))) + +Substation.is_structurally_critical = model.Relationship(f"{Substation} is structurally critical") +model.where(Substation.critical_rank <= CRITICAL_THRESHOLD).define( + Substation.is_structurally_critical() +) + +# The grid's size, number of connected components, number of Louvain communities, and whether it is +# CONNECTED (one component) or FRAGMENTED. +GridTopology = model.Concept("GridTopology", identify_by={"id": Integer}) +GridTopology.n_substations = model.Property(f"{GridTopology} has {Integer:n_substations} substations") +GridTopology.n_components = model.Property(f"{GridTopology} has {Integer:n_components} components") +GridTopology.n_communities = model.Property(f"{GridTopology} has {Integer:n_communities} communities") +GridTopology.connectivity = model.Property(f"{GridTopology} is {String:connectivity}") +model.define(GridTopology.new(id=1)) +model.define( + GridTopology.n_substations(aggs.count(Substation).per(GridTopology)), + GridTopology.n_components(aggs.count(distinct(Substation.component)).per(GridTopology)), + GridTopology.n_communities(aggs.count(distinct(Substation.grid_community)).per(GridTopology)), +) +model.where(GridTopology.n_components == 1).define(GridTopology.connectivity("CONNECTED")) +model.where(GridTopology.n_components != 1).define(GridTopology.connectivity("FRAGMENTED")) + +# Each Louvain community with its member substations' names, in id order. +GridRegion = model.Concept("GridRegion", identify_by={"community": Integer}) +GridRegion.members = model.Property(f"{GridRegion} has members {String:members}") +model.define(GridRegion.new(community=Substation.grid_community)) +model.define( + GridRegion.members( + aggs.string_join(Substation.name, sep=", ", index=Substation.id) + .per(GridRegion) + .where(Substation.grid_community == GridRegion.community) + ) +) diff --git a/energy_grid_planning/model/interconnection_compliance.py b/energy_grid_planning/model/interconnection_compliance.py new file mode 100644 index 00000000..e1f05a8d --- /dev/null +++ b/energy_grid_planning/model/interconnection_compliance.py @@ -0,0 +1,93 @@ +"""Interconnection compliance: each data center request's capacity, structural-risk, and low-carbon checks, +whether it is compliant, and the compliance counts.""" + +from relationalai.semantics import Float, Integer, not_ +from relationalai.semantics.std import aggregates as aggs + +# Declare Substation.predicted_load and is_structurally_critical, the stage outputs the checks read. +from . import grid_topology, load_forecast # noqa: F401 +from .schema import DataCenterRequest, Generator, Substation, model + +# -------------------------------------------------- +# Stage 4: Rules -- Interconnection Queue Compliance +# -------------------------------------------------- +# Accretive chain: each rule consumes ontology enrichments from earlier stages. +# Rule 1 reads Substation.predicted_load (Stage 1). +# Rule 2 reads Substation.is_structurally_critical (Stage 2). +# Rule 3 reads Generator.emissions_rate (base data) to derive low-carbon capacity. +# All flags are written back as Relationships — queryable and consumable downstream. + +# Rule 1: Capacity check -- consumes predicted_load from Stage 1 +DataCenterRequest.fails_capacity = model.Relationship(f"{DataCenterRequest} fails capacity check") +SubRef_rule = Substation.ref() +effective_load_rule = SubRef_rule.predicted_load | SubRef_rule.current_load_mw +model.where( + DataCenterRequest.substation(SubRef_rule), + DataCenterRequest.requested_mw + effective_load_rule > SubRef_rule.max_capacity_mw, +).define(DataCenterRequest.fails_capacity()) + +# Rule 2: Structural risk -- uses centrality-based criticality from Stage 2 +DataCenterRequest.fails_structural = model.Relationship(f"{DataCenterRequest} fails structural risk check") +SubRef_sr = Substation.ref() +model.where( + DataCenterRequest.substation(SubRef_sr), + SubRef_sr.is_structurally_critical(), +).define(DataCenterRequest.fails_structural()) + +# Rule 3: Low-carbon mandate -- check if DC's low-carbon requirement can be met +# Low-carbon = zero-emission generation (renewable + nuclear), keyed on emissions_rate == 0. +# The requirement is a fraction of the substation's generation (0.60 means 60%). +Substation.low_carbon_gen_mw = model.Property(f"{Substation} has {Float:low_carbon_gen_mw}") +Substation.total_gen_mw = model.Property(f"{Substation} has {Float:total_gen_mw}") +model.define( + Substation.low_carbon_gen_mw( + aggs.sum(Generator.capacity_mw) + .where(Generator.substation(Substation), Generator.emissions_rate == 0.0) + .per(Substation) + ) +) +model.define( + Substation.total_gen_mw( + aggs.sum(Generator.capacity_mw) + .where(Generator.substation(Substation)) + .per(Substation) + ) +) + +DataCenterRequest.fails_low_carbon = model.Relationship(f"{DataCenterRequest} fails low-carbon mandate") +SubRef_lc = Substation.ref() +model.where( + DataCenterRequest.substation(SubRef_lc), + (SubRef_lc.low_carbon_gen_mw | 0.0) + < DataCenterRequest.low_carbon_requirement_pct * SubRef_lc.total_gen_mw, +).define(DataCenterRequest.fails_low_carbon()) +# A substation without generating capacity cannot meet any positive requirement. +model.where( + DataCenterRequest.substation(SubRef_lc), + DataCenterRequest.low_carbon_requirement_pct > 0, + not_(SubRef_lc.total_gen_mw > 0), +).define(DataCenterRequest.fails_low_carbon()) + +# Composite: compliant if none of the checks fail +DataCenterRequest.is_compliant = model.Relationship(f"{DataCenterRequest} is compliant") +model.where( + model.not_(DataCenterRequest.fails_capacity()), + model.not_(DataCenterRequest.fails_structural()), + model.not_(DataCenterRequest.fails_low_carbon()), +).define(DataCenterRequest.is_compliant()) + +# How many requests there are, how many are compliant, and how many are flagged (not compliant). +ComplianceSummary = model.Concept("ComplianceSummary", identify_by={"id": Integer}) +ComplianceSummary.n_requests = model.Property(f"{ComplianceSummary} has {Integer:n_requests} requests") +ComplianceSummary.n_compliant = model.Property(f"{ComplianceSummary} has {Integer:n_compliant} compliant requests") +ComplianceSummary.n_flagged = model.Property(f"{ComplianceSummary} has {Integer:n_flagged} flagged requests") +model.define(ComplianceSummary.new(id=1)) +model.define( + ComplianceSummary.n_requests(aggs.count(DataCenterRequest).per(ComplianceSummary)), + ComplianceSummary.n_compliant( + aggs.count(DataCenterRequest).per(ComplianceSummary).where(DataCenterRequest.is_compliant()) | 0 + ), + ComplianceSummary.n_flagged( + aggs.count(DataCenterRequest).per(ComplianceSummary).where(not_(DataCenterRequest.is_compliant())) | 0 + ), +) diff --git a/energy_grid_planning/model/investment_frontier.py b/energy_grid_planning/model/investment_frontier.py new file mode 100644 index 00000000..36abbbd9 --- /dev/null +++ b/energy_grid_planning/model/investment_frontier.py @@ -0,0 +1,171 @@ +"""Investment frontier: each investment level's portfolio of approved requests and upgrades, the budget +range, the marginal value per added budget, and the knee point.""" + +from relationalai.semantics import Float, Integer, sum +from relationalai.semantics.std import aggregates as aggs + +# Declare the approval and upgrade variables each portfolio reads. +from . import investment_solve # noqa: F401 +from .schema import ( + DataCenterRequest, + InvestmentLevel, + InvestmentPortfolio, + SubstationUpgrade, + model, +) + +# -------------------------------------------------- +# Configure inputs +# -------------------------------------------------- + +AMORTIZATION_YEARS = 20 # upgrade cost spread over 20 years + +# -------------------------------------------------- +# Portfolio per InvestmentLevel, from the solved values +# -------------------------------------------------- +# One InvestmentPortfolio row per scenario: approved requests, their MW and +# revenue, the selected upgrades' cost (in dollars, to match revenue), and the +# net value (revenue less the upgrade cost amortized over AMORTIZATION_YEARS). +x_ap, x_up = Float.ref(), Float.ref() +model.define( + portfolio := InvestmentPortfolio.new(investment_level_name=InvestmentLevel.name), + portfolio.investment_level(InvestmentLevel), +) +model.define( + InvestmentPortfolio.dc_count( + ( + aggs.count(DataCenterRequest) + .where( + InvestmentPortfolio.investment_level(InvestmentLevel), + DataCenterRequest.x_approve(InvestmentLevel, x_ap), + x_ap > 0.5, + ) + .per(InvestmentPortfolio) + ) + | 0 + ) +) +model.define( + InvestmentPortfolio.total_mw( + ( + sum(DataCenterRequest, DataCenterRequest.requested_mw) + .where( + InvestmentPortfolio.investment_level(InvestmentLevel), + DataCenterRequest.x_approve(InvestmentLevel, x_ap), + x_ap > 0.5, + ) + .per(InvestmentPortfolio) + ) + | 0.0 + ) +) +model.define( + InvestmentPortfolio.annual_revenue( + ( + sum(DataCenterRequest, DataCenterRequest.annual_revenue) + .where( + InvestmentPortfolio.investment_level(InvestmentLevel), + DataCenterRequest.x_approve(InvestmentLevel, x_ap), + x_ap > 0.5, + ) + .per(InvestmentPortfolio) + ) + | 0.0 + ) +) +model.define( + InvestmentPortfolio.upgrade_cost( + ( + sum(SubstationUpgrade, SubstationUpgrade.cost_million * 1e6) + .where( + InvestmentPortfolio.investment_level(InvestmentLevel), + SubstationUpgrade.x_upgrade(InvestmentLevel, x_up), + x_up > 0.5, + ) + .per(InvestmentPortfolio) + ) + | 0.0 + ) +) +model.define( + InvestmentPortfolio.upgrade_count( + ( + aggs.count(SubstationUpgrade) + .where( + InvestmentPortfolio.investment_level(InvestmentLevel), + SubstationUpgrade.x_upgrade(InvestmentLevel, x_up), + x_up > 0.5, + ) + .per(InvestmentPortfolio) + ) + | 0 + ) +) +model.define( + InvestmentPortfolio.upgrade_mw( + ( + sum(SubstationUpgrade, SubstationUpgrade.capacity_increase_mw) + .where( + InvestmentPortfolio.investment_level(InvestmentLevel), + SubstationUpgrade.x_upgrade(InvestmentLevel, x_up), + x_up > 0.5, + ) + .per(InvestmentPortfolio) + ) + | 0.0 + ) +) +model.define( + InvestmentPortfolio.net_value( + InvestmentPortfolio.annual_revenue - InvestmentPortfolio.upgrade_cost / AMORTIZATION_YEARS + ) +) + +# The number of investment levels and their smallest and largest budgets. +InvestmentRange = model.Concept("InvestmentRange", identify_by={"id": Integer}) +InvestmentRange.n_levels = model.Property(f"{InvestmentRange} has {Integer:n_levels} levels") +InvestmentRange.min_budget = model.Property(f"{InvestmentRange} has smallest budget {Float:min_budget}") +InvestmentRange.max_budget = model.Property(f"{InvestmentRange} has largest budget {Float:max_budget}") +model.define(InvestmentRange.new(id=1)) +model.define( + InvestmentRange.n_levels(aggs.count(InvestmentLevel).per(InvestmentRange)), + InvestmentRange.min_budget(aggs.min(InvestmentLevel.budget_cap).per(InvestmentRange)), + InvestmentRange.max_budget(aggs.max(InvestmentLevel.budget_cap).per(InvestmentRange)), +) + +# Marginal value of each budget step: net value gained per added $M from a level +# to the next larger budget. The largest level has no next step. +higher, step_from, step_to = InvestmentLevel.ref(), InvestmentLevel.ref(), InvestmentLevel.ref() +model.define(InvestmentLevel.next_level(step_to)).where( + step_to.budget_cap + == aggs.min(higher.budget_cap).where(higher.budget_cap > InvestmentLevel.budget_cap).per(InvestmentLevel) +) +next_portfolio = InvestmentPortfolio.ref() +model.define( + InvestmentPortfolio.marginal_per_m_to_next_level( + (next_portfolio.net_value - InvestmentPortfolio.net_value) / (step_to.budget_cap - step_from.budget_cap) + ) +).where( + InvestmentPortfolio.investment_level(step_from), + step_from.next_level(step_to), + next_portfolio.investment_level(step_to), +) + +# The knee is the level where the marginal value falls the most, from the step +# into it to the step out of it; on a tie, the smaller budget. A frontier whose +# marginal value never falls has no knee. The drop is negated so both rank keys sort ascending. +prev_portfolio = InvestmentPortfolio.ref() +model.define( + InvestmentPortfolio.marginal_drop( + prev_portfolio.marginal_per_m_to_next_level - InvestmentPortfolio.marginal_per_m_to_next_level + ) +).where( + prev_portfolio.investment_level(step_from), + step_from.next_level(step_to), + InvestmentPortfolio.investment_level(step_to), +) +model.define(InvestmentPortfolio.is_knee_point()).where( + InvestmentPortfolio.investment_level(step_to), + InvestmentPortfolio.marginal_drop > 0, + aggs.rank(-InvestmentPortfolio.marginal_drop, step_to.budget_cap) == 1, +) diff --git a/energy_grid_planning/model/investment_solve.py b/energy_grid_planning/model/investment_solve.py new file mode 100644 index 00000000..21a4836b --- /dev/null +++ b/energy_grid_planning/model/investment_solve.py @@ -0,0 +1,110 @@ +"""Investment solve: the joint data center approval and substation upgrade problem, solved once for all +investment levels, and its status and objective.""" + +from relationalai.semantics import Float, String, sum +from relationalai.semantics.reasoners.prescriptive import Problem + +# Declares Substation.predicted_load, the load the capacity constraint reads. +from . import load_forecast # noqa: F401 +from .schema import ( + DataCenterRequest, + InvestmentLevel, + Substation, + SubstationUpgrade, + model, +) + +# -------------------------------------------------- +# Stage 5: Optimize -- Joint DC Approval + Grid Upgrade +# Accretive chain: the capacity constraint uses predicted_load from Stage 1 +# (via the | fallback pattern), matching the rules engine. All solve results +# (x_approve, x_upgrade per InvestmentLevel) are written to the ontology — +# queryable via model.select(), not parsed from solver output. +# One solve across 5 InvestmentLevel scenarios produces the Pareto frontier. +# -------------------------------------------------- + +# Annual revenue of a request if approved: its megawatts times its revenue per megawatt. The objective +# and each portfolio's revenue read it. +DataCenterRequest.annual_revenue = model.Property(f"{DataCenterRequest} earns {Float:annual_revenue} a year") +model.define( + DataCenterRequest.annual_revenue(DataCenterRequest.requested_mw * DataCenterRequest.annual_revenue_per_mw) +) + +# Decision variables indexed by InvestmentLevel +DataCenterRequest.x_approve = model.Property( + f"{DataCenterRequest} in {InvestmentLevel} has {Float:x_approve}" +) +SubstationUpgrade.x_upgrade = model.Property( + f"{SubstationUpgrade} in {InvestmentLevel} has {Float:x_upgrade}" +) + +# Float refs for variable binding in constraints/objective +x_a = Float.ref("xa") +x_u = Float.ref("xu") + +# Refs for aggregation joins +DCRef = DataCenterRequest.ref() +UpgRef = SubstationUpgrade.ref() + +# Problem formulation +problem = Problem(model, Float, name="energy_grid_planning") + +problem.solve_for(DataCenterRequest.x_approve(InvestmentLevel, x_a), type="bin", + name=["approve", InvestmentLevel.name, DataCenterRequest.id]) +problem.solve_for(SubstationUpgrade.x_upgrade(InvestmentLevel, x_u), type="bin", + name=["upgrade", InvestmentLevel.name, SubstationUpgrade.id]) + +# C1: Substation capacity per investment level +# Uses predicted_load from Stage 1 (with current_load fallback) — the accretive chain. +x_a_c = Float.ref("xa_c") +x_u_c = Float.ref("xu_c") +effective_load = Substation.predicted_load | Substation.current_load_mw + +# Each upgrade's capacity and each request's MW is weighted by its own variable. +# A substation with no upgrade options adds no capacity (`| 0.0`). +problem.satisfy( + model.where( + InvestmentLevel, + DataCenterRequest.substation(Substation), + ).require( + Substation.max_capacity_mw + - effective_load + + ( + sum(UpgRef, x_u_c * UpgRef.capacity_increase_mw) + .where( + UpgRef.substation == Substation, + UpgRef.x_upgrade(InvestmentLevel, x_u_c), + ) + .per(Substation, InvestmentLevel) + | 0.0 + ) + >= sum(DCRef, x_a_c * DCRef.requested_mw) + .where( + DCRef.substation == Substation, + DCRef.x_approve(InvestmentLevel, x_a_c), + ) + .per(Substation, InvestmentLevel) + ) +) + +# C2: Budget per investment level +problem.satisfy(model.where( + SubstationUpgrade.x_upgrade(InvestmentLevel, x_u), +).require( + sum(x_u * SubstationUpgrade.cost_million).per(InvestmentLevel) <= InvestmentLevel.budget_cap +)) + +# Objective: maximize total DC revenue across all levels +problem.maximize( + sum(InvestmentLevel, x_a * DataCenterRequest.annual_revenue).where( + DataCenterRequest.x_approve(InvestmentLevel, x_a) + ) +) + +# Each refresh of the deployed model runs this solve (one solve for all levels). +problem.configure("highs", time_limit_sec=120) + +# The solve's status and objective, which the deployed model publishes for the queries. +SolveStatus = model.Relationship(f"energy grid solve status is {String:status}") +SolveObjective = model.Relationship(f"energy grid solve objective is {Float:objective}") +model.define(SolveStatus(problem.termination_status()), SolveObjective(problem.objective_value())) diff --git a/energy_grid_planning/model/load_forecast.py b/energy_grid_planning/model/load_forecast.py new file mode 100644 index 00000000..a6aa4315 --- /dev/null +++ b/energy_grid_planning/model/load_forecast.py @@ -0,0 +1,46 @@ +"""Load forecast: each substation's predicted peak load, its growth over the current load, and the first +forecast month in which the predicted load exceeds its capacity.""" + +from relationalai.semantics import Float, Integer +from relationalai.semantics.std import aggregates as aggs +from relationalai.semantics.std.math import maximum + +from .schema import DemandForecast, Substation, model + +# -------------------------------------------------- +# Stage 1: Forecast -- Substation Load +# -------------------------------------------------- +# Enrich each Substation with a predicted_load property consumed by downstream +# stages: the maximum DemandForecast per substation. +Substation.predicted_load = model.Property(f"{Substation} has {Float:predicted_load}") +model.define( + Substation.predicted_load( + aggs.max(DemandForecast.predicted_load_mw) + .where(DemandForecast.substation(Substation)) + .per(Substation) + ) +) + +# Growth of the predicted peak over the current load (floored at 0.1 MW, so an idle +# substation still gets a growth figure), and the first forecast month whose +# predicted load exceeds the substation's capacity. +Substation.growth_rate = model.Property(f"{Substation} has load growth {Float:growth_rate}") +model.define( + Substation.growth_rate( + (Substation.predicted_load - Substation.current_load_mw) + / maximum(Substation.current_load_mw, 0.1) + ) +) +Substation.breach_period = model.Property( + f"{Substation} first exceeds capacity at {Integer:breach_period} months" +) +model.define( + Substation.breach_period( + aggs.min(DemandForecast.forecast_period) + .where( + DemandForecast.substation(Substation), + DemandForecast.predicted_load_mw > Substation.max_capacity_mw, + ) + .per(Substation) + ) +) diff --git a/energy_grid_planning/model/reasoning.py b/energy_grid_planning/model/reasoning.py deleted file mode 100644 index f8b8d866..00000000 --- a/energy_grid_planning/model/reasoning.py +++ /dev/null @@ -1,509 +0,0 @@ -"""Reasoning for the energy grid template: forecast, topology, corridors, compliance, and investment.""" - -from relationalai.semantics import Float, Hash, Integer, String, not_, sum, where -from relationalai.semantics.reasoners.graph import Graph -from relationalai.semantics.reasoners.prescriptive import Problem -from relationalai.semantics.std import aggregates as aggs -from relationalai.semantics.std.math import maximum - -from .schema import ( - DataCenterRequest, - DCSubstation, - DemandForecast, - Generator, - GeneratorSubstation, - InvestmentLevel, - InvestmentPortfolio, - Substation, - SubstationUpgrade, - TransmissionLine, - model, -) - -AMORTIZATION_YEARS = 20 # upgrade cost spread over 20 years -CRITICAL_THRESHOLD = 3 # top-N substations by combined centrality rank are "structurally critical" -MAX_CORRIDOR_HOPS = 6 - -# -------------------------------------------------- -# Stage 1: Forecast -- Substation Load -# -------------------------------------------------- -# Enrich each Substation with a predicted_load property consumed by downstream -# stages: the maximum DemandForecast per substation. -Substation.predicted_load = model.Property(f"{Substation} has {Float:predicted_load}") -model.define( - Substation.predicted_load( - aggs.max(DemandForecast.predicted_load_mw) - .where(DemandForecast.substation(Substation)) - .per(Substation) - ) -) - -# Growth of the predicted peak over the current load (floored at 0.1 MW, so an idle -# substation still gets a growth figure), and the first forecast month whose -# predicted load exceeds the substation's capacity. -Substation.growth_rate = model.Property(f"{Substation} has load growth {Float:growth_rate}") -model.define( - Substation.growth_rate( - (Substation.predicted_load - Substation.current_load_mw) - / maximum(Substation.current_load_mw, 0.1) - ) -) -Substation.breach_period = model.Property( - f"{Substation} first exceeds capacity at {Integer:breach_period} months" -) -model.define( - Substation.breach_period( - aggs.min(DemandForecast.forecast_period) - .where( - DemandForecast.substation(Substation), - DemandForecast.predicted_load_mw > Substation.max_capacity_mw, - ) - .per(Substation) - ) -) - -# -------------------------------------------------- -# Stage 2: Graph -- Grid Topology & Structural Vulnerability -# -------------------------------------------------- - -grid_graph = Graph( - model, - name="grid_graph", - directed=False, - weighted=False, - node_concept=Substation, - aggregator="sum", -) - -# Edges: active transmission lines between substations. -line_ref = TransmissionLine.ref() -model.define(grid_graph.Edge.new(src=line_ref.from_substation, dst=line_ref.to_substation)).where( - line_ref.is_active == True -) - -# a) Weakly Connected Components -wcc = grid_graph.weakly_connected_component() -Substation.component = model.Property(f"{Substation} in component {String:component}") -wcc_node, wcc_comp = Substation.ref(), Substation.ref() -model.define(wcc_node.component(wcc_comp.id)).where(wcc(wcc_node, wcc_comp)) - -# b) Community Detection (Louvain) -community = grid_graph.louvain() -comm_label = Integer.ref("comm") - -# c) Centrality Analysis (betweenness, degree, eigenvector) -betweenness = grid_graph.betweenness_centrality() -btwn_score = Float.ref("btwn") - -degree = grid_graph.degree_centrality() -deg_score = Float.ref("deg") - -eigenvector = grid_graph.eigenvector_centrality() -eig_score = Float.ref("eig") - -# Store graph results directly on Substation. -Substation.grid_community = model.Property( - f"{Substation} in grid community {Integer:grid_community}" -) -Substation.betweenness = model.Property(f"{Substation} has {Float:betweenness}") -Substation.degree_centrality = model.Property(f"{Substation} has {Float:degree_centrality}") -Substation.eigenvector_centrality = model.Property( - f"{Substation} has {Float:eigenvector_centrality}" -) - -sub_ref = Substation.ref() -model.define(sub_ref.grid_community(comm_label)).where(community(sub_ref, comm_label)) -model.define(sub_ref.betweenness(btwn_score)).where(betweenness(sub_ref, btwn_score)) -model.define(sub_ref.degree_centrality(deg_score)).where(degree(sub_ref, deg_score)) -model.define(sub_ref.eigenvector_centrality(eig_score)).where(eigenvector(sub_ref, eig_score)) - -# Composite critical rank from all three centrality metrics. -Substation.betweenness_rank = model.Property(f"{Substation} has {Integer:betweenness_rank}") -Substation.degree_rank = model.Property(f"{Substation} has {Integer:degree_rank}") -Substation.eigenvector_rank = model.Property(f"{Substation} has {Integer:eigenvector_rank}") -Substation.combined_rank = model.Property(f"{Substation} has {Integer:combined_rank}") -Substation.critical_rank = model.Property(f"{Substation} has {Integer:critical_rank}") - -model.define( - Substation.betweenness_rank(aggs.rank(aggs.desc(Substation.betweenness, Substation.id))) -) -model.define( - Substation.degree_rank(aggs.rank(aggs.desc(Substation.degree_centrality, Substation.id))) -) -model.define( - Substation.eigenvector_rank( - aggs.rank(aggs.desc(Substation.eigenvector_centrality, Substation.id)) - ) -) -model.define( - Substation.combined_rank( - Substation.betweenness_rank + Substation.degree_rank + Substation.eigenvector_rank - ) -) -model.define(Substation.critical_rank(aggs.rank(Substation.combined_rank, Substation.id))) - -Substation.is_structurally_critical = model.Relationship(f"{Substation} is structurally critical") -model.where(Substation.critical_rank <= CRITICAL_THRESHOLD).define( - Substation.is_structurally_critical() -) - -# -------------------------------------------------- -# Stage 3: Paths -- Transmission Corridors & Contingency -# PREVIEW capability; requires relationalai>=1.15. -# -------------------------------------------------- -# Composes on Stage 2's Substation.betweenness. Where Stage 2 scores a *node*, -# paths scores the *corridor* feeding each data center: enumerate generator-sub -> -# DC-sub transmission routes, rank each by total betweenness summed along its hops -# (most fragile = greatest through-traffic exposure), then re-enumerate with the -# highest-betweenness substation offline to see which DC substations reroute. - -# Bidirectional Substation<->Substation grid edge from active transmission lines. -Substation.connects_to = model.Relationship( - f"{Substation} connects to {Substation}", short_name="connects_to" -) -tl_fwd = TransmissionLine.ref() -s_from, s_to = Substation.ref(), Substation.ref() -model.where( - tl_fwd.from_substation(s_from), - tl_fwd.to_substation(s_to), - tl_fwd.is_active == True, -).define(s_from.connects_to(s_to)) -tl_rev = TransmissionLine.ref() -s_a, s_b = Substation.ref(), Substation.ref() -model.where( - tl_rev.from_substation(s_a), - tl_rev.to_substation(s_b), - tl_rev.is_active == True, -).define(s_b.connects_to(s_a)) - -# Typed endpoints: substations hosting a generator (source) and a DC request (sink). -gen_ref, gen_sub = Generator.ref(), Substation.ref() -model.where(gen_ref.substation(gen_sub)).define(GeneratorSubstation(gen_sub)) -dc_ref, dc_sub = DataCenterRequest.ref(), Substation.ref() -model.where(dc_ref.substation(dc_sub)).define(DCSubstation(dc_sub)) - -# Enumerate generator-sub -> DC-sub corridors (finite repeat; the grid is meshed/cyclic). -corridor_src, corridor_dst = GeneratorSubstation.ref(), DCSubstation.ref() -corridor = ( - model.path( - corridor_src, Substation.connects_to.repeat(1, MAX_CORRIDOR_HOPS), corridor_dst - ) - .all() - .paths() -) - -# Each corridor's substations in hop order, which the deployed model publishes for the queries. -CorridorStep = model.Relationship( - f"corridor {Hash:corridor} has {Substation:substation} at hop {Integer:hop}" -) -model.where(corridor).define( - CorridorStep(corridor, Substation(corridor.nodes), corridor.nodes["index"]) -) - -# Each DC substation's fragility load is the highest corridor score among the simple -# corridors ending at it, where a corridor's score sums Stage 2's betweenness over its -# nodes. The grid is cyclic, so .all().paths() also yields walks that revisit a node; -# not_(where(i < j, p.nodes(i) == p.nodes(j))) drops them in the same where() as the sum, -# so on every corridor that remains the position sum equals the distinct-substation sum. -i, j = Integer.ref(), Integer.ref() -Substation.fragility_load = model.Property(f"{Substation} has {Float:fragility_load}") -model.where( - corridor, - not_(where(i < j, corridor.nodes(i) == corridor.nodes(j))), # simple corridors only - total := aggs.sum(Substation(corridor.nodes).betweenness).per(corridor), - frag := aggs.max(total).per(corridor_dst), -).define(corridor_dst.fragility_load(frag)) - -# -------------------------------------------------- -# Stage 4: Rules -- Interconnection Queue Compliance -# -------------------------------------------------- -# Accretive chain: each rule consumes ontology enrichments from earlier stages. -# Rule 1 reads Substation.predicted_load (Stage 1). -# Rule 2 reads Substation.is_structurally_critical (Stage 2). -# Rule 3 reads Generator.emissions_rate (base data) to derive low-carbon capacity. -# All flags are written back as Relationships — queryable and consumable downstream. - -# Rule 1: Capacity check -- consumes predicted_load from Stage 1 -DataCenterRequest.fails_capacity = model.Relationship(f"{DataCenterRequest} fails capacity check") -SubRef_rule = Substation.ref() -effective_load_rule = SubRef_rule.predicted_load | SubRef_rule.current_load_mw -model.where( - DataCenterRequest.substation(SubRef_rule), - DataCenterRequest.requested_mw + effective_load_rule > SubRef_rule.max_capacity_mw, -).define(DataCenterRequest.fails_capacity()) - -# Rule 2: Structural risk -- uses centrality-based criticality from Stage 2 -DataCenterRequest.fails_structural = model.Relationship(f"{DataCenterRequest} fails structural risk check") -SubRef_sr = Substation.ref() -model.where( - DataCenterRequest.substation(SubRef_sr), - SubRef_sr.is_structurally_critical(), -).define(DataCenterRequest.fails_structural()) - -# Rule 3: Low-carbon mandate -- check if DC's low-carbon requirement can be met -# Low-carbon = zero-emission generation (renewable + nuclear), keyed on emissions_rate == 0. -# The requirement is a fraction of the substation's generation (0.60 means 60%). -Substation.low_carbon_gen_mw = model.Property(f"{Substation} has {Float:low_carbon_gen_mw}") -Substation.total_gen_mw = model.Property(f"{Substation} has {Float:total_gen_mw}") -model.define( - Substation.low_carbon_gen_mw( - aggs.sum(Generator.capacity_mw) - .where(Generator.substation(Substation), Generator.emissions_rate == 0.0) - .per(Substation) - ) -) -model.define( - Substation.total_gen_mw( - aggs.sum(Generator.capacity_mw) - .where(Generator.substation(Substation)) - .per(Substation) - ) -) - -DataCenterRequest.fails_low_carbon = model.Relationship(f"{DataCenterRequest} fails low-carbon mandate") -SubRef_lc = Substation.ref() -model.where( - DataCenterRequest.substation(SubRef_lc), - (SubRef_lc.low_carbon_gen_mw | 0.0) - < DataCenterRequest.low_carbon_requirement_pct * SubRef_lc.total_gen_mw, -).define(DataCenterRequest.fails_low_carbon()) -# A substation without generating capacity cannot meet any positive requirement. -model.where( - DataCenterRequest.substation(SubRef_lc), - DataCenterRequest.low_carbon_requirement_pct > 0, - not_(SubRef_lc.total_gen_mw > 0), -).define(DataCenterRequest.fails_low_carbon()) - -# Composite: compliant if none of the checks fail -DataCenterRequest.is_compliant = model.Relationship(f"{DataCenterRequest} is compliant") -model.where( - model.not_(DataCenterRequest.fails_capacity()), - model.not_(DataCenterRequest.fails_structural()), - model.not_(DataCenterRequest.fails_low_carbon()), -).define(DataCenterRequest.is_compliant()) - -# -------------------------------------------------- -# Stage 5: Optimize -- Joint DC Approval + Grid Upgrade -# Accretive chain: the capacity constraint uses predicted_load from Stage 1 -# (via the | fallback pattern), matching the rules engine. All solve results -# (x_approve, x_upgrade per InvestmentLevel) are written to the ontology — -# queryable via model.select(), not parsed from solver output. -# One solve across 5 InvestmentLevel scenarios produces the Pareto frontier. -# -------------------------------------------------- - -# Decision variables indexed by InvestmentLevel -DataCenterRequest.x_approve = model.Property( - f"{DataCenterRequest} in {InvestmentLevel} has {Float:x_approve}" -) -SubstationUpgrade.x_upgrade = model.Property( - f"{SubstationUpgrade} in {InvestmentLevel} has {Float:x_upgrade}" -) - -# Float refs for variable binding in constraints/objective -x_a = Float.ref("xa") -x_u = Float.ref("xu") - -# Refs for aggregation joins -DCRef = DataCenterRequest.ref() -UpgRef = SubstationUpgrade.ref() - -# Problem formulation -problem = Problem(model, Float, name="energy_grid_planning") - -problem.solve_for(DataCenterRequest.x_approve(InvestmentLevel, x_a), type="bin", - name=["approve", InvestmentLevel.name, DataCenterRequest.id]) -problem.solve_for(SubstationUpgrade.x_upgrade(InvestmentLevel, x_u), type="bin", - name=["upgrade", InvestmentLevel.name, SubstationUpgrade.id]) - -# C1: Substation capacity per investment level -# Uses predicted_load from Stage 1 (with current_load fallback) — the accretive chain. -x_a_c = Float.ref("xa_c") -x_u_c = Float.ref("xu_c") -effective_load = Substation.predicted_load | Substation.current_load_mw - -# Each upgrade's capacity and each request's MW is weighted by its own variable. -# A substation with no upgrade options adds no capacity (`| 0.0`). -problem.satisfy( - model.where( - InvestmentLevel, - DataCenterRequest.substation(Substation), - ).require( - Substation.max_capacity_mw - - effective_load - + ( - sum(UpgRef, x_u_c * UpgRef.capacity_increase_mw) - .where( - UpgRef.substation == Substation, - UpgRef.x_upgrade(InvestmentLevel, x_u_c), - ) - .per(Substation, InvestmentLevel) - | 0.0 - ) - >= sum(DCRef, x_a_c * DCRef.requested_mw) - .where( - DCRef.substation == Substation, - DCRef.x_approve(InvestmentLevel, x_a_c), - ) - .per(Substation, InvestmentLevel) - ) -) - -# C2: Budget per investment level -problem.satisfy(model.where( - SubstationUpgrade.x_upgrade(InvestmentLevel, x_u), -).require( - sum(x_u * SubstationUpgrade.cost_million).per(InvestmentLevel) <= InvestmentLevel.budget_cap -)) - -# Objective: maximize total DC revenue across all levels -problem.maximize( - sum(InvestmentLevel, x_a * DataCenterRequest.annual_revenue_per_mw * DataCenterRequest.requested_mw).where( - DataCenterRequest.x_approve(InvestmentLevel, x_a) - ) -) - -# Each refresh of the deployed model runs this solve (one solve for all levels). -problem.configure("highs", time_limit_sec=120) - -# The solve's status and objective, which the deployed model publishes for the queries. -SolveStatus = model.Relationship(f"energy grid solve status is {String:status}") -SolveObjective = model.Relationship(f"energy grid solve objective is {Float:objective}") -model.define(SolveStatus(problem.termination_status()), SolveObjective(problem.objective_value())) - -# -------------------------------------------------- -# Portfolio per InvestmentLevel, from the solved values -# -------------------------------------------------- -# One InvestmentPortfolio row per scenario: approved requests, their MW and -# revenue, the selected upgrades' cost (in dollars, to match revenue), and the -# net value (revenue less the upgrade cost amortized over AMORTIZATION_YEARS). -x_ap, x_up = Float.ref(), Float.ref() -model.define( - portfolio := InvestmentPortfolio.new(investment_level_name=InvestmentLevel.name), - portfolio.investment_level(InvestmentLevel), -) -model.define( - InvestmentPortfolio.dc_count( - ( - aggs.count(DataCenterRequest) - .where( - InvestmentPortfolio.investment_level(InvestmentLevel), - DataCenterRequest.x_approve(InvestmentLevel, x_ap), - x_ap > 0.5, - ) - .per(InvestmentPortfolio) - ) - | 0 - ) -) -model.define( - InvestmentPortfolio.total_mw( - ( - sum(DataCenterRequest, DataCenterRequest.requested_mw) - .where( - InvestmentPortfolio.investment_level(InvestmentLevel), - DataCenterRequest.x_approve(InvestmentLevel, x_ap), - x_ap > 0.5, - ) - .per(InvestmentPortfolio) - ) - | 0.0 - ) -) -model.define( - InvestmentPortfolio.annual_revenue( - ( - sum(DataCenterRequest, DataCenterRequest.requested_mw * DataCenterRequest.annual_revenue_per_mw) - .where( - InvestmentPortfolio.investment_level(InvestmentLevel), - DataCenterRequest.x_approve(InvestmentLevel, x_ap), - x_ap > 0.5, - ) - .per(InvestmentPortfolio) - ) - | 0.0 - ) -) -model.define( - InvestmentPortfolio.upgrade_cost( - ( - sum(SubstationUpgrade, SubstationUpgrade.cost_million * 1e6) - .where( - InvestmentPortfolio.investment_level(InvestmentLevel), - SubstationUpgrade.x_upgrade(InvestmentLevel, x_up), - x_up > 0.5, - ) - .per(InvestmentPortfolio) - ) - | 0.0 - ) -) -model.define( - InvestmentPortfolio.upgrade_count( - ( - aggs.count(SubstationUpgrade) - .where( - InvestmentPortfolio.investment_level(InvestmentLevel), - SubstationUpgrade.x_upgrade(InvestmentLevel, x_up), - x_up > 0.5, - ) - .per(InvestmentPortfolio) - ) - | 0 - ) -) -model.define( - InvestmentPortfolio.upgrade_mw( - ( - sum(SubstationUpgrade, SubstationUpgrade.capacity_increase_mw) - .where( - InvestmentPortfolio.investment_level(InvestmentLevel), - SubstationUpgrade.x_upgrade(InvestmentLevel, x_up), - x_up > 0.5, - ) - .per(InvestmentPortfolio) - ) - | 0.0 - ) -) -model.define( - InvestmentPortfolio.net_value( - InvestmentPortfolio.annual_revenue - InvestmentPortfolio.upgrade_cost / AMORTIZATION_YEARS - ) -) - -# Marginal value of each budget step: net value gained per added $M from a level -# to the next larger budget. The largest level has no next step. -higher, step_from, step_to = InvestmentLevel.ref(), InvestmentLevel.ref(), InvestmentLevel.ref() -model.define(InvestmentLevel.next_level(step_to)).where( - step_to.budget_cap - == aggs.min(higher.budget_cap).where(higher.budget_cap > InvestmentLevel.budget_cap).per(InvestmentLevel) -) -next_portfolio = InvestmentPortfolio.ref() -model.define( - InvestmentPortfolio.marginal_per_m_to_next_level( - (next_portfolio.net_value - InvestmentPortfolio.net_value) / (step_to.budget_cap - step_from.budget_cap) - ) -).where( - InvestmentPortfolio.investment_level(step_from), - step_from.next_level(step_to), - next_portfolio.investment_level(step_to), -) - -# The knee is the level where the marginal value falls the most, from the step -# into it to the step out of it; on a tie, the smaller budget. A frontier whose -# marginal value never falls has no knee. -prev_portfolio = InvestmentPortfolio.ref() -model.define( - InvestmentPortfolio.marginal_drop( - prev_portfolio.marginal_per_m_to_next_level - InvestmentPortfolio.marginal_per_m_to_next_level - ) -).where( - prev_portfolio.investment_level(step_from), - step_from.next_level(step_to), - InvestmentPortfolio.investment_level(step_to), -) -model.define(InvestmentPortfolio.is_knee_point()).where( - InvestmentPortfolio.investment_level(step_to), - InvestmentPortfolio.marginal_drop > 0, - aggs.rank(aggs.desc(InvestmentPortfolio.marginal_drop), step_to.budget_cap) == 1, -) diff --git a/energy_grid_planning/queries/energy_grid_report.py b/energy_grid_planning/queries/energy_grid_report.py index 067bc363..5b5cad46 100644 --- a/energy_grid_planning/queries/energy_grid_report.py +++ b/energy_grid_planning/queries/energy_grid_report.py @@ -14,17 +14,24 @@ from model import ( CRITICAL_THRESHOLD, MAX_CORRIDOR_HOPS, - CorridorStep, + ComplianceSummary, + CorridorSummary, DataCenterRequest, + GridRegion, + GridTopology, InvestmentLevel, InvestmentPortfolio, + InvestmentRange, SolveObjective, SolveStatus, Substation, SubstationUpgrade, model, ) -from relationalai.semantics import Float, Hash, Integer +from relationalai.semantics import Float + +# How many corridors Stage 3 lists. +TOP_CORRIDORS = 5 def main() -> None: @@ -81,36 +88,30 @@ def main() -> None: print("STAGE 2: GRAPH -- Grid Topology & Structural Vulnerability") print("=" * 60) - wcc_df = ( - model.select( - Substation.id.alias("substation_id"), - Substation.name.alias("substation_name"), - Substation.component.alias("component_id"), - ) - .to_df() - ) + topology = model.select( + GridTopology.n_substations.alias("substations"), + GridTopology.n_components.alias("components"), + GridTopology.n_communities.alias("communities"), + GridTopology.connectivity.alias("connectivity"), + ).to_df().iloc[0] - num_components = wcc_df["component_id"].nunique() - total_substations = len(wcc_df) + num_components = int(topology["components"]) print( - f"\n Grid connectivity: {total_substations} substations, {num_components} component(s)" + f"\n Grid connectivity: {int(topology['substations'])} substations, {num_components} component(s)" ) - if num_components == 1: + if topology["connectivity"] == "CONNECTED": print(" CONNECTED: All substations reachable from any other.") else: print(f" FRAGMENTED: {num_components} isolated grid segments detected!") - community_df = model.select( - Substation.id.alias("substation_id"), - Substation.name.alias("name"), - Substation.grid_community.alias("community"), - ).to_df() - - num_communities = community_df["community"].nunique() - print(f"\n Grid community structure (Louvain): {num_communities} region(s)") - for comm_id, group in community_df.groupby("community"): - members = ", ".join(group["name"].tolist()) - print(f" Region {comm_id}: {members}") + regions = ( + model.select(GridRegion.community.alias("community"), GridRegion.members.alias("members")) + .to_df() + .sort_values("community") + ) + print(f"\n Grid community structure (Louvain): {int(topology['communities'])} region(s)") + for _, region in regions.iterrows(): + print(f" Region {int(region['community'])}: {region['members']}") centrality_df = ( model.select( @@ -165,80 +166,39 @@ def main() -> None: print("STAGE 3: PATHS -- Transmission Corridors & Contingency") print("=" * 60) - # Reassemble corridor node sequences in pandas for human-readable route labels (string- - # joining names is a pandas job) and for the contingency re-enumeration below. Selecting - # names alongside the score would fan out rows, so the node-sequence projection is a - # SEPARATE query from the scoring above. - corridor, hop = Hash.ref(), Integer.ref() - corridor_df = model.where(CorridorStep(corridor, Substation, hop)).select( - corridor.alias("corridor"), - hop.alias("hop"), - Substation.id.alias("substation_id"), - Substation.name.alias("substation_name"), - ).to_df() - betw_df = model.select( - Substation.id.alias("substation_id"), - Substation.name.alias("substation_name"), - Substation.betweenness.alias("betweenness"), - ).to_df() - betw_by_id = dict(zip(betw_df["substation_id"], betw_df["betweenness"].fillna(0.0))) - name_by_id = dict(zip(betw_df["substation_id"], betw_df["substation_name"])) - corridor_df["betweenness"] = corridor_df["substation_id"].map(betw_by_id).fillna(0.0) - - - def most_fragile_corridor_per_dc(removed_id=None): - """Highest total-betweenness SIMPLE corridor terminating at each DC substation. - - Used to recover each winning corridor's node names (for printing) and for the - contingency re-enumeration. The model publishes the per-DC maximum load as - Substation.fragility_load; this reproduces it and adds the route node sequence. - """ - best = {} - for _, grp in corridor_df.groupby("corridor"): - ordered = grp.sort_values("hop") - ids = ordered["substation_id"].tolist() - if len(set(ids)) != len(ids): - continue # simple paths only (the grid is cyclic) - if removed_id is not None and removed_id in ids: - continue - load = float(ordered["betweenness"].sum()) - dest = ids[-1] - # On equal loads, keep the route whose substation IDs sort first, so the pick is stable. - if dest not in best or load > best[dest][1] or (load == best[dest][1] and ids < best[dest][2]): - best[dest] = (ordered["substation_name"].tolist(), load, ids) - return best - - - baseline_corridors = most_fragile_corridor_per_dc() - # Count only SIMPLE corridors (drop node-repeating walks; the grid is cyclic). Kept in - # pandas via node-sequence reassembly: native count(corridor) fans out over the simple- - # path filter and count(distinct(corridor)) collapses to all-walks -- neither is the - # simple-corridor count. - n_corridors = len([ - cid - for cid, grp in corridor_df.groupby("corridor") - if len(set(grp["substation_id"])) == len(grp["substation_id"]) - ]) + # The deployed model publishes the corridor counts, each DC substation's most fragile route, and + # the contingency's reroutes. + corridors = model.select( + CorridorSummary.n_corridors.alias("corridors"), + CorridorSummary.n_served.alias("served"), + CorridorSummary.n_served_contingency.alias("served_contingency"), + CorridorSummary.n_rerouted.alias("rerouted"), + CorridorSummary.n_lost.alias("lost"), + ).to_df().iloc[0] + most_fragile = ( + model.where(Substation.fragility_rank <= TOP_CORRIDORS) + .select( + Substation.fragility_rank.alias("rank"), + Substation.fragility_load.alias("load"), + Substation.fragile_route.alias("route"), + ) + .to_df() + .sort_values("rank") + ) print( - f"\n {n_corridors} generator-sub -> DC-sub corridors (<= {MAX_CORRIDOR_HOPS} hops, simple); " - f"most-fragile corridor for {len(baseline_corridors)} DC substation(s):" + f"\n {int(corridors['corridors'])} generator-sub -> DC-sub corridors (<= {MAX_CORRIDOR_HOPS} hops, simple); " + f"most-fragile corridor for {int(corridors['served'])} DC substation(s):" ) - for dest, (route, load, _) in sorted(baseline_corridors.items(), key=lambda kv: (-kv[1][1], kv[0]))[:5]: - print(f" betweenness-load {round(load, 3)}: " + " -> ".join(route)) - - # Contingency: take the highest-betweenness substation offline and re-enumerate. - if betw_by_id: - # On a betweenness tie, the smallest substation ID goes offline. - top_id = min(betw_by_id, key=lambda sub_id: (-betw_by_id[sub_id], sub_id)) - after_corridors = most_fragile_corridor_per_dc(removed_id=top_id) - rerouted = len( - [d for d in baseline_corridors if d in after_corridors and baseline_corridors[d][0] != after_corridors[d][0]] - ) - lost = [d for d in baseline_corridors if d not in after_corridors] + for _, row in most_fragile.iterrows(): + print(f" betweenness-load {round(float(row['load']), 3)}: {row['route']}") + + # Contingency: the highest-betweenness substation goes offline and every corridor through it is dropped. + offline = model.where(Substation.is_offline()).select(Substation.name.alias("name")).to_df() + if len(offline) > 0: print( f"\n Contingency -- highest-betweenness substation offline " - f"({name_by_id.get(top_id, top_id)}): {len(baseline_corridors)} -> {len(after_corridors)} " - f"DC substations served, {rerouted} reroute, {len(lost)} lose all corridors." + f"({offline['name'].iloc[0]}): {int(corridors['served'])} -> {int(corridors['served_contingency'])} " + f"DC substations served, {int(corridors['rerouted'])} reroute, {int(corridors['lost'])} lose all corridors." ) @@ -292,7 +252,12 @@ def _query_flag(relationship, flag_name): compliance_df = compliance_df.merge(compliant_ids_df, on="dc_id", how="left") compliance_df["is_compliant"] = compliance_df["is_compliant"].fillna("N") - num_dc = len(compliance_df) + compliance_counts = model.select( + ComplianceSummary.n_requests.alias("requests"), + ComplianceSummary.n_compliant.alias("compliant"), + ComplianceSummary.n_flagged.alias("flagged"), + ).to_df().iloc[0] + num_dc = int(compliance_counts["requests"]) print(f"\n Evaluating {num_dc} DC requests against 3 declarative compliance rules...") print( @@ -307,8 +272,8 @@ def _query_flag(relationship, flag_name): f"{r['structural_flag']:>5} {r['is_compliant']:>4}" ) - compliant_count = len(compliance_df[compliance_df["is_compliant"] == "Y"]) - flagged_count = len(compliance_df[compliance_df["is_compliant"] == "N"]) + compliant_count = int(compliance_counts["compliant"]) + flagged_count = int(compliance_counts["flagged"]) print( f"\n Summary: {compliant_count} compliant, {flagged_count} flagged (out of {num_dc} requests)" ) @@ -318,10 +283,17 @@ def _query_flag(relationship, flag_name): print("STAGE 5: OPTIMIZE -- Joint Interconnection + Upgrade") print("=" * 60) - budgets = model.select(InvestmentLevel.budget_cap).to_df().iloc[:, 0].astype(float) + levels = model.select( + InvestmentRange.n_levels.alias("n_levels"), + InvestmentRange.min_budget.alias("min_budget"), + InvestmentRange.max_budget.alias("max_budget"), + ).to_df().iloc[0] status = model.select(SolveStatus).to_df().iloc[:, 0].tolist() objective = model.select(SolveObjective).to_df().iloc[:, 0].tolist() - print(f"\n Solved across {len(budgets)} investment levels (${budgets.min():,.0f}M-${budgets.max():,.0f}M)") + print( + f"\n Solved across {int(levels['n_levels'])} investment levels " + f"(${float(levels['min_budget']):,.0f}M-${float(levels['max_budget']):,.0f}M)" + ) print(f" Status: {', '.join(status)}") # Portfolio totals default to zero, so without a solution they would read as an empty plan. if not objective: @@ -367,7 +339,7 @@ def _query_flag(relationship, flag_name): DataCenterRequest.name.alias("dc_name"), DataCenterRequest.hyperscaler.alias("hyperscaler"), DataCenterRequest.requested_mw.alias("requested_mw"), - DataCenterRequest.annual_revenue_per_mw.alias("rev_per_mw"), + DataCenterRequest.annual_revenue.alias("revenue"), ) .to_df() ) @@ -457,7 +429,7 @@ def _query_flag(relationship, flag_name): print( f" {row['dc_name']} ({row['hyperscaler']}): " f"{float(row['requested_mw']):.0f} MW, " - f"${float(row['requested_mw']) * float(row['rev_per_mw']):,.0f}/yr" + f"${float(row['revenue']):,.0f}/yr" ) level_upg = upgrade_result_df[upgrade_result_df["level"] == level_name] if len(upgrade_result_df) > 0 else pd.DataFrame() diff --git a/energy_grid_planning/runbook.md b/energy_grid_planning/runbook.md index 1abb1d27..3ad39265 100644 --- a/energy_grid_planning/runbook.md +++ b/energy_grid_planning/runbook.md @@ -106,7 +106,7 @@ Plan routing sub-questions to graph, rules, and prescriptive reasoners. 1 connected component, 3 Louvain communities (North Texas, West Texas, Gulf Coast); DFW, Houston, San Antonio flagged `is_structurally_critical`; 7 of 10 DC requests target critical nodes. -### 6. Trace fragile transmission corridors (PREVIEW, requires `relationalai>=1.15`) +### 6. Trace fragile transmission corridors (PREVIEW, requires `relationalai>=1.27`) **Prompt** @@ -116,7 +116,7 @@ Plan routing sub-questions to graph, rules, and prescriptive reasoners. **Response** -421 generator-substation to DC-substation corridors. The most fragile carries a betweenness-load of 99.833, routing through the Dallas-Fort Worth / Abilene Central / Houston Ship Channel hubs. Taking the top substation (Dallas-Fort Worth) offline reroutes the other DC substations' corridors; the meshed grid stays connected (no full isolation). Persists `Substation.fragility_load`. +421 generator-substation to DC-substation corridors. The most fragile carries a betweenness-load of 99.833, routing through the Dallas-Fort Worth / Abilene Central / Houston Ship Channel hubs. Taking the top substation (Dallas-Fort Worth) offline reroutes the other DC substations' corridors; the meshed grid stays connected (no full isolation). Persists each DC substation's `Substation.fragility_load`, its most fragile route (`fragile_route`), and its route with the offline substation removed (`contingency_route`). ### 7. Screen DC requests diff --git a/entity_resolution/model/__init__.py b/entity_resolution/model/__init__.py index 346b8b32..ebcf016e 100644 --- a/entity_resolution/model/__init__.py +++ b/entity_resolution/model/__init__.py @@ -1,17 +1,42 @@ """Entity-resolution model: loaded source facts and the reasoning over them. -`rai models deploy --path model` deploys everything this package declares. +`rai models deploy --path model` deploys everything this package declares. The stages live in five +modules, each of which imports the modules whose declarations it reads: + 1. Graph -- weakly connected components over the accepted match edges cluster records + into insured parties (`match_graph.py`). + 2. Rules -- confidence tiers, band sizes, and the blocking reduction (`match_bands.py`); + each party's records, golden record, total exposure, and accumulation-limit + breach (`resolved_parties.py`); the breaches confirming the review queue + would surface (`review_queue.py`). + 3. Prescriptive -- which breached parties to cede to reinsurance within the premium budget + (`reinsurance_cessions.py`). + +`model/source.py` normalizes, blocks, and scores candidate pairs into the auto-merge and review +bands; `queries/resolution_report.py` prints the report from the deployed model. """ -from .reasoning import ( - ACCUMULATION_LIMIT, +from .match_bands import ( + comparison_reduction, + num_all_pairs, + num_auto_merges, + num_review_pairs, +) +from .match_graph import num_edges, num_nodes +from .reinsurance_cessions import ( REINSURANCE_BUDGET, - REINSURANCE_RATE, SolveStatus, - num_edges, - num_nodes, + ceded_excess, + ceded_premium, problem, ) +from .resolved_parties import ( + ACCUMULATION_LIMIT, + REINSURANCE_RATE, + num_parties, + num_party_breaches, + num_record_breaches, +) +from .review_queue import num_confirmed_breaches, num_surfaced_breaches from .schema import CandidateMatch, CandidatePairCount, Record, ResolvedParty, ReviewPair, model from .source import AUTO_MERGE, REVIEW_FLOOR, load_ground_truth @@ -27,9 +52,20 @@ "ResolvedParty", "ReviewPair", "SolveStatus", + "ceded_excess", + "ceded_premium", + "comparison_reduction", "load_ground_truth", "model", + "num_all_pairs", + "num_auto_merges", + "num_confirmed_breaches", "num_edges", "num_nodes", + "num_parties", + "num_party_breaches", + "num_record_breaches", + "num_review_pairs", + "num_surfaced_breaches", "problem", ] diff --git a/entity_resolution/model/match_bands.py b/entity_resolution/model/match_bands.py new file mode 100644 index 00000000..0bda6a5d --- /dev/null +++ b/entity_resolution/model/match_bands.py @@ -0,0 +1,53 @@ +"""Match bands: each accepted match's confidence tier, how many pairs land in the auto-merge and +review bands, and how far blocking cuts the number of record pairs compared.""" + +from relationalai.semantics import Float, Integer +from relationalai.semantics.std import aggregates as aggs +from relationalai.semantics.std import floats + +from .schema import CandidateMatch, CandidatePairCount, Record, ReviewPair, model + +# -------------------------------------------------- +# Configure inputs +# -------------------------------------------------- + +# An accepted match scoring at or above this is HIGH confidence, below it MEDIUM. +HIGH_TIER = 0.90 + +# -------------------------------------------------- +# Confidence tiers of the accepted matches +# -------------------------------------------------- + +model.define(CandidateMatch.confidence_tier("HIGH")).where( + CandidateMatch.score >= HIGH_TIER +) +model.define(CandidateMatch.confidence_tier("MEDIUM")).where( + CandidateMatch.score < HIGH_TIER +) + +# -------------------------------------------------- +# Band sizes and the blocking reduction +# -------------------------------------------------- + +# Pairs in the auto-merge band (accepted matches) and in the review band. +num_auto_merges = model.Relationship(f"auto-merge accepted {Integer:n_matches} pairs") +num_review_pairs = model.Relationship(f"the review band holds {Integer:n_pairs} pairs") +model.define( + num_auto_merges(aggs.count(CandidateMatch) | 0), + num_review_pairs(aggs.count(ReviewPair) | 0), +) + +# Every unordered pair of records, and the share of those comparisons that +# blocking avoids. +num_all_pairs = model.Relationship(f"there are {Integer:n_pairs} possible record pairs") +_n_records = Integer.ref() +model.where(_n_records == aggs.count(Record)).define( + num_all_pairs(_n_records * (_n_records - 1) // 2) +) +comparison_reduction = model.Relationship( + f"blocking avoids {Float:reduction} of the possible comparisons" +) +_candidates, _possible = Integer.ref(), Integer.ref() +model.where(CandidatePairCount(_candidates), num_all_pairs(_possible)).define( + comparison_reduction(1 - floats.float(_candidates) / floats.float(_possible)) +) diff --git a/entity_resolution/model/match_graph.py b/entity_resolution/model/match_graph.py new file mode 100644 index 00000000..b046b5d0 --- /dev/null +++ b/entity_resolution/model/match_graph.py @@ -0,0 +1,30 @@ +"""Match graph: weakly connected components over the accepted match edges cluster records into one +insured party, closing transitive chains, and the graph's size.""" + +from relationalai.semantics import Integer +from relationalai.semantics.reasoners.graph import Graph + +from .schema import CandidateMatch, Record, model + +# Cluster records connected by accepted match edges. +graph = Graph(model, directed=False, weighted=False, node_concept=Record, name="match_graph") + +match_ref = CandidateMatch.ref() +rec_a, rec_b = Record.ref(), Record.ref() +model.where(match_ref.rec_a == rec_a, match_ref.rec_b == rec_b).define( + graph.Edge.new(src=rec_a, dst=rec_b) +) + +graph.Node.entity_id = graph.weakly_connected_component() + +rep_node = Record.ref() +model.where(Record.entity_id == rep_node).define( + Record.entity_key(rep_node.record_id) +) + +# The graph's size, which the deployed model publishes for the queries. +node_count, edge_count = Integer.ref(), Integer.ref() +num_nodes = model.Relationship(f"the match graph has {Integer:node_count} nodes") +num_edges = model.Relationship(f"the match graph has {Integer:edge_count} edges") +model.where(graph.num_nodes()(node_count)).define(num_nodes(node_count)) +model.where(graph.num_edges()(edge_count)).define(num_edges(edge_count)) diff --git a/entity_resolution/model/reasoning.py b/entity_resolution/model/reasoning.py deleted file mode 100644 index 21ba1cc9..00000000 --- a/entity_resolution/model/reasoning.py +++ /dev/null @@ -1,135 +0,0 @@ -"""Graph, rules-based, and prescriptive reasoning for entity resolution. - -Resolution is the step that makes the downstream reasoning correct. An insurer's -policyholder records are scattered across policy systems (auto, home, life) and -an acquired book, so the same insured looks like several customers -- and their -combined exposure to the carrier is invisible until the records are resolved. -`model/source.py` normalizes, blocks, and scores candidate pairs into two bands -- -AUTO_MERGE (merge automatically) and REVIEW (held for a steward). This module -declares the reasoning over them: - -- Stage 1 -- Graph: weakly-connected-components over the auto-merged match edges - clusters records into one insured party, closing transitive chains. -- Stage 2 -- Rules-based: confidence tiers on matches, a duplicate flag, and the - payoff -- total exposure per resolved party and an accumulation-limit breach - flag. At the record level no policy looks dangerous; resolved, households breach. -- Stage 3 -- Prescriptive: with a finite reinsurance budget, choose which breached - households to cede to reinsurance (a knapsack) to transfer the most excess - exposure off the book. Each refresh of the deployed model runs the solve. - -`queries/resolution_report.py` prints Stage 4 from the deployed model: the -record-level vs resolved-level contrast, the review queue (and the breach it still -hides), the cession plan, and pairwise precision / recall / F1. -""" - -from relationalai.semantics import Float, Integer, String -from relationalai.semantics.reasoners.graph import Graph -from relationalai.semantics.reasoners.prescriptive import Problem -from relationalai.semantics.std import aggregates - -from .schema import CandidateMatch, Record, ResolvedParty, model - -HIGH_TIER = 0.90 - -ACCUMULATION_LIMIT = 1_000_000.0 -REINSURANCE_RATE = 0.12 -REINSURANCE_BUDGET = 120_000.0 - - -def cluster_accepted_matches(): - """Cluster records connected by accepted match edges.""" - graph = Graph(model, directed=False, weighted=False, node_concept=Record, name="match_graph") - - match_ref = CandidateMatch.ref() - rec_a, rec_b = Record.ref(), Record.ref() - model.where(match_ref.rec_a == rec_a, match_ref.rec_b == rec_b).define( - graph.Edge.new(src=rec_a, dst=rec_b) - ) - - graph.Node.entity_id = graph.weakly_connected_component() - - rep_node = Record.ref() - model.where(Record.entity_id == rep_node).define( - Record.entity_key(rep_node.record_id) - ) - - # The graph's size, which the deployed model publishes for the queries. - node_count, edge_count = Integer.ref(), Integer.ref() - num_nodes = model.Relationship(f"the match graph has {Integer:node_count} nodes") - num_edges = model.Relationship(f"the match graph has {Integer:edge_count} edges") - model.where(graph.num_nodes()(node_count)).define(num_nodes(node_count)) - model.where(graph.num_edges()(edge_count)).define(num_edges(edge_count)) - return num_nodes, num_edges - - -def derive_exposure_and_breaches() -> None: - """Derive match tiers, resolved membership, exposure, and breaches.""" - model.define(CandidateMatch.confidence_tier("HIGH")).where( - CandidateMatch.score >= HIGH_TIER - ) - model.define(CandidateMatch.confidence_tier("MEDIUM")).where( - CandidateMatch.score < HIGH_TIER - ) - - records_per_entity = aggregates.count(Record).per(Record.entity_key) - model.define(Record.is_duplicate(Record)).where(records_per_entity >= 2) - - model.define(ResolvedParty.new(key=Record.entity_key)) - record, party = Record.ref(), ResolvedParty.ref() - model.where(record.entity_key == party.key).define( - record.resolved_party(party) - ) - - party_record = Record.ref() - model.where(party_record.entity_key == ResolvedParty.key).define( - ResolvedParty.total_exposure( - aggregates.sum(party_record.coverage_amount).per(ResolvedParty) - ) - ) - model.define(ResolvedParty.is_over_limit(ResolvedParty)).where( - ResolvedParty.total_exposure > ACCUMULATION_LIMIT - ) - model.where(ResolvedParty.total_exposure > ACCUMULATION_LIMIT).define( - ResolvedParty.excess( - ResolvedParty.total_exposure - ACCUMULATION_LIMIT - ) - ) - model.define( - ResolvedParty.premium(ResolvedParty.excess * REINSURANCE_RATE) - ) - - -def choose_reinsurance_cessions(): - """Declare the reinsurance-budget knapsack for breached parties.""" - problem = Problem(model, Float, name="entity_resolution") - problem.solve_for( - ResolvedParty.cede, - where=[ResolvedParty.is_over_limit()], - name=["cede", ResolvedParty.key], - type="bin", - lower=0.0, - upper=1.0, - ) - problem.satisfy( - model.require( - aggregates.sum( - ResolvedParty.premium * ResolvedParty.cede - ) - <= REINSURANCE_BUDGET - ), - name=["reinsurance_budget"], - ) - problem.maximize( - aggregates.sum(ResolvedParty.excess * ResolvedParty.cede) - ) - problem.configure("highs", time_limit_sec=60) - return problem - - -num_nodes, num_edges = cluster_accepted_matches() -derive_exposure_and_breaches() -problem = choose_reinsurance_cessions() - -# The solve's status, which the deployed model publishes for the queries. -SolveStatus = model.Relationship(f"reinsurance solve status is {String:status}") -model.define(SolveStatus(problem.termination_status())) diff --git a/entity_resolution/model/reinsurance_cessions.py b/entity_resolution/model/reinsurance_cessions.py new file mode 100644 index 00000000..ccbb82ef --- /dev/null +++ b/entity_resolution/model/reinsurance_cessions.py @@ -0,0 +1,55 @@ +"""Reinsurance cessions: the knapsack that chooses which breached parties to cede within the premium +budget, the solve's status, and the excess exposure and premium the plan cedes.""" + +from relationalai.semantics import Float, String +from relationalai.semantics.reasoners.prescriptive import Problem +from relationalai.semantics.std import aggregates as aggs + +# Declares the over-limit flag, excess, and premium the decision reads. +from . import resolved_parties # noqa: F401 +from .schema import ResolvedParty, model + +# -------------------------------------------------- +# Configure inputs +# -------------------------------------------------- + +REINSURANCE_BUDGET = 120_000.0 + +# The reinsurance-budget knapsack for breached parties. +problem = Problem(model, Float, name="entity_resolution") +problem.solve_for( + ResolvedParty.cede, + where=[ResolvedParty.is_over_limit()], + name=["cede", ResolvedParty.key], + type="bin", + lower=0.0, + upper=1.0, +) +problem.satisfy( + model.require( + aggs.sum( + ResolvedParty.premium * ResolvedParty.cede + ) + <= REINSURANCE_BUDGET + ), + name=["reinsurance_budget"], +) +problem.maximize( + aggs.sum(ResolvedParty.excess * ResolvedParty.cede) +) +problem.configure("highs", time_limit_sec=60) + +# The solve's status, which the deployed model publishes for the queries. +SolveStatus = model.Relationship(f"reinsurance solve status is {String:status}") +model.define(SolveStatus(problem.termination_status())) + +# The excess exposure and premium of the ceded parties (zero for an empty plan). They are +# nullary relationships: a property computed from the solution on ResolvedParty would fail +# the deploy. +ceded_excess = model.Relationship(f"the cession plan cedes {Float:excess} of excess exposure") +ceded_premium = model.Relationship(f"the cession plan pays {Float:premium} of premium") +_ceded = ResolvedParty.cede > 0.5 +model.define( + ceded_excess(aggs.sum(ResolvedParty, ResolvedParty.excess).where(_ceded) | 0.0), + ceded_premium(aggs.sum(ResolvedParty, ResolvedParty.premium).where(_ceded) | 0.0), +) diff --git a/entity_resolution/model/resolved_parties.py b/entity_resolution/model/resolved_parties.py new file mode 100644 index 00000000..9baf679c --- /dev/null +++ b/entity_resolution/model/resolved_parties.py @@ -0,0 +1,89 @@ +"""Resolved parties: one party per cluster of matched records, the records and golden record it +holds, its total exposure to the carrier, whether it breaches the accumulation limit, and the excess +and reinsurance premium of a breach.""" + +from relationalai.semantics import Integer +from relationalai.semantics.std import aggregates as aggs + +# Declares Record.entity_key, the party key each record resolves to. +from . import match_graph # noqa: F401 +from .schema import Record, ResolvedParty, model + +# -------------------------------------------------- +# Configure inputs +# -------------------------------------------------- + +ACCUMULATION_LIMIT = 1_000_000.0 +REINSURANCE_RATE = 0.12 + +# -------------------------------------------------- +# Resolved membership, exposure, and breaches +# -------------------------------------------------- + +model.define(ResolvedParty.new(key=Record.entity_key)) +record, party = Record.ref(), ResolvedParty.ref() +model.where(record.entity_key == party.key).define( + record.resolved_party(party) +) + +party_record = Record.ref() +model.where(party_record.entity_key == ResolvedParty.key).define( + ResolvedParty.total_exposure( + aggs.sum(party_record, party_record.coverage_amount).per(ResolvedParty) + ) +) +model.define(ResolvedParty.is_over_limit(ResolvedParty)).where( + ResolvedParty.total_exposure > ACCUMULATION_LIMIT +) +model.where(ResolvedParty.total_exposure > ACCUMULATION_LIMIT).define( + ResolvedParty.excess( + ResolvedParty.total_exposure - ACCUMULATION_LIMIT + ) +) +model.define( + ResolvedParty.premium(ResolvedParty.excess * REINSURANCE_RATE) +) + +# -------------------------------------------------- +# Party size and golden record +# -------------------------------------------------- + +# Records per party; a party with more than one record is multi-record, and each of its +# records is a duplicate. +ResolvedParty.n_records = model.Property(f"{ResolvedParty} has {Integer:n_records} records") +_member = Record.ref() +model.where(_member.entity_key == ResolvedParty.key).define( + ResolvedParty.n_records(aggs.count(_member).per(ResolvedParty)) +) +ResolvedParty.is_multi_record = model.Relationship(f"{ResolvedParty} holds more than one record") +model.where(ResolvedParty.n_records > 1).define(ResolvedParty.is_multi_record()) +model.where( + Record.resolved_party(ResolvedParty), ResolvedParty.is_multi_record(), +).define(Record.is_duplicate()) + +# The golden record is the party's latest record by creation date (ISO dates sort as text), the +# higher record id breaking a tie. +ResolvedParty.golden_record = model.Relationship( + f"{ResolvedParty} has golden {Record:golden_record}" +) +model.where( + _member.entity_key == ResolvedParty.key, + aggs.rank_desc(_member.created_at, _member.record_id).per(ResolvedParty) == 1, +).define(ResolvedParty.golden_record(_member)) + +# -------------------------------------------------- +# Counts the report prints +# -------------------------------------------------- + +num_parties = model.Relationship(f"the records resolve into {Integer:n_parties} parties") +num_record_breaches = model.Relationship( + f"the records include {Integer:n_records} over the accumulation limit" +) +num_party_breaches = model.Relationship( + f"the resolved parties include {Integer:n_parties} over the accumulation limit" +) +model.define( + num_parties(aggs.count(ResolvedParty) | 0), + num_record_breaches(aggs.count(Record).where(Record.coverage_amount > ACCUMULATION_LIMIT) | 0), + num_party_breaches(aggs.count(ResolvedParty).where(ResolvedParty.is_over_limit()) | 0), +) diff --git a/entity_resolution/model/review_queue.py b/entity_resolution/model/review_queue.py new file mode 100644 index 00000000..e1d6c3d1 --- /dev/null +++ b/entity_resolution/model/review_queue.py @@ -0,0 +1,56 @@ +"""Review queue: the accumulation picture if every review-band pair were confirmed. Records +re-cluster over the accepted and review edges, each confirmed party's exposure is totaled, and the +parties over the accumulation limit are counted against those auto-resolution finds.""" + +from relationalai.semantics import Float, Integer +from relationalai.semantics.reasoners.graph import Graph +from relationalai.semantics.std import aggregates as aggs + +from .resolved_parties import ACCUMULATION_LIMIT, num_party_breaches +from .schema import CandidateMatch, Record, ReviewPair, model + +# Weakly connected components over the accepted and the review-band pairs. +review_graph = Graph( + model, directed=False, weighted=False, node_concept=Record, name="review_graph" +) +_match, _review = CandidateMatch.ref(), ReviewPair.ref() +_rec_a, _rec_b = Record.ref(), Record.ref() +model.where(_match.rec_a == _rec_a, _match.rec_b == _rec_b).define( + review_graph.Edge.new(src=_rec_a, dst=_rec_b) +) +model.where(_review.rec_a == _rec_a, _review.rec_b == _rec_b).define( + review_graph.Edge.new(src=_rec_a, dst=_rec_b) +) +review_graph.Node.confirmed_id = review_graph.weakly_connected_component() + +# Each record's confirmed party key is its component's representative record id. +Record.confirmed_key = model.Property(f"{Record} has confirmed party key {Integer:confirmed_key}") +_rep_node = Record.ref() +model.where(Record.confirmed_id == _rep_node).define(Record.confirmed_key(_rep_node.record_id)) + +# The parties confirming the review queue would resolve, and their total exposure. +ConfirmedParty = model.Concept("ConfirmedParty", identify_by={"key": Integer}) +ConfirmedParty.total_exposure = model.Property(f"{ConfirmedParty} has {Float:total_exposure}") +model.define(ConfirmedParty.new(key=Record.confirmed_key)) +_member = Record.ref() +model.where(_member.confirmed_key == ConfirmedParty.key).define( + ConfirmedParty.total_exposure(aggs.sum(_member, _member.coverage_amount).per(ConfirmedParty)) +) + +# Confirmed parties over the accumulation limit, and how many of them auto-resolution misses. +num_confirmed_breaches = model.Relationship( + f"confirming the review queue gives {Integer:n_parties} parties over the accumulation limit" +) +num_surfaced_breaches = model.Relationship( + f"confirming the review queue surfaces {Integer:n_parties} breached parties that resolution " + "misses" +) +model.define( + num_confirmed_breaches( + aggs.count(ConfirmedParty).where(ConfirmedParty.total_exposure > ACCUMULATION_LIMIT) | 0 + ) +) +_confirmed, _resolved = Integer.ref(), Integer.ref() +model.where(num_confirmed_breaches(_confirmed), num_party_breaches(_resolved)).define( + num_surfaced_breaches(_confirmed - _resolved) +) diff --git a/entity_resolution/model/source.py b/entity_resolution/model/source.py index d33a59b6..346c27a5 100644 --- a/entity_resolution/model/source.py +++ b/entity_resolution/model/source.py @@ -97,6 +97,7 @@ def digits_only(s: str) -> str: return re.sub(r"\D", "", s or "") +# PyRel has no Jaro-Winkler (windowed character-matching) primitive, so pair scoring runs here. def jaro_winkler(s1: str, s2: str) -> float: """Return Jaro-Winkler string similarity in [0, 1].""" if s1 == s2: diff --git a/entity_resolution/queries/resolution_report.py b/entity_resolution/queries/resolution_report.py index 9813e39f..453cafc7 100644 --- a/entity_resolution/queries/resolution_report.py +++ b/entity_resolution/queries/resolution_report.py @@ -16,93 +16,93 @@ REINSURANCE_BUDGET, REINSURANCE_RATE, REVIEW_FLOOR, - CandidateMatch, CandidatePairCount, Record, ResolvedParty, ReviewPair, SolveStatus, + ceded_excess, + ceded_premium, + comparison_reduction, load_ground_truth, model, + num_all_pairs, + num_auto_merges, + num_confirmed_breaches, num_edges, num_nodes, + num_parties, + num_party_breaches, + num_record_breaches, + num_review_pairs, + num_surfaced_breaches, ) + +def published(relationship): + """The one value a nullary relationship of the deployed model holds.""" + return model.select(relationship.alias("value")).to_df()["value"].iloc[0] + + if __name__ == "__main__": resolved = model.select( Record.record_id.alias("record_id"), Record.entity_key.alias("entity_id"), - Record.source_system.alias("source_system"), - Record.full_name.alias("full_name"), - Record.created_at.alias("created_at"), - Record.coverage_amount.alias("coverage_amount"), ).to_df() resolved["entity_id"] = resolved["entity_id"].astype(str) record_ids = sorted(int(record_id) for record_id in resolved["record_id"]) - - candidate_count = int(model.select(CandidatePairCount).to_df().iloc[0, 0]) - n_matches = len(model.select(CandidateMatch.pair_id).to_df()) - review_df = ( - model.select( - ReviewPair.pair_id.alias("pair_id"), - ReviewPair.rec_a.record_id.alias("rec_a"), - ReviewPair.rec_b.record_id.alias("rec_b"), - ) - .to_df() - .sort_values("pair_id") - ) + auto_entity = dict(zip(resolved["record_id"], resolved["entity_id"])) n_records = len(record_ids) - all_pairs = n_records * (n_records - 1) // 2 print("=" * 64) print("Blocking & scoring") print("=" * 64) print(f"Records: {n_records}") - print(f"All possible pairs: {all_pairs}") + print(f"All possible pairs: {int(published(num_all_pairs))}") print( - f"Candidate pairs: {candidate_count} " - f"({100 * (1 - candidate_count / all_pairs):.1f}% fewer comparisons)" + f"Candidate pairs: {int(published(CandidatePairCount))} " + f"({100 * float(published(comparison_reduction)):.1f}% fewer comparisons)" ) - print(f"Auto-merge matches: {n_matches} (score >= {AUTO_MERGE})") - print(f"Held for review: {len(review_df)} ([{REVIEW_FLOOR}, {AUTO_MERGE}))") + print(f"Auto-merge matches: {int(published(num_auto_merges))} (score >= {AUTO_MERGE})") + n_review = int(published(num_review_pairs)) + print(f"Held for review: {n_review} ([{REVIEW_FLOOR}, {AUTO_MERGE}))") - n_nodes = int(model.select(num_nodes.alias("n")).to_df()["n"].iloc[0]) - n_edges = int(model.select(num_edges.alias("n")).to_df()["n"].iloc[0]) + n_nodes = int(published(num_nodes)) + n_edges = int(published(num_edges)) print(f"Graph: {n_nodes} nodes, {n_edges} match edges") - n_entities = resolved["entity_id"].nunique() print("\n" + "=" * 64) print("Resolved parties") print("=" * 64) - print(f"Auto-resolved {n_records} records into {n_entities} insured parties.") + print(f"Auto-resolved {n_records} records into {int(published(num_parties))} insured parties.") - resolved = resolved.sort_values(["entity_id", "created_at"]) - golden = resolved.groupby("entity_id").tail(1).set_index("entity_id") - sizes = resolved.groupby("entity_id").size() - print("\nMulti-record parties (golden record in CAPS):") - for entity_id in sizes[sizes > 1].index: - golden_record = golden.loc[entity_id] - members = resolved[resolved["entity_id"] == entity_id] - exposure = members["coverage_amount"].sum() - print( - f" {golden_record['full_name'].upper():<22} " - f"{len(members)} policies total exposure ${exposure:>12,.0f}" - ) - - record_level_breaches = int((resolved["coverage_amount"] > ACCUMULATION_LIMIT).sum()) - over = ( + multi_record = ( model.select( - ResolvedParty.key.alias("id"), + ResolvedParty.key.alias("entity_id"), + ResolvedParty.golden_record.full_name.alias("name"), + ResolvedParty.n_records.alias("n_records"), ResolvedParty.total_exposure.alias("exposure"), ) - .where(ResolvedParty.is_over_limit()) + .where(ResolvedParty.is_multi_record()) .to_df() ) + multi_record["entity_id"] = multi_record["entity_id"].astype(str) + print("\nMulti-record parties (golden record in CAPS):") + for _, party in multi_record.sort_values("entity_id").iterrows(): + print( + f" {party['name'].upper():<22} " + f"{int(party['n_records'])} policies total exposure ${party['exposure']:>12,.0f}" + ) + + n_breached = int(published(num_party_breaches)) print("\n" + "=" * 64) print(f"Accumulation control (limit ${ACCUMULATION_LIMIT:,.0f})") print("=" * 64) - print(f"Policies over the limit at the RECORD level: {record_level_breaches}") - print(f"Households over the limit after RESOLUTION: {len(over)}") + print( + "Policies over the limit at the RECORD level: " + f"{int(published(num_record_breaches))}" + ) + print(f"Households over the limit after RESOLUTION: {n_breached}") status = model.select(SolveStatus).to_df().iloc[:, 0].tolist() print( @@ -112,7 +112,7 @@ ) ceded = ( model.select( - ResolvedParty.key.alias("id"), + ResolvedParty.golden_record.full_name.alias("name"), ResolvedParty.total_exposure.alias("exposure"), ResolvedParty.excess.alias("excess"), ResolvedParty.premium.alias("premium"), @@ -120,58 +120,32 @@ ) .where(ResolvedParty.is_over_limit()) .to_df() + .sort_values("excess", ascending=False) ) - ceded["id"] = ceded["id"].astype(str) - name_by_entity = golden["full_name"].to_dict() - ceded["name"] = ceded["id"].map(name_by_entity).fillna("(party)") - ceded = ceded.sort_values("excess", ascending=False) - total_premium = total_ceded = 0.0 for _, row in ceded.iterrows(): - chosen = row["cede"] > 0.5 - mark = "CEDE " if chosen else "keep " - if chosen: - total_premium += row["premium"] - total_ceded += row["excess"] + mark = "CEDE " if row["cede"] > 0.5 else "keep " print( f" {mark} {row['name']:<22} exposure " f"${row['exposure']:>11,.0f} excess ${row['excess']:>9,.0f} " f"premium ${row['premium']:>8,.0f}" ) - if len(over) and ceded.empty: + if n_breached and ceded.empty: print(" No cession plan: the solve returned no solution (see the status above).") else: print( - f" -> ceded ${total_ceded:,.0f} of excess exposure for " - f"${total_premium:,.0f} premium (of ${REINSURANCE_BUDGET:,.0f})" + f" -> ceded ${float(published(ceded_excess)):,.0f} of excess exposure for " + f"${float(published(ceded_premium)):,.0f} premium (of ${REINSURANCE_BUDGET:,.0f})" ) - auto_entity = dict(zip(resolved["record_id"], resolved["entity_id"])) - coverage_by_record = dict(zip(resolved["record_id"], resolved["coverage_amount"])) - confirmed = {record_id: auto_entity[record_id] for record_id in record_ids} - for _, row in review_df.iterrows(): - rec_a, rec_b = int(row["rec_a"]), int(row["rec_b"]) - target, source = confirmed[rec_a], confirmed[rec_b] - for record_id in record_ids: - if confirmed[record_id] == source: - confirmed[record_id] = target - confirmed_exposure: dict[str, float] = {} - for record_id in record_ids: - party_id = confirmed[record_id] - confirmed_exposure[party_id] = ( - confirmed_exposure.get(party_id, 0.0) + coverage_by_record[record_id] - ) - confirmed_breaches = sum( - 1 for exposure in confirmed_exposure.values() if exposure > ACCUMULATION_LIMIT - ) print("\n" + "=" * 64) print("Review queue") print("=" * 64) - print(f"Pairs held for steward review: {len(review_df)}") + print(f"Pairs held for steward review: {n_review}") print( "Breaches surfaced only if the review queue is confirmed: " - f"{confirmed_breaches - len(over)} " - f"(resolution would then show {confirmed_breaches} breached " - f"households, not {len(over)})" + f"{int(published(num_surfaced_breaches))} " + f"(resolution would then show {int(published(num_confirmed_breaches))} breached " + f"households, not {n_breached})" ) truth_df = load_ground_truth() @@ -191,6 +165,10 @@ "in data/ground_truth.csv" ) else: + review_df = model.select( + ReviewPair.rec_a.record_id.alias("rec_a"), + ReviewPair.rec_b.record_id.alias("rec_b"), + ).to_df() true_pairs = { (rec_a, rec_b) for rec_a, rec_b in combinations(record_ids, 2) diff --git a/entity_resolution/runbook.md b/entity_resolution/runbook.md index e7ca2d05..7421bd80 100644 --- a/entity_resolution/runbook.md +++ b/entity_resolution/runbook.md @@ -38,7 +38,7 @@ record level, and cedes $927k of excess exposure to reinsurance for $111k. > **How to use this walkthrough.** Each section below is a Prompt that an analyst pastes into a fresh agent session loaded with the named `/rai-*` skill. Prompts are designed to run **in order, in a single session** — every step relies on enrichments the previous steps wrote back to the shared ontology, so the agent inherits accumulated model state across prompts. -Keep the shared declarations in `model/schema.py`, source preparation and fact loading in `model/source.py`, graph, rules-based, and prescriptive reasoning in `model/reasoning.py`, and the queries and reporting that read the deployed model in `queries/resolution_report.py`. +Keep the shared declarations in `model/schema.py`, source preparation and fact loading in `model/source.py`, graph clustering in `model/match_graph.py`, match bands in `model/match_bands.py`, resolved parties and their exposure in `model/resolved_parties.py`, the review queue in `model/review_queue.py`, reinsurance cessions in `model/reinsurance_cessions.py`, and the queries and reporting that read the deployed model in `queries/resolution_report.py`. ### 1. Build the ontology @@ -81,7 +81,7 @@ Blocking reduces 1,275 possible pairs to 28 candidates. 25 score >= 0.70 and loa **Prompt** ``` -/rai-graph-analysis In model/reasoning.py, determine which records refer to the same insured party. Treat each CandidateMatch as an undirected link and group records connected directly or through a chain of matches into one party (connected components). Weakly-connected-components returns the representative record, so also derive a stable integer party key from it, and report how many parties the 51 records auto-resolve into. +/rai-graph-analysis In model/match_graph.py, determine which records refer to the same insured party. Treat each CandidateMatch as an undirected link and group records connected directly or through a chain of matches into one party (connected components). Weakly-connected-components returns the representative record, so also derive a stable integer party key from it, and report how many parties the 51 records auto-resolve into. ``` **Response** @@ -98,14 +98,14 @@ Weakly-connected-components over 51 nodes and 25 auto-merge edges resolves the r **Response** -`CandidateMatch.confidence_tier` set to HIGH (20) or MEDIUM (5) across the 25 auto-merge matches. `Record.is_duplicate` flags 35 records -- every record sharing its party with at least one other -- derived by counting records per `entity_key` and flagging parties of size two or more. +`CandidateMatch.confidence_tier` set to HIGH (20) or MEDIUM (5) across the 25 auto-merge matches. `Record.is_duplicate` flags 35 records -- every record sharing its party with at least one other -- derived from each party's record count (`ResolvedParty.n_records`), flagging the records of parties of size two or more. ### 6. Aggregate exposure and flag accumulation breaches **Prompt** ``` -/rai-pyrel Declare ResolvedParty and its stable properties and relationships in model/schema.py. In model/reasoning.py, create one ResolvedParty per party key, relate each Record to its party, total the coverage across its policies, and flag parties whose total exposure exceeds the $1,000,000 accumulation limit. How many policies breach the limit at the record level versus how many households breach it after resolution? +/rai-pyrel Declare ResolvedParty and its stable properties and relationships in model/schema.py. In model/resolved_parties.py, create one ResolvedParty per party key, relate each Record to its party, total the coverage across its policies, and flag parties whose total exposure exceeds the $1,000,000 accumulation limit. How many policies breach the limit at the record level versus how many households breach it after resolution? ``` **Response** @@ -117,7 +117,7 @@ A `ResolvedParty` per party key carries `total_exposure` (summed `coverage_amoun **Prompt** ``` -/rai-prescriptive-problem In model/reasoning.py, choose reinsurance cessions for the breached parties. We can spend a $120,000 reinsurance premium this period, at a 12% rate on line, to cede the excess exposure of breached households (premium = 12% of the amount over the limit). Which households should we cede to transfer the most excess exposure off the book? Each breached household is cede-or-not (binary), total premium must stay within budget, and we maximize the excess exposure ceded. +/rai-prescriptive-problem In model/reinsurance_cessions.py, choose reinsurance cessions for the breached parties. We can spend a $120,000 reinsurance premium this period, at a 12% rate on line, to cede the excess exposure of breached households (premium = 12% of the amount over the limit). Which households should we cede to transfer the most excess exposure off the book? Each breached household is cede-or-not (binary), total premium must stay within budget, and we maximize the excess exposure ceded. ``` **Response** @@ -129,7 +129,7 @@ A binary `ResolvedParty.cede` over the 4 breached households; budget constraint **Prompt** ``` -/rai-pyrel In queries/resolution_report.py, query the deployed model to report how many matches are held in the review queue and whether confirming them changes the accumulation picture. Also score the auto-resolution against the data/ground_truth.csv labels: pairwise precision, recall, and F1. +/rai-pyrel In model/review_queue.py, work out whether confirming the pairs held in the review queue changes the accumulation picture: cluster the records over the accepted and review pairs, total each confirmed party's coverage, and count the parties over the limit. In queries/resolution_report.py, report how many pairs are held in the review queue and that result, and score the auto-resolution against the data/ground_truth.csv labels: pairwise precision, recall, and F1. ``` **Response** @@ -138,4 +138,4 @@ A binary `ResolvedParty.cede` over the 4 breached households; budget constraint ## Data -Bundled CSVs in `data/`: `records.csv` (51 policy records across AUTO / HOME / LIFE / LEGACY, covering 30 people, with per-policy `coverage_amount`) and `ground_truth.csv` (record_id → true party label). Three cases are placed deliberately: a transitive chain (`M. O'Brien`) that only clustering resolves, a same-name trap (two distinct Chicago "John Smith" policyholders) that scoring keeps apart, and a review-band duplicate (`Ethan Brooks` / `E. Brooks`) whose hidden combined exposure breaches the limit only once confirmed. The dataset is fixed and hand-curated so the walkthrough's numbers are stable. `model/source.py` reads and loads the data; `model/reasoning.py` declares the reasoning chain, and `queries/resolution_report.py` reports from the deployed model. +Bundled CSVs in `data/`: `records.csv` (51 policy records across AUTO / HOME / LIFE / LEGACY, covering 30 people, with per-policy `coverage_amount`) and `ground_truth.csv` (record_id → true party label). Three cases are placed deliberately: a transitive chain (`M. O'Brien`) that only clustering resolves, a same-name trap (two distinct Chicago "John Smith" policyholders) that scoring keeps apart, and a review-band duplicate (`Ethan Brooks` / `E. Brooks`) whose hidden combined exposure breaches the limit only once confirmed. The dataset is fixed and hand-curated so the walkthrough's numbers are stable. `model/source.py` reads and loads the data; the other modules in `model/` declare the reasoning chain, and `queries/resolution_report.py` reports from the deployed model. diff --git a/entity_resolution/template-docs.yaml b/entity_resolution/template-docs.yaml index 0c1bbb07..80f8eb0f 100644 --- a/entity_resolution/template-docs.yaml +++ b/entity_resolution/template-docs.yaml @@ -203,9 +203,9 @@ guided_walkthrough: representative ID, giving later calculations a key for the insured party. focus: - file: model/reasoning.py + file: model/match_graph.py anchors: - - start: 'def cluster_accepted_matches():' + - start: 'graph = Graph(model, directed=False, weighted=False, node_concept=Record, name="match_graph")' end: Record.entity_key(rep_node.record_id) end_offset: 1 references: @@ -244,7 +244,7 @@ guided_walkthrough: ResolvedParty.excess(...) measures how much coverage exceeds it for the reinsurance decision. focus: - file: model/reasoning.py + file: model/resolved_parties.py anchors: - start: model.define(ResolvedParty.new(key=Record.entity_key)) end: ResolvedParty.total_exposure - ACCUMULATION_LIMIT @@ -262,7 +262,7 @@ guided_walkthrough: ResolvedParty.total_exposure(...): anchor: start: party_record = Record.ref() - end: aggregates.sum(party_record.coverage_amount).per(ResolvedParty) + end: aggs.sum(party_record, party_record.coverage_amount).per(ResolvedParty) end_offset: 2 ACCUMULATION_LIMIT: anchor: @@ -292,10 +292,10 @@ guided_walkthrough: limit. Each refresh of the deployed model runs that solve, though a small budget may leave some excess with the insurer. focus: - file: model/reasoning.py + file: model/reinsurance_cessions.py anchors: - - start: 'def choose_reinsurance_cessions():' - end: return problem + - start: 'problem = Problem(model, Float, name="entity_resolution")' + end: problem.configure("highs", time_limit_sec=60) references: Problem(model, Float): anchor: @@ -318,7 +318,7 @@ guided_walkthrough: problem.maximize(...): anchor: start: problem.maximize( - end: aggregates.sum(ResolvedParty.excess * ResolvedParty.cede) + end: aggs.sum(ResolvedParty.excess * ResolvedParty.cede) end_offset: 1 problem.configure(...): anchor: diff --git a/factory_production/README.md b/factory_production/README.md index 4e10e075..d6fd21cc 100644 --- a/factory_production/README.md +++ b/factory_production/README.md @@ -41,7 +41,7 @@ Manufacturing operations must decide how much of each product to make at each fa ## What's included -- `model/` -- the deployed model package, deployed with `rai models deploy --path model`: `schema.py` declares the concepts, `source.py` loads the sample data and checks it, `reasoning.py` states the constraints, objective, and the solve with sensitivity analysis +- `model/` -- the deployed model package, deployed with `rai models deploy --path model`: `schema.py` declares the concepts, `source.py` loads the sample data and checks it, `production_plan.py` states the constraints, objective, and the solve with sensitivity analysis, `plan_marginals.py` publishes the shadow prices, reduced costs, basis statuses, and the capacity ranking, and `capacity_utilization.py` publishes each factory's hours used and idle - `queries/plan_and_sensitivity.py` -- the report from the deployed model: production plan, shadow prices, reduced costs, basis statuses, and capacity utilization - `runbook.md` -- a paste-testable walkthrough that reproduces the template step by step with the RAI skills; as important a reference as the script itself - `data/factories.csv` -- Factory names and available resource-hours @@ -221,7 +221,9 @@ Use this sequence to deploy the model and query it: │ ├── __init__.py # exports of the deployed model │ ├── schema.py # concepts and properties │ ├── source.py # sample data and its checks -│ └── reasoning.py # LP, sensitivity solve, and the published status, objective, and marginals +│ ├── production_plan.py # LP, sensitivity solve, and the published status and objective +│ ├── plan_marginals.py # published shadow prices, reduced costs, basis statuses, and capacity ranking +│ └── capacity_utilization.py # published hours used and idle hours per factory ├── queries/ │ └── plan_and_sensitivity.py # report and sensitivity read-back from the deployed model └── data/ @@ -274,7 +276,7 @@ Because the objective is a maximization, the signs mirror a minimize-cost model: Sensitivity marginals are exact for a linear program. They describe the rate of change at the current optimum -- the range over which that rate holds is not reported (there is no RHS/coefficient ranging) -- and a large, discrete change (adding a factory, removing a product) is a structural change best answered by re-solving. -See `model/reasoning.py` and `queries/plan_and_sensitivity.py` for the implementation and `runbook.md` for the skill-driven reproduction. +See `model/production_plan.py`, `model/plan_marginals.py`, `model/capacity_utilization.py`, and `queries/plan_and_sensitivity.py` for the implementation and `runbook.md` for the skill-driven reproduction. ## Customize this template diff --git a/factory_production/model/__init__.py b/factory_production/model/__init__.py index 36362e5f..f95b4207 100644 --- a/factory_production/model/__init__.py +++ b/factory_production/model/__init__.py @@ -41,6 +41,14 @@ constraint name string. (A variable's back-pointer, such as ``quantity_var.product``, is derived automatically from its field names; a constraint's is declared.) +The model is split by concern, and each module imports the modules whose declarations it reads: + +- `production_plan.py`: the product-mix LP, its solve with sensitivity analysis, and the solve's + status and objective. +- `plan_marginals.py`: the shadow prices, reduced costs, and basis statuses, and the ranking of the + capacities by shadow price. +- `capacity_utilization.py`: the hours each factory's plan uses and leaves idle. + Run: `rai models deploy --path model` deploys this package to the schemas in raiconfig.yaml and waits for its first refresh, which runs the solve. Then @@ -49,23 +57,26 @@ per-factory capacity-utilization summary from the deployed model. """ -from .reasoning import ( +from .capacity_utilization import FactoryHoursUsed, FactoryIdleHours +from .plan_marginals import ( + CapacityPriceRank, CapacityShadowPrice, ProductBasisStatus, ProductReducedCost, - SolveStatus, - TotalProfit, - problem, ) +from .production_plan import SolveStatus, TotalProfit, problem from .schema import Factory, Product, model from .source import DATA_DIR, EXPECTED_FACTORIES, EXPECTED_PRODUCTS __all__ = [ + "CapacityPriceRank", "CapacityShadowPrice", "DATA_DIR", "EXPECTED_FACTORIES", "EXPECTED_PRODUCTS", "Factory", + "FactoryHoursUsed", + "FactoryIdleHours", "Product", "ProductBasisStatus", "ProductReducedCost", diff --git a/factory_production/model/capacity_utilization.py b/factory_production/model/capacity_utilization.py new file mode 100644 index 00000000..c32114cb --- /dev/null +++ b/factory_production/model/capacity_utilization.py @@ -0,0 +1,26 @@ +"""Capacity utilization: the hours each factory's plan uses and the hours it leaves idle.""" + +from relationalai.semantics import Float, sum + +# Declares Product.x_quantity, the solved quantity the hours are computed from. +from . import production_plan # noqa: F401 +from .schema import Factory, Product, model + +# Each product takes quantity / rate hours of its factory, and a factory uses the sum over its +# products. These are relationships, not Factory properties: the solve reads Factory, and a +# Factory property computed from the solution fails the deploy. +FactoryHoursUsed = model.Relationship(f"{Factory} uses {Float:hours_used} hours") +model.define( + FactoryHoursUsed( + Factory, + sum(Product, Product.x_quantity / Product.rate).where(Product.factory == Factory).per(Factory), + ) +) + +# The hours a factory's plan leaves unused. A capacity with idle hours is slack, so its +# shadow price is zero. +FactoryIdleHours = model.Relationship(f"{Factory} leaves {Float:idle_hours} hours idle") +hours_used = Float.ref() +model.where(FactoryHoursUsed(Factory, hours_used)).define( + FactoryIdleHours(Factory, Factory.avail - hours_used) +) diff --git a/factory_production/model/plan_marginals.py b/factory_production/model/plan_marginals.py new file mode 100644 index 00000000..106c6130 --- /dev/null +++ b/factory_production/model/plan_marginals.py @@ -0,0 +1,35 @@ +"""Plan marginals: each factory capacity's shadow price, each product's reduced cost and basis status, +and the ranking of the capacities by shadow price.""" + +from relationalai.semantics import Float, Integer, String +from relationalai.semantics.std import aggregates as aggs + +from .production_plan import cap, quantity_var +from .schema import Factory, Product, model + +# The sensitivity marginals, which the deployed model publishes for the queries: each factory +# capacity's shadow price and each product's reduced cost and basis status, keyed by the entity +# they belong to. +capacity_price, reduced_cost, basis_status = Float.ref(), Float.ref(), String.ref() +CapacityShadowPrice = model.Relationship(f"{Factory} has capacity shadow price {Float:shadow_price}") +ProductReducedCost = model.Relationship(f"{Product} has reduced cost {Float:reduced_cost}") +ProductBasisStatus = model.Relationship(f"{Product} has basis status {String:basis_status}") +model.where(cap.shadow_price(capacity_price)).define( + CapacityShadowPrice(cap.factory, capacity_price) +) +model.where(quantity_var.reduced_cost(reduced_cost)).define( + ProductReducedCost(quantity_var.product, reduced_cost) +) +model.where(quantity_var.basis_status(basis_status)).define( + ProductBasisStatus(quantity_var.product, basis_status) +) + +# The capacities ranked by shadow price, largest first, ties broken by factory name. With a +# maximize objective every shadow price is >= 0, so the first is the factory whose marginal +# hour earns the most: the capacity to expand first. The price is negated so both keys sort +# ascending, a form every backend ranks. +CapacityPriceRank = model.Relationship(f"{Factory} ranks {Integer:rank} by capacity shadow price") +model.where( + CapacityShadowPrice(Factory, capacity_price), + capacity_rank := aggs.rank(-capacity_price, Factory.name), +).define(CapacityPriceRank(Factory, capacity_rank)) diff --git a/factory_production/model/reasoning.py b/factory_production/model/production_plan.py similarity index 75% rename from factory_production/model/reasoning.py rename to factory_production/model/production_plan.py index 1bee62af..d5b84020 100644 --- a/factory_production/model/reasoning.py +++ b/factory_production/model/production_plan.py @@ -1,4 +1,5 @@ -"""Factory production decision problem: maximize profit, with the marginals of one sensitivity solve.""" +"""Production plan: the product-mix LP that maximizes profit within each factory's capacity, solved +with sensitivity analysis, and the solve's status and objective.""" from relationalai.semantics import Float, String, sum from relationalai.semantics.reasoners.prescriptive import Problem @@ -57,23 +58,6 @@ TotalProfit = model.Relationship(f"factory production total profit is {Float:profit}") model.define(SolveStatus(problem.termination_status()), TotalProfit(problem.objective_value())) -# The sensitivity marginals, which the deployed model publishes for the queries: each factory -# capacity's shadow price and each product's reduced cost and basis status, keyed by the entity -# they belong to. -capacity_price, reduced_cost, basis_status = Float.ref(), Float.ref(), String.ref() -CapacityShadowPrice = model.Relationship(f"{Factory} has capacity shadow price {Float:shadow_price}") -ProductReducedCost = model.Relationship(f"{Product} has reduced cost {Float:reduced_cost}") -ProductBasisStatus = model.Relationship(f"{Product} has basis status {String:basis_status}") -model.where(cap.shadow_price(capacity_price)).define( - CapacityShadowPrice(cap.factory, capacity_price) -) -model.where(quantity_var.reduced_cost(reduced_cost)).define( - ProductReducedCost(quantity_var.product, reduced_cost) -) -model.where(quantity_var.basis_status(basis_status)).define( - ProductBasisStatus(quantity_var.product, basis_status) -) - # -------------------------------------------------- # Customize # -------------------------------------------------- diff --git a/factory_production/queries/plan_and_sensitivity.py b/factory_production/queries/plan_and_sensitivity.py index be0afe3e..eb4a6c13 100644 --- a/factory_production/queries/plan_and_sensitivity.py +++ b/factory_production/queries/plan_and_sensitivity.py @@ -11,8 +11,11 @@ from model import ( EXPECTED_FACTORIES, EXPECTED_PRODUCTS, + CapacityPriceRank, CapacityShadowPrice, Factory, + FactoryHoursUsed, + FactoryIdleHours, Product, ProductBasisStatus, ProductReducedCost, @@ -20,7 +23,7 @@ TotalProfit, model, ) -from relationalai.semantics import Float, String +from relationalai.semantics import Float, Integer, String if __name__ == "__main__": status = model.select(SolveStatus).to_df().iloc[:, 0].tolist() @@ -38,13 +41,11 @@ raise SystemExit(f"total profit changed: expected 200000, got {profit}") # --- The solved production plan ------------------------------------------------- - # Read populated quantities once for the plan checks and capacity summary. + # Read populated quantities once for the plan checks. plan_df = ( model.select( Product.factory.name.alias("factory"), Product.name.alias("product"), - Product.factory.avail.alias("avail"), - Product.rate.alias("rate"), Product.x_quantity.alias("quantity"), ) .to_df() @@ -137,11 +138,22 @@ # --- Acting on it: which factory's capacity is the bottleneck? ------------------ # With a maximize objective every capacity shadow price is >= 0, so the largest one is - # the factory whose marginal hour earns the most -- the capacity to expand first. - bottleneck = max(zip(cap_df["factory"], cap_df["shadow_price"]), key=lambda fp: fp[1]) + # the factory whose marginal hour earns the most -- the capacity to expand first. The + # model ranks the capacities by shadow price; the bottleneck is the first. + price_rank = Integer.ref() + bottleneck = ( + model.select(Factory.name.alias("factory"), shadow_price.alias("shadow_price")) + .where( + CapacityShadowPrice(Factory, shadow_price), + CapacityPriceRank(Factory, price_rank), + price_rank == 1, + ) + .to_df() + .iloc[0] + ) print( - f"\nMost profit-sensitive capacity: {bottleneck[0]} " - f"(d profit / d hour = {bottleneck[1]:+.2f})" + f"\nMost profit-sensitive capacity: {bottleneck['factory']} " + f"(d profit / d hour = {float(bottleneck['shadow_price']):+.2f})" ) # -------------------------------------------------- @@ -150,14 +162,20 @@ # Ties the shadow prices above back to the plan: in this data the binding factory has # zero idle hours and a positive shadow price, while idle hours mean slack and a zero # price. Only idle => zero-price holds in general; a binding capacity can still price at - # zero under degeneracy, so read the prices, not just the idle column. - plan_df["hours"] = plan_df["quantity"] / plan_df["rate"] + # zero under degeneracy, so read the prices, not just the idle column. The model + # publishes each factory's hours used and idle hours. + hours_used, idle_hours = Float.ref(), Float.ref() util = ( - plan_df.groupby("factory") - .agg(avail=("avail", "first"), hours_used=("hours", "sum")) - .reset_index() + model.select( + Factory.name.alias("factory"), + Factory.avail.alias("avail"), + hours_used.alias("hours_used"), + idle_hours.alias("idle"), + ) + .where(FactoryHoursUsed(Factory, hours_used), FactoryIdleHours(Factory, idle_hours)) + .to_df() + .sort_values("factory", ignore_index=True) ) - util["idle"] = util["avail"] - util["hours_used"] print("\n" + "=" * 50) print("Factory Capacity Summary") print("=" * 50) diff --git a/financial_index_replication/model/__init__.py b/financial_index_replication/model/__init__.py index 538a7a68..d588b0f8 100644 --- a/financial_index_replication/model/__init__.py +++ b/financial_index_replication/model/__init__.py @@ -1,23 +1,35 @@ """Financial index replication model: bundled sample data and the decision problem. +Modules: `portfolio_selection.py` (the replication policy and the decision problem that picks +the basket), `tracking_quality.py` (monthly replica returns against the index and their tracking +error), and `portfolio_exposure.py` (sector exposure and turnover). Each module imports the +modules whose declarations it reads. + `rai models deploy --path model` deploys everything this package declares. """ -from .reasoning import ( +from .portfolio_exposure import ImpliedTurnover, SectorExposure +from .portfolio_selection import ( MAX_ADV_PARTICIPATION, MAX_WEIGHT, - MONTHS_PER_YEAR, N_REPLICATION_NAMES, PORTFOLIO_VALUE, SECTOR_ACTIVE_BAND, SolveStatus, TotalResidual, + num_stocks, selected, stock_return, weight, ) from .schema import ReturnMonth, Sector, Stock, model from .source import DATA_DIR +from .tracking_quality import ( + MONTHS_PER_YEAR, + AnnualizedTrackingError, + MeanAbsResidual, + TrackingMonth, +) __all__ = [ "DATA_DIR", @@ -27,12 +39,18 @@ "N_REPLICATION_NAMES", "PORTFOLIO_VALUE", "SECTOR_ACTIVE_BAND", + "AnnualizedTrackingError", + "ImpliedTurnover", + "MeanAbsResidual", "ReturnMonth", "Sector", + "SectorExposure", "SolveStatus", "Stock", "TotalResidual", + "TrackingMonth", "model", + "num_stocks", "selected", "stock_return", "weight", diff --git a/financial_index_replication/model/portfolio_exposure.py b/financial_index_replication/model/portfolio_exposure.py new file mode 100644 index 00000000..169eb44e --- /dev/null +++ b/financial_index_replication/model/portfolio_exposure.py @@ -0,0 +1,45 @@ +"""Portfolio exposure: each sector's solved weight against its benchmark weight, and the turnover +from the previous portfolio that the solved weights imply.""" + +from relationalai.semantics import Float, String +from relationalai.semantics.std import aggregates as aggs +from relationalai.semantics.std import math + +# Declares Stock.x_weight, the solved replication weights the exposures read. +from . import portfolio_selection # noqa: F401 +from .schema import Sector, Stock, model + +# -------------------------------------------------- +# Sector exposure +# -------------------------------------------------- + +# One row per sector, kept apart from Sector: the solve reads Sector, so a property +# computed from the solution there fails the deploy. +SectorExposure = model.Concept("SectorExposure", identify_by={"sector_name": String}) +SectorExposure.weight = model.Property(f"{SectorExposure} holds {Float:weight} of the portfolio") +SectorExposure.benchmark_weight = model.Property( + f"{SectorExposure} has benchmark weight {Float:benchmark_weight}" +) +SectorExposure.active_weight = model.Property( + f"{SectorExposure} has active weight {Float:active_weight}" +) +model.define(SectorExposure.new(sector_name=Sector.sector_name)) +model.define( + SectorExposure.weight( + aggs.sum(Stock, Stock.x_weight) + .per(SectorExposure) + .where(Stock.sector == SectorExposure.sector_name) + ) +) +model.define(SectorExposure.benchmark_weight(Sector.benchmark_weight)).where( + Sector.sector_name == SectorExposure.sector_name +) +model.define(SectorExposure.active_weight(SectorExposure.weight - SectorExposure.benchmark_weight)) + +# -------------------------------------------------- +# Turnover +# -------------------------------------------------- + +# Implied turnover: the sum over stocks of the absolute change from the previous weight. +ImpliedTurnover = model.Relationship(f"the replica's implied turnover is {Float:turnover}") +model.define(ImpliedTurnover(aggs.sum(Stock, math.abs(Stock.x_weight - Stock.previous_weight)))) diff --git a/financial_index_replication/model/reasoning.py b/financial_index_replication/model/portfolio_selection.py similarity index 90% rename from financial_index_replication/model/reasoning.py rename to financial_index_replication/model/portfolio_selection.py index ff934fe2..7f1ce4fa 100644 --- a/financial_index_replication/model/reasoning.py +++ b/financial_index_replication/model/portfolio_selection.py @@ -1,7 +1,8 @@ -"""Sparse index replication: decision problem and solver settings. +"""Portfolio selection: the number of stocks in the universe, the replication policy, the decision +problem that picks the basket, and the solver settings. -Declares, at module level, everything the deployment needs beyond the source -facts in `model/source.py`: +Declares, at module level, everything the deployment needs to choose the basket +beyond the source facts in `model/source.py`: - Choose exactly 20 names and their portfolio weights. - Minimize full-history tracking residuals versus the benchmark. @@ -13,8 +14,9 @@ `queries/replication_report.py` prints the report from the deployed model. """ -from relationalai.semantics import Float, String, sum +from relationalai.semantics import Float, Integer, String, sum from relationalai.semantics.reasoners.prescriptive import Problem +from relationalai.semantics.std import aggregates as aggs from .schema import ReturnMonth, Sector, Stock, model from .source import stocks_csv @@ -28,7 +30,6 @@ SECTOR_ACTIVE_BAND = 0.04 PORTFOLIO_VALUE = 10_000_000 MAX_ADV_PARTICIPATION = 0.05 -MONTHS_PER_YEAR = 12 # Basic feasibility checks before building and solving the optimization model. eligible_stock_count = stocks_csv["ticker"].nunique() @@ -43,6 +44,10 @@ f"investment, got {N_REPLICATION_NAMES * MAX_WEIGHT:.2f}." ) +# The number of stocks the basket is chosen from. +num_stocks = model.Relationship(f"the universe has {Integer:n_stocks} stocks") +model.define(num_stocks(aggs.count(Stock))) + # -------------------------------------------------- # Model the decision problem # -------------------------------------------------- diff --git a/financial_index_replication/model/tracking_quality.py b/financial_index_replication/model/tracking_quality.py new file mode 100644 index 00000000..bf4d28c4 --- /dev/null +++ b/financial_index_replication/model/tracking_quality.py @@ -0,0 +1,70 @@ +"""Tracking quality: each month's replica return and its difference from the index, and the +annualized tracking error and mean absolute residual that summarize them.""" + +from relationalai.semantics import Float, String +from relationalai.semantics.std import aggregates as aggs +from relationalai.semantics.std import math + +# Declares Stock.x_weight, the solved replication weights the replica return reads. +from . import portfolio_selection # noqa: F401 +from .schema import ReturnMonth, Stock, model + +# -------------------------------------------------- +# Configure inputs +# -------------------------------------------------- + +MONTHS_PER_YEAR = 12 + +# -------------------------------------------------- +# Monthly returns and differences from the index +# -------------------------------------------------- + +# One row per month, kept apart from ReturnMonth: the solve reads ReturnMonth, so a +# property computed from the solution there fails the deploy. +TrackingMonth = model.Concept("TrackingMonth", identify_by={"date": String}) +TrackingMonth.replica_return = model.Property( + f"{TrackingMonth} has replica return {Float:replica_return}" +) +TrackingMonth.replica_difference = model.Property( + f"{TrackingMonth} has replica difference {Float:replica_difference}" +) +model.define(TrackingMonth.new(date=ReturnMonth.date)) + +# The replica's return is the weighted sum of the stock returns of the month, and its +# difference is that return less the index return. A month without stock returns has neither. +_return = Float.ref() +_priced = (Stock.monthly_return(ReturnMonth, _return), ReturnMonth.date == TrackingMonth.date) +model.define( + TrackingMonth.replica_return( + aggs.sum(Stock, Stock.x_weight * _return).per(TrackingMonth).where(*_priced) + ) +) +model.where(ReturnMonth.date == TrackingMonth.date).define( + TrackingMonth.replica_difference(TrackingMonth.replica_return - ReturnMonth.index_return) +) + +# -------------------------------------------------- +# Summary measures +# -------------------------------------------------- + +# Annualized tracking error: the root mean square of the monthly differences, +# scaled by the square root of the months in a year. +AnnualizedTrackingError = model.Relationship( + f"the replica's annualized tracking error is {Float:tracking_error}" +) +model.define( + AnnualizedTrackingError( + math.sqrt( + aggs.avg( + TrackingMonth, TrackingMonth.replica_difference * TrackingMonth.replica_difference + ) + ) + * math.sqrt(MONTHS_PER_YEAR) + ) +) + +# Mean absolute monthly difference of the replica from the index. +MeanAbsResidual = model.Relationship( + f"the replica's mean absolute monthly residual is {Float:residual}" +) +model.define(MeanAbsResidual(aggs.avg(TrackingMonth, math.abs(TrackingMonth.replica_difference)))) diff --git a/financial_index_replication/queries/replication_report.py b/financial_index_replication/queries/replication_report.py index 4da9b035..0dedf9a8 100644 --- a/financial_index_replication/queries/replication_report.py +++ b/financial_index_replication/queries/replication_report.py @@ -21,23 +21,33 @@ N_REPLICATION_NAMES, PORTFOLIO_VALUE, SECTOR_ACTIVE_BAND, + AnnualizedTrackingError, + ImpliedTurnover, + MeanAbsResidual, ReturnMonth, - Sector, + SectorExposure, SolveStatus, Stock, TotalResidual, + TrackingMonth, model, + num_stocks, selected, stock_return, weight, ) + +def published(relationship): + """The one figure a nullary relationship of the model publishes.""" + return model.select(relationship).to_df().iloc[0, 0] + + if __name__ == "__main__": print("=" * 70) print("FINANCIAL INDEX REPLICATION") print("=" * 70) - n_stocks = len(model.select(Stock.ticker).to_df()) - print(f"Universe: {n_stocks} stocks") + print(f"Universe: {published(num_stocks)} stocks") print(f"Selected names: exactly {N_REPLICATION_NAMES}") print(f"Max position: {MAX_WEIGHT:.0%}") print(f"Sector active band: +/- {SECTOR_ACTIVE_BAND:.0%}") @@ -109,15 +119,6 @@ unpriced = [t for t in weights.index if t not in returns_wide or returns_wide[t].isna().any()] if unpriced: raise SystemExit(f"Held stocks {unpriced} lack a monthly return in the deployed model.") - portfolio_returns = returns_wide[weights.index].mul(weights, axis=1).sum(axis=1) - tracking_diff = portfolio_returns - index_series["index_return"] - - def annualized_tracking_error(): - monthly_rms = sqrt((tracking_diff ** 2).mean()) - return monthly_rms * sqrt(MONTHS_PER_YEAR) - - def mean_abs_tracking(): - return tracking_diff.abs().mean() print("\n=== Selected Replication Basket ===") print( @@ -141,19 +142,12 @@ def mean_abs_tracking(): ) ) - sector_report = ( - solution_df.groupby("sector", as_index=False)["weight"].sum() - .merge( - model.select( - Sector.sector_name.alias("sector"), - Sector.benchmark_weight.alias("benchmark_weight"), - ).to_df(), - on="sector", - ) - ) - sector_report["active_weight"] = ( - sector_report["weight"] - sector_report["benchmark_weight"] - ) + sector_report = model.select( + SectorExposure.sector_name.alias("sector"), + SectorExposure.weight.alias("weight"), + SectorExposure.benchmark_weight.alias("benchmark_weight"), + SectorExposure.active_weight.alias("active_weight"), + ).to_df() print("\n=== Sector Exposure ===") print( @@ -167,24 +161,13 @@ def mean_abs_tracking(): ) ) - previous_df = model.select( - Stock.ticker.alias("ticker"), - Stock.previous_weight.alias("previous_weight"), - ).to_df() - turnover = ( - solution_df.set_index("ticker")["weight"] - .reindex(previous_df["ticker"], fill_value=0.0) - .sub(previous_df.set_index("ticker")["previous_weight"]) - .abs() - .sum() - ) - print("\n=== Tracking Quality ===") - print(f"Annualized tracking error: {annualized_tracking_error():.2%}") - print(f"Mean abs monthly residual: {mean_abs_tracking():.4%}") - print(f"Implied turnover: {turnover:.2%}") + print(f"Annualized tracking error: {published(AnnualizedTrackingError):.2%}") + print(f"Mean abs monthly residual: {published(MeanAbsResidual):.4%}") + print(f"Implied turnover: {published(ImpliedTurnover):.2%}") - # Simple benchmark: equal-weight the 20 most correlated stocks. + # Simple benchmark: equal-weight the 20 most correlated stocks. It stays in pandas, whose + # ranking keeps a stock with an undefined correlation (constant returns) last. top_corr_ids = ( returns_wide .corrwith(index_series["index_return"]) @@ -200,11 +183,20 @@ def mean_abs_tracking(): MONTHS_PER_YEAR ) + # Every index month is written; a month without stock returns has an empty replica return. + replica_returns = ( + model.select( + TrackingMonth.date.alias("date"), + TrackingMonth.replica_return.alias("replica_return"), + ) + .to_df() + .set_index("date")["replica_return"] + ) replica_returns_csv = DATA_DIR / "replica_returns.csv" pd.DataFrame({ "date": index_series.index, "index_return": index_series["index_return"].values, - "replica_return": portfolio_returns.reindex(index_series.index).values, + "replica_return": replica_returns.reindex(index_series.index).values, }).to_csv(replica_returns_csv, index=False) print("\n=== Baseline Comparison ===") diff --git a/financial_index_replication/runbook.md b/financial_index_replication/runbook.md index e65a625a..d76db232 100644 --- a/financial_index_replication/runbook.md +++ b/financial_index_replication/runbook.md @@ -39,7 +39,7 @@ Each prompt is pasted into a fresh agent session loaded with the named `/rai-*` **Prompt:** /rai-prescriptive-problem Which 20 stocks, and at what weights, best replicate the benchmark's monthly returns? Select exactly 20 names (binary) and assign continuous weights that sum to 1, with at most 10% in any one name and a weight only if the name is selected; keep each sector within ±4% of its benchmark weight; respect a trading-capacity limit (the change from the previous weight, scaled by a $10 million portfolio value, can't exceed 5% of a stock's average dollar volume); and define each month's tracking residual as benchmark return minus basket return. Minimize the total absolute monthly tracking error, and persist the selection and weights to the ontology. -**Response:** `model/reasoning.py` returns a 20-name basket. The decision is `Stock.x_selected` (exactly 20 names) plus `Stock.x_weight` (summing to 1) and per-month residual variables. This is a cardinality-constrained tracking MILP: depending on the solver it either solves to OPTIMAL or returns a strong feasible incumbent at the time limit — either way the exact names and weights can vary, so treat the tracking quality below, not a specific basket, as the result. In `model/reasoning.py` the solve is declared with `problem.configure(...)`, so each refresh of the deployed model runs it. +**Response:** `model/portfolio_selection.py` returns a 20-name basket. The decision is `Stock.x_selected` (exactly 20 names) plus `Stock.x_weight` (summing to 1) and per-month residual variables. This is a cardinality-constrained tracking MILP: depending on the solver it either solves to OPTIMAL or returns a strong feasible incumbent at the time limit — either way the exact names and weights can vary, so treat the tracking quality below, not a specific basket, as the result. In `model/portfolio_selection.py` the solve is declared with `problem.configure(...)`, so each refresh of the deployed model runs it. ## 4. Assess tracking quality @@ -49,4 +49,4 @@ Each prompt is pasted into a fresh agent session loaded with the named `/rai-*` ## Data -Bundled CSVs in `data/`: 50 stocks, 42 monthly index returns, 2,100 stock-month returns. The policy parameters (20 names, 10% max weight, ±4% sector band, ADV limit) are constants in `model/reasoning.py`; the report writes a `replica_returns.csv` of monthly basket vs benchmark returns. The reusable model is split between `model/schema.py` and `model/source.py`, while `model/reasoning.py` declares the decision problem and the solve, and `queries/replication_report.py` reads the deployed model for the result queries and reporting. +Bundled CSVs in `data/`: 50 stocks, 42 monthly index returns, 2,100 stock-month returns. The policy parameters (20 names, 10% max weight, ±4% sector band, ADV limit) are constants in `model/portfolio_selection.py`; the report writes a `replica_returns.csv` of monthly basket vs benchmark returns. The reusable model is split between `model/schema.py` and `model/source.py`. `model/portfolio_selection.py` declares the decision problem and the solve; `model/tracking_quality.py` computes the monthly replica returns, their differences from the index, and the tracking error; and `model/portfolio_exposure.py` computes the sector exposures and the implied turnover. `queries/replication_report.py` reads those figures from the deployed model, prints them, and computes the equal-weight baseline of the stocks most correlated with the index. diff --git a/financial_index_replication/template-docs.yaml b/financial_index_replication/template-docs.yaml index 6c1fcb89..a39bb8de 100644 --- a/financial_index_replication/template-docs.yaml +++ b/financial_index_replication/template-docs.yaml @@ -138,7 +138,7 @@ guided_walkthrough: monthly tracking fields prepare the model to compare the basket’s returns with the index in the next step. focus: - file: model/reasoning.py + file: model/portfolio_selection.py anchors: - start: Stock.x_selected = model.Property end: name=["weight", Stock.ticker], @@ -183,7 +183,7 @@ guided_walkthrough: the index. This comparison uses past returns and does not guarantee the basket will follow the index as closely in future months. focus: - file: model/reasoning.py + file: model/portfolio_selection.py anchors: - start: '# Monthly benchmark residual:' end: sum(ReturnMonth, pos_error + neg_error).where( @@ -223,7 +223,7 @@ guided_walkthrough: average daily trading value, which limits the trades needed to move from the previous portfolio. focus: - file: model/reasoning.py + file: model/portfolio_selection.py anchors: - start: '# Select exactly N names and invest all capital.' end: PORTFOLIO_VALUE * (Stock.previous_weight - weight) @@ -273,7 +273,7 @@ guided_walkthrough: and total tracking residual through the model's own relationships, so the report can read them after the deployment. focus: - file: model/reasoning.py + file: model/portfolio_selection.py anchors: - start: problem.configure("highs", time_limit_sec=300) end: model.define(SolveStatus(problem.termination_status()), TotalResidual(problem.objective_value())) @@ -294,38 +294,40 @@ guided_walkthrough: - id: inspect-basket title: Check tracking against the index explanation: |- - model.select(...) queries the model for every stock's solved selection - and weight. The printed basket lists only weights above 0.01% of the - portfolio, so a selected stock with zero weight does not appear in it. + Each month's gap is the replica's return less the index return. + TrackingMonth.replica_return weights every stock's return that month by + its solved Stock.x_weight and adds them, and + TrackingMonth.replica_difference subtracts the index return from that + sum. - portfolio_returns calculates the basket’s monthly returns from every - nonzero solved weight and the stock returns, and tracking_diff compares them with the - index returns. annualized_tracking_error() summarizes the monthly gaps - as a yearly tracking measure, showing how closely this basket followed - the index in the sample months. + AnnualizedTrackingError scales the root mean square of the monthly + differences to a yearly tracking measure, showing how closely this + basket followed the index in the sample months. The report + queries the model for these figures and for every stock's solved + selection and weight. The printed basket lists only weights above + 0.01% of the portfolio, so a selected stock with zero weight does + not appear in it. focus: - file: queries/replication_report.py + file: model/tracking_quality.py anchors: - - start: solution_df = ( - end: return monthly_rms * sqrt(MONTHS_PER_YEAR) + - start: "# The replica's return is the weighted sum" + end: '* math.sqrt(MONTHS_PER_YEAR)' + end_offset: 2 references: - model.select(...): - anchor: - start: model.select( - end: .to_df() - occurrence: 4 - portfolio_returns: + TrackingMonth.replica_return: anchor: - start: weights = solution_df.set_index("ticker")["weight"] - end: portfolio_returns = returns_wide[weights.index].mul(weights, axis=1).sum(axis=1) - tracking_diff: + start: TrackingMonth.replica_return( + end: .where(*_priced) + end_offset: 1 + TrackingMonth.replica_difference: anchor: - start: tracking_diff = portfolio_returns - index_series["index_return"] - end: tracking_diff = portfolio_returns - index_series["index_return"] - annualized_tracking_error(): + start: TrackingMonth.replica_difference( + end: TrackingMonth.replica_difference( + AnnualizedTrackingError: anchor: - start: 'def annualized_tracking_error():' - end: return monthly_rms * sqrt(MONTHS_PER_YEAR) + start: AnnualizedTrackingError = model.Relationship( + end: '* math.sqrt(MONTHS_PER_YEAR)' + end_offset: 2 links: - title: Query a model href: /build/guides/modeling/query-a-model/ diff --git a/fraud-detection/README.md b/fraud-detection/README.md index 86e97990..3913987b 100644 --- a/fraud-detection/README.md +++ b/fraud-detection/README.md @@ -132,7 +132,7 @@ Use this sequence to deploy the model, train the classifier, and print the audit predictive: name: fraud_gnn # created on first use if it doesn't exist gnns: - fraud_classifier: # the GNN's name in model/reasoning.py + fraud_classifier: # the GNN's name in model/fraud_classifier.py registry: .FRAUD_DETECTION model: FRAUD_CLASSIFIER version: V1 # train.py registers this version @@ -234,4 +234,4 @@ Use this sequence to deploy the model, train the classifier, and print the audit The teardown removes the deployed objects and keeps the two schemas, with the classifier's experiments and registered versions in the public schema. -To run the same pipeline over your own Snowflake tables, call `load_snowflake_data()` in `model/__init__.py` in place of `load_local_data()`. It reads `ACCOUNTS`, `TRANSACTIONS`, `TRAIN`, `VAL`, and `TEST` from the database and schema you pass, which need change tracking and a derived `audit_cost` column on the transactions table. Size the predictive reasoner for your data with `reasoners.predictive.size` in `raiconfig.yaml` (a GPU size for the full PaySim tables; a deployed GNN runs on its reasoner's device), and raise `AUDIT_BUDGET_HOURS` and the training settings in `model/reasoning.py` to match its scale. A profile sized for the full PaySim tables trains with `n_epochs=20`, `train_batch_size=512`, and `head_layers=2`, budgets `AUDIT_BUDGET_HOURS = 2000.0`, and solves with `time_limit_sec=300`. +To run the same pipeline over your own Snowflake tables, call `load_snowflake_data()` in `model/__init__.py` in place of `load_local_data()`. It reads `ACCOUNTS`, `TRANSACTIONS`, `TRAIN`, `VAL`, and `TEST` from the database and schema you pass, which need change tracking. Size the predictive reasoner for your data with `reasoners.predictive.size` in `raiconfig.yaml` (a GPU size for the full PaySim tables; a deployed GNN runs on its reasoner's device), and raise `AUDIT_BUDGET_HOURS` in `model/investigation_queue.py` and the training settings in `model/fraud_classifier.py` to match its scale. A profile sized for the full PaySim tables trains with `n_epochs=20`, `train_batch_size=512`, and `head_layers=2`, budgets `AUDIT_BUDGET_HOURS = 2000.0`, and solves with `time_limit_sec=300`. diff --git a/fraud-detection/model/__init__.py b/fraud-detection/model/__init__.py index b4b6ace7..c2c8780e 100644 --- a/fraud-detection/model/__init__.py +++ b/fraud-detection/model/__init__.py @@ -3,18 +3,22 @@ Predict-then-optimize on a small bundled demo dataset (~16K transactions, ~50% fraud -- class-balanced to give the GNN enough positive signal on CPU). `load_local_data()` maps the CSVs through `model.data()`; no Snowflake data -loading or GPU is required. The five stages are declared in `model/reasoning.py`: +loading or GPU is required. The five stages live in four modules, each of +which imports the modules whose declarations it reads: 1. Graph -- PageRank on an Account-Account funds-flow graph, fed to - the GNN as a continuous node feature. + the GNN as a continuous node feature (`account_signals.py`). 2. Rules -- `Account.activity_count`, sender-side transaction volume, - fed to the GNN as an integer feature. + fed to the GNN as an integer feature (`account_signals.py`). 3. Predictive -- GNN binary classification of fraudulent transactions on - the Transaction-to-Account bipartite graph. + the Transaction-to-Account bipartite graph + (`fraud_classifier.py`). 4. Bridge -- alert score combining the GNN probability with the - dataset's pre-existing `is_flagged_fraud` heuristic. + dataset's pre-existing `is_flagged_fraud` heuristic, and + the alert queue order (`alert_scores.py`). 5. Prescriptive-- investigator-budget allocation (knapsack MILP): maximize expected loss averted (alert_score * amount) subject to a - fixed-hours audit budget plus a per-receiver cap. + fixed-hours audit budget plus a per-receiver cap, compared + with a naive sort-and-take queue (`investigation_queue.py`). The rule-based identity-graph intro remains in fraud_detection_rules.ipynb. @@ -23,12 +27,15 @@ place of `load_local_data()`. """ -from .reasoning import ( +from .account_signals import acct_graph +from .alert_scores import AuditCandidate +from .fraud_classifier import TrainClassBalance, gnn +from .investigation_queue import ( AUDIT_BUDGET_HOURS, - AuditCandidate, + AuditQueue, + AuditUplift, SolveObjective, SolveStatus, - gnn, problem, ) from .schema import ( @@ -42,33 +49,27 @@ ValTable, model, ) -from .source import ( - LARGE_AMOUNT_THRESHOLD, - LARGE_AUDIT_COST_HOURS, - SMALL_AUDIT_COST_HOURS, - load_local_data, - load_snowflake_data, -) +from .source import load_local_data, load_snowflake_data -load_local_data( - large_amount_threshold=LARGE_AMOUNT_THRESHOLD, - small_audit_cost_hours=SMALL_AUDIT_COST_HOURS, - large_audit_cost_hours=LARGE_AUDIT_COST_HOURS, -) +load_local_data() __all__ = [ "AUDIT_BUDGET_HOURS", "Account", "AuditCandidate", + "AuditQueue", + "AuditUplift", "SolveObjective", "SolveStatus", "Test", "TestTable", "Train", + "TrainClassBalance", "TrainTable", "Transaction", "Val", "ValTable", + "acct_graph", "gnn", "load_snowflake_data", "model", diff --git a/fraud-detection/model/account_signals.py b/fraud-detection/model/account_signals.py new file mode 100644 index 00000000..e07f7ac5 --- /dev/null +++ b/fraud-detection/model/account_signals.py @@ -0,0 +1,52 @@ +"""Account signals for the fraud classifier: PageRank on the funds-flow graph and each account's +count of sent transfers.""" + +from relationalai.semantics import Float, Integer, count +from relationalai.semantics.reasoners.graph import Graph + +from .schema import Account, Transaction, model + +# Account->Account funds-flow graph: one edge per transaction from sender +# to receiver. `node_concept=Account` means `acct_graph.Node IS Account`, +# so graph-algorithm results attach directly to Account without a +# DataFrame round-trip. `aggregator="sum"` collapses multi-edges that +# arise when the same pair of accounts trades more than once. +acct_graph = Graph( + model, directed=True, weighted=False, + node_concept=Account, aggregator="sum", + name="funds_flow_graph", +) +_sender = Account.ref() +_receiver = Account.ref() +_txn_ref = Transaction.ref() +model.define(acct_graph.Edge.new(src=_sender, dst=_receiver)).where( + _txn_ref.sender(_sender), + _txn_ref.receiver(_receiver), +) + +# -------------------------------------------------- +# Stage 1: Graph -- account centrality via PageRank +# -------------------------------------------------- +# PageRank returns a binary Relationship (account, score). Bind it to an +# explicit Account.pagerank Property so the GNN table materialiser sees a +# named column. +pagerank_rel = acct_graph.pagerank() +Account.pagerank = model.Property(f"{Account} has {Float:pagerank}") +_a_pr = Account.ref() +_score_pr = Float.ref() +model.define(_a_pr.pagerank(_score_pr)).where(pagerank_rel(_a_pr, _score_pr)) + +# -------------------------------------------------- +# Stage 2: Rules -- account activity (derivation rule) +# -------------------------------------------------- +# Canonical PyRel rule pattern: a derivation Property whose value is computed +# by aggregation. Sender-side count is a reasonable proxy for activity in a +# mule-style pattern; a symmetric sender-or-receiver count would need an +# OR-join the PyRel aggregation surface doesn't expose directly. The output +# feeds the GNN as an integer feature (see `fraud_classifier.py`). + +Account.activity_count = model.Property( + f"{Account} has {Integer:activity_count}") +model.define(Account.activity_count( + count(Transaction).per(Account) +)).where(Transaction.name_orig == Account.account_id) diff --git a/fraud-detection/model/alert_scores.py b/fraud-detection/model/alert_scores.py new file mode 100644 index 00000000..a5a1bd64 --- /dev/null +++ b/fraud-detection/model/alert_scores.py @@ -0,0 +1,47 @@ +"""Alert scores: each scored test transaction's alert score, its place in the alert queue, and the +expected loss an audit of it averts.""" + +from relationalai.semantics import Float, Integer +from relationalai.semantics.std import aggregates as aggs + +# Declares Transaction.predictions, the GNN scores the alert score reads. +from . import fraud_classifier # noqa: F401 +from .schema import Transaction, model + +# Alert-score mixing weights: final score = ALPHA * is_flagged_fraud + (1-ALPHA) * GNN prob +ALPHA_FLAG = 0.3 + +# -------------------------------------------------- +# Stage 4: Bridge -- alert score +# -------------------------------------------------- +# Combine PaySim's built-in isFlaggedFraud heuristic with GNN probability. The +# score is a property of its own concept, not of Transaction: the GNN reads the +# Transaction table, so a Transaction property derived from the predictions +# would make the predictions depend on themselves. +AuditCandidate = model.Concept("AuditCandidate", identify_by={"transaction_id": Integer}) +AuditCandidate.alert_score = model.Property( + f"{AuditCandidate} has {Float:alert_score}") +model.define(AuditCandidate.new(transaction_id=Transaction.transaction_id)).where( + Transaction.predictions +) +model.define(AuditCandidate.alert_score( + ALPHA_FLAG * Transaction.is_flagged_fraud + + (1 - ALPHA_FLAG) * Transaction.predictions.probs +)).where( + Transaction.predictions, + Transaction.transaction_id == AuditCandidate.transaction_id, +) + +# The alert queue order: highest alert score first, ties broken by the lower +# transaction id. The score is negated so both keys sort ascending: the Logic +# engine's rank does not mix ascending and descending keys. +AuditCandidate.alert_rank = model.Property(f"{AuditCandidate} has {Integer:alert_rank}") +model.define(AuditCandidate.alert_rank( + aggs.rank(-AuditCandidate.alert_score, AuditCandidate.transaction_id) +)) + +# Expected loss an audit averts: the alert score times the amount at stake. +AuditCandidate.expected_loss = model.Property(f"{AuditCandidate} has {Float:expected_loss}") +model.define(AuditCandidate.expected_loss( + AuditCandidate.alert_score * Transaction.amount +)).where(Transaction.transaction_id == AuditCandidate.transaction_id) diff --git a/fraud-detection/model/fraud_classifier.py b/fraud-detection/model/fraud_classifier.py new file mode 100644 index 00000000..509a5b89 --- /dev/null +++ b/fraud-detection/model/fraud_classifier.py @@ -0,0 +1,81 @@ +"""Fraud classifier: the GNN that scores test transactions for fraud, and the class balance of its +training labels.""" + +from relationalai.semantics import DateTime, Float, Integer +from relationalai.semantics.reasoners.graph import Graph +from relationalai.semantics.reasoners.predictive import GNN, PropertyTransformer +from relationalai.semantics.std import aggregates as aggs + +# Declares Account.pagerank and Account.activity_count, the GNN's account features. +from . import account_signals # noqa: F401 +from .schema import Account, Test, Train, Transaction, Val, model + +SEED = 42 + +# Directed Transaction->Account bipartite graph: used by the GNN for +# sender/receiver message-passing. +gnn_graph = Graph(model, directed=True, weighted=False, name="transaction_account_graph") +Edge = gnn_graph.Edge +model.define(Edge.new(src=Transaction, dst=Account)).where( + Transaction.sender(Account) +) +model.define(Edge.new(src=Transaction, dst=Account)).where( + Transaction.receiver(Account) +) + +# PropertyTransformer -- drop PK/FK string IDs, keep typed behavioural +# fields plus the Stage-1 graph output and Stage-2 rule flags. +pt = PropertyTransformer( + drop=[ + Account.account_id, + Transaction.transaction_id, Transaction.name_orig, Transaction.name_dest, + Transaction.sender, Transaction.receiver, + Transaction.audit_cost, # operational parameter for the MILP, not a GNN feature + ], + category=[Account.account_type_prefix, Transaction.trans_type], + continuous=[ + Transaction.amount, + Transaction.old_balance_orig, Transaction.new_balance_orig, + Transaction.old_balance_dest, Transaction.new_balance_dest, + Account.pagerank, # graph-reasoner feature (Stage 1) + ], + integer=[ + Transaction.step, + Transaction.is_flagged_fraud, + Account.activity_count, # rule-derived feature (Stage 2) + ], + datetime=[Transaction.step_ts], + time_col=[Transaction.step_ts], +) + +# -------------------------------------------------- +# Stage 3: Predictive -- GNN binary classification +# -------------------------------------------------- +# `name` ties this GNN to the registered model and version that +# `reasoners.predictive.gnns.fraud_classifier` names in raiconfig.yaml: +# train.py registers the trained run there, and every refresh scores the +# test split with it. +gnn = GNN( + name="fraud_classifier", + graph=gnn_graph, property_transformer=pt, + train=Train, validation=Val, + task_type="binary_classification", eval_metric="roc_auc", + has_time_column=True, stream_logs=False, seed=SEED, + n_epochs=10, lr=0.005, + temporal_strategy="last", +) +Transaction.predictions = gnn.predictions(domain=Test) + +# Class balance of the training labels: how many labeled transactions, how +# many of them are fraud, and the fraud rate. +TrainClassBalance = model.Relationship( + f"the training split has {Integer:transactions} transactions, {Integer:fraud} of them fraud, " + f"a fraud rate of {Float:fraud_rate}" +) +_train_label = Integer.ref() +_labeled = Train(Transaction, DateTime.ref(), _train_label) +model.define(TrainClassBalance( + aggs.count(Transaction).where(_labeled), + aggs.sum(Transaction, _train_label).where(_labeled), + aggs.avg(Transaction, _train_label).where(_labeled), +)) diff --git a/fraud-detection/model/investigation_queue.py b/fraud-detection/model/investigation_queue.py new file mode 100644 index 00000000..32155bfc --- /dev/null +++ b/fraud-detection/model/investigation_queue.py @@ -0,0 +1,150 @@ +"""Investigation queue: each transaction's audit cost, the investigator-budget MILP that picks the +audits, and the optimized and naive audit queues the report compares.""" + +from relationalai.semantics import Float, Integer, String, count, sum +from relationalai.semantics.reasoners.prescriptive import Problem +from relationalai.semantics.std import aggregates as aggs + +from .alert_scores import AuditCandidate +from .schema import Account, Transaction, model + +# Each audit consumes hours proportional to transaction size: an audit of a +# transaction over the threshold takes deeper forensic work. +LARGE_AMOUNT_THRESHOLD = 1_000_000.0 +SMALL_AUDIT_COST_HOURS = 1.0 # audit of a transaction <= $1M +LARGE_AUDIT_COST_HOURS = 5.0 # audit of a transaction > $1M + +# Prescriptive phase: investigator-hours budget + per-audit cost model. +# `Transaction.audit_cost` carries the hours each audit takes. This makes the +# MILP a real knapsack problem: a ranker sorting by alert_score alone ignores +# the cost side and over-spends. +AUDIT_BUDGET_HOURS = 80.0 # total investigator hours available +PER_ACCOUNT_CAP = 1 # at most 1 audit per receiver account (avoid flooding) + +# Audit hours: the large cost over the threshold, the small cost otherwise +# (a transaction without an amount included). +model.where(Transaction.amount > LARGE_AMOUNT_THRESHOLD).define( + Transaction.audit_cost(LARGE_AUDIT_COST_HOURS) +) +model.where(model.not_(Transaction.amount > LARGE_AMOUNT_THRESHOLD)).define( + Transaction.audit_cost(SMALL_AUDIT_COST_HOURS) +) + +# -------------------------------------------------- +# Stage 5: Prescriptive -- knapsack MILP investigator-budget allocation +# -------------------------------------------------- +Txn_ref = Transaction.ref() +Cand_ref = AuditCandidate.ref() +select_ref = Float.ref() +problem = Problem(model, Float, name="fraud_detection") + +# Decision variable: audit this transaction? (binary), one per scored +# transaction (AuditCandidate rows exist for the test-set transactions only). +AuditCandidate.x_audit = model.Property( + f"{AuditCandidate} audited as {Float:x}") +problem.solve_for( + AuditCandidate.x_audit(select_ref), + type="bin", + name=["audit", AuditCandidate.transaction_id], +) + +# Constraint: total investigator hours <= budget +# sum over audited transactions of audit_cost <= AUDIT_BUDGET_HOURS +problem.satisfy(model.where( + Cand_ref.x_audit(select_ref), + Txn_ref.transaction_id == Cand_ref.transaction_id, +).require( + sum(Cand_ref, Txn_ref.audit_cost * select_ref) <= AUDIT_BUDGET_HOURS +)) + +# Constraint: per-receiver-account cap (at most PER_ACCOUNT_CAP audits per receiver) +Acct_ref = Account.ref() +Txn_rc = Transaction.ref() +Cand_rc = AuditCandidate.ref() +select_rc = Float.ref() +problem.satisfy(model.where( + Cand_rc.x_audit(select_rc), + Txn_rc.transaction_id == Cand_rc.transaction_id, + Txn_rc.name_dest == Acct_ref.account_id, +).require( + sum(Cand_rc, select_rc).per(Acct_ref) <= PER_ACCOUNT_CAP +)) + +# Objective: maximize expected loss averted +# E[loss averted | audit] = alert_score * transaction_amount +# Ranking by alert_score alone is suboptimal here: it ignores both the amount +# at stake and the hours each audit takes. +sel_obj = Float.ref() +Cand_obj = AuditCandidate.ref() +problem.maximize(sum( + Cand_obj.expected_loss * sel_obj +).where( + Cand_obj.x_audit(sel_obj), +)) + +# Each refresh of the deployed model runs this solve. +problem.configure("highs", time_limit_sec=120) + +# The solve's status and objective, which the deployed model publishes for the queries. +SolveStatus = model.Relationship(f"fraud audit solve status is {String:status}") +SolveObjective = model.Relationship(f"fraud audit objective is {Float:objective}") +model.define(SolveStatus(problem.termination_status()), SolveObjective(problem.objective_value())) + +# -------------------------------------------------- +# Audit queues: the MILP's selection and a naive sort-and-take baseline +# -------------------------------------------------- +# The naive queue takes candidates in alert-queue order, ignoring audit costs +# and the per-receiver cap, for as long as their cumulative audit hours fit the +# same budget. +AuditCandidate.naive_cumulative_hours = model.Property( + f"{AuditCandidate} has {Float:naive_cumulative_hours}") +model.define(AuditCandidate.naive_cumulative_hours( + aggs.cumsum_asc(AuditCandidate.alert_rank, Transaction.audit_cost) +)).where(Transaction.transaction_id == AuditCandidate.transaction_id) + +# One queue per strategy. Values computed from the solution live on AuditQueue, +# not AuditCandidate: such a property on the concept the solve reads fails the deploy. +AuditQueue = model.Concept("AuditQueue", identify_by={"strategy": String}) +AuditQueue.audits = model.Relationship(f"{AuditQueue} audits {AuditCandidate}") +model.define(AuditQueue.new(strategy="optimized"), AuditQueue.new(strategy="naive")) +_queue = AuditQueue.ref() +model.where(_queue.strategy == "optimized", AuditCandidate.x_audit > 0.5).define( + _queue.audits(AuditCandidate) +) +model.where( + _queue.strategy == "naive", + AuditCandidate.naive_cumulative_hours <= AUDIT_BUDGET_HOURS, +).define(_queue.audits(AuditCandidate)) + +# Each queue's size, investigator hours, and expected loss captured (zero for +# an empty queue), and its audits per transaction type. +AuditQueue.n_audits = model.Property(f"{AuditQueue} holds {Integer:n_audits} audits") +AuditQueue.hours_used = model.Property(f"{AuditQueue} uses {Float:hours_used} hours") +AuditQueue.captured_loss = model.Property(f"{AuditQueue} captures {Float:captured_loss}") +AuditQueue.audits_by_type = model.Relationship( + f"{AuditQueue} holds {Integer:n_audits} audits of type {String:trans_type}") +_queued = ( + AuditQueue.audits(AuditCandidate), + Transaction.transaction_id == AuditCandidate.transaction_id, +) +model.define( + AuditQueue.n_audits(count(AuditCandidate).per(AuditQueue).where(*_queued) | 0), + AuditQueue.hours_used( + sum(AuditCandidate, Transaction.audit_cost).per(AuditQueue).where(*_queued) | 0.0 + ), + AuditQueue.captured_loss( + sum(AuditCandidate, AuditCandidate.expected_loss).per(AuditQueue).where(*_queued) | 0.0 + ), +) +_trans_type = String.ref() +model.where(*_queued, Transaction.trans_type == _trans_type).define(AuditQueue.audits_by_type( + count(AuditCandidate).per(AuditQueue, _trans_type), _trans_type +)) + +# How much more expected loss the MILP captures than the naive queue. +AuditUplift = model.Relationship(f"the MILP captures {Float:uplift} more than the naive queue") +_objective = Float.ref() +_naive = AuditQueue.ref() +model.where(SolveObjective(_objective), _naive.strategy == "naive").define( + AuditUplift(_objective - _naive.captured_loss) +) diff --git a/fraud-detection/model/reasoning.py b/fraud-detection/model/reasoning.py deleted file mode 100644 index 533ff3f2..00000000 --- a/fraud-detection/model/reasoning.py +++ /dev/null @@ -1,203 +0,0 @@ -"""Fraud-detection reasoning: account graph signals, the fraud GNN, alert scores, and the investigation-queue MILP.""" - -from relationalai.semantics import Float, Integer, String, count, sum -from relationalai.semantics.reasoners.graph import Graph -from relationalai.semantics.reasoners.predictive import GNN, PropertyTransformer -from relationalai.semantics.reasoners.prescriptive import Problem - -from .schema import Account, Test, Train, Transaction, Val, model - -SEED = 42 - -# Alert-score mixing weights: final score = ALPHA * is_flagged_fraud + (1-ALPHA) * GNN prob -ALPHA_FLAG = 0.3 - -# Prescriptive phase: investigator-hours budget + per-audit cost model. -# Each audit consumes hours proportional to transaction size (big transfers -# take deeper forensic work), which `Transaction.audit_cost` carries. This -# makes the MILP a real knapsack problem: a ranker sorting by alert_score -# alone ignores the cost side and over-spends. -AUDIT_BUDGET_HOURS = 80.0 # total investigator hours available -PER_ACCOUNT_CAP = 1 # at most 1 audit per receiver account (avoid flooding) - -# Directed Transaction->Account bipartite graph: used by the GNN for -# sender/receiver message-passing. -gnn_graph = Graph(model, directed=True, weighted=False, name="transaction_account_graph") -Edge = gnn_graph.Edge -model.define(Edge.new(src=Transaction, dst=Account)).where( - Transaction.sender(Account) -) -model.define(Edge.new(src=Transaction, dst=Account)).where( - Transaction.receiver(Account) -) - -# Account->Account funds-flow graph: one edge per transaction from sender -# to receiver. `node_concept=Account` means `acct_graph.Node IS Account`, -# so graph-algorithm results attach directly to Account without a -# DataFrame round-trip. `aggregator="sum"` collapses multi-edges that -# arise when the same pair of accounts trades more than once. -acct_graph = Graph( - model, directed=True, weighted=False, - node_concept=Account, aggregator="sum", - name="funds_flow_graph", -) -_sender = Account.ref() -_receiver = Account.ref() -_txn_ref = Transaction.ref() -model.define(acct_graph.Edge.new(src=_sender, dst=_receiver)).where( - _txn_ref.sender(_sender), - _txn_ref.receiver(_receiver), -) - -# -------------------------------------------------- -# Stage 1: Graph -- account centrality via PageRank -# -------------------------------------------------- -# PageRank returns a binary Relationship (account, score). Bind it to an -# explicit Account.pagerank Property so the GNN table materialiser sees a -# named column. -pagerank_rel = acct_graph.pagerank() -Account.pagerank = model.Property(f"{Account} has {Float:pagerank}") -_a_pr = Account.ref() -_score_pr = Float.ref() -model.define(_a_pr.pagerank(_score_pr)).where(pagerank_rel(_a_pr, _score_pr)) - -# -------------------------------------------------- -# Stage 2: Rules -- account activity (derivation rule) -# -------------------------------------------------- -# Canonical PyRel rule pattern: a derivation Property whose value is computed -# by aggregation. Sender-side count is a reasonable proxy for activity in a -# mule-style pattern; a symmetric sender-or-receiver count would need an -# OR-join the PyRel aggregation surface doesn't expose directly. The output -# feeds the GNN as an integer feature via the PropertyTransformer below. - -Account.activity_count = model.Property( - f"{Account} has {Integer:activity_count}") -model.define(Account.activity_count( - count(Transaction).per(Account) -)).where(Transaction.name_orig == Account.account_id) - -# PropertyTransformer -- drop PK/FK string IDs, keep typed behavioural -# fields plus the Stage-1 graph output and Stage-2 rule flags. -pt = PropertyTransformer( - drop=[ - Account.account_id, - Transaction.transaction_id, Transaction.name_orig, Transaction.name_dest, - Transaction.sender, Transaction.receiver, - Transaction.audit_cost, # operational parameter for the MILP, not a GNN feature - ], - category=[Account.account_type_prefix, Transaction.trans_type], - continuous=[ - Transaction.amount, - Transaction.old_balance_orig, Transaction.new_balance_orig, - Transaction.old_balance_dest, Transaction.new_balance_dest, - Account.pagerank, # graph-reasoner feature (Stage 1) - ], - integer=[ - Transaction.step, - Transaction.is_flagged_fraud, - Account.activity_count, # rule-derived feature (Stage 2) - ], - datetime=[Transaction.step_ts], - time_col=[Transaction.step_ts], -) - -# -------------------------------------------------- -# Stage 3: Predictive -- GNN binary classification -# -------------------------------------------------- -# `name` ties this GNN to the registered model and version that -# `reasoners.predictive.gnns.fraud_classifier` names in raiconfig.yaml: -# train.py registers the trained run there, and every refresh scores the -# test split with it. -gnn = GNN( - name="fraud_classifier", - graph=gnn_graph, property_transformer=pt, - train=Train, validation=Val, - task_type="binary_classification", eval_metric="roc_auc", - has_time_column=True, stream_logs=False, seed=SEED, - n_epochs=10, lr=0.005, - temporal_strategy="last", -) -Transaction.predictions = gnn.predictions(domain=Test) - -# -------------------------------------------------- -# Stage 4: Bridge -- alert score -# -------------------------------------------------- -# Combine PaySim's built-in isFlaggedFraud heuristic with GNN probability. The -# score is a property of its own concept, not of Transaction: the GNN reads the -# Transaction table, so a Transaction property derived from the predictions -# would make the predictions depend on themselves. -AuditCandidate = model.Concept("AuditCandidate", identify_by={"transaction_id": Integer}) -AuditCandidate.alert_score = model.Property( - f"{AuditCandidate} has {Float:alert_score}") -model.define(AuditCandidate.new(transaction_id=Transaction.transaction_id)).where( - Transaction.predictions -) -model.define(AuditCandidate.alert_score( - ALPHA_FLAG * Transaction.is_flagged_fraud - + (1 - ALPHA_FLAG) * Transaction.predictions.probs -)).where( - Transaction.predictions, - Transaction.transaction_id == AuditCandidate.transaction_id, -) - -# -------------------------------------------------- -# Stage 5: Prescriptive -- knapsack MILP investigator-budget allocation -# -------------------------------------------------- -Txn_ref = Transaction.ref() -Cand_ref = AuditCandidate.ref() -select_ref = Float.ref() -problem = Problem(model, Float, name="fraud_detection") - -# Decision variable: audit this transaction? (binary), one per scored -# transaction (AuditCandidate rows exist for the test-set transactions only). -AuditCandidate.x_audit = model.Property( - f"{AuditCandidate} audited as {Float:x}") -problem.solve_for( - AuditCandidate.x_audit(select_ref), - type="bin", - name=["audit", AuditCandidate.transaction_id], -) - -# Constraint: total investigator hours <= budget -# sum over audited transactions of audit_cost <= AUDIT_BUDGET_HOURS -problem.satisfy(model.where( - Cand_ref.x_audit(select_ref), - Txn_ref.transaction_id == Cand_ref.transaction_id, -).require( - sum(Cand_ref, Txn_ref.audit_cost * select_ref) <= AUDIT_BUDGET_HOURS -)) - -# Constraint: per-receiver-account cap (at most PER_ACCOUNT_CAP audits per receiver) -Acct_ref = Account.ref() -Txn_rc = Transaction.ref() -Cand_rc = AuditCandidate.ref() -select_rc = Float.ref() -problem.satisfy(model.where( - Cand_rc.x_audit(select_rc), - Txn_rc.transaction_id == Cand_rc.transaction_id, - Txn_rc.name_dest == Acct_ref.account_id, -).require( - sum(Cand_rc, select_rc).per(Acct_ref) <= PER_ACCOUNT_CAP -)) - -# Objective: maximize expected loss averted -# E[loss averted | audit] = alert_score * transaction_amount -# Ranking by alert_score alone is suboptimal here: it ignores both the amount -# at stake and the hours each audit takes. -sel_obj = Float.ref() -Txn_obj = Transaction.ref() -Cand_obj = AuditCandidate.ref() -problem.maximize(sum( - Cand_obj.alert_score * Txn_obj.amount * sel_obj -).where( - Cand_obj.x_audit(sel_obj), - Txn_obj.transaction_id == Cand_obj.transaction_id, -)) - -# Each refresh of the deployed model runs this solve. -problem.configure("highs", time_limit_sec=120) - -# The solve's status and objective, which the deployed model publishes for the queries. -SolveStatus = model.Relationship(f"fraud audit solve status is {String:status}") -SolveObjective = model.Relationship(f"fraud audit objective is {Float:objective}") -model.define(SolveStatus(problem.termination_status()), SolveObjective(problem.objective_value())) diff --git a/fraud-detection/model/source.py b/fraud-detection/model/source.py index 3fa682b3..aa06c0a5 100644 --- a/fraud-detection/model/source.py +++ b/fraud-detection/model/source.py @@ -2,7 +2,6 @@ from pathlib import Path -import numpy as np from pandas import read_csv from .schema import ( @@ -19,34 +18,18 @@ PAYSIM_DIR = Path(__file__).parents[1] / "data" / "paysim_mini" -# Each audit consumes hours proportional to transaction size: an audit of a -# transaction over the threshold takes deeper forensic work. -LARGE_AMOUNT_THRESHOLD = 1_000_000.0 -SMALL_AUDIT_COST_HOURS = 1.0 # audit of a transaction <= $1M -LARGE_AUDIT_COST_HOURS = 5.0 # audit of a transaction > $1M - -def load_local_data( - data_dir: Path = PAYSIM_DIR, - *, - large_amount_threshold: float, - small_audit_cost_hours: float, - large_audit_cost_hours: float, -) -> None: +def load_local_data(data_dir: Path = PAYSIM_DIR) -> None: """Load bundled PaySim CSVs and map them to the shared schema.""" accounts_df = read_csv(data_dir / "accounts.csv") transactions_df = read_csv(data_dir / "transactions.csv", parse_dates=["step_ts"]) - transactions_df["audit_cost"] = np.where( - transactions_df["amount"] > large_amount_threshold, - large_audit_cost_hours, - small_audit_cost_hours, - ) train_df = read_csv(data_dir / "train.csv", parse_dates=["step_ts"]) val_df = read_csv(data_dir / "val.csv", parse_dates=["step_ts"]) test_df = read_csv(data_dir / "test.csv", parse_dates=["step_ts"]) model.define(Account.new(model.data(accounts_df).to_schema())) - model.define(Transaction.new(model.data(transactions_df).to_schema())) + # Audit cost is a rule on the amount (investigation_queue.py), never a loaded column. + model.define(Transaction.new(model.data(transactions_df).to_schema(exclude=["audit_cost"]))) model.define(TrainTable.new(model.data(train_df).to_schema())) model.define(ValTable.new(model.data(val_df).to_schema())) model.define(TestTable.new(model.data(test_df).to_schema())) @@ -72,11 +55,7 @@ def load_snowflake_data(database: str, schema: str) -> None: """Load PaySim Snowflake tables and map them to the shared schema. To run the model over your own tables, call this from `model/__init__.py` - instead of `load_local_data()`. TRANSACTIONS carries the `audit_cost` column - (hours), derived in Snowflake: - SELECT *, CASE WHEN amount > 1000000 THEN 5.0 ELSE 1.0 END AS audit_cost - FROM RAW_TRANSACTIONS; - and the tables need change tracking. + instead of `load_local_data()`. The tables need change tracking. """ accounts = model.Table(f"{database}.{schema}.ACCOUNTS") transactions = model.Table(f"{database}.{schema}.TRANSACTIONS") @@ -85,7 +64,8 @@ def load_snowflake_data(database: str, schema: str) -> None: test = model.Table(f"{database}.{schema}.TEST") model.define(Account.new(accounts.to_schema())) - model.define(Transaction.new(transactions.to_schema())) + # Audit cost is a rule on the amount (investigation_queue.py), never a loaded column. + model.define(Transaction.new(transactions.to_schema(exclude=["audit_cost"]))) model.define(TrainTable.new(train.to_schema())) model.define(ValTable.new(validation.to_schema())) model.define(TestTable.new(test.to_schema())) diff --git a/fraud-detection/queries/fraud_report.py b/fraud-detection/queries/fraud_report.py index 9962fc18..02bdda54 100644 --- a/fraud-detection/queries/fraud_report.py +++ b/fraud-detection/queries/fraud_report.py @@ -11,29 +11,62 @@ from model import ( AUDIT_BUDGET_HOURS, AuditCandidate, + AuditQueue, + AuditUplift, SolveObjective, SolveStatus, - Train, + TrainClassBalance, Transaction, model, ) -from relationalai.semantics import DateTime, Float, Integer, select +from pandas import Index +from relationalai.semantics import Float, Integer, String + +TOP_ALERTS = 20 + + +def type_counts(strategy: str, first_seen): + """One audit queue's audits per transaction type from the model, most first; ties keep the + order in which their types first appear in `first_seen`.""" + queue = AuditQueue.ref() + n_ref, type_ref = Integer.ref(), String.ref() + by_type = ( + model.where(queue.strategy == strategy, queue.audits_by_type(n_ref, type_ref)) + .select(type_ref.alias("trans_type"), n_ref.alias("count")) + .to_df() + .set_index("trans_type")["count"] + ) + order = Index(first_seen.drop_duplicates(), name="trans_type") + return by_type.reindex(order).astype(int).sort_values(ascending=False, kind="stable") + + +def queue_summary(strategy: str): + """One audit queue's size, investigator hours, and captured expected loss.""" + queue = AuditQueue.ref() + return ( + model.where(queue.strategy == strategy) + .select( + queue.n_audits.alias("audits"), + queue.hours_used.alias("hours"), + queue.captured_loss.alias("captured_loss"), + ) + .to_df() + .iloc[0] + ) def main() -> None: # Class-balance profile of the training labels (baseline ROC_AUC = 0.5) - train_txn = Transaction.ref() - train_ts = DateTime.ref() - train_label = Integer.ref() - _label_df = select( - train_txn.transaction_id.alias("transaction_id"), - train_label.alias("label"), - ).where(Train(train_txn, train_ts, train_label)).to_df() - if len(_label_df): - _l = _label_df["label"] + n_ref, fraud_ref, rate_ref = Integer.ref(), Integer.ref(), Float.ref() + balance = ( + model.where(TrainClassBalance(n_ref, fraud_ref, rate_ref)) + .select(n_ref.alias("n"), fraud_ref.alias("fraud"), rate_ref.alias("fraud_rate")) + .to_df() + ) + if len(balance): print("\n=== Fraud class balance (train split) ===") - print(f" n={len(_l)} fraud={int(_l.sum())} " - f"fraud_rate={_l.mean():.1%}") + print(f" n={int(balance['n'].iloc[0])} fraud={int(balance['fraud'].iloc[0])} " + f"fraud_rate={float(balance['fraud_rate'].iloc[0]):.1%}") print(" Baseline ROC_AUC = 0.5") Txn_ref = Transaction.ref() @@ -46,6 +79,7 @@ def main() -> None: Txn_ref.amount.alias("amount"), Txn_ref.name_dest.alias("receiver"), score_ref.alias("alert_score"), + Cand_ref.alert_rank.alias("alert_rank"), ) .where( Cand_ref.alert_score(score_ref), @@ -57,8 +91,9 @@ def main() -> None: print("\n(no predictions returned)") return - print("\n=== Top-20 alert-scored transactions ===") - print(_alert_df.sort_values("alert_score", ascending=False).head(20).to_string(index=False)) + print(f"\n=== Top-{TOP_ALERTS} alert-scored transactions ===") + top_alerts = _alert_df.sort_values("alert_rank").head(TOP_ALERTS).drop(columns="alert_rank") + print(top_alerts.to_string(index=False)) print("\n" + "=" * 60) print("Stage 5: Prescriptive -- investigator-budget allocation") @@ -69,52 +104,38 @@ def main() -> None: print(f"\nMILP Status: {', '.join(status)}") if objective: objective_value = float(objective[0]) - # Compare against a naive sort-and-take baseline: pick top transactions by - # alert_score, ignoring audit-cost and per-receiver caps, consuming hours - # until the budget is spent. The audit cost is the model's own per- - # transaction cost, the one the MILP constraint reads. - amount_ref = Float.ref() - cost_ref = Float.ref() - _full_df = ( - model.select( - Txn_ref.transaction_id.alias("transaction_id"), - Txn_ref.trans_type.alias("trans_type"), - amount_ref.alias("amount"), - cost_ref.alias("audit_cost"), - score_ref.alias("alert_score"), - ) - .where( - Cand_ref.alert_score(score_ref), + # Compare against the naive sort-and-take queue the model publishes: top + # transactions by alert_score, ignoring audit-cost and per-receiver caps, + # consuming hours until the budget is spent. + naive = queue_summary("naive") + naive_queue = AuditQueue.ref() + naive_order = ( + model.where( + naive_queue.strategy == "naive", + naive_queue.audits(Cand_ref), Txn_ref.transaction_id == Cand_ref.transaction_id, - Txn_ref.amount == amount_ref, - Txn_ref.audit_cost == cost_ref, + ) + .select( + Cand_ref.alert_rank.alias("alert_rank"), + Txn_ref.trans_type.alias("trans_type"), ) .to_df() + .sort_values("alert_rank")["trans_type"] ) - _full_df["amount"] = _full_df["amount"].astype("float64") - _full_df["alert_score"] = _full_df["alert_score"].astype("float64") - _full_df["audit_cost"] = _full_df["audit_cost"].astype("float64") - _full_df["expected_loss"] = _full_df["alert_score"] * _full_df["amount"] - _naive = _full_df.sort_values( - ["alert_score", "transaction_id"], ascending=[False, True] - ).copy() - _naive["cumulative_hours"] = _naive["audit_cost"].cumsum() - _naive_fit = _naive[_naive["cumulative_hours"] <= AUDIT_BUDGET_HOURS] - _naive_obj = float(_naive_fit["expected_loss"].sum()) - _naive_types = {k: int(v) for k, v in _naive_fit["trans_type"].value_counts().items()} + _naive_types = {k: int(v) for k, v in type_counts("naive", naive_order).items()} + uplift = float(model.select(AuditUplift).to_df().iloc[0, 0]) quality = "optimal" if status == ["OPTIMAL"] else "best found" print(f"Captured expected loss ({quality} within budget): ${objective_value:,.0f}") print(f" MILP (cost-aware + per-receiver cap) -> ${objective_value:,.0f} " f"captured across the audit queue") print(f" Naive top-by-alert-score (budget only, same {AUDIT_BUDGET_HOURS:g}-hour budget) -> " - f"${_naive_obj:,.0f} captured across {len(_naive_fit)} audits " + f"${float(naive['captured_loss']):,.0f} captured across {int(naive['audits'])} audits " f"(by type: {_naive_types})") - uplift = objective_value - _naive_obj print(f" MILP uplift over naive sort: ${uplift:+,.0f}") # Report the selected audit queue print("\n=== Selected audit queue ===") - sel_ref = Float.ref() + queue_ref = AuditQueue.ref() cost_ref = Float.ref() audit_df = ( model.select( @@ -126,8 +147,8 @@ def main() -> None: cost_ref.alias("audit_cost"), ) .where( - Cand_ref.x_audit(sel_ref), - sel_ref > 0.5, + queue_ref.strategy == "optimized", + queue_ref.audits(Cand_ref), Cand_ref.alert_score(score_ref), Txn_ref.transaction_id == Cand_ref.transaction_id, Txn_ref.audit_cost == cost_ref, @@ -140,12 +161,12 @@ def main() -> None: else: audit_df["amount"] = audit_df["amount"].astype("float64") audit_df["audit_cost"] = audit_df["audit_cost"].astype("float64") - hours_used = float(audit_df["audit_cost"].sum()) - print(f" {len(audit_df)} audits scheduled; " - f"{hours_used:.1f}/{AUDIT_BUDGET_HOURS:.0f} investigator hours used") + optimized = queue_summary("optimized") + print(f" {int(optimized['audits'])} audits scheduled; " + f"{float(optimized['hours']):.1f}/{AUDIT_BUDGET_HOURS:.0f} investigator hours used") print(audit_df.to_string(index=False)) print("\n By trans_type:") - print(audit_df["trans_type"].value_counts().to_string()) + print(type_counts("optimized", audit_df["trans_type"]).to_string()) print("\n" + "=" * 60) print("Report complete") diff --git a/fraud-detection/runbook.md b/fraud-detection/runbook.md index bece3840..8cd9f59c 100644 --- a/fraud-detection/runbook.md +++ b/fraud-detection/runbook.md @@ -39,8 +39,14 @@ that captures the most expected loss within an 80 investigator-hour budget. - `model/source.py` provides explicit `load_local_data()` and `load_snowflake_data()` functions; `model/__init__.py` calls the local one, and deploys with `rai models deploy --path model`. -- `model/reasoning.py` declares the account graph signals, the fraud GNN, the - alert score, and the 80-hour audit problem. +- `model/account_signals.py` declares the account graph signals: PageRank on + the funds-flow graph and each account's sent-transfer count. +- `model/fraud_classifier.py` declares the fraud GNN and the class balance of + its training labels. +- `model/alert_scores.py` declares the alert score, the alert queue order, and + each candidate's expected loss. +- `model/investigation_queue.py` declares the audit costs, the 80-hour audit + problem, and the optimized and naive audit queues the report compares. - `train.py` trains the GNN over the deployed splits and registers its version. - `queries/fraud_report.py` prints the alert queue and the audit schedule from the deployed model. @@ -64,8 +70,8 @@ that captures the most expected loss within an 80 investigator-hour budget. ```text /rai-ontology Load the bundled PaySim CSVs with load_local_data(): accounts (each with an id and account-type prefix), transactions (each with a type, -amount, sender and receiver balances, sender and receiver accounts, fraud flag, -and derived audit cost), and the train/validation/test task files. Use the +amount, sender and receiver balances, sender and receiver accounts, and fraud +flag), and the train/validation/test task files. Use the Account and Transaction declarations from model/schema.py and connect each transaction to its sender and receiver accounts. ``` @@ -73,8 +79,8 @@ transaction to its sender and receiver accounts. **Response** `load_local_data()` loads `Account` (~32,661 customer and merchant accounts), -`Transaction` (~16,426 rows with `trans_type`, `amount`, balance fields, -`is_flagged_fraud`, and a derived audit cost), and the train/validation/test +`Transaction` (~16,426 rows with `trans_type`, `amount`, balance fields, and +`is_flagged_fraud`), and the train/validation/test task files (~11,498 / 2,463 / 2,465 rows). The test set is the unlabeled decision set. @@ -165,8 +171,8 @@ depends on the connected engine and environment. /rai-prescriptive-problem Choose which test transactions to audit to maximize captured expected loss — alert score times amount — within an 80 investigator-hour budget (each audit costs its transaction's audit_cost in -hours), with at most one audit per receiving account. Persist the audit -decision as AuditCandidate.x_audit. +hours: 5 for a transaction over $1M, 1 otherwise), with at most one audit per +receiving account. Persist the audit decision as AuditCandidate.x_audit. ``` **Response** @@ -199,16 +205,15 @@ Use `load_snowflake_data()` when your accounts, transactions, and task splits already live in Snowflake: 1. Call `load_snowflake_data(DATABASE, SCHEMA)` in `model/__init__.py` in place - of `load_local_data(...)`, with the location of `ACCOUNTS`, `TRANSACTIONS`, + of `load_local_data()`, with the location of `ACCOUNTS`, `TRANSACTIONS`, `TRAIN`, `VAL`, and `TEST`. -2. Provide `audit_cost` on `TRANSACTIONS`; the loader maps the column without - recomputing it. -3. Update the feature mapping and task-column accesses in `model/reasoning.py` - for your schema. -4. Deploy, train, and size the predictive reasoner for your data in +2. Update the feature mapping and task-column accesses in + `model/fraud_classifier.py` for your schema. +3. Deploy, train, and size the predictive reasoner for your data in `raiconfig.yaml`. The Snowflake loader maps the same schema, so the reasoning stages and the `AuditCandidate.x_audit` result are unchanged. Raise `AUDIT_BUDGET_HOURS` (80 by -default) and the training settings in `model/reasoning.py` to match the larger +default) in `model/investigation_queue.py` and the training settings in +`model/fraud_classifier.py` to match the larger dataset. diff --git a/fraud-detection/template-docs.yaml b/fraud-detection/template-docs.yaml index 1c602c17..488c8a0c 100644 --- a/fraud-detection/template-docs.yaml +++ b/fraud-detection/template-docs.yaml @@ -76,9 +76,8 @@ guided_walkthrough: title: Connect transactions to the account network explanation: |- Python’s read_csv function reads the two CSV data sources into DataFrames - named accounts_df and transactions_df. The source loader also estimates - the time needed to review each transfer from its amount. Account.new(...) - and Transaction.new(...) map the imported records to instances of the + named accounts_df and transactions_df. Account.new(...) and + Transaction.new(...) map the imported records to instances of the Account and Transaction concepts shown in the Model Explorer. Transaction.sender(...) and Transaction.receiver(...) define @@ -97,16 +96,15 @@ guided_walkthrough: transactions_df: anchor: start: transactions_df = read_csv - end: small_audit_cost_hours, - end_offset: 1 + end: transactions_df = read_csv Account.new(...): anchor: start: model.define(Account.new(model.data(accounts_df).to_schema())) end: model.define(Account.new(model.data(accounts_df).to_schema())) Transaction.new(...): anchor: - start: model.define(Transaction.new(model.data(transactions_df).to_schema())) - end: model.define(Transaction.new(model.data(transactions_df).to_schema())) + start: model.define(Transaction.new(model.data(transactions_df).to_schema( + end: model.define(Transaction.new(model.data(transactions_df).to_schema( Transaction.sender(...): anchor: start: model.define(Transaction.sender(Transaction, Account)).where( @@ -131,7 +129,7 @@ guided_walkthrough: acct_graph.pagerank() runs a graph algorithm that scores each account based on which other accounts send it money, giving more weight to connections from higher-scoring senders. Account.pagerank stores the score as an account property, which the fraud classifier uses alongside payment details to estimate whether a transfer may be fraudulent. focus: - file: model/reasoning.py + file: model/account_signals.py anchors: - start: acct_graph = Graph( end: model.define(_a_pr.pagerank(_score_pr)).where(pagerank_rel(_a_pr, _score_pr)) @@ -167,7 +165,7 @@ guided_walkthrough: count(Transaction).per(Account) counts transfers by account, and the .where(...) condition matches each transfer’s sender ID to an account ID so that only outgoing transfers contribute. The classifier uses the result with the network score from step 2 and payment details to estimate whether a transfer may be fraudulent. focus: - file: model/reasoning.py + file: model/account_signals.py anchors: - start: Account.activity_count = model.Property( end: )).where(Transaction.name_orig == Account.account_id) @@ -199,7 +197,7 @@ guided_walkthrough: gnn.predictions(domain=Test) assigns a predicted fraud probability to each transaction in the test set each time the deployed model refreshes. The next step combines that probability with the source data’s fraud flag to help prioritize cases for review. focus: - file: model/reasoning.py + file: model/fraud_classifier.py anchors: - start: gnn = GNN( end: Transaction.predictions = gnn.predictions(domain=Test) @@ -228,7 +226,7 @@ guided_walkthrough: The combined score helps prioritize reviews, but it does not prove that a transfer is fraudulent. The next step uses the score alongside transfer amount and available investigator time to choose cases for review. focus: - file: model/reasoning.py + file: model/alert_scores.py anchors: - start: AuditCandidate = model.Concept( end: Transaction.transaction_id == AuditCandidate.transaction_id, @@ -258,11 +256,11 @@ guided_walkthrough: - id: allocate-investigation-capacity title: Choose the highest-value investigations within capacity explanation: |- - problem.solve_for(...) defines a decision variable: a yes-or-no choice to investigate each transfer with an alert score. Two constraints narrow those choices: an investigator-hours budget caps total review time, and a receiver-account cap limits how many selected transfers go to the same account. + problem.solve_for(...) defines a decision variable: a yes-or-no choice to investigate each transfer with an alert score. Two constraints narrow those choices: an investigator-hours budget caps total review time, and a receiver-account cap limits how many selected transfers go to the same account. A rule on each transfer’s amount sets its review time, Transaction.audit_cost: a transfer over $1M takes five hours, any other one hour. - problem.maximize(...) seeks the set of reviews with the most estimated loss averted, calculated from each selected transfer’s alert score and amount. problem.configure(...) sets the solver the deployed model runs on each refresh to find a choice that satisfies both constraints instead of simply ranking transfers by score. + problem.maximize(...) seeks the set of reviews with the most estimated loss averted, the sum of each selected transfer’s AuditCandidate.expected_loss: its alert score times its amount. problem.configure(...) sets the solver the deployed model runs on each refresh to find a choice that satisfies both constraints instead of simply ranking transfers by score. focus: - file: model/reasoning.py + file: model/investigation_queue.py anchors: - start: problem.solve_for( end: problem.configure("highs", time_limit_sec=120) @@ -287,7 +285,7 @@ guided_walkthrough: problem.maximize(...): anchor: start: problem.maximize(sum( - end: Txn_obj.transaction_id == Cand_obj.transaction_id, + end: Cand_obj.x_audit(sel_obj), end_offset: 1 problem.configure(...): anchor: diff --git a/hospital_staffing/README.md b/hospital_staffing/README.md index 5daa7ce9..d34758e3 100644 --- a/hospital_staffing/README.md +++ b/hospital_staffing/README.md @@ -37,7 +37,7 @@ The result is a frontier of overtime cost against unmet demand: each sweep point ## What's included -- **Model**: nurse, shift, availability, and assignment concepts, the staffing constraints, two anchor solves, and an epsilon-constraint sweep between them — in the `model/` package (`schema.py` declares the concepts, `source.py` loads the sample data, `reasoning.py` states the decision problems), which `rai models deploy --path model` deploys to your Snowflake account, where each refresh runs every solve. +- **Model**: nurse, shift, availability, and assignment concepts, the staffing constraints, two anchor solves, and an epsilon-constraint sweep between them — in the `model/` package (`schema.py` declares the concepts, `source.py` loads the sample data, `shift_staffing.py` states the decision problems, `frontier_analysis.py` states the frontier, marginal analysis, and knee), which `rai models deploy --path model` deploys to your Snowflake account, where each refresh runs every solve. - **Query**: `queries/staffing_frontier.py`, which prints the report from the deployed model. - **Runbook**: `runbook.md` — a paste-testable walkthrough that reproduces the template step by step with the RAI skills; as important a reference as the model itself. - **Sample data**: `data/nurses.csv` (nurse roster with skill levels, hourly costs, and overtime parameters), `data/shifts.csv` (shift definitions with timing, staffing requirements, and patient demand), and `data/availability.csv` (nurse-to-shift availability matrix). @@ -253,7 +253,8 @@ Use this sequence to deploy the model and query it: │ ├── __init__.py # exports of the deployed model │ ├── schema.py # concepts, properties, sweep and frontier points │ ├── source.py # sample data -│ └── reasoning.py # anchor and sweep problems, published results +│ ├── shift_staffing.py # anchor and sweep problems, published results +│ └── frontier_analysis.py # frontier order, marginal rates, knee ├── queries/ │ └── staffing_frontier.py # report from the deployed model └── data/ @@ -286,13 +287,13 @@ For the full concept and property definitions, see `model/schema.py`; `runbook.m **Define concepts and load CSV data.** The model defines three core concepts: nurses with skill levels and cost parameters, shifts with coverage requirements and patient demand, and an availability relationship linking nurses to shifts. A per-availability `Assignment` carries the binary staffing decision the solver fills in. -**Define decision variables, constraints, and objective.** A `staffing_problem` helper in `model/reasoning.py` declares one named Problem with the full formulation. It registers four variable types -- the binary assignment, each nurse's overtime hours, and each shift's patients-served and unmet-demand quantities -- and applies all constraints: availability, minimum staffing, skill coverage, overtime tracking, and patient-demand accounting (each nurse works one to two shifts; every shift meets its minimum-nurse floor). A single weighted objective would bundle overtime cost and unmet demand into one penalty sum, forcing the modeler to pick a penalty weight up front. This template splits them: the primary objective minimizes overtime cost, while unmet demand is bounded by an epsilon constraint that caps total unmet demand across all shifts. This eliminates the arbitrary penalty weight and reveals the true tradeoff. +**Define decision variables, constraints, and objective.** A `staffing_problem` helper in `model/shift_staffing.py` declares one named Problem with the full formulation. It registers four variable types -- the binary assignment, each nurse's overtime hours, and each shift's patients-served and unmet-demand quantities -- and applies all constraints: availability, minimum staffing, skill coverage, overtime tracking, and patient-demand accounting (each nurse works one to two shifts; every shift meets its minimum-nurse floor). A single weighted objective would bundle overtime cost and unmet demand into one penalty sum, forcing the modeler to pick a penalty weight up front. This template splits them: the primary objective minimizes overtime cost, while unmet demand is bounded by an epsilon constraint that caps total unmet demand across all shifts. This eliminates the arbitrary penalty weight and reveals the true tradeoff. **Solve anchor points and run the epsilon sweep.** Two anchor solves establish the feasible unmet-demand range: anchor 1 minimizes overtime with no demand constraint (the cheapest schedule, which may leave patients unserved), and anchor 2 minimizes unmet demand (the best achievable service level). The epsilon sweep then traces interior points between the anchors, each solve minimizing overtime cost subject to a progressively tighter cap on unmet demand. Every solve is declared in the model: each sweep point's cap is a rule over the two anchors' results, so a refresh solves the anchors first and the sweep after them. Each solve publishes its status, overtime cost, unmet demand, and assignments as a `FrontierPoint`. -**Pareto analysis output.** The query prints the frontier (a cap sweep) showing how overtime cost rises as the unmet-demand cap tightens. Marginal analysis computes the cost of reducing unmet demand by one patient, and a knee detector flags the last point reached at no extra cost, or, when no improvement is free, the point where the marginal cost per patient jumps by the largest ratio. The knee is a starting point for choosing a cost-service balance, not a proven optimum. If a sweep point fails, the report stops the sweep there and leaves the best-service anchor out of the frontier. +**Pareto analysis output.** The model reads the published points as a frontier: the cheapest anchor, the sweep points up to the first that failed, and the best-service anchor when the whole sweep solved, each labeled and numbered in order. The query prints the frontier (a cap sweep) showing how overtime cost rises as the unmet-demand cap tightens. Marginal analysis, a rule over consecutive frontier points, computes the cost of reducing unmet demand by one patient, and the knee rules flag the last point reached at no extra cost, or, when no improvement is free, the point where the marginal cost per patient jumps by the largest ratio. The model also lists the nurses on each shift at the knee. The knee is a starting point for choosing a cost-service balance, not a proven optimum. If a sweep point fails, the frontier ends there and leaves the best-service anchor out. -See `model/reasoning.py` for the implementation, and `runbook.md` for the skill-driven reproduction. +See `model/shift_staffing.py` and `model/frontier_analysis.py` for the implementation, and `runbook.md` for the skill-driven reproduction. ## Customize this template @@ -306,8 +307,8 @@ Focus on the first changes most users will make. ### Tune parameters -- **Frontier resolution** — increase `N_INTERIOR` in `model/reasoning.py` for a finer-grained Pareto frontier (more interior epsilon points between the two anchors). -- **Solve budget** — `time_limit_sec` on `problem.configure("highs", ...)` in `model/reasoning.py` caps each solve; raise it if larger rosters time out. +- **Frontier resolution** — increase `N_INTERIOR` in `model/shift_staffing.py` for a finer-grained Pareto frontier (more interior epsilon points between the two anchors). +- **Solve budget** — `time_limit_sec` on `problem.configure("highs", ...)` in `model/shift_staffing.py` caps each solve; raise it if larger rosters time out. ### Extend the model diff --git a/hospital_staffing/model/__init__.py b/hospital_staffing/model/__init__.py index fefb1a06..0e569e06 100644 --- a/hospital_staffing/model/__init__.py +++ b/hospital_staffing/model/__init__.py @@ -7,7 +7,9 @@ Every solve is a named Problem in the model: the two anchors, and the sweep points whose unmet-demand bounds are rules over the anchors' results, so one refresh solves the anchors -first and then the sweep. +first and then the sweep (`shift_staffing.py`). The model then reads the results as a +frontier: which solves form it, the marginal cost of each step along it, and the knee +(`frontier_analysis.py`). Run: `rai models deploy --path model` deploys this package to the schemas in @@ -15,8 +17,20 @@ `python -m queries.staffing_frontier` then prints the report from the deployed model. """ -from .reasoning import N_INTERIOR +from .frontier_analysis import FreeKnee, FrontierStep, JumpKnee from .schema import FrontierPoint, Nurse, Shift, SweepPoint, model +from .shift_staffing import N_INTERIOR from .source import DATA_DIR -__all__ = ["DATA_DIR", "N_INTERIOR", "FrontierPoint", "Nurse", "Shift", "SweepPoint", "model"] +__all__ = [ + "DATA_DIR", + "N_INTERIOR", + "FreeKnee", + "FrontierPoint", + "FrontierStep", + "JumpKnee", + "Nurse", + "Shift", + "SweepPoint", + "model", +] diff --git a/hospital_staffing/model/frontier_analysis.py b/hospital_staffing/model/frontier_analysis.py new file mode 100644 index 00000000..1007b5a9 --- /dev/null +++ b/hospital_staffing/model/frontier_analysis.py @@ -0,0 +1,139 @@ +"""Frontier analysis: which solves form the frontier and in what order, the marginal cost of each +service improvement along it, and the knee.""" + +from relationalai.semantics import Float, Integer, String, not_, where +from relationalai.semantics.std import aggregates as aggs +from relationalai.semantics.std import math, strings + +from .schema import FrontierPoint, model +from .shift_staffing import N_INTERIOR + +# -------------------------------------------------- +# Configure inputs +# -------------------------------------------------- + +# Smallest change that counts: a step that changes unmet demand by no more than this many +# patients is flat, and a rate of no more than this many dollars per patient is free. +TOLERANCE = 1e-6 + +# -------------------------------------------------- +# Frontier points +# -------------------------------------------------- + +# Position 0 is the cheapest anchor, 1..N_INTERIOR the sweep, N_INTERIOR + 1 the +# best-service anchor. +FrontierPoint.label = model.Property(f"{FrontierPoint} has label {String:label}") +model.where(FrontierPoint.position == 0).define(FrontierPoint.label("cheapest")) +model.where(FrontierPoint.position == N_INTERIOR + 1).define(FrontierPoint.label("best_service")) +model.where(FrontierPoint.position >= 1, FrontierPoint.position <= N_INTERIOR).define( + FrontierPoint.label(strings.concat("eps_", strings.string(FrontierPoint.position))) +) + +# A solve is on the frontier when it solved to optimality and every sweep point up to it +# did: the frontier ends at the first sweep point that did not solve, and the best-service +# anchor is on it only when the whole sweep solved. +FrontierPoint.on_frontier = model.Relationship(f"{FrontierPoint} is on the frontier") +FrontierPoint.sweep_solved = model.Property( + f"{FrontierPoint} follows {Integer:sweep_solved} optimal sweep points" +) +swept = FrontierPoint.ref() +model.define(FrontierPoint.sweep_solved( + aggs.count(swept).per(FrontierPoint).where( + swept.status == "OPTIMAL", + swept.position >= 1, + swept.position <= N_INTERIOR, + swept.position <= FrontierPoint.position, + ) +)) +model.where(FrontierPoint.position == 0, FrontierPoint.status == "OPTIMAL").define( + FrontierPoint.on_frontier() +) +model.where( + FrontierPoint.position >= 1, + FrontierPoint.position <= N_INTERIOR, + FrontierPoint.sweep_solved == FrontierPoint.position, +).define(FrontierPoint.on_frontier()) +model.where( + FrontierPoint.position == N_INTERIOR + 1, + FrontierPoint.status == "OPTIMAL", + FrontierPoint.sweep_solved == N_INTERIOR, +).define(FrontierPoint.on_frontier()) + +# The frontier's order: 1 for the cheapest anchor. The frontier is the positions from 0 up to +# its end, so point n is position n - 1. +FrontierPoint.number = model.Property(f"{FrontierPoint} is number {Integer:number} on the frontier") +model.where(FrontierPoint.on_frontier()).define(FrontierPoint.number(FrontierPoint.position + 1)) + +# -------------------------------------------------- +# Marginal analysis +# -------------------------------------------------- + +# FrontierStep n is the move from frontier point n to point n + 1: the overtime cost it adds, +# the unmet demand it removes, and the dollars per patient that costs. A flat step removes +# no unmet demand and has no rate. +FrontierStep = model.Concept("FrontierStep", identify_by={"number": Integer}) +FrontierStep.cost_added = model.Property(f"{FrontierStep} adds {Float:cost_added} of overtime cost") +FrontierStep.unmet_removed = model.Property( + f"{FrontierStep} removes {Float:unmet_removed} of unmet demand" +) +FrontierStep.rate = model.Property(f"{FrontierStep} costs {Float:rate} per patient") +step_from, step_to = FrontierPoint.ref(), FrontierPoint.ref() +model.where(step_to.number == step_from.number + 1).define( + FrontierStep.new(number=step_from.number) +) +model.where(FrontierStep.number == step_from.number, step_to.number == step_from.number + 1).define( + FrontierStep.cost_added(step_to.overtime_cost - step_from.overtime_cost), + FrontierStep.unmet_removed(step_from.unmet_demand - step_to.unmet_demand), +) +model.where(math.abs(FrontierStep.unmet_removed) > TOLERANCE).define( + FrontierStep.rate(FrontierStep.cost_added / FrontierStep.unmet_removed) +) + +# -------------------------------------------------- +# Knee +# -------------------------------------------------- + +# When service improves for free before the first paid step, the knee is the last free +# point; otherwise it is the point after the step whose rate is the largest multiple of +# the rate before it. A rate ($ per patient) is never compared with a ratio. With no +# paid step there is no knee, and a frontier of fewer than two steps has none. +first_paid = Integer.ref() +paid_step = FrontierStep.ref() +FirstPaidStep = model.Relationship(f"the first step with a rate above zero is {Integer:number}") +model.define(FirstPaidStep(aggs.min(paid_step.number).where(paid_step.rate > TOLERANCE))) + +# Free improvement: the knee is the point where the first paid step starts, and the figure +# is that step's rate. +FreeKnee = model.Relationship( + f"the knee is frontier point {Integer:number}, the last free improvement, before a step " + f"costing {Float:next_rate} per patient" +) +model.where(FirstPaidStep(first_paid), first_paid > 1, FrontierStep.number == first_paid).define( + FreeKnee(first_paid, FrontierStep.rate) +) + +# Largest jump: each paid step is followed by one at some multiple of its rate. The knee is +# the point after the step with the largest multiple above zero (the earliest on a tie), +# and the figure is that multiple. When no multiple is above zero the knee is point 2. +JumpKnee = model.Relationship( + f"the knee is frontier point {Integer:number}, where marginal cost jumps {Float:jump} times" +) +FrontierStep.rate_multiple = model.Property( + f"{FrontierStep} is followed by a step at {Float:rate_multiple} times its rate" +) +next_step, any_step = FrontierStep.ref(), FrontierStep.ref() +model.where(FrontierStep.rate > TOLERANCE, next_step.number == FrontierStep.number + 1).define( + FrontierStep.rate_multiple(next_step.rate / FrontierStep.rate) +) +model.where( + FirstPaidStep(first_paid), + first_paid == 1, + FrontierStep.rate_multiple > 0, + aggs.rank(-FrontierStep.rate_multiple, FrontierStep.number) == 1, +).define(JumpKnee(FrontierStep.number + 1, FrontierStep.rate_multiple)) +model.where( + FirstPaidStep(first_paid), + first_paid == 1, + FrontierStep.number == 2, + not_(where(any_step.rate_multiple > 0)), +).define(JumpKnee(2, 0.0)) diff --git a/hospital_staffing/model/schema.py b/hospital_staffing/model/schema.py index 1312846d..6590fd7e 100644 --- a/hospital_staffing/model/schema.py +++ b/hospital_staffing/model/schema.py @@ -33,7 +33,7 @@ Assignment.x_assigned = Property(f"{Assignment} is {Float:assigned}") # Epsilon-constraint points: SweepPoint i bounds total unmet demand by its eps_unmet, -# a rule over the two anchor solves' results (model/reasoning.py). +# a rule over the two anchor solves' results (model/shift_staffing.py). SweepPoint = Concept("SweepPoint", identify_by={"index": Integer}) SweepPoint.eps_unmet = Property(f"{SweepPoint} allows {Float:eps_unmet}") diff --git a/hospital_staffing/model/reasoning.py b/hospital_staffing/model/shift_staffing.py similarity index 98% rename from hospital_staffing/model/reasoning.py rename to hospital_staffing/model/shift_staffing.py index e0fd3b65..2f2e7e25 100644 --- a/hospital_staffing/model/reasoning.py +++ b/hospital_staffing/model/shift_staffing.py @@ -1,4 +1,5 @@ -"""Hospital staffing decision problems: two anchor solves and an epsilon-constraint sweep between them.""" +"""Shift staffing decision problems: two anchor solves and an epsilon-constraint sweep between +them.""" from relationalai.semantics import Float, String, std, sum from relationalai.semantics.reasoners.prescriptive import Problem diff --git a/hospital_staffing/queries/staffing_frontier.py b/hospital_staffing/queries/staffing_frontier.py index 2ec4f71c..12dd3c24 100644 --- a/hospital_staffing/queries/staffing_frontier.py +++ b/hospital_staffing/queries/staffing_frontier.py @@ -6,16 +6,18 @@ detection, and the nurse assignments at the knee. """ -from model import N_INTERIOR, FrontierPoint, Nurse, Shift, SweepPoint, model - - -def frontier_label(position): - if position == 0: - return "cheapest" - if position == N_INTERIOR + 1: - return "best_service" - return f"eps_{position}" - +from model import ( + N_INTERIOR, + FreeKnee, + FrontierPoint, + FrontierStep, + JumpKnee, + Nurse, + Shift, + SweepPoint, + model, +) +from relationalai.semantics import Float, Integer if __name__ == "__main__": status = model.select( @@ -74,30 +76,39 @@ def solved(position): print(f"Unmet demand targets: {[f'{eps_by_index[i]:.1f}' for i in sorted(eps_by_index)]}") print(f"{'=' * 70}") - # The report stops reading the sweep at its first failed point, and then leaves the - # best-service anchor out of the frontier, so no marginal rate spans the failed interval. - pareto = [{"position": cheapest, **points.loc[cheapest].to_dict()}] + # The model publishes the frontier: the cheapest anchor and the sweep points up to the first + # that failed, then the best-service anchor only when the whole sweep solved, so no marginal + # rate spans a failed interval. The report stops reading the sweep at the first failed point. + pareto = ( + model.select( + FrontierPoint.position.alias("position"), + FrontierPoint.number.alias("number"), + FrontierPoint.label.alias("label"), + FrontierPoint.overtime_cost.alias("overtime_cost"), + FrontierPoint.unmet_demand.alias("unmet_demand"), + ) + .where(FrontierPoint.on_frontier()) + .to_df() + .sort_values("number") + .to_dict("records") + ) + on_frontier = {pt["position"] for pt in pareto} sweep_complete = True for i in range(1, N_INTERIOR + 1): eps = eps_by_index.get(i) eps_text = f"{eps:.1f}" if eps is not None else "?" - if not solved(i): + if i not in on_frontier: point_status = points.loc[i, "status"] if i in points.index else "none" print(f" Point {i} (unmet<={eps_text}): {point_status} -- stopping") sweep_complete = False break pt = points.loc[i] - pareto.append({"position": i, **pt.to_dict()}) print( f" Point {i} (unmet<={eps_text}): overtime=${pt['overtime_cost']:.2f}, " f"actual_unmet={pt['unmet_demand']:.1f} [{pt['status']}]" ) - if sweep_complete: - pareto.append({"position": best, **points.loc[best].to_dict()}) - else: + if not sweep_complete: print(" The frontier below ends at the last solved sweep point.") - for pt in pareto: - pt["label"] = frontier_label(pt["position"]) # -------------------------------------------------- # Pareto analysis @@ -108,8 +119,8 @@ def solved(position): print(f"{'=' * 70}") print(f"{'#':>3} {'Label':>14} {'Unmet Demand':>14} {'Overtime Cost':>14}") print("-" * 48) - for j, pt in enumerate(pareto): - print(f"{j+1:>3} {pt['label']:>14} {pt['unmet_demand']:>14.1f} ${pt['overtime_cost']:>13.2f}") + for pt in pareto: + print(f"{pt['number']:>3} {pt['label']:>14} {pt['unmet_demand']:>14.1f} ${pt['overtime_cost']:>13.2f}") # ASCII Pareto plot: Overtime Cost (y) vs Unmet Demand (x) if len(pareto) >= 2: @@ -144,55 +155,69 @@ def solved(position): # Marginal analysis if len(pareto) >= 3: print("\nMarginal analysis (cost of reducing unmet demand by 1 patient):") - rates = [] - for j in range(len(pareto) - 1): - d_cost = pareto[j+1]['overtime_cost'] - pareto[j]['overtime_cost'] - d_unmet = pareto[j]['unmet_demand'] - pareto[j+1]['unmet_demand'] - if abs(d_unmet) > 1e-6: - rate = d_cost / d_unmet - rates.append(rate) - print(f" {pareto[j]['label']:>14} → {pareto[j+1]['label']:<14}: " - f"Δcost=${d_cost:>+10.2f}, Δunmet={-d_unmet:>+6.1f}, " - f"marginal=${rate:>8.2f}/patient") - else: - rates.append(0) - - # When service improves for free before the first paid step, the knee is the last free - # point; otherwise it is the largest ratio between consecutive positive rates. A rate - # ($ per patient) is never compared with a ratio. With no paid step there is no knee. - if len(rates) >= 2: - first_paid = next((j for j, rate in enumerate(rates) if rate > 1e-6), None) - if first_paid is None: - knee_idx = None - elif first_paid > 0: - knee_idx = first_paid - knee_text = (f"the last free improvement; the next costs " - f"${rates[first_paid]:.2f}/patient") - else: - max_jump, knee_idx = 0, 1 - for j in range(len(rates) - 1): - if rates[j] > 1e-6 and rates[j+1] / rates[j] > max_jump: - max_jump, knee_idx = rates[j+1] / rates[j], j + 1 - knee_text = f"marginal cost jumps {max_jump:.1f}x beyond this point" - if knee_idx is None: - print("\n No knee: no service improvement has a positive marginal cost.") - else: - print(f"\n Knee: Point {knee_idx + 1} ({pareto[knee_idx]['label']}) -- {knee_text}") - print(f" Recommendation: Target {pareto[knee_idx]['unmet_demand']:.0f} unmet patients " - f"at ${pareto[knee_idx]['overtime_cost']:.2f} overtime cost -- " - f"further service improvement costs significantly more per patient.") - - # Print nurse assignments at the knee point - knee_assignments = model.select( - Nurse.name.alias("nurse"), Shift.name.alias("shift") - ).where( - FrontierPoint.position == int(pareto[knee_idx]["position"]), - FrontierPoint.assigns(Nurse, Shift), - ).to_df() - if not knee_assignments.empty: - print("\n Knee-point assignments:") - by_shift = knee_assignments.groupby("shift")["nurse"] - - for shift, nurses in by_shift: - nurses = ", ".join(sorted(nurses)) - print(f" {shift}: {nurses}") + # The model publishes each step between consecutive frontier points; a flat step has + # no rate, so it has no line. + steps = ( + model.select( + FrontierStep.number.alias("number"), + FrontierStep.cost_added.alias("cost_added"), + FrontierStep.unmet_removed.alias("unmet_removed"), + FrontierStep.rate.alias("rate"), + ) + .to_df() + .sort_values("number") + ) + for step in steps.itertuples(): + j = step.number - 1 + print(f" {pareto[j]['label']:>14} → {pareto[j+1]['label']:<14}: " + f"Δcost=${step.cost_added:>+10.2f}, Δunmet={-step.unmet_removed:>+6.1f}, " + f"marginal=${step.rate:>8.2f}/patient") + + # The model publishes the knee: when service improves for free before the first paid + # step, the last free point; otherwise the point after the largest jump between + # consecutive rates. With no paid step there is no knee. + free_number, next_rate, jump_number, jump = ( + Integer.ref(), Float.ref(), Integer.ref(), Float.ref() + ) + free_knee = ( + model.where(FreeKnee(free_number, next_rate)) + .select(free_number.alias("number"), next_rate.alias("next_rate")) + .to_df() + ) + jump_knee = ( + model.where(JumpKnee(jump_number, jump)) + .select(jump_number.alias("number"), jump.alias("jump")) + .to_df() + ) + if not free_knee.empty: + knee_number = int(free_knee["number"].iloc[0]) + knee_text = (f"the last free improvement; the next costs " + f"${free_knee['next_rate'].iloc[0]:.2f}/patient") + elif not jump_knee.empty: + knee_number = int(jump_knee["number"].iloc[0]) + knee_text = f"marginal cost jumps {jump_knee['jump'].iloc[0]:.1f}x beyond this point" + else: + knee_number = None + if knee_number is None: + print("\n No knee: no service improvement has a positive marginal cost.") + else: + knee = pareto[knee_number - 1] + print(f"\n Knee: Point {knee_number} ({knee['label']}) -- {knee_text}") + print(f" Recommendation: Target {knee['unmet_demand']:.0f} unmet patients " + f"at ${knee['overtime_cost']:.2f} overtime cost -- " + f"further service improvement costs significantly more per patient.") + + # Print nurse assignments at the knee point + knee_assignments = model.select( + Nurse.name.alias("nurse"), Shift.name.alias("shift") + ).where( + FrontierPoint.position == int(knee["position"]), + FrontierPoint.assigns(Nurse, Shift), + ).to_df() + if not knee_assignments.empty: + print("\n Knee-point assignments:") + by_shift = knee_assignments.groupby("shift")["nurse"] + + for shift, nurses in by_shift: + nurses = ", ".join(sorted(nurses)) + print(f" {shift}: {nurses}") diff --git a/humanitarian-aid-supply-chain/README.md b/humanitarian-aid-supply-chain/README.md index 8b0de0fa..df1df617 100644 --- a/humanitarian-aid-supply-chain/README.md +++ b/humanitarian-aid-supply-chain/README.md @@ -42,7 +42,7 @@ Built using **graph analysis** — PageRank (an iterative random-walk algorithm) ## What's included -- **Model**: the model configuration, graph creation, and the PageRank, degree centrality, indegree, and outdegree metrics, in the `model/` package (`schema.py` declares the concepts, `source.py` loads the sample data, `reasoning.py` states the graph and metrics). `rai models deploy --path model` deploys it to your Snowflake account, where each refresh computes the metrics. +- **Model**: the model configuration, graph creation, and the PageRank, degree centrality, indegree, and outdegree metrics, in the `model/` package (`schema.py` declares the concepts, `source.py` loads the sample data, `supply_network.py` states the graph, the metrics, and the strategic categories). `rai models deploy --path model` deploys it to your Snowflake account, where each refresh computes the metrics. - **Query**: `queries/distribution_point_ranking.py` - prints the detailed report from the deployed model - **Runbook**: `runbook.md` — a paste-testable walkthrough that reproduces the template step by step with the RAI skills; as important a reference as the script itself. - **Interactive app**: `app.py` - Streamlit web application with visualizations and interactive analysis, querying the deployed model @@ -190,7 +190,7 @@ humanitarian-aid-supply-chain/ │ ├── __init__.py # exports of the deployed model │ ├── schema.py # DistributionPoint and SupplyRoute concepts │ ├── source.py # loads the sample CSVs -│ └── reasoning.py # flow weight, graph, and metrics +│ └── supply_network.py # flow weight, graph, metrics, and categories ├── queries/ │ └── distribution_point_ranking.py # report from the deployed model ├── app.py # optional Streamlit dashboard (queries the deployed model) @@ -239,7 +239,7 @@ CSV files → model/ (deployed) → Calculate PageRank → Calculate Degree Cent **Display strategic analysis and recommendations.** `queries/distribution_point_ranking.py` prints a ranked table of all points with both metrics, the strategic-category breakdown, network-wide and regional statistics, and recommendations for response teams. The Streamlit app adds an interactive overview, a color-coded network visualization, filterable rankings with CSV export, and per-category detail. -See `model/reasoning.py` and `queries/distribution_point_ranking.py` for the implementation, and `runbook.md` for the skill-driven reproduction. +See `model/supply_network.py` and `queries/distribution_point_ranking.py` for the implementation, and `runbook.md` for the skill-driven reproduction. ## Customize this template @@ -254,7 +254,7 @@ Focus on the first changes most users will make. ### Tune parameters - **PageRank damping factor** — higher damping (0.90-0.95) emphasizes network structure over teleportation; lower damping (0.70-0.80) emphasizes direct connections over global influence. -- **Edge-weight formula** — change the `flow_weight` formula in `model/reasoning.py` to reweight the graph. Higher weights indicate stronger connections that PageRank favors. +- **Edge-weight formula** — change the `flow_weight` formula in `model/supply_network.py` to reweight the graph. Higher weights indicate stronger connections that PageRank favors. The current formula `(route_capacity * reliability_score) / distance_km` balances all three factors. Alternatives: - Capacity-focused: `route_capacity` (maximize throughput) diff --git a/humanitarian-aid-supply-chain/model/__init__.py b/humanitarian-aid-supply-chain/model/__init__.py index 017e13a3..82a42af8 100644 --- a/humanitarian-aid-supply-chain/model/__init__.py +++ b/humanitarian-aid-supply-chain/model/__init__.py @@ -7,6 +7,9 @@ - Apply PageRank to identify the most influential distribution hubs where aid naturally flows. - Calculate Degree Centrality to find highly connected critical nodes that serve as network hubs. - Calculate each point's incoming and outgoing route counts. +- Classify each point into a strategic category from its PageRank and Degree Centrality. + +`supply_network.py` states the flow weight, the graph, the metrics, and the categories. Run: `rai models deploy --path model` deploys this package to the schemas in @@ -15,9 +18,9 @@ `streamlit run app.py` starts the interactive app, both from the deployed model. """ -from .reasoning import degree_centrality, graph, indegree, outdegree, pagerank from .schema import DistributionPoint, SupplyRoute, model from .source import DATA_DIR +from .supply_network import degree_centrality, graph, indegree, outdegree, pagerank __all__ = [ "DATA_DIR", diff --git a/humanitarian-aid-supply-chain/model/reasoning.py b/humanitarian-aid-supply-chain/model/supply_network.py similarity index 96% rename from humanitarian-aid-supply-chain/model/reasoning.py rename to humanitarian-aid-supply-chain/model/supply_network.py index 8586c711..1f932a17 100644 --- a/humanitarian-aid-supply-chain/model/reasoning.py +++ b/humanitarian-aid-supply-chain/model/supply_network.py @@ -1,4 +1,5 @@ -"""Supply route graph: PageRank, degree centrality, route counts, and strategic categories.""" +"""Supply route graph: each route's flow weight, PageRank, degree centrality, each point's route counts, and +its strategic category.""" from relationalai.semantics import Float, Integer, String, define from relationalai.semantics.reasoners.graph import Graph diff --git a/humanitarian-aid-supply-chain/queries/distribution_point_ranking.py b/humanitarian-aid-supply-chain/queries/distribution_point_ranking.py index 7c61fd9a..57f20d32 100644 --- a/humanitarian-aid-supply-chain/queries/distribution_point_ranking.py +++ b/humanitarian-aid-supply-chain/queries/distribution_point_ranking.py @@ -26,8 +26,8 @@ DistributionPoint.category.alias("category"), ).to_df() - # Sort by PageRank (primary) then Degree Centrality (secondary) - results = results.sort_values(["pagerank", "degree_centrality"], ascending=False) + # Sort by PageRank (primary) then Degree Centrality (secondary), ties to the smaller id + results = results.sort_values(["pagerank", "degree_centrality", "id"], ascending=[False, False, True]) results.insert(0, 'rank', range(1, len(results) + 1)) # Display header diff --git a/it-dependency-mapping/README.md b/it-dependency-mapping/README.md index 14919720..db72a1f6 100644 --- a/it-dependency-mapping/README.md +++ b/it-dependency-mapping/README.md @@ -44,7 +44,7 @@ Built using RelationalAI's **variable-length path enumeration** (`model.path(... ## What's included -- **Model**: the features, dependency edges, path pattern, and depth rule in the `model/` package (`schema.py` declares the concepts, `source.py` loads the sample data, `reasoning.py` states the path pattern and depth rule), which `rai models deploy --path model` deploys to your Snowflake account. +- **Model**: the features, dependency edges, path pattern, and depth rule in the `model/` package (`schema.py` declares the concepts, `source.py` loads the sample data, `downstream_paths.py` states the path pattern, depth rule, and path summaries, `maximal_chains.py` marks the maximal and longest chains), which `rai models deploy --path model` deploys to your Snowflake account. - **Query**: `queries/dependency_chain_report.py` -- prints the path counts, maximal chains, and owner blast radius from the deployed model. - **Runbook**: `runbook.md` — a paste-testable walkthrough that reproduces the template step by step with the RAI skills; as important a reference as the code in `model/`. - **Data**: `data/features.csv` (14 features across tiers) and `data/dependencies.csv` (15 dependency edges) @@ -162,7 +162,8 @@ it-dependency-mapping/ │ ├── __init__.py # exports of the deployed model │ ├── schema.py # Feature concept and contributes_to relationship │ ├── source.py # loads the sample CSVs -│ └── reasoning.py # path pattern and depth rule +│ ├── downstream_paths.py # path pattern, depth rule, path counts and summaries +│ └── maximal_chains.py # maximal chains and the longest one ├── queries/ │ └── dependency_chain_report.py # report printed from the deployed model └── data/ @@ -210,13 +211,13 @@ CSV files --> Define Feature + contributes_to --> Enumerate downstream paths --> **Load the ontology.** A `Feature` is any node in the estate -- a raw source, pipeline, feature job, service, or dashboard -- with `id`, `name`, `owner`, and `deploy_tier` loaded from `data/features.csv`. The `contributes_to` self-relationship records that an upstream feature feeds a downstream one, forming the dependency DAG from `data/dependencies.csv`. -**Enumerate downstream paths.** A variable-length traversal of 1 to `MAX_DEPTH` `contributes_to` edges, enumerated with `.all().paths()`, walks every downstream dependency path. The model publishes each path as one row per visited node, and the number of paths that start at each feature (a feature with no downstream path has no count or depth row, and the report shows it as 0); grouping by path reassembles the ordered chain, and the hop count comes from the maximum node index. +**Enumerate downstream paths.** A variable-length traversal of 1 to `MAX_DEPTH` `contributes_to` edges, enumerated with `.all().paths()`, walks every downstream dependency path. The model publishes each path as one row per visited node, and the number of paths that start at each feature (a feature with no downstream path has a count and depth of 0). It also publishes a summary of each path: its hop count (the maximum node index), number of features and distinct owners, and its chain label, the feature names in step order joined with `->`. **Persist longest downstream depth.** The longest path starting at each feature is its downstream depth. RelationalAI computes it in PyRel — a max over path length per source endpoint — and defines it straight onto the feature as a first-class `max_downstream_depth` relationship, with no DataFrame round-trip, so later queries can rank features by reach without re-enumerating paths. -**Reduce to maximal chains.** The full path set contains every sub-chain. A path is *maximal* when its node sequence is not a contiguous sub-chain of any other enumerated path -- it cannot be extended upstream or downstream. Filtering to maximal chains leaves only the end-to-end propagation paths. The single longest maximal chain is the worst-case blast radius: joining owner metadata onto its features shows every person a change at the root would have to clear before it reaches the final consumer. +**Reduce to maximal chains.** The full path set contains every sub-chain. A path is *maximal* when its node sequence is not a contiguous sub-chain of any other enumerated path -- it cannot be extended upstream or downstream. The model marks the maximal chains, which leaves only the end-to-end propagation paths, and the single longest one (most hops, ties by chain label and then path id). The longest maximal chain is the worst-case blast radius: its owner count and the owner metadata of its features show every person a change at the root would have to clear before it reaches the final consumer. -See `model/reasoning.py` for the implementation, `queries/dependency_chain_report.py` for the report, and `runbook.md` for the skill-driven reproduction. +See `model/downstream_paths.py` and `model/maximal_chains.py` for the implementation, `queries/dependency_chain_report.py` for the report, and `runbook.md` for the skill-driven reproduction. ## Expected output @@ -253,7 +254,7 @@ The deepest chain runs five hops from a raw source all the way to a downstream d ### Tune parameters -- `MAX_DEPTH` (default `8`, at the top of `model/reasoning.py`) bounds the traversal length. Raise it if your estate has longer chains than the sample; lower it to cap enumeration on a denser graph. Chains longer than `MAX_DEPTH` are not enumerated, so below the estate's longest chain the report's maximal chains are maximal only within that bound, not end to end. +- `MAX_DEPTH` (default `8`, at the top of `model/downstream_paths.py`) bounds the traversal length. Raise it if your estate has longer chains than the sample; lower it to cap enumeration on a denser graph. Chains longer than `MAX_DEPTH` are not enumerated, so below the estate's longest chain the report's maximal chains are maximal only within that bound, not end to end. ### Extend the model diff --git a/it-dependency-mapping/model/__init__.py b/it-dependency-mapping/model/__init__.py index f1df094f..91ffc26d 100644 --- a/it-dependency-mapping/model/__init__.py +++ b/it-dependency-mapping/model/__init__.py @@ -8,12 +8,16 @@ - Enumerates every downstream dependency path with ``model.path(Feature.contributes_to.repeat(1, N)).all().paths()`` -- because the estate is acyclic, every enumerated path is simple. -- Publishes each path's steps, the number of paths starting at each feature, - and each feature's longest downstream depth (Feature.max_downstream_depth). +- Publishes each path's steps, the number of paths starting at each feature, each + feature's longest downstream depth (Feature.max_downstream_depth), and each + path's hop count, feature count, owner count, and chain label. +- Marks the maximal chains (longest non-extendable dependency chains, with + shorter sub-chains dropped) and the longest of them. `downstream_paths.py` + holds the paths and their summaries; `maximal_chains.py` holds the maximal and + longest chains and imports the module whose declarations it reads. -The report reduces the published paths to their maximal chains (longest -non-extendable dependency chains, with shorter sub-chains dropped) and prints -per-feature path counts, the deepest chains, and the owners along the longest. +The report prints the path total, per-feature path counts and longest downstream +depth, the maximal chains, and the owners along the longest chain. Run: `rai models deploy --path model` deploys this package to the schemas in @@ -21,8 +25,19 @@ queries.dependency_chain_report` then prints the report from the deployed model. """ -from .reasoning import MAX_DEPTH, DependencyPathStep +from .downstream_paths import MAX_DEPTH, DependencyPathStep, NumPaths, PathSummary +from .maximal_chains import LongestChain, MaximalChain from .schema import Feature, model from .source import DATA_DIR -__all__ = ["DATA_DIR", "MAX_DEPTH", "DependencyPathStep", "Feature", "model"] +__all__ = [ + "DATA_DIR", + "MAX_DEPTH", + "DependencyPathStep", + "Feature", + "LongestChain", + "MaximalChain", + "NumPaths", + "PathSummary", + "model", +] diff --git a/it-dependency-mapping/model/reasoning.py b/it-dependency-mapping/model/downstream_paths.py similarity index 58% rename from it-dependency-mapping/model/reasoning.py rename to it-dependency-mapping/model/downstream_paths.py index e73c95f9..9591d373 100644 --- a/it-dependency-mapping/model/reasoning.py +++ b/it-dependency-mapping/model/downstream_paths.py @@ -1,6 +1,7 @@ -"""Downstream dependency paths: path enumeration and each feature's longest downstream depth.""" +"""Downstream dependency paths: path enumeration, each feature's path count and longest downstream +depth, and each path's hop count, feature count, owner count, and chain label.""" -from relationalai.semantics import Hash, Integer +from relationalai.semantics import Hash, Integer, String, distinct from relationalai.semantics.std import aggregates as aggs from .schema import Feature, model @@ -45,3 +46,34 @@ model.where(p).define(DependencyPathStep(p, Feature(p.nodes), p.nodes["index"])) Feature.paths_downstream = model.Relationship(f"{Feature} starts {Integer:paths_downstream} paths") model.define(src.paths_downstream(aggs.count(p).per(src))).where(p) + +# A feature with no outgoing edge starts no path, so its count and depth are zero. +Feature.has_downstream = model.Relationship(f"{Feature} has a downstream feature") +Feature.has_upstream = model.Relationship(f"{Feature} has an upstream feature") +_next, _previous = Feature.ref(), Feature.ref() +model.where(Feature.contributes_to(_next)).define(Feature.has_downstream()) +model.where(_previous.contributes_to(Feature)).define(Feature.has_upstream()) +model.where(model.not_(Feature.has_downstream())).define( + Feature.paths_downstream(0), Feature.max_downstream_depth(0) +) + +# The number of enumerated paths. +NumPaths = model.Relationship(f"the estate has {Integer:num_paths} downstream dependency paths") +model.define(NumPaths(aggs.count(p))).where(p) + +# Each path's hop count (its last step), number of features, number of distinct owners, and chain +# label: the feature names in step order joined with " -> ". +PathSummary = model.Relationship( + f"dependency path {Hash:path} has {Integer:hops} hops over {Integer:n_features} features " + f"with {Integer:n_owners} owners as chain {String:chain}" +) +_path, _node, _step = Hash.ref(), Feature.ref(), Integer.ref() +model.where(DependencyPathStep(_path, _node, _step)).define( + PathSummary( + _path, + aggs.max(_step).per(_path), + aggs.count(_step).per(_path), + aggs.count(distinct(_node.owner)).per(_path), + aggs.string_join(_node.name, sep=" -> ", index=_step).per(_path), + ) +) diff --git a/it-dependency-mapping/model/maximal_chains.py b/it-dependency-mapping/model/maximal_chains.py new file mode 100644 index 00000000..768a70c9 --- /dev/null +++ b/it-dependency-mapping/model/maximal_chains.py @@ -0,0 +1,34 @@ +"""Maximal dependency chains: the paths no other enumerated path extends, and the longest of them.""" + +from relationalai.semantics import Hash, Integer, String +from relationalai.semantics.std import aggregates as aggs + +# Declares the path steps and summaries and the Feature.has_upstream and has_downstream flags. +from .downstream_paths import MAX_DEPTH, DependencyPathStep, PathSummary +from .schema import Feature, model + +# A path is maximal when no enumerated path contains it as a contiguous stretch: no feature feeds +# its first feature and none follows its last. A path of MAX_DEPTH hops is maximal too, because no +# longer path is enumerated. In an acyclic estate only a path's last feature can lack a downstream +# feature. +MaximalChain = model.Relationship(f"dependency path {Hash:path} is a maximal chain") +_path, _step = Hash.ref(), Integer.ref() +_first, _last, _end = Feature.ref(), Feature.ref(), Feature.ref() +model.where( + DependencyPathStep(_path, _first, 0), + DependencyPathStep(_path, _last, _step), + model.not_(_first.has_upstream()), + model.not_(_last.has_downstream()), +).define(MaximalChain(_path)) +model.where(DependencyPathStep(_path, _end, MAX_DEPTH)).define(MaximalChain(_path)) + +# The longest maximal chain: most hops first, ties broken by the chain label and then the path id, +# so exactly one path qualifies even when two chains share a label. The hop count is negated so +# every key sorts ascending. +LongestChain = model.Relationship(f"dependency path {Hash:path} is the longest maximal chain") +_hops, _n_features, _n_owners, _chain = Integer.ref(), Integer.ref(), Integer.ref(), String.ref() +model.where( + MaximalChain(_path), + PathSummary(_path, _hops, _n_features, _n_owners, _chain), + aggs.rank(-_hops, _chain, _path) == 1, +).define(LongestChain(_path)) diff --git a/it-dependency-mapping/queries/dependency_chain_report.py b/it-dependency-mapping/queries/dependency_chain_report.py index df5e77aa..c88637b0 100644 --- a/it-dependency-mapping/queries/dependency_chain_report.py +++ b/it-dependency-mapping/queries/dependency_chain_report.py @@ -8,41 +8,23 @@ along the single longest chain (the upgrade / incident blast radius). """ -from model import MAX_DEPTH, DependencyPathStep, Feature, model -from relationalai.semantics import Hash, Integer +from model import ( + MAX_DEPTH, + DependencyPathStep, + Feature, + LongestChain, + MaximalChain, + NumPaths, + PathSummary, + model, +) +from relationalai.semantics import Hash, Integer, String if __name__ == "__main__": print("=== IT Dependency Mapping: downstream paths ===") - # The node sequence of each path (for display-side reassembly), as the model - # publishes it. - path, step = Hash.ref(), Integer.ref() - paths_df = ( - model.where(DependencyPathStep(path, Feature, step)) - .select( - path.alias("path_id"), - step.alias("step"), - Feature.id.alias("feature_id"), - Feature.name.alias("feature_name"), - ) - .to_df() - ) - paths_df = paths_df.sort_values(["path_id", "step"]) - - # Reassemble each path: order steps by node index, join the visited features into - # an ordered chain. The hop count is the max node index (a path over N edges has - # nodes at indices 0..N). String-joining names into a chain label is a pandas job. - chains = ( - paths_df.groupby("path_id") - .agg( - hops=("step", "max"), - node_ids=("feature_id", lambda s: tuple(s)), - chain=("feature_name", lambda s: " -> ".join(s)), - ) - .reset_index() - ) - - print(f"\nTotal downstream dependency paths (1-{MAX_DEPTH} hops): {len(chains)}") + total_paths = int(model.select(NumPaths).to_df().iloc[0, 0]) + print(f"\nTotal downstream dependency paths (1-{MAX_DEPTH} hops): {total_paths}") # -------------------------------------------------- # Per-feature path counts and longest downstream depth (in-PyRel aggregates) @@ -55,7 +37,7 @@ Feature.deploy_tier.alias("deploy_tier"), ).to_df() - # Paths starting at each feature, counted in the model (see model/reasoning.py). + # Paths starting at each feature, counted in the model (see model/downstream_paths.py). paths_started = Integer.ref() paths_started_df = ( model.where(Feature.paths_downstream(paths_started)) @@ -63,25 +45,17 @@ .to_df() ) - # Read the persisted depth back for the display table. Features with no outgoing - # path (the leaf dashboards) have no max_downstream_depth row -- fill them as 0. + # Read the persisted depth back for the display table; leaf features carry 0. max_depth_df = model.select( Feature.id.alias("feature_id"), Feature.max_downstream_depth.alias("max_downstream_depth"), ).to_df() - # Build the per-feature display table from the query results above (NOT from a - # pandas groupby on chains): paths_downstream from the count query, depth from the - # persisted property. + # Build the per-feature display table from the query results above: paths_downstream + # from the count query, depth from the persisted property. feature_summary = feature_df.merge( paths_started_df, on="feature_id", how="left" ).merge(max_depth_df, on="feature_id", how="left") - feature_summary["paths_downstream"] = ( - feature_summary["paths_downstream"].fillna(0).astype(int) - ) - feature_summary["max_downstream_depth"] = ( - feature_summary["max_downstream_depth"].fillna(0).astype(int) - ) print("\n=== Per-feature downstream reach ===") print( @@ -99,34 +73,33 @@ # -------------------------------------------------- # Maximal chains: longest non-extendable dependency chains # -------------------------------------------------- - # A path is maximal when its node sequence is not a contiguous sub-chain of any - # other enumerated path -- i.e. it cannot be extended upstream or downstream. - # This collapses the full path set to the small set of end-to-end chains. - - all_sequences = list(chains["node_ids"]) - - - def is_sub_chain(short, long): - """True if `short` is a contiguous sub-sequence of the longer `long`.""" - if len(short) >= len(long): - return False - return any( - long[i : i + len(short)] == short - for i in range(len(long) - len(short) + 1) - ) - - - maximal = chains[ - chains["node_ids"].apply( - lambda seq: not any( - is_sub_chain(seq, other) for other in all_sequences if other != seq - ) - ) - ].copy() - maximal = maximal.sort_values(["hops", "chain"], ascending=[False, True]) + # The model marks the paths no other enumerated path extends upstream or downstream, + # collapsing the full path set to the small set of end-to-end chains. + + path, hops, n_features, n_owners, chain = ( + Hash.ref(), + Integer.ref(), + Integer.ref(), + Integer.ref(), + String.ref(), + ) + summary_columns = ( + hops.alias("hops"), + n_features.alias("n_features"), + n_owners.alias("n_owners"), + chain.alias("chain"), + ) + # The path id keeps distinct chains that share a label as separate rows and breaks ties + # in the same order as the model's longest-chain rank. + maximal = ( + model.where(MaximalChain(path), PathSummary(path, hops, n_features, n_owners, chain)) + .select(path.alias("path"), *summary_columns) + .to_df() + .sort_values(["hops", "chain", "path"], ascending=[False, True, True]) + ) print( - f"\n=== Maximal dependency chains ({len(maximal)} of {len(chains)} paths) ===" + f"\n=== Maximal dependency chains ({len(maximal)} of {total_paths} paths) ===" ) for _, r in maximal.iterrows(): print(f" {r['hops']} hops: {r['chain']}") @@ -135,23 +108,35 @@ def is_sub_chain(short, long): # Owners along the single longest chain (blast radius) # -------------------------------------------------- # The longest chain is the worst-case propagation path: a change at its root has - # to clear every owner along the way. Join owner metadata onto its features. + # to clear every owner along the way. The model publishes its span; its features + # are read back in step order. - owner_by_id = dict(zip(feature_df["feature_id"], feature_df["owner"])) - name_by_id = dict(zip(feature_df["feature_id"], feature_df["feature_name"])) - tier_by_id = dict(zip(feature_df["feature_id"], feature_df["deploy_tier"])) - - longest = maximal.iloc[0] - longest_ids = longest["node_ids"] - distinct_owners = len({owner_by_id[i] for i in longest_ids}) + longest = ( + model.where(LongestChain(path), PathSummary(path, hops, n_features, n_owners, chain)) + .select(*summary_columns) + .to_df() + .iloc[0] + ) + step = Integer.ref() + longest_features = ( + model.where(LongestChain(path), DependencyPathStep(path, Feature, step)) + .select( + step.alias("step"), + Feature.name.alias("feature_name"), + Feature.owner.alias("owner"), + Feature.deploy_tier.alias("deploy_tier"), + ) + .to_df() + .sort_values("step") + ) print(f"\n=== Longest dependency chain: {longest['hops']} hops ===") print(f" Chain: {longest['chain']}") - print(f" Spans {len(longest_ids)} features and {distinct_owners} owners:") - for i in longest_ids: - print(f" - {name_by_id[i]:<30} owner={owner_by_id[i]:<14} tier={tier_by_id[i]}") + print(f" Spans {longest['n_features']} features and {longest['n_owners']} owners:") + for _, f in longest_features.iterrows(): + print(f" - {f['feature_name']:<30} owner={f['owner']:<14} tier={f['deploy_tier']}") print( - f"\n A change at '{name_by_id[longest_ids[0]]}' propagates through " - f"{len(longest_ids) - 1} downstream feature(s) before reaching " - f"'{name_by_id[longest_ids[-1]]}'." + f"\n A change at '{longest_features['feature_name'].iloc[0]}' propagates through " + f"{longest['hops']} downstream feature(s) before reaching " + f"'{longest_features['feature_name'].iloc[-1]}'." ) diff --git a/memory_supply_allocation/README.md b/memory_supply_allocation/README.md index a5cf09d7..5a708c52 100644 --- a/memory_supply_allocation/README.md +++ b/memory_supply_allocation/README.md @@ -43,12 +43,12 @@ This template shows how RelationalAI answers that question on a single shared mo ## What's included -- `model/` -- the deployed model: `schema.py` declares the concepts and the forecast task relationships, `source.py` loads the bundled CSVs and the rolling-horizon disruption data, `reasoning.py` states the rules, the supplier-capability GNN, the three rolling-horizon problems with the rules that publish their results, the dependency-chain paths, and the two what-ifs +- `model/` -- the deployed model: `schema.py` declares the concepts and the forecast task relationships, `source.py` loads the bundled CSVs and the rolling-horizon disruption data, and one module per stage states the rules: `customer_dependencies.py` (Stage 1 yield and floor rules), `capability_forecast.py` (the supplier-capability GNN and its forecast), `rolling_horizon.py` (the three rolling-horizon problems with the rules that publish their results, plan diffs, and per-customer allocation and demand), `dependency_chains.py` (the dependency-chain paths and routes), and `disruption_what_ifs.py` (the two what-ifs and their widest impacts) - `train.py` -- trains the supplier-capability GNN over the deployed splits and registers its version - `queries/allocation_report.py` -- prints the forecast summary, each rolling-horizon solve with its plan diff and service levels, the dependency chains, the what-if rankings, and a headline from the deployed model - `runbook.md` -- a paste-testable walkthrough that reproduces the template step by step with the RAI skills, one prompt per stage - Sample data: 13 CSVs under `data/` (customers, products, periods, demand, suppliers, capacity, inputs, dependencies, and the disruption schedule) -- Outputs: per-iteration LP status, margin and allocations, dependency chains, and what-if rankings, all queryable from the deployed ontology; the report derives plan diffs and service levels from the published allocations +- Outputs: per-iteration LP status, margin and allocations, dependency chains, and what-if rankings, all queryable from the deployed ontology; the model publishes each iteration's plan diff against the prior plan and each customer's allocation and demand ## Prerequisites @@ -153,7 +153,7 @@ Use this sequence to deploy the model, train the GNN, and query the rolling-hori predictive: name: memory_supply_gnn # created on first use if it doesn't exist gnns: - supplier_capability: # the GNN's name in model/reasoning.py + supplier_capability: # the GNN's name in model/capability_forecast.py registry: .MEMORY_SUPPLY_ALLOCATION model: SUPPLIER_CAPABILITY version: V1 # train.py registers this version @@ -278,7 +278,11 @@ Use this sequence to deploy the model, train the GNN, and query the rolling-hori │ ├── __init__.py # exports for train.py and the query │ ├── schema.py # concepts and the forecast task relationships │ ├── source.py # loads the CSVs, the GNN splits, and the disruption data -│ └── reasoning.py # rules, GNN, rolling-horizon problems, paths, what-ifs +│ ├── customer_dependencies.py # Stage 1: yield, floor, and SPOF rules +│ ├── capability_forecast.py # Stage 2: GNN and forecast +│ ├── rolling_horizon.py # Stage 3: rolling-horizon problems, plan diffs, allocation and demand +│ ├── dependency_chains.py # Stage 4: dependency chains and routes +│ └── disruption_what_ifs.py # Stage 4: supplier-offline and input-shortage what-ifs ├── queries/ │ └── allocation_report.py # prints the forecast, plans, chains, and what-ifs └── data/ # sample input CSVs @@ -324,7 +328,7 @@ The model is one shared ontology that all four reasoners read and write. - **Primary identifiers**: single-column integer ids for the base entities; composite keys for the junctions (e.g. `Demand` is keyed by `(customer_id, product_id, period_id)`). - **Important invariants**: demand and capacity are non-negative USD; `base_service_floor_pct`, `elevated_floor_pct`, `declared_yield_pct`, `intensity`, and `capability_pct` are fractions in `[0, 1]`; each customer's allocation must lie between its service floor and its yield-adjusted demand. -Alongside the base entities, Stage 1 rules-authors several derived `Customer` attributes (yield limits, elevated floors, single-point-of-failure flags), and Stages 2–4 create intermediate and output concepts — a supplier-capability forecast, per-iteration effective capacity, and per-scenario margin — that persist in the ontology for later querying. For the full concept and property definitions, see `model/schema.py`; `model/reasoning.py` holds the rules, the GNN, and the problems, and `runbook.md` builds them step by step with the RAI skills. +Alongside the base entities, Stage 1 rules-authors several derived `Customer` attributes (yield limits, elevated floors, single-point-of-failure flags), and Stages 2–4 create intermediate and output concepts — a supplier-capability forecast, per-iteration effective capacity, and per-scenario margin — that persist in the ontology for later querying. For the full concept and property definitions, see `model/schema.py`; the stage modules in `model/` hold the rules, the GNN, and the problems, and `runbook.md` builds them step by step with the RAI skills. ## How it works @@ -356,16 +360,16 @@ Each solve is its own named `Problem` (`memory_supply_allocation_iter_0` to `_2` ### Tune parameters -- **`USE_PRECOMPUTED_FORECAST`** (`model/reasoning.py`): `True` deploys no GNN and loads the bundled forecast snapshot instead — the fastest path for iteration; skip the Train step. +- **`USE_PRECOMPUTED_FORECAST`** (`model/capability_forecast.py`): `True` deploys no GNN and loads the bundled forecast snapshot instead — the fastest path for iteration; skip the Train step. - **`HORIZON_END_PERIOD`** (`model/source.py`) and `data/periods.csv`: change the horizon length (keep the two in sync). - **`data/disruption_reveal.csv`**: edit the rolling-horizon disruption schedule. Each row is `(reveal_period, target_type, target_id, parameter_name, parameter_value, start_period, end_period, narrative)`; lower `parameter_value` to increase severity. A supplier disruption applies from `start_period` through `end_period`; an input disruption holds from its reveal through the end of the horizon, ignoring `end_period`. -- **GNN knobs** (`GNN_N_EPOCHS`, `GNN_LR`, `GNN_SEED` in `model/reasoning.py`): training depth, learning rate, and reproducibility seed. The predictive reasoner's size in `raiconfig.yaml` decides the device. +- **GNN knobs** (`GNN_N_EPOCHS`, `GNN_LR`, `GNN_SEED` in `model/capability_forecast.py`): training depth, learning rate, and reproducibility seed. The predictive reasoner's size in `raiconfig.yaml` decides the device. ### Extend the model - **Adjust floors and yields**: edit `base_service_floor_pct` in `customers.csv` and `declared_yield_pct` / `elevated_floor_pct` in `dependencies.csv`; the Stage-1 rules pick up new values without code changes. - **Change the objective**: allocations are already in USD, so maximize `sum(Demand.x_alloc)` over the horizon instead of the margin-weighted sum to optimize revenue instead of margin. -- **Add constraints or outputs**: add a `problem.satisfy(...)` block in Stage 3 of `model/reasoning.py`, or persist a new derived property back to the ontology as Stages 1 and 4 do. +- **Add constraints or outputs**: add a `problem.satisfy(...)` block in Stage 3 of `model/rolling_horizon.py`, or persist a new derived property back to the ontology as Stages 1 and 4 do. ### Scale up / productionize diff --git a/memory_supply_allocation/model/__init__.py b/memory_supply_allocation/model/__init__.py index 986ad1ca..2e25555b 100644 --- a/memory_supply_allocation/model/__init__.py +++ b/memory_supply_allocation/model/__init__.py @@ -9,7 +9,7 @@ `Customer.is_dependency_spof`, from the dependency relation. - Stage 2 (Predictive): a node-regression GNN predicts `capability_pct` per (supplier, month); the clipped prediction is `SupplierCapabilityForecast`. - Set `USE_PRECOMPUTED_FORECAST = True` in `model/reasoning.py` to load the + Set `USE_PRECOMPUTED_FORECAST = True` in `model/capability_forecast.py` to load the bundled forecast CSV instead. - Stage 3 (Prescriptive): monthly margin-max LP over a 36-month horizon, run as a 3-step rolling horizon. A baseline solve at month 1, then disruption @@ -22,19 +22,34 @@ offline, (2) raw-material input shortage. Each surfaces affected (product, period) cells without re-solving the LP. +Each stage lives in its own module, and each module imports the modules whose +declarations it reads: `customer_dependencies.py` (Stage 1), `capability_forecast.py` +(Stage 2), `rolling_horizon.py` (Stage 3), `dependency_chains.py` and +`disruption_what_ifs.py` (Stage 4). + `rai models deploy --path model` deploys this package to the schemas in raiconfig.yaml, `python train.py` trains and registers the GNN, and `python -m queries.allocation_report` prints the results of a refresh. """ -from .reasoning import ( +from .capability_forecast import NumForecastRows, gnn +from .dependency_chains import ( + DependencyChain, + DependencyChainStep, + NumDependencyChains, +) +from .disruption_what_ifs import ( OFFLINE_DROP_THRESHOLD, SHORTAGE_DROP_THRESHOLD, - DependencyChainStep, OfflineDrop, + ShortageAverageDrop, ShortageDrop, +) +from .rolling_horizon import ( + CustomerService, + EffectiveCapacityCells, + PlanDiff, allocations, - gnn, ) from .schema import ( Customer, @@ -54,12 +69,19 @@ "OFFLINE_DROP_THRESHOLD", "SHORTAGE_DROP_THRESHOLD", "Customer", + "CustomerService", "Demand", + "DependencyChain", "DependencyChainStep", "EffectiveCapacity", + "EffectiveCapacityCells", "Input", + "NumDependencyChains", + "NumForecastRows", "OfflineDrop", + "PlanDiff", "Product", + "ShortageAverageDrop", "ShortageDrop", "Supplier", "SupplierCapabilityForecast", diff --git a/memory_supply_allocation/model/capability_forecast.py b/memory_supply_allocation/model/capability_forecast.py new file mode 100644 index 00000000..698ea764 --- /dev/null +++ b/memory_supply_allocation/model/capability_forecast.py @@ -0,0 +1,114 @@ +"""Capability forecast: the supplier-capability GNN (or the bundled forecast snapshot), the clipped +forecast per supplier and month, and the forecast's row count.""" + +import pandas as pd +from relationalai.semantics import Float, Integer +from relationalai.semantics.reasoners.graph import Graph +from relationalai.semantics.reasoners.predictive import GNN, PropertyTransformer +from relationalai.semantics.std import aggregates +from relationalai.semantics.std import math as rmath + +from .schema import ( + Supplier, + SupplierCapabilityForecast, + SupplierObservation, + Test, + Train, + Val, + model, +) +from .source import DATA_DIR + +# -------------------------------------------------- +# Configure inputs +# -------------------------------------------------- + +# Stage 2 (Predictive) configuration. +# Default behavior is an actual GNN regression run on Supplier capability; +# set USE_PRECOMPUTED_FORECAST=True to skip training and load the bundled +# forecast CSV directly (useful for fast iteration / offline reproducibility). +USE_PRECOMPUTED_FORECAST = False +GNN_N_EPOCHS = 30 +GNN_LR = 0.005 +GNN_SEED = 42 + +# -------------------------------------------------- +# Stage 2: Predictive -- supplier capability forecast +# -------------------------------------------------- +# +# Default: a node-regression GNN on Supplier predicts capability_pct per +# (supplier, period) from static features + historical observations; train.py +# trains and registers it, and every refresh predicts with the registered +# version. Either path populates the same SupplierCapabilityForecast concept; +# downstream stages don't care which ran. + +if USE_PRECOMPUTED_FORECAST: + gnn = None + forecast_df = pd.read_csv(DATA_DIR / "supplier_capability_forecast.csv") + model.define(SupplierCapabilityForecast.new(model.data(forecast_df).to_schema())) +else: + # GNN graph: each observation links to its supplier; suppliers in the same + # region link to each other so feature signal flows between similar fabs. + gnn_graph = Graph(model, directed=True, weighted=False, name="gnn_graph") + GEdge = gnn_graph.Edge + model.define(GEdge.new(src=SupplierObservation, dst=Supplier)).where( + SupplierObservation.supplier_id == Supplier.id + ) + SupRef = Supplier.ref() + model.define(GEdge.new(src=Supplier, dst=SupRef)).where( + Supplier.region == SupRef.region, + Supplier.id < SupRef.id, + ) + + pt = PropertyTransformer( + drop=[ + Supplier.id, + Supplier.name, + Supplier.type, + SupplierObservation.id, + SupplierObservation.supplier_id, + SupplierObservation.period_id, + SupplierObservation.capability_pct, # target — don't leak + ], + category=[Supplier.region], + continuous=[Supplier.geopolitical_exposure_score], + integer=[ + Supplier.equipment_age_months, + Supplier.process_node_nm, + Supplier.workforce_size_k, + ], + ) + + # `name` ties this GNN to the registered model and version that + # `reasoners.predictive.gnns.supplier_capability` names in raiconfig.yaml. + gnn = GNN( + name="supplier_capability", + graph=gnn_graph, + property_transformer=pt, + train=Train, + validation=Val, + task_type="regression", + eval_metric="rmse", + has_time_column=False, + stream_logs=False, + seed=GNN_SEED, + n_epochs=GNN_N_EPOCHS, + lr=GNN_LR, + ) + SupplierObservation.predictions = gnn.predictions(domain=Test) + + # Forecast = predicted capability, clipped to [0.85, 1.0]. + predicted = Float.ref() + model.where( + SupplierObservation.predictions.predicted_value(predicted), + ).define( + SupplierCapabilityForecast.new( + supplier_id=SupplierObservation.supplier_id, + period_id=SupplierObservation.period_id, + capability_pct=rmath.round(rmath.clip(predicted, 0.85, 1.0), 4), + ) + ) + +# The forecast's row count. +NumForecastRows = model.Relationship(f"the capability forecast has {Integer:num_rows} rows") +model.define(NumForecastRows(aggregates.count(SupplierCapabilityForecast))) diff --git a/memory_supply_allocation/model/customer_dependencies.py b/memory_supply_allocation/model/customer_dependencies.py new file mode 100644 index 00000000..b3c56f2b --- /dev/null +++ b/memory_supply_allocation/model/customer_dependencies.py @@ -0,0 +1,64 @@ +"""Customer dependencies: each customer's yield and floor from the dependency relation, the +customer-to-customer dependency edge, and the single-point-of-failure flag.""" + +from relationalai.semantics import Float, Integer +from relationalai.semantics.std import aggregates + +from .schema import Customer, Dependency, model + +# -------------------------------------------------- +# Stage 1: Rules -- derive customer yield/floor properties + graph edges +# -------------------------------------------------- + +Property = model.Property + +# Per-customer max declared yield across outgoing dependencies (0.0 if none). +Customer.max_declared_yield_pct = Property(f"{Customer} has {Float:max_declared_yield_pct}") +max_yield_expr = ( + aggregates.max(Dependency.declared_yield_pct) + .per(Customer) + .where(Dependency.downstream_id == Customer.id) + | 0.0 +) +model.define(Customer.max_declared_yield_pct(max_yield_expr)) + +# Per-customer elevated floor across incoming dependencies (0.0 if none). +Customer.elevated_floor_pct = Property(f"{Customer} has {Float:elevated_floor_pct}") +elevated_expr = ( + aggregates.max(Dependency.elevated_floor_pct) + .per(Customer) + .where(Dependency.upstream_id == Customer.id) + | 0.0 +) +model.define(Customer.elevated_floor_pct(elevated_expr)) + +# Customer-to-customer dependency relationship for Stage 4 path traversal. +Customer.depends_on = model.Relationship(f"{Customer:downstream} depends on {Customer:upstream}") +_c_down = Customer.ref("c_down") +_c_up = Customer.ref("c_up") +model.where( + Dependency.downstream_id == _c_down.id, + Dependency.upstream_id == _c_up.id, +).define(Customer.depends_on(_c_down, _c_up)) + +# Count of incoming dependencies (how many downstream signals protect this customer). +Customer.n_incoming_dependencies = Property(f"{Customer} has {Integer:n_incoming_dependencies}") +incoming_count_expr = ( + aggregates.count(Dependency).per(Customer).where(Dependency.upstream_id == Customer.id) | 0 +) +model.define(Customer.n_incoming_dependencies(incoming_count_expr)) + +# Boolean: this customer's effective floor exceeds its base. +Customer.has_elevated_floor = model.Relationship(f"{Customer} has elevated floor") +model.where( + Customer.elevated_floor_pct > Customer.base_service_floor_pct, +).define(Customer.has_elevated_floor()) + +# Boolean: single point of failure in the dependency graph (1 protecting edge). +Customer.is_dependency_spof = model.Relationship( + f"{Customer} is dependency single point of failure" +) +model.where( + Customer.n_incoming_dependencies == 1, + Customer.elevated_floor_pct > Customer.base_service_floor_pct, +).define(Customer.is_dependency_spof()) diff --git a/memory_supply_allocation/model/dependency_chains.py b/memory_supply_allocation/model/dependency_chains.py new file mode 100644 index 00000000..a4c5a56a --- /dev/null +++ b/memory_supply_allocation/model/dependency_chains.py @@ -0,0 +1,46 @@ +"""Dependency chains: every 1-3 hop customer-customer dependency chain, each chain read as a route of +customer names, and the number of chains.""" + +from relationalai.semantics import Integer, String +from relationalai.semantics.std import aggregates +from relationalai.semantics.std.path import PathTraversal + +# Declares Customer.depends_on, the edge the chains follow. +from . import customer_dependencies # noqa: F401 +from .schema import Customer, model + +# -------------------------------------------------- +# Stage 4: Graph (PATHS) -- dependency chains +# -------------------------------------------------- +# Every 1-3 hop customer-customer dependency chain. The enumeration is declared +# here, in the model: a deployed model only has the path tables its own rules +# ask for. Each chain's customers are published with their step index. +chain = model.path(Customer.depends_on.repeat(1, 3)).all().paths() +DependencyChainStep = model.Relationship( + f"{PathTraversal:chain} of {Integer:hops} hops visits {Customer} at step {Integer:step}" +) +model.where(chain).define( + DependencyChainStep(chain, chain.length, Customer(chain.nodes), chain.nodes["index"]) +) + +# Each chain read as its customers' names in step order, "A -> B -> C". +DependencyChain = model.Relationship( + f"{PathTraversal:chain} of {Integer:hops} hops reads {String:route}" +) +_hops, _step, _stop = Integer.ref(), Integer.ref(), Customer.ref() +model.where(chain).define( + DependencyChain( + chain, + chain.length, + aggregates.string_join(_stop.name, sep=" -> ", index=_step) + .per(chain) + .where(DependencyChainStep(chain, _hops, _stop, _step)), + ) +) + +# The number of chains. +NumDependencyChains = model.Relationship(f"there are {Integer:num_chains} dependency chains") +_counted, _route = PathTraversal.ref(), String.ref() +model.define( + NumDependencyChains(aggregates.count(_counted).where(DependencyChain(_counted, _hops, _route))) +) diff --git a/memory_supply_allocation/model/disruption_what_ifs.py b/memory_supply_allocation/model/disruption_what_ifs.py new file mode 100644 index 00000000..c359dc9a --- /dev/null +++ b/memory_supply_allocation/model/disruption_what_ifs.py @@ -0,0 +1,193 @@ +"""Disruption what-ifs: baseline capacity per product and month, the capacity a supplier going offline or an +input shortage removes, each supplier's and input's affected cells, and the widest impact of each.""" + +from relationalai.semantics import Float, Integer, String, count, sum +from relationalai.semantics.std import aggregates + +# Declares SupplierCapabilityForecast's rows, the forecast the baseline capacity reads. +from . import capability_forecast # noqa: F401 +from .schema import ( + Input, + InputUsage, + Product, + Supplier, + SupplierCapabilityForecast, + SupplierOfflineImpact, + SupplierProductCapacity, + model, +) + +# -------------------------------------------------- +# Configure inputs +# -------------------------------------------------- + +# What-if thresholds: a supplier's offline impact counts (product, period) +# cells losing more than 10% of capacity; an input shortage (30% availability) +# counts cells losing more than 5%. +OFFLINE_DROP_THRESHOLD = 0.10 +SHORTAGE_AVAILABILITY = 0.30 +SHORTAGE_DROP_THRESHOLD = 0.05 + +Property = model.Property +SPC = SupplierProductCapacity + +# -------------------------------------------------- +# Stage 4: what-if analyses +# -------------------------------------------------- + +# What-ifs (no re-solve) on the baseline forecast. Baseline capacity per +# (product, period): every supplier at its forecast capability, every input +# fully available. + +BaselineCapacity = model.Relationship( + f"product {Integer:product_id} in period {Integer:period_id} has baseline capacity {Float:usd}" +) +model.where( + SupplierCapabilityForecast.supplier_id == SPC.supplier_id, + SupplierCapabilityForecast.period_id == SPC.period_id, +).define( + BaselineCapacity( + SPC.product_id, + SPC.period_id, + sum(SPC, SPC.nominal_capacity_usd * SupplierCapabilityForecast.capability_pct).per( + SPC.product_id, SPC.period_id + ), + ) +) +baseline = Float.ref() + +# Both what-ifs measure drops relative to baseline capacity, so they skip cells +# with zero baseline capacity, where the relative drop is undefined. + +# What-if 1: a supplier going offline removes its share of each cell's capacity. +OfflineDrop = model.Relationship( + f"{Supplier} offline cuts product {Integer:product_id} in period {Integer:period_id} by {Float:drop_pct}" +) +model.where( + Supplier.id == SPC.supplier_id, + SupplierCapabilityForecast.supplier_id == SPC.supplier_id, + SupplierCapabilityForecast.period_id == SPC.period_id, + BaselineCapacity(SPC.product_id, SPC.period_id, baseline), + baseline > 0, +).define( + OfflineDrop( + Supplier, + SPC.product_id, + SPC.period_id, + SPC.nominal_capacity_usd * SupplierCapabilityForecast.capability_pct / baseline, + ) +) + +# Persist what-if 1 output to the ontology so a downstream analyst can query +# supplier-offline risk. +offline_product, offline_period, offline_drop = Integer.ref(), Integer.ref(), Float.ref() +significant_offline = [ + OfflineDrop(Supplier, offline_product, offline_period, offline_drop), + offline_drop > OFFLINE_DROP_THRESHOLD, +] +model.define( + SupplierOfflineImpact.new( + supplier_id=Supplier.id, + n_affected_cells=count(offline_product, offline_period) + .per(Supplier) + .where(*significant_offline) + | 0, + max_cap_drop_pct=aggregates.max(offline_drop).per(Supplier).where(*significant_offline) + | 0.0, + ) +) + +# The products behind those cells, by product id, comma-separated; empty when the supplier loses +# no cell above the threshold. +SupplierOfflineImpact.affected_products = Property( + f"{SupplierOfflineImpact} has affected products {String:affected_products}" +) +model.define( + SupplierOfflineImpact.affected_products( + aggregates.string_join(Product.name, sep=", ", index=Product.id) + .per(SupplierOfflineImpact) + .where( + Supplier.id == SupplierOfflineImpact.supplier_id, + *significant_offline, + Product.id == offline_product, + ) + | "" + ) +) + +# The supplier whose offline impact reaches the most cells, the lowest id among ties; none when no +# supplier loses a cell above the threshold. +SupplierOfflineImpact.has_widest_impact = model.Relationship( + f"{SupplierOfflineImpact} has the widest offline impact" +) +model.where( + SupplierOfflineImpact.n_affected_cells > 0, + aggregates.rank( + -SupplierOfflineImpact.n_affected_cells, SupplierOfflineImpact.supplier_id + ) + == 1, +).define(SupplierOfflineImpact.has_widest_impact()) + +# What-if 2: an input at 30% availability scales each exposed product's +# capacity by 1 - intensity * (1 - availability) in every period. +ShortageDrop = model.Relationship( + f"{Input} shortage cuts product {Integer:product_id} in period {Integer:period_id} by {Float:drop_pct}" +) +model.where( + InputUsage.input_id == Input.id, + BaselineCapacity(InputUsage.product_id, offline_period, baseline), + baseline > 0, +).define( + ShortageDrop( + Input, + InputUsage.product_id, + offline_period, + InputUsage.intensity * (1.0 - SHORTAGE_AVAILABILITY), + ) +) + +# Persist what-if 2 output so the input-shortage risk ranking is queryable. +Input.shortage_impact_cells = Property(f"{Input} has {Integer:shortage_impact_cells}") +shortage_product, shortage_period, shortage_drop = Integer.ref(), Integer.ref(), Float.ref() +model.define( + Input.shortage_impact_cells( + count(shortage_product, shortage_period) + .per(Input) + .where( + ShortageDrop(Input, shortage_product, shortage_period, shortage_drop), + shortage_drop > SHORTAGE_DROP_THRESHOLD, + ) + | 0 + ) +) + +# The mean drop over the cells above the threshold, per input and exposed product. +ShortageAverageDrop = model.Relationship( + f"{Input} shortage cuts product {Integer:product_id} by {Float:avg_drop_pct} on average" +) +_cut_period, _cut_drop = Integer.ref(), Float.ref() +model.where( + ShortageDrop(Input, shortage_product, shortage_period, shortage_drop), + shortage_drop > SHORTAGE_DROP_THRESHOLD, +).define( + ShortageAverageDrop( + Input, + shortage_product, + aggregates.avg(_cut_period, _cut_drop) + .per(Input, shortage_product) + .where( + ShortageDrop(Input, shortage_product, _cut_period, _cut_drop), + _cut_drop > SHORTAGE_DROP_THRESHOLD, + ), + ) +) + +# The input whose shortage reaches the most cells, the lowest id among ties; none when no input +# loses a cell above the threshold. +Input.has_widest_shortage_impact = model.Relationship( + f"{Input} has the widest shortage impact" +) +model.where( + Input.shortage_impact_cells > 0, + aggregates.rank(-Input.shortage_impact_cells, Input.id) == 1, +).define(Input.has_widest_shortage_impact()) diff --git a/memory_supply_allocation/model/reasoning.py b/memory_supply_allocation/model/reasoning.py deleted file mode 100644 index 98b801ba..00000000 --- a/memory_supply_allocation/model/reasoning.py +++ /dev/null @@ -1,456 +0,0 @@ -"""Dependency rules, the supplier-capability GNN, the rolling-horizon LPs, and the what-ifs.""" - -import pandas as pd -from relationalai.semantics import Float, Integer, String, count, not_, sum -from relationalai.semantics.reasoners.graph import Graph -from relationalai.semantics.reasoners.predictive import GNN, PropertyTransformer -from relationalai.semantics.reasoners.prescriptive import Problem -from relationalai.semantics.std import aggregates -from relationalai.semantics.std import math as rmath -from relationalai.semantics.std.path import PathTraversal - -from .schema import ( - CapabilityOverride, - Customer, - Demand, - Dependency, - EffectiveCapacity, - Input, - InputMultiplier, - InputUsage, - Iteration, - Product, - Supplier, - SupplierCapabilityForecast, - SupplierObservation, - SupplierOfflineImpact, - SupplierProductCapacity, - Test, - Train, - Val, - model, -) -from .source import DATA_DIR, iter_specs - -SOLVE_TIME_LIMIT_SEC = 60 - -# Stage 2 (Predictive) configuration. -# Default behavior is an actual GNN regression run on Supplier capability; -# set USE_PRECOMPUTED_FORECAST=True to skip training and load the bundled -# forecast CSV directly (useful for fast iteration / offline reproducibility). -USE_PRECOMPUTED_FORECAST = False -GNN_N_EPOCHS = 30 -GNN_LR = 0.005 -GNN_SEED = 42 - -# What-if thresholds: a supplier's offline impact counts (product, period) -# cells losing more than 10% of capacity; an input shortage (30% availability) -# counts cells losing more than 5%. -OFFLINE_DROP_THRESHOLD = 0.10 -SHORTAGE_AVAILABILITY = 0.30 -SHORTAGE_DROP_THRESHOLD = 0.05 - -# -------------------------------------------------- -# Stage 1: Rules -- derive customer yield/floor properties + graph edges -# -------------------------------------------------- - -Property = model.Property - -# Per-customer max declared yield across outgoing dependencies (0.0 if none). -Customer.max_declared_yield_pct = Property(f"{Customer} has {Float:max_declared_yield_pct}") -max_yield_expr = ( - aggregates.max(Dependency.declared_yield_pct) - .per(Customer) - .where(Dependency.downstream_id == Customer.id) - | 0.0 -) -model.define(Customer.max_declared_yield_pct(max_yield_expr)) - -# Per-customer elevated floor across incoming dependencies (0.0 if none). -Customer.elevated_floor_pct = Property(f"{Customer} has {Float:elevated_floor_pct}") -elevated_expr = ( - aggregates.max(Dependency.elevated_floor_pct) - .per(Customer) - .where(Dependency.upstream_id == Customer.id) - | 0.0 -) -model.define(Customer.elevated_floor_pct(elevated_expr)) - -# Customer-to-customer dependency relationship for Stage 4 path traversal. -Customer.depends_on = model.Relationship(f"{Customer:downstream} depends on {Customer:upstream}") -_c_down = Customer.ref("c_down") -_c_up = Customer.ref("c_up") -model.where( - Dependency.downstream_id == _c_down.id, - Dependency.upstream_id == _c_up.id, -).define(Customer.depends_on(_c_down, _c_up)) - -# Count of incoming dependencies (how many downstream signals protect this customer). -Customer.n_incoming_dependencies = Property(f"{Customer} has {Integer:n_incoming_dependencies}") -incoming_count_expr = ( - aggregates.count(Dependency).per(Customer).where(Dependency.upstream_id == Customer.id) | 0 -) -model.define(Customer.n_incoming_dependencies(incoming_count_expr)) - -# Boolean: this customer's effective floor exceeds its base. -Customer.has_elevated_floor = model.Relationship(f"{Customer} has elevated floor") -model.where( - Customer.elevated_floor_pct > Customer.base_service_floor_pct, -).define(Customer.has_elevated_floor()) - -# Boolean: single point of failure in the dependency graph (1 protecting edge). -Customer.is_dependency_spof = model.Relationship( - f"{Customer} is dependency single point of failure" -) -model.where( - Customer.n_incoming_dependencies == 1, - Customer.elevated_floor_pct > Customer.base_service_floor_pct, -).define(Customer.is_dependency_spof()) - -# -------------------------------------------------- -# Stage 2: Predictive -- supplier capability forecast -# -------------------------------------------------- -# -# Default: a node-regression GNN on Supplier predicts capability_pct per -# (supplier, period) from static features + historical observations; train.py -# trains and registers it, and every refresh predicts with the registered -# version. Either path populates the same SupplierCapabilityForecast concept; -# downstream stages don't care which ran. - -if USE_PRECOMPUTED_FORECAST: - gnn = None - forecast_df = pd.read_csv(DATA_DIR / "supplier_capability_forecast.csv") - model.define(SupplierCapabilityForecast.new(model.data(forecast_df).to_schema())) -else: - # GNN graph: each observation links to its supplier; suppliers in the same - # region link to each other so feature signal flows between similar fabs. - gnn_graph = Graph(model, directed=True, weighted=False, name="gnn_graph") - GEdge = gnn_graph.Edge - model.define(GEdge.new(src=SupplierObservation, dst=Supplier)).where( - SupplierObservation.supplier_id == Supplier.id - ) - SupRef = Supplier.ref() - model.define(GEdge.new(src=Supplier, dst=SupRef)).where( - Supplier.region == SupRef.region, - Supplier.id < SupRef.id, - ) - - pt = PropertyTransformer( - drop=[ - Supplier.id, - Supplier.name, - Supplier.type, - SupplierObservation.id, - SupplierObservation.supplier_id, - SupplierObservation.period_id, - SupplierObservation.capability_pct, # target — don't leak - ], - category=[Supplier.region], - continuous=[Supplier.geopolitical_exposure_score], - integer=[ - Supplier.equipment_age_months, - Supplier.process_node_nm, - Supplier.workforce_size_k, - ], - ) - - # `name` ties this GNN to the registered model and version that - # `reasoners.predictive.gnns.supplier_capability` names in raiconfig.yaml. - gnn = GNN( - name="supplier_capability", - graph=gnn_graph, - property_transformer=pt, - train=Train, - validation=Val, - task_type="regression", - eval_metric="rmse", - has_time_column=False, - stream_logs=False, - seed=GNN_SEED, - n_epochs=GNN_N_EPOCHS, - lr=GNN_LR, - ) - SupplierObservation.predictions = gnn.predictions(domain=Test) - - # Forecast = predicted capability, clipped to [0.85, 1.0]. - predicted = Float.ref() - model.where( - SupplierObservation.predictions.predicted_value(predicted), - ).define( - SupplierCapabilityForecast.new( - supplier_id=SupplierObservation.supplier_id, - period_id=SupplierObservation.period_id, - capability_pct=rmath.round(rmath.clip(predicted, 0.85, 1.0), 4), - ) - ) - -# -------------------------------------------------- -# Stage 3: Prescriptive -- monthly rolling-horizon LP -# -------------------------------------------------- -# -# Effective capacity per (iteration, product, period) inside the iteration's -# horizon = sum over suppliers of nominal capacity x capability (the forecast, -# or the iteration's revealed override), times the iteration's input multiplier. -# The LP at iteration K references only its own rows. - -Capability = model.Relationship( - f"in {Iteration} supplier {Integer:supplier_id} in period {Integer:period_id} has capability {Float:capability_pct}" -) -model.where( - Iteration, - not_( - CapabilityOverride.iter_id == Iteration.iter_id, - CapabilityOverride.supplier_id == SupplierCapabilityForecast.supplier_id, - CapabilityOverride.period_id == SupplierCapabilityForecast.period_id, - ), -).define( - Capability( - Iteration, - SupplierCapabilityForecast.supplier_id, - SupplierCapabilityForecast.period_id, - SupplierCapabilityForecast.capability_pct, - ) -) -model.where( - CapabilityOverride.iter_id == Iteration.iter_id, - CapabilityOverride.supplier_id == SupplierCapabilityForecast.supplier_id, - CapabilityOverride.period_id == SupplierCapabilityForecast.period_id, -).define( - Capability( - Iteration, - CapabilityOverride.supplier_id, - CapabilityOverride.period_id, - CapabilityOverride.capability_pct, - ) -) - -SPC = SupplierProductCapacity -capability = Float.ref() -model.where( - SPC.period_id >= Iteration.horizon_start, - Capability(Iteration, SPC.supplier_id, SPC.period_id, capability), -).define( - EffectiveCapacity.new( - iter_id=Iteration.iter_id, product_id=SPC.product_id, period_id=SPC.period_id - ) -) -# Every demanded cell in the horizon also gets a row, at zero capacity when no -# capability covers it (before the GNN is trained, or a gap in the forecast), so -# the capacity constraint below never leaves a demanded cell unbounded. -model.where(Demand.period_id >= Iteration.horizon_start).define( - EffectiveCapacity.new( - iter_id=Iteration.iter_id, product_id=Demand.product_id, period_id=Demand.period_id - ) -) -model.where( - InputMultiplier.iter_id == EffectiveCapacity.iter_id, - InputMultiplier.product_id == EffectiveCapacity.product_id, -).define( - EffectiveCapacity.effective_capacity_usd( - ( - sum(SPC, SPC.nominal_capacity_usd * capability) - .per(EffectiveCapacity) - .where( - Iteration.iter_id == EffectiveCapacity.iter_id, - SPC.product_id == EffectiveCapacity.product_id, - SPC.period_id == EffectiveCapacity.period_id, - Capability(Iteration, SPC.supplier_id, SPC.period_id, capability), - ) - | 0.0 - ) - * InputMultiplier.mult - ) -) - -# One Problem per iteration, each over its own horizon. Each Problem's status, -# total margin, and allocations are published under the Problem's name. -allocations = [] -for spec in iter_specs: - iter_id = spec["iter_id"] - horizon_start = spec["horizon_start"] - name = f"memory_supply_allocation_iter_{iter_id}" - - problem = Problem(model, Float, name=name) - # `populate=False` keeps the three Problems from writing the same - # `Demand.x_alloc` property; each iteration's values are read through its own - # `alloc.values(...)`, published below as that iteration's allocations. - alloc = problem.solve_for( - Demand.x_alloc, - type="cont", - lower=0.0, - name=["alloc", Demand.customer_id, Demand.product_id, Demand.period_id], - where=[Demand.period_id >= horizon_start], - populate=False, - ) - - # Capacity constraint scoped to this iteration's effective-capacity rows. - problem.satisfy( - model.where(EffectiveCapacity.iter_id == iter_id).require( - sum(Demand.x_alloc) - .per(EffectiveCapacity) - .where( - Demand.product_id == EffectiveCapacity.product_id, - Demand.period_id == EffectiveCapacity.period_id, - ) - <= EffectiveCapacity.effective_capacity_usd - ), - name=[ - "cap", - EffectiveCapacity.iter_id, - EffectiveCapacity.product_id, - EffectiveCapacity.period_id, - ], - ) - - # Demand cap (yield-aware), base floor, elevated floor -- all scoped to horizon. - problem.satisfy( - model.where( - Demand.customer_id == Customer.id, - Demand.period_id >= horizon_start, - ).require(Demand.x_alloc <= (1.0 - Customer.max_declared_yield_pct) * Demand.demand_usd), - name=["dcap", Demand.customer_id, Demand.product_id, Demand.period_id], - ) - problem.satisfy( - model.where( - Demand.customer_id == Customer.id, - Demand.period_id >= horizon_start, - ).require(Demand.x_alloc >= Customer.base_service_floor_pct * Demand.demand_usd), - name=["bfloor", Demand.customer_id, Demand.product_id, Demand.period_id], - ) - problem.satisfy( - model.where( - Demand.customer_id == Customer.id, - Demand.period_id >= horizon_start, - ).require(Demand.x_alloc >= Customer.elevated_floor_pct * Demand.demand_usd), - name=["efloor", Demand.customer_id, Demand.product_id, Demand.period_id], - ) - - # Objective: margin-weighted allocation over the current horizon. - problem.maximize( - sum(Demand.x_alloc * Product.margin_pct).where( - Demand.product_id == Product.id, - Demand.period_id >= horizon_start, - ) - ) - # Each refresh of the deployed model runs this solve. - problem.configure("highs", time_limit_sec=SOLVE_TIME_LIMIT_SEC) - - # The solve's status and objective, which the deployed model publishes for the queries. - status = model.Relationship(f"{name} solve status is {String:status}") - margin = model.Relationship(f"{name} total margin is {Float:margin}") - model.define(status(problem.termination_status()), margin(problem.objective_value())) - - # The iteration's allocation per demand row (USD), published for the queries. - allocated = model.Relationship(f"{name} allocates {Float:alloc_usd} to {Demand}") - alloc_value = Float.ref() - model.where(alloc.values(0, alloc_value)).define(allocated(alloc_value, alloc.demand)) - allocations.append((spec, status, margin, allocated)) - -# -------------------------------------------------- -# Stage 4: Graph (PATHS) -- dependency chains, then what-if analyses -# -------------------------------------------------- -# Every 1-3 hop customer-customer dependency chain. The enumeration is declared -# here, in the model: a deployed model only has the path tables its own rules -# ask for. Each chain's customers are published with their step index. -chain = model.path(Customer.depends_on.repeat(1, 3)).all().paths() -DependencyChainStep = model.Relationship( - f"{PathTraversal:chain} of {Integer:hops} hops visits {Customer} at step {Integer:step}" -) -model.where(chain).define( - DependencyChainStep(chain, chain.length, Customer(chain.nodes), chain.nodes["index"]) -) - -# What-ifs (no re-solve) on the baseline forecast. Baseline capacity per -# (product, period): every supplier at its forecast capability, every input -# fully available. - -BaselineCapacity = model.Relationship( - f"product {Integer:product_id} in period {Integer:period_id} has baseline capacity {Float:usd}" -) -model.where( - SupplierCapabilityForecast.supplier_id == SPC.supplier_id, - SupplierCapabilityForecast.period_id == SPC.period_id, -).define( - BaselineCapacity( - SPC.product_id, - SPC.period_id, - sum(SPC, SPC.nominal_capacity_usd * SupplierCapabilityForecast.capability_pct).per( - SPC.product_id, SPC.period_id - ), - ) -) -baseline = Float.ref() - -# Both what-ifs measure drops relative to baseline capacity, so they skip cells -# with zero baseline capacity, where the relative drop is undefined. - -# What-if 1: a supplier going offline removes its share of each cell's capacity. -OfflineDrop = model.Relationship( - f"{Supplier} offline cuts product {Integer:product_id} in period {Integer:period_id} by {Float:drop_pct}" -) -model.where( - Supplier.id == SPC.supplier_id, - SupplierCapabilityForecast.supplier_id == SPC.supplier_id, - SupplierCapabilityForecast.period_id == SPC.period_id, - BaselineCapacity(SPC.product_id, SPC.period_id, baseline), - baseline > 0, -).define( - OfflineDrop( - Supplier, - SPC.product_id, - SPC.period_id, - SPC.nominal_capacity_usd * SupplierCapabilityForecast.capability_pct / baseline, - ) -) - -# Persist what-if 1 output to the ontology so a downstream analyst can query -# supplier-offline risk. -offline_product, offline_period, offline_drop = Integer.ref(), Integer.ref(), Float.ref() -significant_offline = [ - OfflineDrop(Supplier, offline_product, offline_period, offline_drop), - offline_drop > OFFLINE_DROP_THRESHOLD, -] -model.define( - SupplierOfflineImpact.new( - supplier_id=Supplier.id, - n_affected_cells=count(offline_product, offline_period) - .per(Supplier) - .where(*significant_offline) - | 0, - max_cap_drop_pct=aggregates.max(offline_drop).per(Supplier).where(*significant_offline) - | 0.0, - ) -) - -# What-if 2: an input at 30% availability scales each exposed product's -# capacity by 1 - intensity * (1 - availability) in every period. -ShortageDrop = model.Relationship( - f"{Input} shortage cuts product {Integer:product_id} in period {Integer:period_id} by {Float:drop_pct}" -) -model.where( - InputUsage.input_id == Input.id, - BaselineCapacity(InputUsage.product_id, offline_period, baseline), - baseline > 0, -).define( - ShortageDrop( - Input, - InputUsage.product_id, - offline_period, - InputUsage.intensity * (1.0 - SHORTAGE_AVAILABILITY), - ) -) - -# Persist what-if 2 output so the input-shortage risk ranking is queryable. -Input.shortage_impact_cells = Property(f"{Input} has {Integer:shortage_impact_cells}") -shortage_product, shortage_period, shortage_drop = Integer.ref(), Integer.ref(), Float.ref() -model.define( - Input.shortage_impact_cells( - count(shortage_product, shortage_period) - .per(Input) - .where( - ShortageDrop(Input, shortage_product, shortage_period, shortage_drop), - shortage_drop > SHORTAGE_DROP_THRESHOLD, - ) - | 0 - ) -) diff --git a/memory_supply_allocation/model/rolling_horizon.py b/memory_supply_allocation/model/rolling_horizon.py new file mode 100644 index 00000000..1876c307 --- /dev/null +++ b/memory_supply_allocation/model/rolling_horizon.py @@ -0,0 +1,248 @@ +"""Rolling-horizon allocation: the capability each iteration sees, its effective capacity per product +and month, one margin-maximising LP per iteration, and each plan's diff and per-customer allocation and demand.""" + +from relationalai.semantics import Float, Integer, String, not_, sum +from relationalai.semantics.reasoners.prescriptive import Problem +from relationalai.semantics.std import aggregates + +# Declare the forecast rows the effective capacity reads (capability_forecast) and the customer +# yield caps and floors the LPs read (customer_dependencies). +from . import ( + capability_forecast, # noqa: F401 + customer_dependencies, # noqa: F401 +) +from .schema import ( + CapabilityOverride, + Customer, + Demand, + EffectiveCapacity, + InputMultiplier, + Iteration, + Product, + SupplierCapabilityForecast, + SupplierProductCapacity, + model, +) +from .source import iter_specs + +# -------------------------------------------------- +# Configure inputs +# -------------------------------------------------- + +SOLVE_TIME_LIMIT_SEC = 60 + +# -------------------------------------------------- +# Stage 3: Prescriptive -- monthly rolling-horizon LP +# -------------------------------------------------- +# +# Effective capacity per (iteration, product, period) inside the iteration's +# horizon = sum over suppliers of nominal capacity x capability (the forecast, +# or the iteration's revealed override), times the iteration's input multiplier. +# The LP at iteration K references only its own rows. + +Capability = model.Relationship( + f"in {Iteration} supplier {Integer:supplier_id} in period {Integer:period_id} has capability {Float:capability_pct}" +) +model.where( + Iteration, + not_( + CapabilityOverride.iter_id == Iteration.iter_id, + CapabilityOverride.supplier_id == SupplierCapabilityForecast.supplier_id, + CapabilityOverride.period_id == SupplierCapabilityForecast.period_id, + ), +).define( + Capability( + Iteration, + SupplierCapabilityForecast.supplier_id, + SupplierCapabilityForecast.period_id, + SupplierCapabilityForecast.capability_pct, + ) +) +model.where( + CapabilityOverride.iter_id == Iteration.iter_id, + CapabilityOverride.supplier_id == SupplierCapabilityForecast.supplier_id, + CapabilityOverride.period_id == SupplierCapabilityForecast.period_id, +).define( + Capability( + Iteration, + CapabilityOverride.supplier_id, + CapabilityOverride.period_id, + CapabilityOverride.capability_pct, + ) +) + +SPC = SupplierProductCapacity +capability = Float.ref() +model.where( + SPC.period_id >= Iteration.horizon_start, + Capability(Iteration, SPC.supplier_id, SPC.period_id, capability), +).define( + EffectiveCapacity.new( + iter_id=Iteration.iter_id, product_id=SPC.product_id, period_id=SPC.period_id + ) +) +# Every demanded cell in the horizon also gets a row, at zero capacity when no +# capability covers it (before the GNN is trained, or a gap in the forecast), so +# the capacity constraint below never leaves a demanded cell unbounded. +model.where(Demand.period_id >= Iteration.horizon_start).define( + EffectiveCapacity.new( + iter_id=Iteration.iter_id, product_id=Demand.product_id, period_id=Demand.period_id + ) +) +model.where( + InputMultiplier.iter_id == EffectiveCapacity.iter_id, + InputMultiplier.product_id == EffectiveCapacity.product_id, +).define( + EffectiveCapacity.effective_capacity_usd( + ( + sum(SPC, SPC.nominal_capacity_usd * capability) + .per(EffectiveCapacity) + .where( + Iteration.iter_id == EffectiveCapacity.iter_id, + SPC.product_id == EffectiveCapacity.product_id, + SPC.period_id == EffectiveCapacity.period_id, + Capability(Iteration, SPC.supplier_id, SPC.period_id, capability), + ) + | 0.0 + ) + * InputMultiplier.mult + ) +) + +# The number of effective-capacity cells each iteration loads. +EffectiveCapacityCells = model.Relationship( + f"in iteration {Integer:iter_id} there are {Integer:n_cells} effective-capacity cells" +) +model.define( + EffectiveCapacityCells( + Iteration.iter_id, + aggregates.count(EffectiveCapacity) + .per(Iteration) + .where(EffectiveCapacity.iter_id == Iteration.iter_id) + | 0, + ) +) + +# One Problem per iteration, each over its own horizon. Each Problem's status, +# total margin, and allocations are published under the Problem's name; the plan +# diff against the prior iteration and each customer's allocated and demanded +# totals are also published per iteration number. +allocations = [] +PlanDiff = model.Relationship( + f"in iteration {Integer:iter_id} {Customer} shifts {Float:delta_usd} against the prior plan" +) +CustomerService = model.Relationship( + f"in iteration {Integer:iter_id} {Customer} is allocated {Float:alloc_usd} of {Float:demand_usd} demand" +) +_alloc_usd, _prior_usd, _demand_alloc_usd = Float.ref(), Float.ref(), Float.ref() +_cell, _demand_cell = Demand.ref(), Demand.ref() + +for spec in iter_specs: + iter_id = spec["iter_id"] + horizon_start = spec["horizon_start"] + name = f"memory_supply_allocation_iter_{iter_id}" + + problem = Problem(model, Float, name=name) + # `populate=False` keeps the three Problems from writing the same + # `Demand.x_alloc` property; each iteration's values are read through its own + # `alloc.values(...)`, published below as that iteration's allocations. + alloc = problem.solve_for( + Demand.x_alloc, + type="cont", + lower=0.0, + name=["alloc", Demand.customer_id, Demand.product_id, Demand.period_id], + where=[Demand.period_id >= horizon_start], + populate=False, + ) + + # Capacity constraint scoped to this iteration's effective-capacity rows. + problem.satisfy( + model.where(EffectiveCapacity.iter_id == iter_id).require( + sum(Demand.x_alloc) + .per(EffectiveCapacity) + .where( + Demand.product_id == EffectiveCapacity.product_id, + Demand.period_id == EffectiveCapacity.period_id, + ) + <= EffectiveCapacity.effective_capacity_usd + ), + name=[ + "cap", + EffectiveCapacity.iter_id, + EffectiveCapacity.product_id, + EffectiveCapacity.period_id, + ], + ) + + # Demand cap (yield-aware), base floor, elevated floor -- all scoped to horizon. + problem.satisfy( + model.where( + Demand.customer_id == Customer.id, + Demand.period_id >= horizon_start, + ).require(Demand.x_alloc <= (1.0 - Customer.max_declared_yield_pct) * Demand.demand_usd), + name=["dcap", Demand.customer_id, Demand.product_id, Demand.period_id], + ) + problem.satisfy( + model.where( + Demand.customer_id == Customer.id, + Demand.period_id >= horizon_start, + ).require(Demand.x_alloc >= Customer.base_service_floor_pct * Demand.demand_usd), + name=["bfloor", Demand.customer_id, Demand.product_id, Demand.period_id], + ) + problem.satisfy( + model.where( + Demand.customer_id == Customer.id, + Demand.period_id >= horizon_start, + ).require(Demand.x_alloc >= Customer.elevated_floor_pct * Demand.demand_usd), + name=["efloor", Demand.customer_id, Demand.product_id, Demand.period_id], + ) + + # Objective: margin-weighted allocation over the current horizon. + problem.maximize( + sum(Demand.x_alloc * Product.margin_pct).where( + Demand.product_id == Product.id, + Demand.period_id >= horizon_start, + ) + ) + # Each refresh of the deployed model runs this solve. + problem.configure("highs", time_limit_sec=SOLVE_TIME_LIMIT_SEC) + + # The solve's status and objective, which the deployed model publishes for the queries. + status = model.Relationship(f"{name} solve status is {String:status}") + margin = model.Relationship(f"{name} total margin is {Float:margin}") + model.define(status(problem.termination_status()), margin(problem.objective_value())) + + # The iteration's allocation per demand row (USD), published for the queries. + allocated = model.Relationship(f"{name} allocates {Float:alloc_usd} to {Demand}") + alloc_value = Float.ref() + model.where(alloc.values(0, alloc_value)).define(allocated(alloc_value, alloc.demand)) + + # The plan diff against the prior iteration's plan: the change in each customer's allocation + # over the cells both plans cover, once the prior solve is OPTIMAL. + if allocations: + _, prior_status, _, prior_allocated = allocations[-1] + model.where( + Customer, + prior_status("OPTIMAL"), + delta_usd := sum(_cell, _alloc_usd - _prior_usd) + .per(Customer) + .where( + allocated(_alloc_usd, _cell), + prior_allocated(_prior_usd, _cell), + _cell.customer_id == Customer.id, + ), + ).define(PlanDiff(iter_id, Customer, delta_usd)) + + # Each customer's allocation and demand over the cells this iteration allocates; the report + # divides them for the service level. + model.where( + Customer, + alloc_usd := sum(_cell, _alloc_usd) + .per(Customer) + .where(allocated(_alloc_usd, _cell), _cell.customer_id == Customer.id), + demand_usd := sum(_demand_cell, _demand_cell.demand_usd) + .per(Customer) + .where(allocated(_demand_alloc_usd, _demand_cell), _demand_cell.customer_id == Customer.id), + ).define(CustomerService(iter_id, Customer, alloc_usd, demand_usd)) + + allocations.append((spec, status, margin, allocated)) diff --git a/memory_supply_allocation/model/source.py b/memory_supply_allocation/model/source.py index 4c3ab504..dd0278c4 100644 --- a/memory_supply_allocation/model/source.py +++ b/memory_supply_allocation/model/source.py @@ -146,6 +146,8 @@ model.define(Iteration.new(model.data(iterations_df).to_schema())) +# A rule form of the multiplier needs a product aggregate; `aggregates.product` is computed as +# exp(sum(log)), an approximation, so the exact float product stays here. def input_multipliers(input_avail): """Capacity multiplier per product given input availability per input id: product over inputs of (1 - intensity * (1 - avail)).""" diff --git a/memory_supply_allocation/queries/allocation_report.py b/memory_supply_allocation/queries/allocation_report.py index 0e0e94a6..e847314d 100644 --- a/memory_supply_allocation/queries/allocation_report.py +++ b/memory_supply_allocation/queries/allocation_report.py @@ -12,16 +12,16 @@ import pandas as pd from model import ( HORIZON_END_PERIOD, - OFFLINE_DROP_THRESHOLD, - SHORTAGE_DROP_THRESHOLD, Customer, - Demand, - DependencyChainStep, - EffectiveCapacity, + CustomerService, + DependencyChain, + EffectiveCapacityCells, Input, - OfflineDrop, + NumDependencyChains, + NumForecastRows, + PlanDiff, Product, - ShortageDrop, + ShortageAverageDrop, Supplier, SupplierCapabilityForecast, SupplierOfflineImpact, @@ -29,7 +29,7 @@ gnn, model, ) -from relationalai.semantics import Float, Integer +from relationalai.semantics import Float, Integer, String from relationalai.semantics.std.path import PathTraversal pd.set_option("display.float_format", lambda v: f"{v:,.2f}") @@ -38,17 +38,7 @@ def main() -> None: - customers_df = model.select( - Customer.id.alias("id"), Customer.name.alias("name"), Customer.industry.alias("industry") - ).to_df() products_df = model.select(Product.id.alias("id"), Product.name.alias("name")).to_df() - demand_df = model.select( - Demand.customer_id.alias("customer_id"), - Demand.product_id.alias("product_id"), - Demand.period_id.alias("period_id"), - Demand.demand_usd.alias("demand_usd"), - ).to_df() - forecast_df = model.select( SupplierCapabilityForecast.supplier_id.alias("supplier_id"), SupplierCapabilityForecast.period_id.alias("period_id"), @@ -56,8 +46,11 @@ def main() -> None: ).to_df() supplier_names = model.select(Supplier.id.alias("id"), Supplier.name.alias("name")).to_df() if gnn is not None: - print(f"GNN predictions: {len(forecast_df)} rows for periods 1..{HORIZON_END_PERIOD}") + num_forecast_rows = int(model.select(NumForecastRows).to_df().iloc[0, 0]) + print(f"GNN predictions: {num_forecast_rows} rows for periods 1..{HORIZON_END_PERIOD}") print("\nPer-supplier capability_pct summary (post-Stage 2):") + # Computed here: on the bundled forecast snapshot one supplier's mean lies exactly on a + # 3-decimal rounding boundary, so an engine's summation order could change the printed digit. fc_summary = ( forecast_df.groupby("supplier_id")["capability_pct"].agg(["mean", "min", "max"]).round(3) ) @@ -68,16 +61,17 @@ def main() -> None: # Stage 3: rolling-horizon solves # -------------------------------------------------- scenario_results = [] - prior_alloc_df = None # for plan-diff between iterations - for spec, status_rel, margin_rel, allocated in allocations: + for spec, status_rel, margin_rel, _ in allocations: iter_id = spec["iter_id"] horizon_start = spec["horizon_start"] print(f"\n{'=' * 60}\nStage 3 iteration {iter_id}: {spec['label']}\n{'=' * 60}") - n_cells = len( - model.where(EffectiveCapacity.iter_id == iter_id) - .select(EffectiveCapacity.product_id, EffectiveCapacity.period_id) + n_cells_ref = Integer.ref() + n_cells = int( + model.where(EffectiveCapacityCells(iter_id, n_cells_ref)) + .select(n_cells_ref) .to_df() + .iloc[0, 0] ) print( f" Horizon: months {horizon_start}-{HORIZON_END_PERIOD}, " @@ -103,7 +97,6 @@ def main() -> None: ) if termination_status != "OPTIMAL": print(f" Status: {termination_status} -- skipping detail output.") - prior_alloc_df = None continue print(f" Status: {termination_status}") @@ -112,33 +105,20 @@ def main() -> None: f"${objective:,.2f}" ) - # This iteration's allocations, which the deployed model publishes. - value_ref = Float.ref() - sol = ( - model.where(allocated(value_ref, Demand)) + # Plan-diff vs prior iteration's allocation (only overlapping periods), which the + # deployed model publishes for every iteration after the first. + delta_ref = Float.ref() + per_customer_delta = ( + model.where(PlanDiff(iter_id, Customer, delta_ref)) .select( - Demand.customer_id.alias("customer_id"), - Demand.product_id.alias("product_id"), - Demand.period_id.alias("period_id"), - value_ref.alias("alloc_usd"), + Customer.id.alias("customer_id"), + Customer.name.alias("name"), + delta_ref.alias("delta_usd_total"), ) .to_df() + .sort_values("customer_id") ) - - # Plan-diff vs prior iteration's allocation (only overlapping periods). - if prior_alloc_df is not None: - overlap = sol.merge( - prior_alloc_df, - on=["customer_id", "product_id", "period_id"], - suffixes=("_now", "_prior"), - ) - overlap["delta_usd"] = overlap["alloc_usd_now"] - overlap["alloc_usd_prior"] - per_customer_delta = ( - overlap.groupby("customer_id")["delta_usd"].sum().rename("delta_usd_total") - ) - per_customer_delta = per_customer_delta.reset_index().merge( - customers_df[["id", "name"]], left_on="customer_id", right_on="id" - ) + if not per_customer_delta.empty: per_customer_delta["delta_$M"] = per_customer_delta["delta_usd_total"] / 1e6 per_customer_delta = per_customer_delta[["name", "delta_$M"]].sort_values("delta_$M") print( @@ -146,18 +126,21 @@ def main() -> None: ) print(per_customer_delta.to_string(index=False)) - prior_alloc_df = sol.copy() - - # Per-customer service level over the current horizon. - sol_merged = sol.merge( - demand_df[["customer_id", "product_id", "period_id", "demand_usd"]], - on=["customer_id", "product_id", "period_id"], - ) + # Per-customer service level over the current horizon, from the allocation and demand totals the + # deployed model publishes. + alloc_ref, demand_ref = Float.ref(), Float.ref() per_customer = ( - sol_merged.groupby("customer_id")[["alloc_usd", "demand_usd"]] - .sum() + model.where(CustomerService(iter_id, Customer, alloc_ref, demand_ref)) + .select( + Customer.id.alias("customer_id"), + Customer.name.alias("name"), + Customer.industry.alias("industry"), + alloc_ref.alias("alloc_usd"), + demand_ref.alias("demand_usd"), + ) + .to_df() + .sort_values("customer_id") .assign(service_level=lambda d: d["alloc_usd"] / d["demand_usd"]) - .join(customers_df.set_index("id")[["name", "industry"]]) .sort_values("demand_usd", ascending=False) ) per_customer["alloc_$B"] = per_customer["alloc_usd"] / 1e9 @@ -188,29 +171,15 @@ def main() -> None: print("Stage 4: Dependency-chain analysis (PATHS), RCA, and what-if") print("=" * 60) - chain_ref, hops_ref, step_ref = PathTraversal.ref(), Integer.ref(), Integer.ref() - paths_df = ( - model.where(DependencyChainStep(chain_ref, hops_ref, Customer, step_ref)) - .select( - chain_ref.alias("path_id"), - hops_ref.alias("hops"), - step_ref.alias("step"), - Customer.name.alias("customer"), - ) - .to_df() - ) - + chain_ref, hops_ref, route_ref = PathTraversal.ref(), Integer.ref(), String.ref() chains = ( - paths_df.sort_values(["path_id", "step"]) - .groupby("path_id") - .agg( - hops=("hops", "first"), - chain=("customer", lambda s: " -> ".join(s)), - ) - .reset_index() + model.where(DependencyChain(chain_ref, hops_ref, route_ref)) + .select(hops_ref.alias("hops"), route_ref.alias("chain"), chain_ref.alias("path_id")) + .to_df() .sort_values(["hops", "chain"]) ) - print(f"\n Total customer-customer dependency paths (1-3 hops): {len(chains)}") + num_chains = int(model.select(NumDependencyChains).to_df().iloc[0, 0]) + print(f"\n Total customer-customer dependency paths (1-3 hops): {num_chains}") print("\n === Dependency chains ===") print(chains[["hops", "chain"]].to_string(index=False)) @@ -230,19 +199,6 @@ def main() -> None: print("What-if 1: supplier-offline impact (no re-solve)") print("=" * 60) product_names = products_df.set_index("id")["name"] - product_ref, period_ref, drop_ref = Integer.ref(), Integer.ref(), Float.ref() - offline_df = ( - model.where( - OfflineDrop(Supplier, product_ref, period_ref, drop_ref), - drop_ref > OFFLINE_DROP_THRESHOLD, - ) - .select( - Supplier.id.alias("supplier_id"), - product_ref.alias("product_id"), - period_ref.alias("period_id"), - ) - .to_df() - ) impact_df = ( model.where(SupplierOfflineImpact.supplier_id == Supplier.id) .select( @@ -250,18 +206,11 @@ def main() -> None: Supplier.name.alias("supplier"), SupplierOfflineImpact.n_affected_cells.alias("n_affected_cells"), SupplierOfflineImpact.max_cap_drop_pct.alias("max_cap_drop_pct"), + SupplierOfflineImpact.affected_products.alias("affected_products"), ) .to_df() .sort_values("supplier_id") ) - impact_df["affected_products"] = [ - ", ".join( - product_names.loc[ - offline_df.loc[offline_df["supplier_id"] == s, "product_id"].unique() - ].tolist() - ) - for s in impact_df["supplier_id"] - ] print("\n === Supplier-offline impact (each supplier in isolation) ===") display_supplier = impact_df.drop(columns=["supplier_id"]).copy() display_supplier["max_cap_drop_%"] = (display_supplier["max_cap_drop_pct"] * 100).round(1) @@ -274,16 +223,13 @@ def main() -> None: print("\n" + "=" * 60) print("What-if 2: input-shortage impact (no re-solve)") print("=" * 60) + product_ref, avg_drop_ref = Integer.ref(), Float.ref() shortage_df = ( - model.where( - ShortageDrop(Input, product_ref, period_ref, drop_ref), - drop_ref > SHORTAGE_DROP_THRESHOLD, - ) + model.where(ShortageAverageDrop(Input, product_ref, avg_drop_ref)) .select( Input.id.alias("input_id"), product_ref.alias("product_id"), - period_ref.alias("period_id"), - drop_ref.alias("cap_drop_pct"), + avg_drop_ref.alias("avg_drop_pct"), ) .to_df() ) @@ -300,8 +246,8 @@ def main() -> None: for i in inputs_df["input_id"]: by_product = ( shortage_df[shortage_df["input_id"] == i] - .groupby("product_id")["cap_drop_pct"] - .mean() + .set_index("product_id")["avg_drop_pct"] + .sort_index() .round(3) ) avg_drops.append( @@ -323,8 +269,20 @@ def main() -> None: print(" Multi-hop dependency chains:") for chain in multihop["chain"]: print(f" {chain}") - if impact_df["n_affected_cells"].max() > 0: - worst_supplier = impact_df.loc[impact_df["n_affected_cells"].idxmax()] + widest_supplier = ( + model.where( + SupplierOfflineImpact.has_widest_impact(), + SupplierOfflineImpact.supplier_id == Supplier.id, + ) + .select( + Supplier.name.alias("supplier"), + SupplierOfflineImpact.n_affected_cells.alias("n_affected_cells"), + SupplierOfflineImpact.max_cap_drop_pct.alias("max_cap_drop_pct"), + ) + .to_df() + ) + if not widest_supplier.empty: + worst_supplier = widest_supplier.iloc[0] print( f" Supplier with widest offline impact: {worst_supplier['supplier']} " f"({worst_supplier['n_affected_cells']} affected cells, " @@ -332,8 +290,16 @@ def main() -> None: ) else: print(" Supplier with widest offline impact: none (no affected cells)") - if inputs_df["n_affected_cells"].max() > 0: - worst_input = inputs_df.loc[inputs_df["n_affected_cells"].idxmax()] + widest_input = ( + model.where(Input.has_widest_shortage_impact()) + .select( + Input.name.alias("input"), + Input.shortage_impact_cells.alias("n_affected_cells"), + ) + .to_df() + ) + if not widest_input.empty: + worst_input = widest_input.iloc[0] print( f" Input with widest shortage impact: {worst_input['input']} " f"({worst_input['n_affected_cells']} affected cells)" diff --git a/memory_supply_allocation/train.py b/memory_supply_allocation/train.py index 4bbecfa6..18c5582d 100644 --- a/memory_supply_allocation/train.py +++ b/memory_supply_allocation/train.py @@ -15,7 +15,7 @@ def main() -> None: if gnn is None: - raise SystemExit("USE_PRECOMPUTED_FORECAST is set in model/reasoning.py: there is no GNN to train.") + raise SystemExit("USE_PRECOMPUTED_FORECAST is set in model/capability_forecast.py: there is no GNN to train.") print("=" * 60) print("Stage 2: Training supplier-capability GNN (regression)") print("=" * 60) diff --git a/planogram_optimization/README.md b/planogram_optimization/README.md index 7677bba7..347cc94e 100644 --- a/planogram_optimization/README.md +++ b/planogram_optimization/README.md @@ -44,7 +44,7 @@ The same pattern applies to any predict-then-optimize problem where the predicti ## What's included -- `model/` -- the model package: `schema.py` (ontology), `source.py` (sample data and its pre-solve checks), and `reasoning.py` (decisions, constraints, and solver configuration); `rai models deploy --path model` deploys it +- `model/` -- the model package: `schema.py` (ontology), `source.py` (sample data and its pre-solve checks), `facing_allocation.py` (decisions, constraints, and solver configuration), and `allocation_usage.py` (each shelf's used length and each category's active SKUs under the chosen facings); `rai models deploy --path model` deploys it - `queries/facings_plan.py` -- prints the report from the deployed model - **Runbook**: `runbook.md` -- a paste-testable walkthrough that reproduces the template step by step with the RAI skills; as important a reference as the script itself. - `data/skus.csv` -- 18 SKUs across 4 categories (snacks, beverages, candy, household_paper) with width, max-facings, and pre-assigned shelf; `sku_id` must be unique, `category` must match a `categories.csv` `category`, and `assigned_shelf_id` must reference a `shelves.csv` `shelf_id`. The `brand` column is loaded but not used by the bundled CSP -- it is reserved for the brand-block contiguity customization described under "Customize this template" @@ -231,7 +231,8 @@ Use this sequence to deploy the model and query it: │ ├── __init__.py │ ├── schema.py │ ├── source.py -│ └── reasoning.py +│ ├── facing_allocation.py +│ └── allocation_usage.py ├── queries/ │ └── facings_plan.py └── data/ @@ -276,7 +277,7 @@ skus + shelves + categories + predicted-demand table → facings / realized_dema **Checks run in the report.** The `implies`-bodied lookup is solver-only; after the deploy, a Python dict re-checks each `(sku_id, facings) -> demand_units` against the deployed demand table, and the report stops if one does not match. The constraints (lookup, capacity, cardinality, active coupling) all go to the solver; the report does not re-evaluate them, and a refresh started outside the report (`rai models deploy`, the refresh procedure, a schedule) runs no checks, so read the solve status (`SolveStatus`) before relying on a refreshed solution. -For the exact PyRel formulation, see `model/reasoning.py`; `runbook.md` reproduces the pipeline step by step with the RAI skills. +For the exact PyRel formulation, see `model/facing_allocation.py` and `model/allocation_usage.py`; `runbook.md` reproduces the pipeline step by step with the RAI skills. ## Customize this template diff --git a/planogram_optimization/model/__init__.py b/planogram_optimization/model/__init__.py index b494c1f3..bb94dc77 100644 --- a/planogram_optimization/model/__init__.py +++ b/planogram_optimization/model/__init__.py @@ -23,21 +23,28 @@ solver-only; the report re-validates `(sku_id, facings) -> demand_units` against the deployed demand table via a Python dict lookup. +The model has two rule modules: `facing_allocation.py` (decisions, constraints, +objective, and solve) and `allocation_usage.py` (shelf length used and active +SKUs per category under the chosen facings). + Run: `rai models deploy --path model` deploys this package to the schemas in raiconfig.yaml and waits for its first refresh, which runs the solve. `python -m queries.facings_plan` then prints the report from the deployed model. """ -from .reasoning import SolveStatus, TotalDemand, problem +from .allocation_usage import CategoryUsage, ShelfUsage +from .facing_allocation import SolveStatus, TotalDemand, problem from .schema import Category, PredictedDemand, Shelf, Sku, model from .source import DATA_DIR __all__ = [ "DATA_DIR", "Category", + "CategoryUsage", "PredictedDemand", "Shelf", + "ShelfUsage", "Sku", "SolveStatus", "TotalDemand", diff --git a/planogram_optimization/model/allocation_usage.py b/planogram_optimization/model/allocation_usage.py new file mode 100644 index 00000000..9da5e9a5 --- /dev/null +++ b/planogram_optimization/model/allocation_usage.py @@ -0,0 +1,33 @@ +"""Allocation usage: the shelf length each shelf uses and the active SKUs each category has under the +chosen facings.""" + +from relationalai.semantics import Integer, String +from relationalai.semantics.std import aggregates as aggs + +# Declares Sku.facings and Sku.active, the decisions the usage totals read. +from . import facing_allocation # noqa: F401 +from .schema import Category, Shelf, Sku, model + +# Values computed from the solution live on concepts of their own, not on Shelf or Category: +# such a property on a concept the solve reads fails the deploy. + +# Each shelf's used length: facings times SKU width, summed over the SKUs on it. A shelf with no +# SKU has no usage. +ShelfUsage = model.Concept("ShelfUsage", identify_by={"shelf_id": Integer}) +ShelfUsage.used_cm = model.Property(f"{ShelfUsage} has {Integer:used_cm}") +model.where(Sku.shelf == Shelf).define(ShelfUsage.new(shelf_id=Shelf.id)) +model.define( + ShelfUsage.used_cm( + aggs.sum(Sku, Sku.facings * Sku.width_cm).per(ShelfUsage).where(Sku.shelf.id == ShelfUsage.shelf_id) + ) +) + +# Each category's number of active SKUs. A category with no SKU has no count. +CategoryUsage = model.Concept("CategoryUsage", identify_by={"name": String}) +CategoryUsage.active_skus = model.Property(f"{CategoryUsage} has {Integer:active_skus}") +model.where(Sku.category == Category.name).define(CategoryUsage.new(name=Category.name)) +model.define( + CategoryUsage.active_skus( + aggs.sum(Sku, Sku.active).per(CategoryUsage).where(Sku.category == CategoryUsage.name) + ) +) diff --git a/planogram_optimization/model/reasoning.py b/planogram_optimization/model/facing_allocation.py similarity index 96% rename from planogram_optimization/model/reasoning.py rename to planogram_optimization/model/facing_allocation.py index 3c34b73d..2735ce29 100644 --- a/planogram_optimization/model/reasoning.py +++ b/planogram_optimization/model/facing_allocation.py @@ -1,4 +1,5 @@ -"""Planogram problem: integer facings per SKU that maximize total predicted demand.""" +"""Facing allocation: the integer facings per SKU that maximize total predicted demand within shelf +capacity and category bounds.""" from relationalai.semantics import Integer, String, sum from relationalai.semantics.reasoners.prescriptive import Problem, implies diff --git a/planogram_optimization/queries/facings_plan.py b/planogram_optimization/queries/facings_plan.py index c645f230..f04145fc 100644 --- a/planogram_optimization/queries/facings_plan.py +++ b/planogram_optimization/queries/facings_plan.py @@ -8,15 +8,16 @@ from model import ( Category, + CategoryUsage, PredictedDemand, Shelf, + ShelfUsage, Sku, SolveStatus, TotalDemand, model, ) from pandas import isna -from relationalai.semantics import sum if __name__ == "__main__": status = model.select(SolveStatus).to_df().iloc[:, 0].tolist() @@ -91,14 +92,14 @@ model.select( Shelf.id, Shelf.name, - sum(Sku.facings * Sku.width_cm).per(Shelf).alias("used_cm"), + ShelfUsage.used_cm.alias("used_cm"), Shelf.length_cm, - ).where(Sku.shelf == Shelf).inspect() + ).where(ShelfUsage.shelf_id == Shelf.id).inspect() print("\nCategory active counts:") model.select( Category.name, - sum(Sku.active).per(Category).alias("active_skus"), + CategoryUsage.active_skus.alias("active_skus"), Category.min_skus_active, Category.max_skus_active, - ).where(Sku.category == Category.name).inspect() + ).where(CategoryUsage.name == Category.name).inspect() diff --git a/planogram_optimization/runbook.md b/planogram_optimization/runbook.md index a15f4727..8a409d2f 100644 --- a/planogram_optimization/runbook.md +++ b/planogram_optimization/runbook.md @@ -85,7 +85,7 @@ Each SKU has a concave demand curve over facing counts — demand rises with fac **Response** -Total predicted weekly demand around **1,600+ units** — the decision picks facings per SKU (binding each SKU's realized demand to its predicted-demand row via a table lookup), with shelf-length and category-cardinality constraints; `Sku.facings`, `Sku.realized_demand`, and `Sku.active` are written back. (The README's sample run reports `OPTIMAL` at 1,656 units; the report stops on any other status, such as a time-limited incumbent.) In `model/reasoning.py` the solve is declared with `problem.configure(...)`, so each refresh of the deployed model runs it. +Total predicted weekly demand around **1,600+ units** — the decision picks facings per SKU (binding each SKU's realized demand to its predicted-demand row via a table lookup), with shelf-length and category-cardinality constraints; `Sku.facings`, `Sku.realized_demand`, and `Sku.active` are written back. (The README's sample run reports `OPTIMAL` at 1,656 units; the report stops on any other status, such as a time-limited incumbent.) In `model/facing_allocation.py` the solve is declared with `problem.configure(...)`, so each refresh of the deployed model runs it. ### 6. Read the planogram diff --git a/pod_placement/README.md b/pod_placement/README.md index b0445958..ce6723d4 100644 --- a/pod_placement/README.md +++ b/pod_placement/README.md @@ -52,7 +52,7 @@ This template encodes that stack as a pure constraint satisfaction and optimizat The bundled CSVs are illustrative demo data tuned so multiple ICs bind at the optimum -- rack-clique forces the distributed-training group onto one rack, CPU / memory / GPU bin-packing then pin it to a single node at exact 100% utilization on all three resources, anti-affinity partitions the alpha-beta and gamma-delta tenant pods across disjoint node sets, deployment co-location affinity co-locates the cache pair, and the spread cap binds for every multi-replica non-overridden deployment. Swap in your own cluster topology and workload to apply the template to a real cluster. -- `model/` -- the model package: `schema.py` declares the concepts, `source.py` loads the sample data, and `reasoning.py` states the decision problem (decisions, constraints, and the solver configuration); `rai models deploy --path model` deploys it +- `model/` -- the model package: `schema.py` declares the concepts, `source.py` loads the sample data, `zone_spread.py` states each deployment's spread cap, `pod_assignment.py` states the decision problem (decisions, constraints, and the solver configuration), and `node_usage.py` totals each node's placed demand; `rai models deploy --path model` deploys it - `queries/placement_report.py` -- prints the report from the deployed model - **Runbook**: `runbook.md` -- a paste-testable walkthrough that reproduces the template step by step with the RAI skills; as important a reference as the script itself. - `data/nodes.csv` -- 8 nodes across 2 zones (`us-east-1a`, `us-east-1b`) and 4 racks; six general-purpose nodes (12000 millicores, 49152 MiB) and two GPU nodes (8000 millicores, 32768 MiB, 4 GPUs each). Total cluster: 88000 millicores, 360448 MiB, 8 GPUs @@ -232,7 +232,9 @@ pod_placement/ __init__.py # exports of the deployed model schema.py # zones, racks, nodes, tenants, deployments, pods source.py # loads the sample CSVs - reasoning.py # decisions, constraints, objective, solve + zone_spread.py # zone count and each deployment's spread cap + pod_assignment.py # decisions, constraints, objective, solve + node_usage.py # CPU, memory, and GPU used per node queries/ placement_report.py # report from the deployed model data/ @@ -248,7 +250,7 @@ pod_placement/ pyproject.toml # dependencies ``` -**Start here**: deploy with `rai models deploy --path model` and run `python -m queries.placement_report` for the solve status and post-solve inspection (the formulation is in `model/reasoning.py`), or follow `runbook.md` to rebuild it step by step. +**Start here**: deploy with `rai models deploy --path model` and run `python -m queries.placement_report` for the solve status and post-solve inspection (the formulation is in `model/pod_assignment.py`), or follow `runbook.md` to rebuild it step by step. ## Sample data @@ -288,11 +290,11 @@ nodes + pods + deployments + affinity / anti-affinity / training relations → 2 **Gang placement is a reified cardinality constraint.** A 0/1 deployment-level indicator forces every replica of a deployment to be placed together or not at all — the per-deployment placed-pod count equals `replicas × placed`, so a partial schedule is impossible. No big-M, no auxiliary indicator stack. -**Failure-domain spread is a two-key aggregate.** With `max_per_zone` precomputed (default `ceil(replicas / num_zones)`, or the row's `max_per_zone_override`), the count of a deployment's pods per zone must stay under its cap. The override is a per-deployment escape hatch: the bundled data uses it on the distributed-training job, whose rack-clique requirement forces all its pods onto one rack — and therefore one zone — which would otherwise collide with the default spread cap. +**Failure-domain spread is a two-key aggregate.** With `max_per_zone` a rule on each deployment (default `ceil(replicas / num_zones)`, or the row's `max_per_zone_override`), the count of a deployment's pods per zone must stay under its cap. The override is a per-deployment escape hatch: the bundled data uses it on the distributed-training job, whose rack-clique requirement forces all its pods onto one rack — and therefore one zone — which would otherwise collide with the default spread cap. Every constraint is pure relational arithmetic (no `implies` bodies), and the report stops unless the solver proved `OPTIMAL` rather than timing out. The report does not re-evaluate the constraints, and a refresh started outside the report (`rai models deploy`, the refresh procedure, a schedule) runs no checks, so read `SolveStatus` before relying on a refreshed solution. -For the exact PyRel formulation, see `model/reasoning.py`; `runbook.md` reproduces the model step by step with the RAI skills. +For the exact PyRel formulation, see `model/pod_assignment.py` and `model/zone_spread.py`; `runbook.md` reproduces the model step by step with the RAI skills. ## Customize this template @@ -308,7 +310,7 @@ For the exact PyRel formulation, see `model/reasoning.py`; `runbook.md` reproduc ### Extend the model -- **Tier-aware placement.** Mark pods with `gpu_units > 0` and add an IC forcing them onto GPU-capable nodes only -- e.g. `model.where(Pod.on_node(Node, 1), Pod.gpu_units >= 1).require(Node.gpu_units >= 1)` (matches the `model.where(...).require(...)` chaining used by every IC in `model/reasoning.py`). Conversely, mark some nodes as "general-purpose only" and forbid GPU workloads there. +- **Tier-aware placement.** Mark pods with `gpu_units > 0` and add an IC forcing them onto GPU-capable nodes only -- e.g. `model.where(Pod.on_node(Node, 1), Pod.gpu_units >= 1).require(Node.gpu_units >= 1)` (matches the `model.where(...).require(...)` chaining used by every IC in `model/pod_assignment.py`). Conversely, mark some nodes as "general-purpose only" and forbid GPU workloads there. - **Migration cost under churn.** Add a `Pod.current_node` data property reflecting the existing assignment, then introduce a per-pod "moved" indicator (`moved = (1 - Pod.on_node(current_node, x))`) and minimize the total move count -- multi-solution then enumerates the N least-disruptive placements. - **NVLink-clique with explicit edges.** The bundled `data/distributed_training.csv` lists every pair in the training group, encoding rack-clique implicitly via the pairwise IC. To model a true edge-restricted clique (e.g. NVLink-2 connectivity between specific GPU pairs only), pre-compute the set of `(node_a, node_b)` pairs that lack a direct NVLink edge in Python and load them as a `NoNVLink` data relationship; then drop the `Na.rack != Nb.rack` clause from `rack_clique_ic` and replace it with `NoNVLink(Na, Nb)` to forbid co-placement on any pair of hosts without a direct NVLink path. - **Spot / preemptible tier.** Mark a subset of pods as preemptible (`Pod.is_preemptible == 1`) and let them displace lower-priority workloads when capacity is tight. Express as a per-node tiered capacity: preemptible pods consume "remaining" capacity, on-demand pods consume the primary allotment. diff --git a/pod_placement/model/__init__.py b/pod_placement/model/__init__.py index 029d56c6..39d5cbf6 100644 --- a/pod_placement/model/__init__.py +++ b/pod_placement/model/__init__.py @@ -45,13 +45,19 @@ can use either argument order. - All ICs are pure relational arithmetic -- no ``implies`` bodies. +The model has three rule modules, and each imports the modules whose +declarations it reads: `zone_spread.py` (the zone count and each deployment's +spread cap), `pod_assignment.py` (decisions, constraints, objective, and +solve), and `node_usage.py` (the CPU, memory, and GPU each node carries). + Run: `rai models deploy --path model` deploys this package to the schemas in raiconfig.yaml and waits for its first refresh, which runs the solve. `python -m queries.placement_report` then prints the report from the deployed model. """ -from .reasoning import PlacedDeployments, SolveStatus, problem, x +from .node_usage import NodeUsage +from .pod_assignment import PlacedDeployments, SolveStatus, problem, x from .schema import Deployment, Node, Pod, Rack, Tenant, Zone, model from .source import DATA_DIR @@ -59,6 +65,7 @@ "DATA_DIR", "Deployment", "Node", + "NodeUsage", "PlacedDeployments", "Pod", "Rack", diff --git a/pod_placement/model/node_usage.py b/pod_placement/model/node_usage.py new file mode 100644 index 00000000..5d192e9f --- /dev/null +++ b/pod_placement/model/node_usage.py @@ -0,0 +1,25 @@ +"""Node usage: the CPU, memory, and GPU each node carries under the chosen placement.""" + +from relationalai.semantics import Integer +from relationalai.semantics.std import aggregates as aggs + +# Declares Pod.on_node, the placement decision the usage totals read. +from . import pod_assignment # noqa: F401 +from .schema import Node, Pod, model + +# Values computed from the solution live on a concept of their own, not on Node: such a property +# on a concept the solve reads fails the deploy. +NodeUsage = model.Concept("NodeUsage", identify_by={"node_id": Integer}) +NodeUsage.cpu_used = model.Property(f"{NodeUsage} has {Integer:cpu_used}") +NodeUsage.memory_used = model.Property(f"{NodeUsage} has {Integer:memory_used}") +NodeUsage.gpu_used = model.Property(f"{NodeUsage} has {Integer:gpu_used}") +model.define(NodeUsage.new(node_id=Node.id)) + +# Each node's CPU, memory, and GPU demand summed over the pods placed on it. +_assigned = Integer.ref() +_on_node = (Pod.on_node(Node, _assigned), Node.id == NodeUsage.node_id) +model.define( + NodeUsage.cpu_used(aggs.sum(Pod, Pod.cpu_millicores * _assigned).per(NodeUsage).where(*_on_node)), + NodeUsage.memory_used(aggs.sum(Pod, Pod.memory_mib * _assigned).per(NodeUsage).where(*_on_node)), + NodeUsage.gpu_used(aggs.sum(Pod, Pod.gpu_units * _assigned).per(NodeUsage).where(*_on_node)), +) diff --git a/pod_placement/model/reasoning.py b/pod_placement/model/pod_assignment.py similarity index 96% rename from pod_placement/model/reasoning.py rename to pod_placement/model/pod_assignment.py index 8ee728d0..def9d7d9 100644 --- a/pod_placement/model/reasoning.py +++ b/pod_placement/model/pod_assignment.py @@ -1,8 +1,10 @@ -"""Pod placement problem: binary pod-to-node assignments that maximize the number of placed deployments.""" +"""Pod assignment: binary pod-to-node assignments that maximize the number of placed deployments.""" from relationalai.semantics import Integer, String, sum from relationalai.semantics.reasoners.prescriptive import Problem +# Declares Deployment.max_per_zone, the spread cap the spread constraint reads. +from . import zone_spread # noqa: F401 from .schema import ( Deployment, DeploymentAffinity, diff --git a/pod_placement/model/schema.py b/pod_placement/model/schema.py index c4856e79..9adbdcbd 100644 --- a/pod_placement/model/schema.py +++ b/pod_placement/model/schema.py @@ -30,6 +30,7 @@ Deployment = model.Concept("Deployment", identify_by={"id": Integer}) Deployment.name = model.Property(f"{Deployment} has {String:name}") Deployment.replicas = model.Property(f"{Deployment} has {Integer:replicas}") +Deployment.max_per_zone_override = model.Property(f"{Deployment} has {Integer:max_per_zone_override}") Deployment.max_per_zone = model.Property(f"{Deployment} has {Integer:max_per_zone}") Deployment.tenant = model.Property(f"{Deployment} belongs to {Tenant:tenant}") diff --git a/pod_placement/model/source.py b/pod_placement/model/source.py index 341cb3ce..d2e9fd13 100644 --- a/pod_placement/model/source.py +++ b/pod_placement/model/source.py @@ -1,9 +1,8 @@ """Load the sample cluster, tenants, deployments, and pods, and check the topology.""" -from math import ceil from pathlib import Path -from pandas import isna, read_csv +from pandas import read_csv from .schema import ( Deployment, @@ -21,15 +20,9 @@ DATA_DIR = Path(__file__).resolve().parents[1] / "data" # -------------------------------------------------- -# Load CSVs and pre-compute per-deployment failure-domain spread caps. -# With N zones, at most ceil(replicas / N) replicas of any one -# deployment land in any single zone -- unless the row supplies an -# explicit `max_per_zone_override` (used for deployments where the -# operator has accepted a wider blast radius, e.g. distributed- -# training groups whose rack-clique requirement is incompatible with -# cross-zone spread). Computed in Python and joined onto Deployment -# as a data property so the spread IC reads as a plain relational -# inequality. +# Load CSVs. The failure-domain spread cap of each deployment is a rule +# over its replicas, the zone count, and the optional +# `max_per_zone_override` (see `zone_spread.py`). # -------------------------------------------------- nodes_csv = read_csv(DATA_DIR / "nodes.csv") @@ -40,52 +33,22 @@ pods_csv = read_csv(DATA_DIR / "pods.csv") dt_csv = read_csv(DATA_DIR / "distributed_training.csv") -num_zones = nodes_csv["zone"].nunique() -if num_zones == 0: +if nodes_csv["zone"].nunique() == 0: raise ValueError("nodes.csv must contain at least one row to define the cluster topology.") - -def _compute_max_per_zone(replicas, override): - if override is not None and not isna(override): - return int(override) - return int(ceil(int(replicas) / num_zones)) - - -deployments_csv = deployments_csv.assign( - max_per_zone=[ - _compute_max_per_zone(r, o) - for r, o in zip( - deployments_csv["replicas"].tolist(), - deployments_csv["max_per_zone_override"].tolist(), - ) - ] -).drop(columns=["max_per_zone_override"]) -# Drop the override column before passing to model.data: rows with NaN -# in any column get silently filtered, so leaving the override column -# in (where it is NaN for most rows) would drop those Deployment rows -# from the model -- breaking the gang IC and the objective. - - -# Zones are derived from the unique values in `nodes.csv` rather than -# committed as a separate CSV -- a node always belongs to exactly one -# zone, and the zone column on nodes.csv is the single source of truth. -_zones_df = nodes_csv[["zone"]].drop_duplicates().rename(columns={"zone": "name"}) -_zone_data = model.data(_zones_df) -model.define(Zone.new(name=_zone_data.name)) - -# Racks and the zone each belongs to. -_racks_df = nodes_csv[["rack"]].drop_duplicates().rename(columns={"rack": "name"}) -_rack_data = model.data(_racks_df) -model.define(Rack.new(name=_rack_data.name)) -_rack_zone_df = nodes_csv[["rack", "zone"]].drop_duplicates() -_rack_zone_data = model.data(_rack_zone_df) +# Zones and racks are derived from the values in `nodes.csv` rather than +# committed as separate CSVs -- a node always belongs to exactly one +# zone and rack, and the zone and rack columns on nodes.csv are the +# single source of truth. +node_data = model.data(nodes_csv) +model.define(Zone.new(name=node_data.zone)) +model.define(Rack.new(name=node_data.rack)) model.define(Rack.zone(Zone)).where( - Rack.name == _rack_zone_data.rack, - Zone.name == _rack_zone_data.zone, + Rack.name == node_data.rack, + Zone.name == node_data.zone, ) # Nodes. -node_data = model.data(nodes_csv) model.define( Node.new( id=node_data.node_id, @@ -107,16 +70,26 @@ def _compute_max_per_zone(replicas, override): ) ) -# Deployments. -dep_data = model.data(deployments_csv) +# Deployments. The override column is loaded as a table of its own: rows with NaN in any +# column get silently filtered by model.data, so leaving it in (where it is NaN for most +# rows) would drop those Deployment rows from the model -- breaking the gang IC and the +# objective. +dep_data = model.data(deployments_csv.drop(columns=["max_per_zone_override"])) model.define( Deployment.new( id=dep_data.deployment_id, name=dep_data.name, replicas=dep_data.replicas, - max_per_zone=dep_data.max_per_zone, ) ) +overrides_csv = ( + deployments_csv[["deployment_id", "max_per_zone_override"]].dropna().astype(int) +) +if not overrides_csv.empty: + override_data = model.data(overrides_csv) + model.define(Deployment.max_per_zone_override(override_data.max_per_zone_override)).where( + Deployment.id == override_data.deployment_id + ) model.define(Deployment.tenant(Tenant)).where( Deployment.id == dep_data.deployment_id, Tenant.id == dep_data.tenant_id, diff --git a/pod_placement/model/zone_spread.py b/pod_placement/model/zone_spread.py new file mode 100644 index 00000000..4e40a557 --- /dev/null +++ b/pod_placement/model/zone_spread.py @@ -0,0 +1,27 @@ +"""Zone spread: the number of zones in the cluster and each deployment's cap on replicas per zone.""" + +from relationalai.semantics import Integer +from relationalai.semantics.std import aggregates as aggs + +from .schema import Deployment, Zone, model + +# -------------------------------------------------- +# Failure-domain spread caps +# -------------------------------------------------- +# With N zones, at most ceil(replicas / N) replicas of any one deployment land in +# any single zone -- unless the deployment has an explicit `max_per_zone_override` +# (used for deployments where the operator has accepted a wider blast radius, e.g. +# distributed-training groups whose rack-clique requirement is incompatible with +# cross-zone spread). The cap is a data property of the deployment so the spread IC +# reads as a plain relational inequality. + +num_zones = model.Relationship(f"the cluster has {Integer:num_zones} zones") +model.define(num_zones(aggs.count(Zone))) + +# The ceiling of replicas / zones, in integer arithmetic. +_zones = Integer.ref() +model.where(num_zones(_zones)).define( + Deployment.max_per_zone( + Deployment.max_per_zone_override | ((Deployment.replicas + _zones - 1) // _zones) + ) +) diff --git a/pod_placement/queries/placement_report.py b/pod_placement/queries/placement_report.py index 4d61a1a0..208a89c6 100644 --- a/pod_placement/queries/placement_report.py +++ b/pod_placement/queries/placement_report.py @@ -8,13 +8,12 @@ from model import ( Deployment, Node, + NodeUsage, PlacedDeployments, Pod, SolveStatus, model, - x, ) -from relationalai.semantics import sum if __name__ == "__main__": # The report stops unless the solver proved OPTIMAL: if you raise `time_limit_sec` and the @@ -36,11 +35,11 @@ model.select( Node.id.alias("node_id"), Node.name.alias("node"), - sum(Pod.cpu_millicores * x).where(Pod.on_node(Node, x)).per(Node).alias("cpu_used"), + NodeUsage.cpu_used.alias("cpu_used"), Node.cpu_millicores.alias("cpu_cap"), - sum(Pod.memory_mib * x).where(Pod.on_node(Node, x)).per(Node).alias("memory_used"), - sum(Pod.gpu_units * x).where(Pod.on_node(Node, x)).per(Node).alias("gpu_used"), - ).inspect() + NodeUsage.memory_used.alias("memory_used"), + NodeUsage.gpu_used.alias("gpu_used"), + ).where(NodeUsage.node_id == Node.id).inspect() print("\nPlaced pods (pod_id -> node_id):") model.select( diff --git a/pod_placement/runbook.md b/pod_placement/runbook.md index aeae050d..a30cc8da 100644 --- a/pod_placement/runbook.md +++ b/pod_placement/runbook.md @@ -39,7 +39,7 @@ Each prompt is pasted into a fresh agent session loaded with the named `/rai-*` **Prompt:** /rai-prescriptive-problem Assign pods to nodes to place as many deployments as possible, treating every rule as hard: a pod goes on at most one node; a deployment is placed only if all its replicas are; per node, total CPU, memory, and GPU requests can't exceed capacity; pods of anti-affine tenants can't share a node; affinity-paired deployments must share a node; each deployment's pods are spread so no zone holds more than its share; and the distributed-training pods must all land on the same rack. Maximize the number of placed deployments and persist the assignment to the ontology. -**Response:** OPTIMAL (MiniZinc constraint solver), objective **12 — all 12 deployments placed**. The model is a binary pod-to-node assignment matrix plus placed indicators (hundreds of variables and constraints across the six rule families); the assignment, `Pod.placed`, and `Deployment.placed` are written back to the ontology. In `model/reasoning.py` the solve is declared with `problem.configure(...)`, so each refresh of the deployed model runs it. +**Response:** OPTIMAL (MiniZinc constraint solver), objective **12 — all 12 deployments placed**. The model is a binary pod-to-node assignment matrix plus placed indicators (hundreds of variables and constraints across the six rule families); the assignment, `Pod.placed`, and `Deployment.placed` are written back to the ontology. In `model/pod_assignment.py` the solve is declared with `problem.configure(...)`, so each refresh of the deployed model runs it. ## 4. Read the placement diff --git a/portfolio_balancing/model/__init__.py b/portfolio_balancing/model/__init__.py index 2f215b79..a62c737a 100644 --- a/portfolio_balancing/model/__init__.py +++ b/portfolio_balancing/model/__init__.py @@ -22,6 +22,11 @@ (values and shadow prices), so one refresh runs the whole sensitivity-guided frontier. Each solve publishes its status and a FrontierPoint per scenario. +Modules: `compliance_flags.py` (Stage 1), `correlation_clusters.py` (Stage 2), +`regime_covariance.py` (the base and crisis covariance), and `efficient_frontier.py` (Stage 3, +the solves and the frontier points they publish). Each module imports the modules whose +declarations it reads. + Run: `rai models deploy --path model` deploys this package to the schemas in raiconfig.yaml and waits for its first refresh, which runs the rules, the graph, @@ -38,18 +43,26 @@ then a base-vs-crisis volatility table per frontier point. """ -from .reasoning import ( - ADAPTIVE_SOLVES, +from .compliance_flags import POSITION_LIMIT, SECTOR_LIMIT, SectorExposure +from .correlation_clusters import ( CORR_THRESHOLD, - CRISIS_ALPHA, + Cluster, + inter_cluster_correlation, + intra_cluster_correlation, + num_clusters, + num_edges, + num_representatives, + num_stocks, +) +from .efficient_frontier import ( + ADAPTIVE_SOLVES, DICHOTOMIC_SOLVES, GRID_SOLVES, N_SOLVES, - POSITION_LIMIT, REFERENCE_SCENARIO, - SECTOR_LIMIT, SolveStatus, ) +from .regime_covariance import CRISIS_ALPHA from .schema import ( Account, FrontierPoint, @@ -76,14 +89,22 @@ "REFERENCE_SCENARIO", "SECTOR_LIMIT", "Account", + "Cluster", "FrontierPoint", "Holding", "Regime", "Scenario", "Sector", + "SectorExposure", "SolveStatus", "Stock", "Transaction", "User", + "inter_cluster_correlation", + "intra_cluster_correlation", "model", + "num_clusters", + "num_edges", + "num_representatives", + "num_stocks", ] diff --git a/portfolio_balancing/model/compliance_flags.py b/portfolio_balancing/model/compliance_flags.py new file mode 100644 index 00000000..216cd24e --- /dev/null +++ b/portfolio_balancing/model/compliance_flags.py @@ -0,0 +1,98 @@ +"""Portfolio compliance rules: each holding's value and share of its account balance, the overconcentrated +holdings, each account's exposure to each sector and the concentrated sector positions, and the high-risk +traders.""" + +from relationalai.semantics import Float, sum + +from .schema import Account, Holding, Sector, Stock, Transaction, User, model + +# -------------------------------------------------- +# Configure inputs +# -------------------------------------------------- + +POSITION_LIMIT = 0.15 # max fraction per stock in Stage 1 compliance rules +SECTOR_LIMIT = 0.30 # max fraction of budget per sector (both stages) + +# -------------------------------------------------- +# Stage 1: Rules -- compliance flags +# -------------------------------------------------- + +# Derived holding value = quantity * purchase_price. +model.define(Holding.value(Holding.quantity * Holding.purchase_price)) + +# Rule 1: Overconcentrated holdings -- position value > POSITION_LIMIT of balance. +Holding.share_of_balance = model.Property(f"{Holding} has {Float:share_of_balance}") +AccountR1 = Account.ref() +model.where(Holding.account(AccountR1)).define( + Holding.share_of_balance(Holding.value / AccountR1.balance) +) +model.where( + Holding.account(AccountR1), + Holding.value > POSITION_LIMIT * AccountR1.balance, +).define(Holding.is_overconcentrated()) + +# Rule 2: Sector concentration -- total sector exposure > SECTOR_LIMIT of balance. +# An account has one exposure to each sector it holds. +SectorExposure = model.Concept( + "SectorExposure", identify_by={"account": Account, "sector": Sector} +) +SectorExposure.exposure = model.Property(f"{SectorExposure} has {Float:sector_exposure}") +SectorExposure.share_of_balance = model.Property( + f"{SectorExposure} has {Float:sector_share_of_balance}" +) +SectorExposure.is_concentrated = model.Relationship(f"{SectorExposure} is concentrated") + +HoldingSC = Holding.ref() +StockSC = Stock.ref() +AccountSC = Account.ref() +SectorSC = Sector.ref() + +model.where( + Holding.account(AccountSC), + Holding.stock(StockSC), + StockSC.sector_ref(SectorSC), +).define(SectorExposure.new(account=AccountSC, sector=SectorSC)) + +model.define( + SectorExposure.exposure( + sum(HoldingSC, HoldingSC.value) + .per(SectorExposure) + .where( + HoldingSC.account(SectorExposure.account), + HoldingSC.stock(StockSC), + StockSC.sector_ref(SectorExposure.sector), + ) + ) +) +model.define( + SectorExposure.share_of_balance(SectorExposure.exposure / SectorExposure.account.balance) +) +model.where( + SectorExposure.exposure > SECTOR_LIMIT * SectorExposure.account.balance +).define(SectorExposure.is_concentrated()) + +# A holding is in a concentrated sector position when its account's exposure to the +# holding's sector is concentrated. +model.where( + Holding.account(AccountSC), + Holding.stock(StockSC), + StockSC.sector_ref(SectorSC), + SectorExposure.account == AccountSC, + SectorExposure.sector == SectorSC, + SectorExposure.is_concentrated(), +).define(Holding.is_sector_concentrated()) + +# Rule 3: High-risk traders -- risk_score > 0.8 AND >5 flagged transactions. +TransactionHR = Transaction.ref() +flagged_count = ( + sum(TransactionHR.is_flagged_val) + .where( + TransactionHR.user(User), + ) + .per(User) +) + +model.where( + User.risk_score > 0.8, + flagged_count > 5, +).define(User.is_high_risk_trader()) diff --git a/portfolio_balancing/model/correlation_clusters.py b/portfolio_balancing/model/correlation_clusters.py new file mode 100644 index 00000000..39d40852 --- /dev/null +++ b/portfolio_balancing/model/correlation_clusters.py @@ -0,0 +1,157 @@ +"""Correlation clusters: each stock's variance, volatility, and pairwise correlation, the correlation graph +and its Louvain clusters, the representative of each cluster (highest Sharpe ratio), and summaries of the +clustering.""" + +from relationalai.semantics import Float, Integer +from relationalai.semantics.reasoners.graph import Graph +from relationalai.semantics.std import aggregates as aggs +from relationalai.semantics.std.math import abs as math_abs +from relationalai.semantics.std.math import sqrt + +from .schema import Stock, model + +# -------------------------------------------------- +# Configure inputs +# -------------------------------------------------- + +CORR_THRESHOLD = 0.3 # |correlation| >= threshold to create a graph edge (Stage 2) + +# -------------------------------------------------- +# Stage 2: Graph -- covariance clustering +# -------------------------------------------------- + +# Derived per-stock variance (covar diagonal, i == j). +PairedStockVar = Stock.ref() +var_ref = Float.ref() +model.where( + Stock.covar(PairedStockVar, var_ref), + Stock.index == PairedStockVar.index, +).define(Stock.variance(var_ref)) + +# Derived per-stock volatility (sqrt of variance). Used downstream to derive +# correlation and the crisis regime covariance -- no numpy, no precompute. +model.define(Stock.volatility(sqrt(Stock.variance))) + +# Derived pairwise correlation: corr(i, j) = covar(i, j) / (vol_i * vol_j). +# Stored as a two-argument property on Stock (keyed by the paired Stock). +PairedStockCorr = Stock.ref() +cov_ij_ref = Float.ref() +model.where( + Stock.covar(PairedStockCorr, cov_ij_ref), +).define( + Stock.correlation( + PairedStockCorr, + cov_ij_ref / (Stock.volatility * PairedStockCorr.volatility), + ) +) + +# Build the undirected correlation graph. Nodes are Stocks; edges link stocks +# with |correlation| >= CORR_THRESHOLD. Correlations are filtered in PyRel +# against the derived Stock.correlation property. +corr_graph = Graph( + model, + name="corr_graph", + directed=False, + weighted=False, + node_concept=Stock, + aggregator="sum", +) + +stock_i_ref = Stock.ref() +stock_j_ref = Stock.ref() +corr_ref = Float.ref() +model.define(corr_graph.Edge.new(src=stock_i_ref, dst=stock_j_ref)).where( + stock_i_ref.correlation(stock_j_ref, corr_ref), + stock_i_ref.index < stock_j_ref.index, + math_abs(corr_ref) >= CORR_THRESHOLD, +) + +# Louvain community detection -- stored as Stock.cluster (integer id). +community = corr_graph.louvain() +cluster_label = Integer.ref("cluster_label") +stock_clust_ref = Stock.ref() +model.define(stock_clust_ref.cluster(cluster_label)).where( + community(stock_clust_ref, cluster_label) +) + +# Representative selection: for each cluster, the single stock with the +# highest Sharpe (return / volatility) is the cluster representative. If +# several stocks co-move strongly they carry near-identical exposure -- +# prefer the best risk-adjusted one and drop the rest from the investable +# universe. This collapses redundant bets instead of merely capping them. +model.define(Stock.sharpe(Stock.returns / Stock.volatility)) + +# Per-cluster maximum Sharpe, written back onto each Stock. +peer_for_max = Stock.ref() +model.define( + Stock.cluster_max_sharpe( + aggs.max(peer_for_max.sharpe) + .where(peer_for_max.cluster == Stock.cluster) + .per(Stock) + ) +) + +# Representative Relationship: stock whose Sharpe equals its cluster's max. +model.where(Stock.sharpe == Stock.cluster_max_sharpe).define(Stock.is_representative()) + +# Complementary Relationship used positively in solver constraints +# (the prescriptive rewriter doesn't accept `model.not_(...)` in a .where()). +model.where(Stock.sharpe < Stock.cluster_max_sharpe).define( + Stock.is_non_representative() +) + + +# -------------------------------------------------- +# Summaries of the clustering +# -------------------------------------------------- + +# The correlation graph's edge count, as the graph counts it. +edge_count = Integer.ref() +num_edges = model.Relationship(f"the correlation graph has {Integer:num_edges} edges") +model.where(corr_graph.num_edges()(edge_count)).define(num_edges(edge_count)) + +# Each Louvain cluster and the number of stocks in it. +Cluster = model.Concept("Cluster", identify_by={"cluster_id": Integer}) +Cluster.size = model.Property(f"{Cluster} has {Integer:size}") +model.define(Cluster.new(cluster_id=Stock.cluster)) +model.define( + Cluster.size(aggs.count(Stock).per(Cluster).where(Stock.cluster == Cluster.cluster_id)) +) + +num_clusters = model.Relationship(f"the stocks form {Integer:num_clusters} clusters") +num_stocks = model.Relationship(f"there are {Integer:num_stocks} stocks") +num_representatives = model.Relationship( + f"{Integer:num_representatives} stocks represent their clusters" +) +model.define(num_clusters(aggs.count(Cluster) | 0)) +model.define(num_stocks(aggs.count(Stock) | 0)) +model.define(num_representatives(aggs.count(Stock).where(Stock.is_representative()) | 0)) + +# Average correlation over the stock pairs (i < j) that share a cluster and over the pairs in +# different clusters; 0.0 when there is no such pair. +intra_cluster_correlation = model.Relationship( + f"stocks in the same cluster have average correlation {Float:intra_cluster_correlation}" +) +inter_cluster_correlation = model.Relationship( + f"stocks in different clusters have average correlation {Float:inter_cluster_correlation}" +) +model.define( + intra_cluster_correlation( + aggs.avg(stock_i_ref, stock_j_ref, corr_ref).where( + stock_i_ref.correlation(stock_j_ref, corr_ref), + stock_i_ref.index < stock_j_ref.index, + stock_i_ref.cluster == stock_j_ref.cluster, + ) + | 0.0 + ) +) +model.define( + inter_cluster_correlation( + aggs.avg(stock_i_ref, stock_j_ref, corr_ref).where( + stock_i_ref.correlation(stock_j_ref, corr_ref), + stock_i_ref.index < stock_j_ref.index, + stock_i_ref.cluster != stock_j_ref.cluster, + ) + | 0.0 + ) +) diff --git a/portfolio_balancing/model/reasoning.py b/portfolio_balancing/model/efficient_frontier.py similarity index 75% rename from portfolio_balancing/model/reasoning.py rename to portfolio_balancing/model/efficient_frontier.py index c4538d70..e4a6d7d2 100644 --- a/portfolio_balancing/model/reasoning.py +++ b/portfolio_balancing/model/efficient_frontier.py @@ -1,27 +1,18 @@ -"""Portfolio compliance rules, correlation graph, and the efficient frontier's decision problems for the portfolio template.""" +"""Efficient frontier: the bi-objective portfolio problems of every scenario (the two anchors, the +minimum-variance solve at the maximum return, and the grid, adaptive, and dichotomic drivers), and the +frontier points each solve publishes with the stock amounts and weights they allocate.""" import warnings from relationalai.semantics import Float, Integer, String, sum -from relationalai.semantics.reasoners.graph import Graph from relationalai.semantics.reasoners.prescriptive import Problem from relationalai.semantics.std import aggregates as aggs -from relationalai.semantics.std.math import abs as math_abs -from relationalai.semantics.std.math import clip, maximum, minimum, sqrt - -from .schema import ( - Account, - FrontierPoint, - Holding, - Regime, - Scenario, - Sector, - Stock, - Transaction, - User, - model, -) -from .source import SCENARIOS +from relationalai.semantics.std.math import clip, maximum, minimum + +# These derive Stock.is_non_representative and Stock.regime_covar, which the constraints and the objective read. +from . import correlation_clusters, regime_covariance # noqa: F401 +from .compliance_flags import SECTOR_LIMIT +from .schema import FrontierPoint, Scenario, Stock, model # The frontier below creates rules in Python loops (one chained solve per return target), # which trips PyRel's "rules created in a loop" perf heuristic. The pattern is deliberate and @@ -32,188 +23,10 @@ # Configure inputs # -------------------------------------------------- -POSITION_LIMIT = 0.15 # max fraction per stock in Stage 1 compliance rules REP_POSITION_LIMIT = 0.30 # max fraction per representative in Stage 3 optimization # (reps carry combined cluster exposure, so cap is higher; # feasibility needs REP_POSITION_LIMIT * num_reps >= 1.0 -- # floor is 1/5 = 0.20, so 0.30 leaves headroom) -SECTOR_LIMIT = 0.30 # max fraction of budget per sector (both stages) -CORR_THRESHOLD = 0.3 # |correlation| >= threshold to create a graph edge (Stage 2) -CRISIS_ALPHA = 0.7 # shrinkage weight for base correlation in crisis regime (Stage 4) - -# -------------------------------------------------- -# Stage 1: Rules -- compliance flags -# -------------------------------------------------- - -# Derived holding value = quantity * purchase_price. -model.define(Holding.value(Holding.quantity * Holding.purchase_price)) - -# Rule 1: Overconcentrated holdings -- position value > POSITION_LIMIT of balance. -AccountR1 = Account.ref() -model.where( - Holding.account(AccountR1), - Holding.value > POSITION_LIMIT * AccountR1.balance, -).define(Holding.is_overconcentrated()) - -# Rule 2: Sector concentration -- total sector exposure > SECTOR_LIMIT of balance. -HoldingSC = Holding.ref() -StockSC = Stock.ref() -AccountSC = Account.ref() -SectorSC = Sector.ref() - -sector_exposure = ( - sum(HoldingSC.value) - .where( - HoldingSC.account(AccountSC), - HoldingSC.stock(StockSC), - StockSC.sector_ref(SectorSC), - ) - .per(AccountSC, SectorSC) -) - -StockR2 = Stock.ref() -model.where( - Holding.account(AccountSC), - Holding.stock(StockR2), - StockR2.sector_ref(SectorSC), - sector_exposure > SECTOR_LIMIT * AccountSC.balance, -).define(Holding.is_sector_concentrated()) - -# Rule 3: High-risk traders -- risk_score > 0.8 AND >5 flagged transactions. -TransactionHR = Transaction.ref() -flagged_count = ( - sum(TransactionHR.is_flagged_val) - .where( - TransactionHR.user(User), - ) - .per(User) -) - -model.where( - User.risk_score > 0.8, - flagged_count > 5, -).define(User.is_high_risk_trader()) - -# -------------------------------------------------- -# Stage 2: Graph -- covariance clustering -# -------------------------------------------------- - -# Derived per-stock variance (covar diagonal, i == j). -PairedStockVar = Stock.ref() -var_ref = Float.ref() -model.where( - Stock.covar(PairedStockVar, var_ref), - Stock.index == PairedStockVar.index, -).define(Stock.variance(var_ref)) - -# Derived per-stock volatility (sqrt of variance). Used downstream to derive -# correlation and the crisis regime covariance -- no numpy, no precompute. -model.define(Stock.volatility(sqrt(Stock.variance))) - -# Derived pairwise correlation: corr(i, j) = covar(i, j) / (vol_i * vol_j). -# Stored as a two-argument property on Stock (keyed by the paired Stock). -PairedStockCorr = Stock.ref() -cov_ij_ref = Float.ref() -model.where( - Stock.covar(PairedStockCorr, cov_ij_ref), -).define( - Stock.correlation( - PairedStockCorr, - cov_ij_ref / (Stock.volatility * PairedStockCorr.volatility), - ) -) - -# Build the undirected correlation graph. Nodes are Stocks; edges link stocks -# with |correlation| >= CORR_THRESHOLD. Correlations are filtered in PyRel -# against the derived Stock.correlation property. -corr_graph = Graph( - model, - name="corr_graph", - directed=False, - weighted=False, - node_concept=Stock, - aggregator="sum", -) - -stock_i_ref = Stock.ref() -stock_j_ref = Stock.ref() -corr_ref = Float.ref() -model.define(corr_graph.Edge.new(src=stock_i_ref, dst=stock_j_ref)).where( - stock_i_ref.correlation(stock_j_ref, corr_ref), - stock_i_ref.index < stock_j_ref.index, - math_abs(corr_ref) >= CORR_THRESHOLD, -) - -# Louvain community detection -- stored as Stock.cluster (integer id). -community = corr_graph.louvain() -cluster_label = Integer.ref("cluster_label") -stock_clust_ref = Stock.ref() -model.define(stock_clust_ref.cluster(cluster_label)).where( - community(stock_clust_ref, cluster_label) -) - -# Representative selection: for each cluster, the single stock with the -# highest Sharpe (return / volatility) is the cluster representative. If -# several stocks co-move strongly they carry near-identical exposure -- -# prefer the best risk-adjusted one and drop the rest from the investable -# universe. This collapses redundant bets instead of merely capping them. -model.define(Stock.sharpe(Stock.returns / Stock.volatility)) - -# Per-cluster maximum Sharpe, written back onto each Stock. -peer_for_max = Stock.ref() -model.define( - Stock.cluster_max_sharpe( - aggs.max(peer_for_max.sharpe) - .where(peer_for_max.cluster == Stock.cluster) - .per(Stock) - ) -) - -# Representative Relationship: stock whose Sharpe equals its cluster's max. -model.where(Stock.sharpe == Stock.cluster_max_sharpe).define(Stock.is_representative()) - -# Complementary Relationship used positively in solver constraints -# (the prescriptive rewriter doesn't accept `model.not_(...)` in a .where()). -model.where(Stock.sharpe < Stock.cluster_max_sharpe).define( - Stock.is_non_representative() -) - -# -------------------------------------------------- -# Stage 3: regime covariance -# -------------------------------------------------- - -# Regime-conditioned covariance is derived in PyRel from the base covariance -# and the derived volatilities: -# base: Sigma(i, j) -# crisis: alpha * Sigma(i, j) + (1 - alpha) * vol_i * vol_j -# The crisis formula is equivalent to correlation shrinkage toward all-ones -# (rho_crisis = alpha * rho + (1 - alpha) * J) re-expressed in covariance -# units. PSD is preserved because the construction is a convex combination of -# PSD matrices. -# Base regime: covariance unchanged. -PairedStockBase = Stock.ref() -base_cov_ref = Float.ref() -base_regime_ref = Regime.ref() -model.where( - Stock.covar(PairedStockBase, base_cov_ref), - base_regime_ref.regime_name == "base", -).define(Stock.regime_covar(PairedStockBase, base_regime_ref, base_cov_ref)) - -# Crisis regime: convex combination of base covariance and vol_i * vol_j. -PairedStockCrisis = Stock.ref() -crisis_cov_ref = Float.ref() -crisis_regime_ref = Regime.ref() -model.where( - Stock.covar(PairedStockCrisis, crisis_cov_ref), - crisis_regime_ref.regime_name == "crisis", -).define( - Stock.regime_covar( - PairedStockCrisis, - crisis_regime_ref, - CRISIS_ALPHA * crisis_cov_ref - + (1 - CRISIS_ALPHA) * Stock.volatility * PairedStockCrisis.volatility, - ) -) # -------------------------------------------------- # Stage 3: Prescriptive -- bi-objective QP with epsilon constraint @@ -239,9 +52,6 @@ N_SOLVES = 6 N_INTERIOR = N_SOLVES - 2 REFERENCE_SCENARIO = "base_1000" # mid-budget, base regime -REF_BUDGET = float( - next(budget for name, budget, _ in SCENARIOS if name == REFERENCE_SCENARIO) -) GRID_SOLVES = [f"grid_{k}" for k in range(1, N_INTERIOR + 1)] ADAPTIVE_SOLVES = [f"adaptive_{k}" for k in range(1, N_INTERIOR + 1)] @@ -510,6 +320,12 @@ def reference_point(name, result, sp=None): return point + +# The reference scenario's budget, which turns a return target into a return rate. +REF_BUDGET = scalar("ref_budget") +model.where(Scenario.name == REFERENCE_SCENARIO).define(REF_BUDGET(Scenario.budget)) +_ref_budget = Float.ref() + # -------------------------------------------------- # Anchors # -------------------------------------------------- @@ -528,7 +344,7 @@ def reference_point(name, result, sp=None): # The minimum-variance solve at the maximum return, shared by all three drivers. hi_rate = scalar("hi_rate") _ret_hi = Float.ref() -model.where(RETURN_HI(_ret_hi)).define(hi_rate(_ret_hi / REF_BUDGET)) +model.where(RETURN_HI(_ret_hi), REF_BUDGET(_ref_budget)).define(hi_rate(_ret_hi / _ref_budget)) hi = frontier_problem("hi", floor=floor_from_rate("hi", hi_rate)) HI = reference_point("hi", hi) @@ -543,8 +359,8 @@ def reference_point(name, result, sp=None): ) for k, label in enumerate(GRID_SOLVES, start=1): rate = scalar(f"{label}_rate") - model.where(LO["ret"](_ret_lo), grid_step(_span)).define( - rate((_ret_lo + k * _span) / REF_BUDGET) + model.where(LO["ret"](_ret_lo), grid_step(_span), REF_BUDGET(_ref_budget)).define( + rate((_ret_lo + k * _span) / _ref_budget) ) frontier_problem(label, floor=floor_from_rate(label, rate)) @@ -642,8 +458,8 @@ def set_interval(interval, ctr, a, b, *where): } rate = scalar(f"{label}_rate") c = Integer.ref() - model.where(popped(c), current.ctr == c).define( - rate(current.estar / REF_BUDGET), + model.where(popped(c), current.ctr == c, REF_BUDGET(_ref_budget)).define( + rate(current.estar / _ref_budget), *[popped_end[n](getattr(current, n)) for n in popped_end], ) result = frontier_problem(label, floor=floor_from_rate(label, rate)) @@ -703,7 +519,20 @@ def set_interval(interval, ctr, a, b, *where): max_step(mx), RETURN_HI(h), ).define(target(minimum(pe + clip(t / maximum(pl, 1e-9), mn, mx), h))) - model.where(target(pe)).define(rate(pe / REF_BUDGET)) + model.where(target(pe), REF_BUDGET(_ref_budget)).define(rate(pe / _ref_budget)) result = frontier_problem(label, floor=floor_from_rate(label, rate)) if k < N_INTERIOR: previous_target, previous_lam = target, reference_point(label, result)["sp"] + +# -------------------------------------------------- +# Allocation weights +# -------------------------------------------------- + +# Each allocated stock's share of its scenario's budget. +FrontierPoint.weight = model.Relationship( + f"{FrontierPoint} holds {Stock} at weight {Float:fp_weight}" +) +_allocated = Float.ref() +model.where(FrontierPoint.allocates(Stock, _allocated)).define( + FrontierPoint.weight(Stock, _allocated / FrontierPoint.scenario.budget) +) diff --git a/portfolio_balancing/model/regime_covariance.py b/portfolio_balancing/model/regime_covariance.py new file mode 100644 index 00000000..aa3af402 --- /dev/null +++ b/portfolio_balancing/model/regime_covariance.py @@ -0,0 +1,52 @@ +"""Regime covariance: the covariance of each stock pair under the base regime (the observed covariance) and +under the crisis regime (the observed covariance shrunk toward the product of the stocks' volatilities).""" + +from relationalai.semantics import Float + +# Derives Stock.volatility, which the crisis covariance reads. +from . import correlation_clusters # noqa: F401 +from .schema import Regime, Stock, model + +# -------------------------------------------------- +# Configure inputs +# -------------------------------------------------- + +CRISIS_ALPHA = 0.7 # shrinkage weight for base correlation in crisis regime (Stage 4) + +# -------------------------------------------------- +# Stage 3: regime covariance +# -------------------------------------------------- + +# Regime-conditioned covariance is derived in PyRel from the base covariance +# and the derived volatilities: +# base: Sigma(i, j) +# crisis: alpha * Sigma(i, j) + (1 - alpha) * vol_i * vol_j +# The crisis formula is equivalent to correlation shrinkage toward all-ones +# (rho_crisis = alpha * rho + (1 - alpha) * J) re-expressed in covariance +# units. PSD is preserved because the construction is a convex combination of +# PSD matrices. +# Base regime: covariance unchanged. +PairedStockBase = Stock.ref() +base_cov_ref = Float.ref() +base_regime_ref = Regime.ref() +model.where( + Stock.covar(PairedStockBase, base_cov_ref), + base_regime_ref.regime_name == "base", +).define(Stock.regime_covar(PairedStockBase, base_regime_ref, base_cov_ref)) + +# Crisis regime: convex combination of base covariance and vol_i * vol_j. +PairedStockCrisis = Stock.ref() +crisis_cov_ref = Float.ref() +crisis_regime_ref = Regime.ref() +model.where( + Stock.covar(PairedStockCrisis, crisis_cov_ref), + crisis_regime_ref.regime_name == "crisis", +).define( + Stock.regime_covar( + PairedStockCrisis, + crisis_regime_ref, + CRISIS_ALPHA * crisis_cov_ref + + (1 - CRISIS_ALPHA) * Stock.volatility * PairedStockCrisis.volatility, + ) +) + diff --git a/portfolio_balancing/queries/portfolio_report.py b/portfolio_balancing/queries/portfolio_report.py index 4090641f..5518a095 100644 --- a/portfolio_balancing/queries/portfolio_report.py +++ b/portfolio_balancing/queries/portfolio_report.py @@ -21,19 +21,25 @@ REFERENCE_SCENARIO, SECTOR_LIMIT, Account, + Cluster, FrontierPoint, Holding, Regime, Scenario, - Sector, + SectorExposure, SolveStatus, Stock, User, + inter_cluster_correlation, + intra_cluster_correlation, model, + num_clusters, + num_edges, + num_representatives, + num_stocks, ) from pandas import DataFrame from relationalai.semantics import Float, String -from relationalai.semantics.std import aggregates as aggs @dataclass(frozen=True) @@ -81,6 +87,7 @@ def dedupe(points): """Sort by return; drop points that collapse onto a neighbour so the frontier is strictly increasing in return.""" out = [] + # Each point is compared with the last point kept, a sequential scan PyRel has no primitive for. for p in sorted(points, key=lambda q: q.ret): if not out or p.ret - out[-1].ret > 1e-6: out.append(p) @@ -106,6 +113,7 @@ def dedupe(points): AccountQ1.account_id.alias("account_id"), Holding.value.alias("value"), AccountQ1.balance.alias("balance"), + Holding.share_of_balance.alias("share_of_balance"), ) .where( Holding.is_overconcentrated(), @@ -127,30 +135,21 @@ def dedupe(points): f" holding_id={int(row['holding_id'])}, ticker={row['ticker']}, " f"account_id={int(row['account_id'])}, " f"value={row['value']:.2f}, balance={row['balance']:.2f}, " - f"pct={row['value'] / row['balance']:.1%}" + f"pct={row['share_of_balance']:.1%}" ) # ---- Rule 2: Sector Concentration ---- - StockQ2 = Stock.ref() - AccountQ2 = Account.ref() - SectorQ2 = Sector.ref() - HoldingQ2 = Holding.ref() - sector_df = ( model.select( - AccountQ2.account_id.alias("account_id"), - SectorQ2.sector_name.alias("sector"), - aggs.sum(HoldingQ2.value).per(AccountQ2, SectorQ2).alias("sector_value"), - AccountQ2.balance.alias("balance"), - ) - .where( - HoldingQ2.is_sector_concentrated(), - HoldingQ2.account(AccountQ2), - HoldingQ2.stock(StockQ2), - StockQ2.sector_ref(SectorQ2), + SectorExposure.account.account_id.alias("account_id"), + SectorExposure.sector.sector_name.alias("sector"), + SectorExposure.exposure.alias("sector_value"), + SectorExposure.account.balance.alias("balance"), + SectorExposure.share_of_balance.alias("share_of_balance"), ) + .where(SectorExposure.is_concentrated()) .to_df() - .drop_duplicates(subset=["account_id", "sector"]) + .sort_values(["account_id", "sector"]) ) print( @@ -165,7 +164,7 @@ def dedupe(points): f" account_id={int(row['account_id'])}, sector={row['sector']}, " f"sector_value={row['sector_value']:.2f}, " f"balance={row['balance']:.2f}, " - f"pct={row['sector_value'] / row['balance']:.1%}" + f"pct={row['share_of_balance']:.1%}" ) # ---- Rule 3: High-Risk Traders ---- @@ -206,48 +205,43 @@ def dedupe(points): StockQ3.sector.alias("sector"), StockQ3.cluster.alias("cluster_id"), ).to_df() - num_clusters = cluster_df["cluster_id"].nunique() - # Query the derived correlation property for stats and edge count. - StockCQ = Stock.ref() - PairedCQ = Stock.ref() - corr_q_ref = Float.ref() - corr_df = ( + # The graph's and the clustering's figures, as the model publishes them. + cluster_stats = ( model.select( - StockCQ.index.alias("i"), - PairedCQ.index.alias("j"), - corr_q_ref.alias("correlation"), + num_edges.alias("edges"), + num_clusters.alias("clusters"), + num_stocks.alias("stocks"), + num_representatives.alias("representatives"), + intra_cluster_correlation.alias("intra"), + inter_cluster_correlation.alias("inter"), ) - .where(StockCQ.correlation(PairedCQ, corr_q_ref)) .to_df() + .iloc[0] ) - corr_df["correlation"] = corr_df["correlation"].astype(float) - # Upper triangle only (i < j) -- correlation is symmetric. - upper_corr = corr_df[corr_df["i"] < corr_df["j"]].copy() - num_edges = int((upper_corr["correlation"].abs() >= CORR_THRESHOLD).sum()) + cluster_size_df = model.select( + Cluster.cluster_id.alias("cluster_id"), Cluster.size.alias("size") + ).to_df() + cluster_sizes = { + int(cid): int(size) + for cid, size in zip(cluster_size_df["cluster_id"], cluster_size_df["size"]) + } print( - f"\n Correlation graph: {num_edges} edges (|correlation| >= {CORR_THRESHOLD})" + f"\n Correlation graph: {int(cluster_stats['edges'])} edges " + f"(|correlation| >= {CORR_THRESHOLD})" ) - print(f" Louvain communities: {num_clusters} cluster(s)") + print(f" Louvain communities: {int(cluster_stats['clusters'])} cluster(s)") for cid, group in cluster_df.sort_values("cluster_id").groupby("cluster_id"): members = ", ".join( f"{row['ticker']} ({row['sector']})" for _, row in group.iterrows() ) - print(f" Cluster {cid} (size {len(group)}): {members}") + print(f" Cluster {cid} (size {cluster_sizes[int(cid)]}): {members}") # Intra- vs inter-cluster average correlation (from the derived property). - cluster_map = dict(zip(cluster_df["stock_index"], cluster_df["cluster_id"])) - is_intra = upper_corr.apply( - lambda r: cluster_map.get(int(r["i"])) == cluster_map.get(int(r["j"])), axis=1 - ) - intra_series = upper_corr.loc[is_intra, "correlation"] - inter_series = upper_corr.loc[~is_intra, "correlation"] - intra_avg = float(intra_series.mean()) if len(intra_series) else 0.0 - inter_avg = float(inter_series.mean()) if len(inter_series) else 0.0 print( - f"\n Avg correlation: intra-cluster = {intra_avg:+.3f}, " - f"inter-cluster = {inter_avg:+.3f}" + f"\n Avg correlation: intra-cluster = {float(cluster_stats['intra']):+.3f}, " + f"inter-cluster = {float(cluster_stats['inter']):+.3f}" ) # Cluster representatives -- the investable universe after redundancy removal. @@ -264,7 +258,8 @@ def dedupe(points): .sort_values("cluster_id") ) print( - f"\n Cluster representatives ({len(rep_df)} of {len(cluster_df)} stocks, " + f"\n Cluster representatives ({int(cluster_stats['representatives'])} of " + f"{int(cluster_stats['stocks'])} stocks, " f"picked by highest Sharpe):" ) for _, row in rep_df.iterrows(): @@ -364,8 +359,10 @@ def dedupe(points): solves = solves.fillna({"marginal": 0.0}) - # Stock amounts of every solve, above the solver's 1e-6 noise floor. + # Stock amounts of every solve, above the solver's 1e-6 noise floor, and each amount's + # share of the scenario's budget. amount_ref = Float.ref() + weight_ref = Float.ref() allocation_df = ( model.select( FrontierPoint.scenario_label.alias("scenario"), @@ -373,8 +370,12 @@ def dedupe(points): Stock.index.alias("stock_index"), Stock.ticker.alias("ticker"), amount_ref.alias("amount"), + weight_ref.alias("weight"), + ) + .where( + FrontierPoint.allocates(Stock, amount_ref), + FrontierPoint.weight(Stock, weight_ref), ) - .where(FrontierPoint.allocates(Stock, amount_ref)) .to_df() ) @@ -409,7 +410,7 @@ def point(solve): ret, risk, marginal = solves.loc[ (solve, REFERENCE_SCENARIO), ["ret", "risk", "marginal"] ] - return Point(solve, float(ret), float(risk), max(0.0, float(marginal))) + return Point(solve, float(ret), float(risk), float(marginal)) RETURN_LO = float(solves.loc[("min_risk", REFERENCE_SCENARIO), "ret"]) RETURN_HI = float(solves.loc[("max_return", REFERENCE_SCENARIO), "ret"]) @@ -645,7 +646,9 @@ def point(solve): raise SystemExit( f"The knee solve {knee_row['solve']} returned no allocation for {sn}." ) - allocations = zip(knee_allocation["ticker"], knee_allocation["amount"]) + allocations = zip( + knee_allocation["ticker"], knee_allocation["amount"], knee_allocation["weight"] + ) meta = scenario_meta[sn] budget = meta["budget"] @@ -663,10 +666,8 @@ def point(solve): allocations, key=lambda item: (-item[1], item[0]), ) - for ticker, quantity in ordered_allocations: - print( - f" {ticker:<8}{float(quantity):>12.2f}{float(quantity) / budget:>9.1%}" - ) + for ticker, quantity, weight in ordered_allocations: + print(f" {ticker:<8}{float(quantity):>12.2f}{float(weight):>9.1%}") print( "\n Each knee is a candidate portfolio, not a recommendation. " diff --git a/portfolio_balancing/runbook.md b/portfolio_balancing/runbook.md index 8b812ac0..7471cfb1 100644 --- a/portfolio_balancing/runbook.md +++ b/portfolio_balancing/runbook.md @@ -42,9 +42,13 @@ without the cluster collapse, the gap would grow. ## Implementation map -- `model/schema.py` creates the shared model and declares all nine concepts, their properties, and their relationships. +- `model/schema.py` creates the shared model and declares the nine concepts that the data and the solves populate, with their properties and relationships. The rule modules declare what they derive from them, such as `SectorExposure` and `Cluster`. - `model/source.py` loads the bundled CSVs, creates the six budget-by-regime scenarios, and maps source fields onto that schema. -- `model/reasoning.py` defines the derived facts, the correlation graph, and the 15 solves of the frontier. Each solve is a named Problem, and each later solve's return target is a rule over earlier solves' results. Every solve publishes a `FrontierPoint` per scenario. `model/__init__.py` exports the deployed model for the query. +- `model/compliance_flags.py` states the Stage 1 rules: each holding's value and share of its account balance, the overconcentrated holdings, each account's `SectorExposure` and the concentrated ones, and the high-risk traders. +- `model/correlation_clusters.py` derives volatility and correlation, builds the correlation graph and its Louvain clusters, picks each cluster's representative, and summarizes the clustering (edge and cluster counts, `Cluster` sizes, intra- and inter-cluster average correlation). +- `model/regime_covariance.py` derives the base and crisis covariance. +- `model/efficient_frontier.py` defines the 15 solves of the frontier. Each solve is a named Problem, and each later solve's return target is a rule over earlier solves' results. Every solve publishes a `FrontierPoint` per scenario, with the weight of each allocated stock. +- `model/__init__.py` exports the deployed model for the query. - `queries/portfolio_report.py` reads the deployed model, prints the four stages, creates the frontier summaries (knee and volatility comparison), and reports the stock amounts and weights for each scenario's candidate portfolio. ## Workflow @@ -61,7 +65,7 @@ without the cluster collapse, the gap would grow. **Response** -`model/schema.py` declares `Stock` (with the binary `Stock.covar(Stock, Stock)` property carrying covariance), `Sector`, `User`, `Account`, `Holding`, `Transaction`, `Regime`, `Scenario`, and `FrontierPoint`. `model/source.py` binds the portfolio concepts to the bundled CSVs (8 stocks, 64 covariance entries). `model/source.py` creates 2 regimes x 3 budgets = 6 scenarios, and each solve in `model/reasoning.py` publishes its frontier points. +`model/schema.py` declares `Stock` (with the binary `Stock.covar(Stock, Stock)` property carrying covariance), `Sector`, `User`, `Account`, `Holding`, `Transaction`, `Regime`, `Scenario`, and `FrontierPoint`. `model/source.py` binds the portfolio concepts to the bundled CSVs (8 stocks, 64 covariance entries). `model/source.py` creates 2 regimes x 3 budgets = 6 scenarios, and each solve in `model/efficient_frontier.py` publishes its frontier points. ### 2. Examine ontology @@ -157,7 +161,7 @@ Crisis vol runs 22-30% above base at every frontier point (budget 1000: min_risk **Response** -Ontology gains a `FrontierPoint(scenario_label, solve)` Concept (6 scenarios x 15 solves) with `return_value`, `risk`, `marginal_risk_per_return`, and `allocates`, which each solve that reaches an accepted status publishes in `model/reasoning.py`. The points and allocations are queryable from the deployed model. The report selects the dichotomic solves' points, sorts them by return (adjacent targets that collapse are deduped), checks that neither return nor risk decreases along each scenario's frontier, and derives the knee flag and the volatilities from them: the frontier shape (base_1000 return 64.87->84.00, variance 4641->8528), knee at p3, and the crisis vol gap (+28.4% min_risk -> +29.6% peak at p1 -> +21.7% at p5). +Ontology gains a `FrontierPoint(scenario_label, solve)` Concept (6 scenarios x 15 solves) with `return_value`, `risk`, `marginal_risk_per_return`, and `allocates`, which each solve that reaches an accepted status publishes in `model/efficient_frontier.py`. The points and allocations are queryable from the deployed model. The report selects the dichotomic solves' points, sorts them by return (adjacent targets that collapse are deduped), checks that neither return nor risk decreases along each scenario's frontier, and derives the knee flag and the volatilities from them: the frontier shape (base_1000 return 64.87->84.00, variance 4641->8528), knee at p3, and the crisis vol gap (+28.4% min_risk -> +29.6% peak at p1 -> +21.7% at p5). ### 10. Review candidate allocations @@ -173,4 +177,4 @@ The report finds the knee of each of the six scenarios' frontiers and prints the ## Data -Bundled CSVs in `data/`: `users.csv` (6), `accounts.csv` (4), `holdings.csv` (15), `transactions.csv` (21), `returns.csv` (8 stocks across 5 sectors), and `covar.csv` (64 symmetric covariance entries). `model/source.py` loads these files; `model/reasoning.py` states the rules, the graph, and the solves; `queries/portfolio_report.py` prints the report. +Bundled CSVs in `data/`: `users.csv` (6), `accounts.csv` (4), `holdings.csv` (15), `transactions.csv` (21), `returns.csv` (8 stocks across 5 sectors), and `covar.csv` (64 symmetric covariance entries). `model/source.py` loads these files; the other modules in `model/` state the rules, the graph, and the solves; `queries/portfolio_report.py` prints the report. diff --git a/portfolio_balancing/template-docs.yaml b/portfolio_balancing/template-docs.yaml index 0ce23a27..5dbd4679 100644 --- a/portfolio_balancing/template-docs.yaml +++ b/portfolio_balancing/template-docs.yaml @@ -257,11 +257,13 @@ guided_walkthrough: title: "Stage 1: Check the current portfolio" explanation: |- Stage 1 checks the current portfolio for three problems. This example - calculates each holding's value, finds its account, and flags the - holding when its value is more than 15% of the account balance. + calculates each holding's value and its share of the account balance, + finds its account, and flags the holding when its value is more than + 15% of the account balance. - Stage 1 also flags an account when one sector makes up more than 30% of - its balance. It flags a user when the user's risk score is above 0.8 + Stage 1 also totals each account's exposure to each sector and flags the + account and sector pair when the exposure is more than 30% of the + account balance. It flags a user when the user's risk score is above 0.8 and the user has more than five flagged transactions. In the sample data, these checks flag four holdings, two account and sector combinations, and two users. @@ -269,7 +271,7 @@ guided_walkthrough: These flags give investment managers a short list of holdings, sector exposures, and users that may need review. focus: - file: model/reasoning.py + file: model/compliance_flags.py anchors: - start: '# Derived holding value = quantity * purchase_price.' end: ).define(Holding.is_overconcentrated()) @@ -294,7 +296,7 @@ guided_walkthrough: Using one representative from each cluster reduces the chance that a new portfolio will include several stocks that behave alike. focus: - file: model/reasoning.py + file: model/correlation_clusters.py anchors: - start: stock_i_ref = Stock.ref() end: community(stock_clust_ref, cluster_label) @@ -349,7 +351,7 @@ guided_walkthrough: earlier Problems. One refresh of the deployed model therefore runs all of them in order. focus: - file: model/reasoning.py + file: model/efficient_frontier.py anchors: - start: problem.minimize( end: PairedStock.x_quantity(Scenario, x_qty_paired), @@ -379,10 +381,11 @@ guided_walkthrough: of its return floor. It records how much more variance is needed when the required return increases by one unit. - For every scenario, the report orders those points by return and labels - them min_risk, p1, p2, and so on. It marks the knee, the point before - variance begins to increase much faster, and adds vol_base and - vol_crisis, the volatility of the matching base and crisis results. + For every scenario, the report orders those points by the reference + scenario's return and labels them min_risk, p1, p2, and so on. It marks + the knee, the point before variance begins to increase much faster, and + adds vol_base and vol_crisis, the volatility of the matching base and + crisis results. These summaries let the final step compare the calculated portfolios and identify the knee of each scenario. The next step shows its stock @@ -437,10 +440,10 @@ guided_walkthrough: rise much faster for each additional unit of required return. It is a candidate to review, not a recommendation. - The final loop uses allocation_df to retrieve the stock amounts that - the knee point's solve published for each of the six scenarios. Amount - shows how much of the scenario's budget is assigned to a stock. Weight - shows the stock's share of the budget. The output excerpt shows the + The final loop uses allocation_df to retrieve the stock amounts and + weights that the knee point's solve published for each of the six + scenarios. Amount shows how much of the scenario's budget is assigned to + a stock. Weight shows the stock's share of the budget. The output excerpt shows the base portfolio for a budget of 1,000. To turn it into a rebalancing plan, link the scenario to an account and compare these target amounts with its current holdings. @@ -458,10 +461,10 @@ guided_walkthrough: file: queries/portfolio_report.py anchors: - start: knee_rows = frontier_df[ - end: allocations = zip(knee_allocation["ticker"], knee_allocation["amount"]) - - start: ordered_allocations = sorted( - end: '{float(quantity) / budget:>9.1%}' + end: 'knee_allocation["ticker"], knee_allocation["amount"], knee_allocation["weight"]' end_offset: 1 + - start: ordered_allocations = sorted( + end: '{float(weight):>9.1%}' references: frontier_df: anchor: @@ -483,8 +486,8 @@ guided_walkthrough: end: '{float(quantity):>12.2f}' Weight: anchor: - start: '{float(quantity) / budget:>9.1%}' - end: '{float(quantity) / budget:>9.1%}' + start: '{float(weight):>9.1%}' + end: '{float(weight):>9.1%}' links: - title: Work with solutions href: /build/guides/reasoning/prescriptive/decision-problems/solutions/ diff --git a/product_configurator/README.md b/product_configurator/README.md index 0fff9a6a..c792cd59 100644 --- a/product_configurator/README.md +++ b/product_configurator/README.md @@ -41,7 +41,7 @@ The configurator scenario here is automotive trim, drawn from the public Renault ## What's included -- `model/` -- ontology, decisions, constraints, and solver configuration, as a package (`schema.py` declares the concepts, `source.py` loads the sample data, `reasoning.py` states the decision problem); `rai models deploy --path model` deploys it +- `model/` -- ontology, decisions, constraints, and solver configuration, as a package (`schema.py` declares the concepts, `source.py` loads the sample data, `build_enumeration.py` states the decision problem, solves it, and prices each build); `rai models deploy --path model` deploys it - `queries/feasible_builds.py` -- prints the report from the deployed model - **Runbook**: `runbook.md` -- a paste-testable walkthrough that reproduces the template step by step with the RAI skills; as important a reference as the script itself. - `data/slots.csv` -- 6 slots (Engine, Transmission, Trim, Sound, Wheels, Roof) @@ -198,7 +198,7 @@ product_configurator/ __init__.py # exports of the deployed model schema.py # Slot, Option, Implies, and Excludes concepts source.py # loads the sample CSVs and checks the catalog for the target region - reasoning.py # decisions, constraints, solver configuration + build_enumeration.py # decisions, constraints, solver configuration, and each build's total price queries/ feasible_builds.py # report from the deployed model data/ @@ -255,9 +255,9 @@ slots + options + implies + excludes + regional rules → region-filtered select - **Excludes** — for each region-allowed pair, `selected[left] + selected[right] <= 1`: at most one of the pair. - **Price ceiling** — the price-weighted sum of selected options stays within `PRICE_CEILING_CENTS`. -**4. Solve in multi-solution mode, deploy, and pivot.** Passing `solution_limit=MAX_CONFIGURATIONS` to `problem.configure(...)` makes each refresh of the deployed model run the search in enumeration mode, returning up to that many distinct feasible builds; the report prints the solve status and the number of builds. The variable handle exposes a `.values(solution_index, value)` relationship over the per-solution outputs; a rule of the model binds the value slot to `1` and publishes just the picked options as the `SelectedOption` relationship, which the report selects, and a `pandas.pivot` collapses the per-option rows into one row per build (one column per slot, plus a dollar total, sorted ascending by price) for buyer-facing display. +**4. Solve in multi-solution mode, deploy, and pivot.** Passing `solution_limit=MAX_CONFIGURATIONS` to `problem.configure(...)` makes each refresh of the deployed model run the search in enumeration mode, returning up to that many distinct feasible builds; the report prints the solve status and the number of builds. The variable handle exposes a `.values(solution_index, value)` relationship over the per-solution outputs; a rule of the model binds the value slot to `1` and publishes just the picked options as the `SelectedOption` relationship and each build's total price in cents as `BuildTotal`, a sum over the build's picked options. The report selects both, and a `pandas.pivot` collapses the per-option rows into one row per build (one column per slot, plus a dollar total, sorted ascending by price) for buyer-facing display. -For the exact PyRel formulation, see `model/reasoning.py`; `runbook.md` reproduces the model step by step with the RAI skills. +For the exact PyRel formulation, see `model/build_enumeration.py`; `runbook.md` reproduces the model step by step with the RAI skills. ## Customize this template diff --git a/product_configurator/model/__init__.py b/product_configurator/model/__init__.py index 54320f6f..fcc58eba 100644 --- a/product_configurator/model/__init__.py +++ b/product_configurator/model/__init__.py @@ -8,15 +8,21 @@ -- a configurator UI rarely wants a single build; a buyer's quote, a sales playbook, and a trade-off slider all need the population of configurations. +Modules: + `schema.py` declares the concepts, `source.py` loads the catalog and checks it for the + target region, and `build_enumeration.py` states the decision problem, solves it, and + publishes the builds and the price of each. + Run: `rai models deploy --path model` deploys this package to the schemas in raiconfig.yaml and waits for its first refresh, which runs the solve. `python -m queries.feasible_builds` then prints the report from the deployed model. """ -from .reasoning import ( +from .build_enumeration import ( MAX_CONFIGURATIONS, PRICE_CEILING_CENTS, + BuildTotal, NumPoints, SelectedOption, SolveSettings, @@ -31,6 +37,7 @@ "MAX_CONFIGURATIONS", "PRICE_CEILING_CENTS", "TARGET_REGION", + "BuildTotal", "Excludes", "Implies", "NumPoints", diff --git a/product_configurator/model/reasoning.py b/product_configurator/model/build_enumeration.py similarity index 86% rename from product_configurator/model/reasoning.py rename to product_configurator/model/build_enumeration.py index 6ac5750b..3083dd01 100644 --- a/product_configurator/model/reasoning.py +++ b/product_configurator/model/build_enumeration.py @@ -1,4 +1,4 @@ -"""Product configuration problem: every feasible build for the target region.""" +"""Build enumeration: every feasible build of the product for the target region, and the price of each.""" from relationalai.semantics import Integer, String, sum from relationalai.semantics.reasoners.prescriptive import Problem @@ -102,3 +102,19 @@ f"product configurator solution {Integer:solution} selects {Option:option}" ) model.where(selected_var.values(solution, 1)).define(SelectedOption(solution, selected_var.option)) + +# -------------------------------------------------- +# Price each build +# -------------------------------------------------- + +# The price of each build: the sum of its selected options' prices, in cents. +BuildTotal = model.Relationship( + f"product configurator solution {Integer:solution} costs {Integer:total_cents} cents" +) +_in_build, _priced = Option.ref(), Option.ref() +model.where(SelectedOption(solution, _in_build)).define( + BuildTotal( + solution, + sum(_priced, _priced.price_cents).per(solution).where(SelectedOption(solution, _priced)), + ) +) diff --git a/product_configurator/model/source.py b/product_configurator/model/source.py index a1f707ac..68cf2b9d 100644 --- a/product_configurator/model/source.py +++ b/product_configurator/model/source.py @@ -42,7 +42,7 @@ # Validate the regional catalog against TARGET_REGION # -------------------------------------------------- -# The ICs in `model/reasoning.py` are scoped via `model.where(Option.allowed_in(TARGET_REGION), ...)`, +# The ICs in `model/build_enumeration.py` are scoped via `model.where(Option.allowed_in(TARGET_REGION), ...)`, # which silently drops any IC whose options are not all region-allowed. The # checks below catch the two failure modes that scoping hides; see the README # troubleshooting blocks for the recovery steps. diff --git a/product_configurator/queries/feasible_builds.py b/product_configurator/queries/feasible_builds.py index e1a2c284..f95b3fcf 100644 --- a/product_configurator/queries/feasible_builds.py +++ b/product_configurator/queries/feasible_builds.py @@ -6,6 +6,7 @@ """ from model import ( + BuildTotal, NumPoints, Option, SelectedOption, @@ -33,21 +34,28 @@ # Inspect every feasible configuration # ------------------------------------------ - # `SelectedOption` holds, per solution, the options the solver picked. Pivot to - # one row per build, one column per slot, sorted ascending by the exact total in cents. + # `SelectedOption` holds, per solution, the options the solver picked, and `BuildTotal` + # the exact total price of each solution in cents. Pivot to one row per build, one + # column per slot, sorted ascending by total price. sol_idx = Integer.ref() + total = Integer.ref() selections_df = ( model.select( sol_idx.alias("solution"), Option.slot.name.alias("slot"), Option.name.alias("option"), - Option.price_cents.alias("price_cents"), ) .where(SelectedOption(sol_idx, Option)) .to_df() ) + total_cents = ( + model.select(sol_idx.alias("solution"), total.alias("total_cents")) + .where(BuildTotal(sol_idx, total)) + .to_df() + .set_index("solution")["total_cents"] + .sort_index() + ) build_view = selections_df.pivot(index="solution", columns="slot", values="option") - total_cents = selections_df.groupby("solution")["price_cents"].sum() build_view["total_$"] = total_cents / 100 build_view = build_view.loc[total_cents.sort_values().index].reset_index() build_view.columns.name = None diff --git a/product_configurator/runbook.md b/product_configurator/runbook.md index 33a1be26..d7ece13c 100644 --- a/product_configurator/runbook.md +++ b/product_configurator/runbook.md @@ -39,7 +39,7 @@ Each prompt is pasted into a fresh agent session loaded with the named `/rai-*` **Prompt:** /rai-prescriptive-problem Enumerate every legal configuration for the EU region that costs at most $20,000. Use a binary "pick this option" decision over the EU-allowed options, require exactly one option per slot, enforce the implies rules (if the head is picked, the tail must be) and the excludes rules (the two can't both be picked), and keep total price within the ceiling. There's no objective — return the full set of feasible builds in multi-solution mode. -**Response:** OPTIMAL — search exhausted (MiniZinc constraint solver in multi-solution mode). **63 distinct feasible builds** found. Because the EU filter drops the V6, the model has 15 binary option variables and 13 constraints (the V6/Manual exclusion drops out with the V6). The selection is `Option.selected`, with the first solution persisted to the ontology. In `model/reasoning.py` the solve is declared with `problem.configure(...)`, so each refresh of the deployed model runs it. +**Response:** OPTIMAL — search exhausted (MiniZinc constraint solver in multi-solution mode). **63 distinct feasible builds** found. Because the EU filter drops the V6, the model has 15 binary option variables and 13 constraints (the V6/Manual exclusion drops out with the V6). The selection is `Option.selected`, with the first solution persisted to the ontology. In `model/build_enumeration.py` the solve is declared with `problem.configure(...)`, so each refresh of the deployed model runs it. ## 4. Read the configuration population @@ -49,4 +49,4 @@ Each prompt is pasted into a fresh agent session loaded with the named `/rai-*` ## Data -Bundled CSVs in `data/`: 6 slots, 16 options, 4 implies rules, 3 excludes rules, regional availability. The target region (EU) and price ceiling ($20,000) are constants in `model/source.py` and `model/reasoning.py`. Full model in `model/`; the report in `queries/feasible_builds.py`. +Bundled CSVs in `data/`: 6 slots, 16 options, 4 implies rules, 3 excludes rules, regional availability. The target region (EU) and price ceiling ($20,000) are constants in `model/source.py` and `model/build_enumeration.py`. Full model in `model/`; the report in `queries/feasible_builds.py`. diff --git a/retail_planning/README.md b/retail_planning/README.md index 52a8b2b1..174fc096 100644 --- a/retail_planning/README.md +++ b/retail_planning/README.md @@ -43,7 +43,7 @@ Assumes familiarity with Python, basic ML concepts (classification, regression, ## What's included -- `model/` -- the deployed model: `schema.py` declares the concepts and the sales task relationships, `source.py` loads the bundled CSVs, `reasoning.py` states the graph, the GNN, the demand bridge, and the markdown and planning problems with the rules that publish their solutions +- `model/` -- the deployed model: `schema.py` declares the concepts and the sales task relationships, `source.py` loads the bundled CSVs, and five modules state the reasoning: `sales_forecast.py` (the graph and the GNN), `article_demand.py` (the demand bridge), `planning_horizon.py` (the number of planning weeks), `markdown_plan.py` (the markdown problem), and `demand_planning.py` (the planning problem), each with the rules that publish its results - `train.py` -- trains the sales GNN over the deployed splits and registers its version - `queries/retail_report.py` -- prints the sales target profile, the adjusted demand, both solve results, and the selected discounts from the deployed model - `retail_planning.py` -- a separate script-mode reference for the full three-GNN pipeline (sales, churn, purchase) against H&M tables in Snowflake. It is not part of the deployed model, and the Quickstart does not run it @@ -156,7 +156,7 @@ Use this sequence to deploy the model, train the GNN, and query the markdown and predictive: name: retail_sales_gnn # created on first use if it doesn't exist gnns: - sales_regression: # the GNN's name in model/reasoning.py + sales_regression: # the GNN's name in model/sales_forecast.py registry: .RETAIL_PLANNING model: SALES_REGRESSION version: V1 # train.py registers this version @@ -285,7 +285,11 @@ retail_planning/ __init__.py # exports for train.py and the query schema.py # concepts, sales task relationships source.py # bundled CSVs and base facts - reasoning.py # graph, GNN, demand bridge, markdown MILP, planning LP + sales_forecast.py # transaction graph, sales GNN + article_demand.py # demand bridge, planning gaps + planning_horizon.py # number of planning weeks + markdown_plan.py # markdown MILP + demand_planning.py # demand/inventory planning LP train.py # trains the GNN and registers its version queries/ retail_report.py # target profile, adjusted demand, both plans @@ -344,7 +348,7 @@ Customer / Article / Transaction data (bundled CSVs) The deployed model trains only the sales GNN (the most demonstrative task): HM_MINI does not ship churn or purchase splits, so the aggregation step uses the sales predictions alone. `retail_planning.py` is the script-mode reference that adds the churn and purchase GNNs against the full H&M tables. -For the full concept and property definitions, see `model/schema.py` and `model/reasoning.py`; `runbook.md` builds them step by step with the RAI skills. +For the full concept and property definitions, see `model/schema.py` and the modules in `model/`; `runbook.md` builds them step by step with the RAI skills. ## How it works @@ -367,8 +371,8 @@ Both problems are solved by HiGHS on each refresh of the deployed model, and the ### Tune parameters -- **Demand scale** (`DEMAND_SCALE` in `model/reasoning.py`): scales the aggregated predictions into demand units. -- **Unmet demand penalty** (`UNMET_PENALTY`): higher values force the demand planner to fulfill more demand at the cost of higher production. +- **Demand scale** (`DEMAND_SCALE` in `model/article_demand.py`): scales the aggregated predictions into demand units. +- **Unmet demand penalty** (`UNMET_PENALTY` in `model/demand_planning.py`): higher values force the demand planner to fulfill more demand at the cost of higher production. - **Solve time limits** (`time_limit_sec` in the `configure` calls): the longest each solve may run on a refresh. - **Discount tiers and demand lifts**: edit `discounts.csv` for finer or coarser pricing granularity. @@ -382,7 +386,7 @@ Both problems are solved by HiGHS on each refresh of the deployed model, and the ### Scale up / productionize - Move from the bundled `data/hm_mini/` CSVs to Snowflake source tables by reading them in `model/source.py`, as `retail_planning.py` does. -- Churn and purchase GNNs need their own task relationships; add them to `model/schema.py` and `model/reasoning.py` and register each under its own name in `raiconfig.yaml`. +- Churn and purchase GNNs need their own task relationships; add them to `model/schema.py` and `model/sales_forecast.py` and register each under its own name in `raiconfig.yaml`. - Pin `relationalai` (see Prerequisites) and keep the GNN `seed` fixed so training stays reproducible across environments. - Set `interval_s` in the deployment `schedules` to refresh the model on a schedule once the registered version is settled. diff --git a/retail_planning/model/__init__.py b/retail_planning/model/__init__.py index 23636c94..5365dacb 100644 --- a/retail_planning/model/__init__.py +++ b/retail_planning/model/__init__.py @@ -15,19 +15,19 @@ week to maximize revenue plus salvage, and a demand/inventory planning (LP) that minimizes production, holding, and unmet-demand cost. +The stages live in `sales_forecast.py` (the graph and the GNN), +`article_demand.py` (the demand bridge), `planning_horizon.py` (the number of +planning weeks), `markdown_plan.py` (the MILP), and `demand_planning.py` (the +LP). Each module imports the modules whose declarations it reads. + `rai models deploy --path model` deploys this package, `python train.py` trains and registers the GNN, and `python -m queries.retail_report` prints the results of a refresh. """ -from .reasoning import ( - ArticleDemand, - DemandPlanCost, - DemandPlanStatus, - MarkdownRevenue, - MarkdownStatus, - PlanningGap, - gnn, -) +from .article_demand import ArticleDemand, PlanningGap +from .demand_planning import DemandPlanCost, DemandPlanStatus +from .markdown_plan import MarkdownRevenue, MarkdownStatus +from .sales_forecast import gnn from .schema import ( Discount, OptArticle, diff --git a/retail_planning/model/article_demand.py b/retail_planning/model/article_demand.py new file mode 100644 index 00000000..ede3b7df --- /dev/null +++ b/retail_planning/model/article_demand.py @@ -0,0 +1,62 @@ +"""Article demand: each article's demand, summed from the sales GNN's predictions, and the planning +articles that lack it.""" + +from relationalai.semantics import Float, Integer +from relationalai.semantics.std import aggregates as aggs + +# Declares Transaction.predictions, the sales predictions the demand sums. +from . import sales_forecast # noqa: F401 +from .schema import OptArticle, ProdCapacity, Transaction, model + +# -------------------------------------------------- +# Configure inputs +# -------------------------------------------------- + +# Scale factor applied when aggregating normalized GNN predictions into +# optimizer demand. HM_MINI prices are [0, ~0.6]-normalized; multiplying +# makes per-article demand comparable to the inventory scale. +DEMAND_SCALE = 200.0 + +# -------------------------------------------------- +# Phase 3: Bridge -- aggregate per-transaction predictions to per-article demand +# -------------------------------------------------- +# Sum predicted_value across all test-period transactions for each article, +# scaled by DEMAND_SCALE so the number is comparable to inventory units. The +# demand is a property of ArticleDemand, a concept of its own: the GNN reads the +# Article table, so an Article property derived from the predictions would make +# the predictions depend on themselves, and an OptArticle property keyed by the +# transactions' article ids would add an OptArticle row for every article. +ArticleDemand = model.Concept("ArticleDemand", identify_by={"article_id": Integer}) +ArticleDemand.adjusted_demand = model.Property( + f"{ArticleDemand} has {Float:adjusted_demand}") +model.define(ArticleDemand.new(article_id=Transaction.t_article_id)).where( + Transaction.predictions, +) +model.define( + ArticleDemand.adjusted_demand( + aggs.sum(Transaction, Transaction.predictions.predicted_value) + .where(Transaction.t_article_id == ArticleDemand.article_id) + .per(ArticleDemand) * DEMAND_SCALE + ) +) + +# Both problems bound an article only where its demand is known: without it the markdown MILP +# drops the article's sales bound and the planning LP its inventory balance, so their plans for +# it mean nothing. Every planning article without predicted demand, and every capacity row +# outside the markdown planning set, is published here for the report to check. The first +# refresh, before `train.py` registers a GNN version, has no demand at all. +PlanningGap = model.Relationship(f"planning article {Integer:article_id} cannot be planned") +known_demand = ArticleDemand.ref() +model.where( + OptArticle, + model.not_(known_demand.article_id == OptArticle.opt_article_id, known_demand.adjusted_demand), +).define(PlanningGap(OptArticle.opt_article_id)) +planned_article = OptArticle.ref() +model.where( + ProdCapacity, + model.not_( + planned_article.opt_article_id == ProdCapacity.pc_article_id, + known_demand.article_id == ProdCapacity.pc_article_id, + known_demand.adjusted_demand, + ), +).define(PlanningGap(ProdCapacity.pc_article_id)) diff --git a/retail_planning/model/demand_planning.py b/retail_planning/model/demand_planning.py new file mode 100644 index 00000000..16a69b17 --- /dev/null +++ b/retail_planning/model/demand_planning.py @@ -0,0 +1,123 @@ +"""Demand planning: the demand/inventory LP that plans production, inventory, and unmet demand for +each planning article and week at least cost, its solve status and cost, and the plan.""" + +from relationalai.semantics import Float, Integer, String, std, sum +from relationalai.semantics.reasoners.prescriptive import Problem + +from .article_demand import ArticleDemand +from .planning_horizon import num_weeks +from .schema import ProdCapacity, Week, model + +# -------------------------------------------------- +# Configure inputs +# -------------------------------------------------- + +# Optimizer tuning knobs -- edit without retraining the GNN. +UNMET_PENALTY = 50.0 + +# -------------------------------------------------- +# Phase 5: Demand/Inventory Planning (LP, minimize cost) +# -------------------------------------------------- +dp_week_ref = Week.ref() +production_ref = Float.ref() +inventory_ref = Float.ref() + +dp = Problem(model, Float, name="retail_demand_planning") + +ProdCapacity.x_production = model.Property( + f"{ProdCapacity} in week {Week} produces {Float:production}") +dp.solve_for( + ProdCapacity.x_production(dp_week_ref, production_ref), + type="cont", lower=0, + upper=ProdCapacity.max_production_per_week, + name=["prod", ProdCapacity.pc_article_id, dp_week_ref.num], + where=[dp_week_ref.num == std.common.range(1, num_weeks + 1)], +) + +inv_week_ref = Integer.ref() +ProdCapacity.x_inventory = model.Property( + f"{ProdCapacity} at end of week {Integer} has inventory {Float:inventory}") +dp.solve_for( + ProdCapacity.x_inventory(inv_week_ref, inventory_ref), + type="cont", lower=0, + name=["inv", ProdCapacity.pc_article_id, inv_week_ref], + where=[inv_week_ref == std.common.range(0, num_weeks + 1)], +) + +unmet_ref = Float.ref() +ProdCapacity.x_unmet = model.Property( + f"{ProdCapacity} in week {Week} has unmet {Float:demand}") +dp.solve_for( + ProdCapacity.x_unmet(dp_week_ref, unmet_ref), + type="cont", lower=0, + name=["unmet", ProdCapacity.pc_article_id, dp_week_ref.num], + where=[dp_week_ref.num == std.common.range(1, num_weeks + 1)], +) + +inv_init_ref = Float.ref() +dp.satisfy(model.where( + ProdCapacity.x_inventory(0, inv_init_ref), +).require(inv_init_ref == ProdCapacity.pc_initial_inventory)) + +inv_curr = Float.ref() +inv_prev = Float.ref() +flow_prod_ref = Float.ref() +flow_unmet_ref = Float.ref() +flow_week_ref = Week.ref() + +dp.satisfy(model.where( + ProdCapacity.x_inventory(flow_week_ref.num, inv_curr), + ProdCapacity.x_inventory(flow_week_ref.num - 1, inv_prev), + ProdCapacity.x_production(flow_week_ref, flow_prod_ref), + ProdCapacity.x_unmet(flow_week_ref, flow_unmet_ref), + ArticleDemand.article_id == ProdCapacity.pc_article_id, +).require( + inv_curr == inv_prev + flow_prod_ref + - ArticleDemand.adjusted_demand * flow_week_ref.demand_multiplier + + flow_unmet_ref +)) + +prod_cost_total = sum( + ProdCapacity, dp_week_ref, + ProdCapacity.production_cost * production_ref, +).where(ProdCapacity.x_production(dp_week_ref, production_ref)) + +hold_cost_total = sum( + ProdCapacity, inv_week_ref, + ProdCapacity.holding_cost_per_week * inventory_ref, +).where( + ProdCapacity.x_inventory(inv_week_ref, inventory_ref), + inv_week_ref >= 1, +) + +unmet_cost_total = sum( + ProdCapacity, dp_week_ref, + UNMET_PENALTY * unmet_ref, +).where(ProdCapacity.x_unmet(dp_week_ref, unmet_ref)) + +dp.minimize(prod_cost_total + hold_cost_total + unmet_cost_total) + +# Each refresh of the deployed model runs this solve. +dp.configure("highs", time_limit_sec=120) + +# The solve's status and objective, which the deployed model publishes for the queries. +DemandPlanStatus = model.Relationship(f"retail demand planning status is {String:status}") +DemandPlanCost = model.Relationship(f"retail demand planning cost is {Float:cost}") +model.define(DemandPlanStatus(dp.termination_status()), DemandPlanCost(dp.objective_value())) + +# The plan, which the deployed model publishes for the queries: production and unmet demand +# for each planning article and week, and inventory at the end of each week (week 0 is the +# opening stock). +ProdCapacity.planned_production = model.Relationship( + f"{ProdCapacity} in week {Week} has planned production {Float:production}") +ProdCapacity.planned_inventory = model.Relationship( + f"{ProdCapacity} at end of week {Integer:week} has planned inventory {Float:inventory}") +ProdCapacity.planned_unmet = model.Relationship( + f"{ProdCapacity} in week {Week} has planned unmet demand {Float:unmet}") +plan_week, plan_end_week, plan_value = Week.ref(), Integer.ref(), Float.ref() +model.where(ProdCapacity.x_production(plan_week, plan_value)).define( + ProdCapacity.planned_production(plan_week, plan_value)) +model.where(ProdCapacity.x_inventory(plan_end_week, plan_value)).define( + ProdCapacity.planned_inventory(plan_end_week, plan_value)) +model.where(ProdCapacity.x_unmet(plan_week, plan_value)).define( + ProdCapacity.planned_unmet(plan_week, plan_value)) diff --git a/retail_planning/model/markdown_plan.py b/retail_planning/model/markdown_plan.py new file mode 100644 index 00000000..7f0b7740 --- /dev/null +++ b/retail_planning/model/markdown_plan.py @@ -0,0 +1,130 @@ +"""Markdown plan: the markdown MILP that picks a discount for each article and week to maximize +revenue plus salvage, its solve status and revenue, and the selected discounts.""" + +from relationalai.semantics import Float, String, sum +from relationalai.semantics.reasoners.prescriptive import Problem + +from .article_demand import ArticleDemand +from .planning_horizon import num_weeks +from .schema import Discount, OptArticle, Week, model + +# -------------------------------------------------- +# Phase 4: Markdown optimization (MILP, maximize revenue) +# -------------------------------------------------- + +Week_ref = Week.ref() +Discount_ref = Discount.ref() +selection_ref = Float.ref() +sales_ref = Float.ref() +cumulative_ref = Float.ref() + +problem = Problem(model, Float, name="retail_markdown") + +OptArticle.x_select = model.Property( + f"{OptArticle} in {Week} has {Discount} if {Float:x}") +problem.solve_for( + OptArticle.x_select(Week_ref, Discount_ref, selection_ref), + type="bin", + name=["select", OptArticle.opt_article_id, Week_ref.num, Discount_ref.discount_pct], +) + +OptArticle.x_sales = model.Property( + f"{OptArticle} in {Week} at {Discount} has {Float:y}") +problem.solve_for( + OptArticle.x_sales(Week_ref, Discount_ref, sales_ref), + type="cont", lower=0, + name=["sales", OptArticle.opt_article_id, Week_ref.num, Discount_ref.discount_pct], +) + +OptArticle.x_cuml_sales = model.Property( + f"{OptArticle} up to {Week} has {Float:z}") +problem.solve_for( + OptArticle.x_cuml_sales(Week_ref, cumulative_ref), + type="cont", lower=0, + name=["cuml", OptArticle.opt_article_id, Week_ref.num], +) + +problem.satisfy(model.where( + OptArticle.x_select(Week_ref, Discount_ref, selection_ref) +).require( + sum(Discount_ref, selection_ref).per(OptArticle, Week_ref) == 1 +)) + +Discount_inner = Discount.ref() +Week_inner = Week.ref() +selection_inner = Float.ref() +problem.satisfy(model.where( + OptArticle.x_select(Week_ref, Discount_ref, selection_ref), + OptArticle.x_select(Week_inner, Discount_inner, selection_inner), + Week_inner.num == Week_ref.num + 1, + Discount_inner.level < Discount_ref.level, +).require( + selection_ref + selection_inner <= 1 +)) + +problem.satisfy(model.where( + OptArticle.x_select(Week_ref, Discount_ref, selection_ref), + OptArticle.x_sales(Week_ref, Discount_ref, sales_ref), + ArticleDemand.article_id == OptArticle.opt_article_id, +).require( + sales_ref <= ArticleDemand.adjusted_demand + * Discount_ref.demand_lift * Week_ref.demand_multiplier * selection_ref +)) + +problem.satisfy(model.where( + Week_ref.num == 1, + OptArticle.x_cuml_sales(Week_ref, cumulative_ref), + OptArticle.x_sales(Week_ref, Discount_ref, sales_ref), +).require( + cumulative_ref == sum(Discount_ref, sales_ref).per(OptArticle, Week_ref) +)) + +Week_prev = Week.ref() +cumulative_prev = Float.ref() +problem.satisfy(model.where( + Week_ref.num > 1, + Week_prev.num == Week_ref.num - 1, + OptArticle.x_cuml_sales(Week_ref, cumulative_ref), + OptArticle.x_cuml_sales(Week_prev, cumulative_prev), + OptArticle.x_sales(Week_ref, Discount_ref, sales_ref), +).require( + cumulative_ref == cumulative_prev + + sum(Discount_ref, sales_ref).per(OptArticle, Week_ref) +)) + +problem.satisfy(model.where( + OptArticle.x_cuml_sales(Week_ref, cumulative_ref) +).require( + cumulative_ref <= OptArticle.initial_inventory +)) + +revenue = sum( + OptArticle, Week_ref, Discount_ref, + OptArticle.initial_price * (1 - Discount_ref.discount_pct / 100) * sales_ref, +).where(OptArticle.x_sales(Week_ref, Discount_ref, sales_ref)) + +salvage = sum( + OptArticle, Week_ref, + OptArticle.initial_price * OptArticle.salvage_rate + * (OptArticle.initial_inventory - cumulative_ref), +).where( + OptArticle.x_cuml_sales(Week_ref, cumulative_ref), + Week_ref.num == num_weeks, +) + +problem.maximize(revenue + salvage) + +# Each refresh of the deployed model runs this solve. +problem.configure("highs", time_limit_sec=120) + +# The solve's status and objective, which the deployed model publishes for the queries. +MarkdownStatus = model.Relationship(f"retail markdown status is {String:status}") +MarkdownRevenue = model.Relationship(f"retail markdown revenue is {Float:revenue}") +model.define(MarkdownStatus(problem.termination_status()), MarkdownRevenue(problem.objective_value())) + +# The selected discount for each article-week. +OptArticle.markdown = model.Relationship(f"{OptArticle} in {Week} is marked down by {Discount}") +model.where( + OptArticle.x_select(Week_ref, Discount_ref, selection_ref), + selection_ref > 0.5, +).define(OptArticle.markdown(Week_ref, Discount_ref)) diff --git a/retail_planning/model/planning_horizon.py b/retail_planning/model/planning_horizon.py new file mode 100644 index 00000000..92d38faa --- /dev/null +++ b/retail_planning/model/planning_horizon.py @@ -0,0 +1,8 @@ +"""Planning horizon: the number of weeks the markdown and demand/inventory problems plan over.""" + +from relationalai.semantics import Integer, count + +from .schema import Week, model + +num_weeks = model.Relationship(f"{Integer}") +model.define(num_weeks(count(Week))) diff --git a/retail_planning/model/reasoning.py b/retail_planning/model/reasoning.py deleted file mode 100644 index 7c0f92ef..00000000 --- a/retail_planning/model/reasoning.py +++ /dev/null @@ -1,353 +0,0 @@ -"""Retail planning reasoning: sales GNN, demand aggregation, markdown MILP, and demand/inventory planning LP.""" - -from relationalai.semantics import Float, Integer, String, count, std, sum -from relationalai.semantics.reasoners.graph import Graph -from relationalai.semantics.reasoners.predictive import GNN, PropertyTransformer -from relationalai.semantics.reasoners.prescriptive import Problem -from relationalai.semantics.std import aggregates as aggs - -from .schema import ( - Article, - Customer, - Discount, - OptArticle, - ProdCapacity, - Test, - Train, - Transaction, - Val, - Week, - model, -) -from .source import NUM_WEEKS - -# Optimizer tuning knobs -- edit without retraining the GNN. -UNMET_PENALTY = 50.0 - -# Scale factor applied when aggregating normalized GNN predictions into -# optimizer demand. HM_MINI prices are [0, ~0.6]-normalized; multiplying -# makes per-article demand comparable to the inventory scale. -DEMAND_SCALE = 200.0 - -# -------------------------------------------------- -# Phase 1: Graph -# -------------------------------------------------- -gnn_graph = Graph(model, name="transaction_graph", directed=True, weighted=False) -Edge = gnn_graph.Edge -model.define(Edge.new(src=Transaction, dst=Customer)).where( - Transaction.t_customer_id == Customer.c_customer_id) -model.define(Edge.new(src=Transaction, dst=Article)).where( - Transaction.t_article_id == Article.a_article_id) - -# PropertyTransformer: every column the model loads is typed. Transaction.price is the sales -# label (the Train and Val values equal it), so it is not a feature. -pt = PropertyTransformer( - category=[ - Customer.fn, Customer.active, Customer.club_member_status, - Customer.fashion_news_frequency, - Article.product_group_name, Article.colour_group_name, - Article.index_group_name, Article.garment_group_name, - Transaction.sales_channel_id, - ], - text=[Article.prod_name], - continuous=[Customer.age], - drop=[ - Customer.c_customer_id, Article.a_article_id, - Transaction.transaction_id, - Transaction.t_customer_id, Transaction.t_article_id, - Transaction.price, - ], - datetime=[Transaction.t_dat], - time_col=[Transaction.t_dat], -) - -# -------------------------------------------------- -# Phase 2: Sales regression GNN (transaction-level) -# -------------------------------------------------- -# `name` ties this GNN to the registered model and version that -# `reasoners.predictive.gnns.sales_regression` names in raiconfig.yaml: -# train.py registers the trained run there, and every refresh scores the -# test split with it. -gnn = GNN( - name="sales_regression", - graph=gnn_graph, property_transformer=pt, - train=Train, validation=Val, - task_type="regression", eval_metric="rmse", - has_time_column=True, stream_logs=False, seed=42, - n_epochs=20, lr=0.005, patience=10, -) -Transaction.predictions = gnn.predictions(domain=Test) - -# -------------------------------------------------- -# Phase 3: Bridge -- aggregate per-transaction predictions to per-article demand -# -------------------------------------------------- -# Sum predicted_value across all test-period transactions for each article, -# scaled by DEMAND_SCALE so the number is comparable to inventory units. The -# demand is a property of ArticleDemand, a concept of its own: the GNN reads the -# Article table, so an Article property derived from the predictions would make -# the predictions depend on themselves, and an OptArticle property keyed by the -# transactions' article ids would add an OptArticle row for every article. -ArticleDemand = model.Concept("ArticleDemand", identify_by={"article_id": Integer}) -ArticleDemand.adjusted_demand = model.Property( - f"{ArticleDemand} has {Float:adjusted_demand}") -model.define(ArticleDemand.new(article_id=Transaction.t_article_id)).where( - Transaction.predictions, -) -model.define( - ArticleDemand.adjusted_demand( - aggs.sum(Transaction, Transaction.predictions.predicted_value) - .where(Transaction.t_article_id == ArticleDemand.article_id) - .per(ArticleDemand) * DEMAND_SCALE - ) -) - -# Both problems bound an article only where its demand is known: without it the markdown MILP -# drops the article's sales bound and the planning LP its inventory balance, so their plans for -# it mean nothing. Every planning article without predicted demand, and every capacity row -# outside the markdown planning set, is published here for the report to check. The first -# refresh, before `train.py` registers a GNN version, has no demand at all. -PlanningGap = model.Relationship(f"planning article {Integer:article_id} cannot be planned") -known_demand = ArticleDemand.ref() -model.where( - OptArticle, - model.not_(known_demand.article_id == OptArticle.opt_article_id, known_demand.adjusted_demand), -).define(PlanningGap(OptArticle.opt_article_id)) -planned_article = OptArticle.ref() -model.where( - ProdCapacity, - model.not_( - planned_article.opt_article_id == ProdCapacity.pc_article_id, - known_demand.article_id == ProdCapacity.pc_article_id, - known_demand.adjusted_demand, - ), -).define(PlanningGap(ProdCapacity.pc_article_id)) - -# -------------------------------------------------- -# Phase 4: Markdown optimization (MILP, maximize revenue) -# -------------------------------------------------- -num_weeks = model.Relationship(f"{Integer}") -model.define(num_weeks(count(Week))) - -Week_ref = Week.ref() -Discount_ref = Discount.ref() -selection_ref = Float.ref() -sales_ref = Float.ref() -cumulative_ref = Float.ref() - -problem = Problem(model, Float, name="retail_markdown") - -OptArticle.x_select = model.Property( - f"{OptArticle} in {Week} has {Discount} if {Float:x}") -problem.solve_for( - OptArticle.x_select(Week_ref, Discount_ref, selection_ref), - type="bin", - name=["select", OptArticle.opt_article_id, Week_ref.num, Discount_ref.discount_pct], -) - -OptArticle.x_sales = model.Property( - f"{OptArticle} in {Week} at {Discount} has {Float:y}") -problem.solve_for( - OptArticle.x_sales(Week_ref, Discount_ref, sales_ref), - type="cont", lower=0, - name=["sales", OptArticle.opt_article_id, Week_ref.num, Discount_ref.discount_pct], -) - -OptArticle.x_cuml_sales = model.Property( - f"{OptArticle} up to {Week} has {Float:z}") -problem.solve_for( - OptArticle.x_cuml_sales(Week_ref, cumulative_ref), - type="cont", lower=0, - name=["cuml", OptArticle.opt_article_id, Week_ref.num], -) - -problem.satisfy(model.where( - OptArticle.x_select(Week_ref, Discount_ref, selection_ref) -).require( - sum(Discount_ref, selection_ref).per(OptArticle, Week_ref) == 1 -)) - -Discount_inner = Discount.ref() -Week_inner = Week.ref() -selection_inner = Float.ref() -problem.satisfy(model.where( - OptArticle.x_select(Week_ref, Discount_ref, selection_ref), - OptArticle.x_select(Week_inner, Discount_inner, selection_inner), - Week_inner.num == Week_ref.num + 1, - Discount_inner.level < Discount_ref.level, -).require( - selection_ref + selection_inner <= 1 -)) - -problem.satisfy(model.where( - OptArticle.x_select(Week_ref, Discount_ref, selection_ref), - OptArticle.x_sales(Week_ref, Discount_ref, sales_ref), - ArticleDemand.article_id == OptArticle.opt_article_id, -).require( - sales_ref <= ArticleDemand.adjusted_demand - * Discount_ref.demand_lift * Week_ref.demand_multiplier * selection_ref -)) - -problem.satisfy(model.where( - Week_ref.num == 1, - OptArticle.x_cuml_sales(Week_ref, cumulative_ref), - OptArticle.x_sales(Week_ref, Discount_ref, sales_ref), -).require( - cumulative_ref == sum(Discount_ref, sales_ref).per(OptArticle, Week_ref) -)) - -Week_prev = Week.ref() -cumulative_prev = Float.ref() -problem.satisfy(model.where( - Week_ref.num > 1, - Week_prev.num == Week_ref.num - 1, - OptArticle.x_cuml_sales(Week_ref, cumulative_ref), - OptArticle.x_cuml_sales(Week_prev, cumulative_prev), - OptArticle.x_sales(Week_ref, Discount_ref, sales_ref), -).require( - cumulative_ref == cumulative_prev - + sum(Discount_ref, sales_ref).per(OptArticle, Week_ref) -)) - -problem.satisfy(model.where( - OptArticle.x_cuml_sales(Week_ref, cumulative_ref) -).require( - cumulative_ref <= OptArticle.initial_inventory -)) - -revenue = sum( - OptArticle, Week_ref, Discount_ref, - OptArticle.initial_price * (1 - Discount_ref.discount_pct / 100) * sales_ref, -).where(OptArticle.x_sales(Week_ref, Discount_ref, sales_ref)) - -salvage = sum( - OptArticle, Week_ref, - OptArticle.initial_price * OptArticle.salvage_rate - * (OptArticle.initial_inventory - cumulative_ref), -).where( - OptArticle.x_cuml_sales(Week_ref, cumulative_ref), - Week_ref.num == num_weeks, -) - -problem.maximize(revenue + salvage) - -# Each refresh of the deployed model runs this solve. -problem.configure("highs", time_limit_sec=120) - -# The solve's status and objective, which the deployed model publishes for the queries. -MarkdownStatus = model.Relationship(f"retail markdown status is {String:status}") -MarkdownRevenue = model.Relationship(f"retail markdown revenue is {Float:revenue}") -model.define(MarkdownStatus(problem.termination_status()), MarkdownRevenue(problem.objective_value())) - -# The selected discount for each article-week. -OptArticle.markdown = model.Relationship(f"{OptArticle} in {Week} is marked down by {Discount}") -model.where( - OptArticle.x_select(Week_ref, Discount_ref, selection_ref), - selection_ref > 0.5, -).define(OptArticle.markdown(Week_ref, Discount_ref)) - -# -------------------------------------------------- -# Phase 5: Demand/Inventory Planning (LP, minimize cost) -# -------------------------------------------------- -dp_week_ref = Week.ref() -production_ref = Float.ref() -inventory_ref = Float.ref() - -dp = Problem(model, Float, name="retail_demand_planning") - -ProdCapacity.x_production = model.Property( - f"{ProdCapacity} in week {Week} produces {Float:production}") -dp.solve_for( - ProdCapacity.x_production(dp_week_ref, production_ref), - type="cont", lower=0, - upper=ProdCapacity.max_production_per_week, - name=["prod", ProdCapacity.pc_article_id, dp_week_ref.num], - where=[dp_week_ref.num == std.common.range(1, NUM_WEEKS + 1)], -) - -inv_week_ref = Integer.ref() -ProdCapacity.x_inventory = model.Property( - f"{ProdCapacity} at end of week {Integer} has inventory {Float:inventory}") -dp.solve_for( - ProdCapacity.x_inventory(inv_week_ref, inventory_ref), - type="cont", lower=0, - name=["inv", ProdCapacity.pc_article_id, inv_week_ref], - where=[inv_week_ref == std.common.range(0, NUM_WEEKS + 1)], -) - -unmet_ref = Float.ref() -ProdCapacity.x_unmet = model.Property( - f"{ProdCapacity} in week {Week} has unmet {Float:demand}") -dp.solve_for( - ProdCapacity.x_unmet(dp_week_ref, unmet_ref), - type="cont", lower=0, - name=["unmet", ProdCapacity.pc_article_id, dp_week_ref.num], - where=[dp_week_ref.num == std.common.range(1, NUM_WEEKS + 1)], -) - -inv_init_ref = Float.ref() -dp.satisfy(model.where( - ProdCapacity.x_inventory(0, inv_init_ref), -).require(inv_init_ref == ProdCapacity.pc_initial_inventory)) - -inv_curr = Float.ref() -inv_prev = Float.ref() -flow_prod_ref = Float.ref() -flow_unmet_ref = Float.ref() -flow_week_ref = Week.ref() - -dp.satisfy(model.where( - ProdCapacity.x_inventory(flow_week_ref.num, inv_curr), - ProdCapacity.x_inventory(flow_week_ref.num - 1, inv_prev), - ProdCapacity.x_production(flow_week_ref, flow_prod_ref), - ProdCapacity.x_unmet(flow_week_ref, flow_unmet_ref), - ArticleDemand.article_id == ProdCapacity.pc_article_id, -).require( - inv_curr == inv_prev + flow_prod_ref - - ArticleDemand.adjusted_demand * flow_week_ref.demand_multiplier - + flow_unmet_ref -)) - -prod_cost_total = sum( - ProdCapacity, dp_week_ref, - ProdCapacity.production_cost * production_ref, -).where(ProdCapacity.x_production(dp_week_ref, production_ref)) - -hold_cost_total = sum( - ProdCapacity, inv_week_ref, - ProdCapacity.holding_cost_per_week * inventory_ref, -).where( - ProdCapacity.x_inventory(inv_week_ref, inventory_ref), - inv_week_ref >= 1, -) - -unmet_cost_total = sum( - ProdCapacity, dp_week_ref, - UNMET_PENALTY * unmet_ref, -).where(ProdCapacity.x_unmet(dp_week_ref, unmet_ref)) - -dp.minimize(prod_cost_total + hold_cost_total + unmet_cost_total) - -# Each refresh of the deployed model runs this solve. -dp.configure("highs", time_limit_sec=120) - -# The solve's status and objective, which the deployed model publishes for the queries. -DemandPlanStatus = model.Relationship(f"retail demand planning status is {String:status}") -DemandPlanCost = model.Relationship(f"retail demand planning cost is {Float:cost}") -model.define(DemandPlanStatus(dp.termination_status()), DemandPlanCost(dp.objective_value())) - -# The plan, which the deployed model publishes for the queries: production and unmet demand -# for each planning article and week, and inventory at the end of each week (week 0 is the -# opening stock). -ProdCapacity.planned_production = model.Relationship( - f"{ProdCapacity} in week {Week} has planned production {Float:production}") -ProdCapacity.planned_inventory = model.Relationship( - f"{ProdCapacity} at end of week {Integer:week} has planned inventory {Float:inventory}") -ProdCapacity.planned_unmet = model.Relationship( - f"{ProdCapacity} in week {Week} has planned unmet demand {Float:unmet}") -plan_week, plan_end_week, plan_value = Week.ref(), Integer.ref(), Float.ref() -model.where(ProdCapacity.x_production(plan_week, plan_value)).define( - ProdCapacity.planned_production(plan_week, plan_value)) -model.where(ProdCapacity.x_inventory(plan_end_week, plan_value)).define( - ProdCapacity.planned_inventory(plan_end_week, plan_value)) -model.where(ProdCapacity.x_unmet(plan_week, plan_value)).define( - ProdCapacity.planned_unmet(plan_week, plan_value)) diff --git a/retail_planning/model/sales_forecast.py b/retail_planning/model/sales_forecast.py new file mode 100644 index 00000000..9a7e711e --- /dev/null +++ b/retail_planning/model/sales_forecast.py @@ -0,0 +1,55 @@ +"""Sales forecast: the transaction graph and the sales-regression GNN.""" + +from relationalai.semantics.reasoners.graph import Graph +from relationalai.semantics.reasoners.predictive import GNN, PropertyTransformer + +from .schema import Article, Customer, Test, Train, Transaction, Val, model + +# -------------------------------------------------- +# Phase 1: Graph +# -------------------------------------------------- +gnn_graph = Graph(model, name="transaction_graph", directed=True, weighted=False) +Edge = gnn_graph.Edge +model.define(Edge.new(src=Transaction, dst=Customer)).where( + Transaction.t_customer_id == Customer.c_customer_id) +model.define(Edge.new(src=Transaction, dst=Article)).where( + Transaction.t_article_id == Article.a_article_id) + +# PropertyTransformer: every column the model loads is typed. Transaction.price is the sales +# label (the Train and Val values equal it), so it is not a feature. +pt = PropertyTransformer( + category=[ + Customer.fn, Customer.active, Customer.club_member_status, + Customer.fashion_news_frequency, + Article.product_group_name, Article.colour_group_name, + Article.index_group_name, Article.garment_group_name, + Transaction.sales_channel_id, + ], + text=[Article.prod_name], + continuous=[Customer.age], + drop=[ + Customer.c_customer_id, Article.a_article_id, + Transaction.transaction_id, + Transaction.t_customer_id, Transaction.t_article_id, + Transaction.price, + ], + datetime=[Transaction.t_dat], + time_col=[Transaction.t_dat], +) + +# -------------------------------------------------- +# Phase 2: Sales regression GNN (transaction-level) +# -------------------------------------------------- +# `name` ties this GNN to the registered model and version that +# `reasoners.predictive.gnns.sales_regression` names in raiconfig.yaml: +# train.py registers the trained run there, and every refresh scores the +# test split with it. +gnn = GNN( + name="sales_regression", + graph=gnn_graph, property_transformer=pt, + train=Train, validation=Val, + task_type="regression", eval_metric="rmse", + has_time_column=True, stream_logs=False, seed=42, + n_epochs=20, lr=0.005, patience=10, +) +Transaction.predictions = gnn.predictions(domain=Test) diff --git a/retail_planning/model/source.py b/retail_planning/model/source.py index 942b9aff..0d4954f6 100644 --- a/retail_planning/model/source.py +++ b/retail_planning/model/source.py @@ -77,7 +77,6 @@ week_csv = read_csv(DATA_DIR / "weeks.csv") model.define(Week.new(model.data(week_csv).to_schema())) -NUM_WEEKS = len(week_csv) prod_csv = read_csv(HM_DIR / "production_capacity.csv", dtype={"article_id": int}) prod_data = model.data(prod_csv) diff --git a/smoker_status_prediction/README.md b/smoker_status_prediction/README.md index 29d5fc5f..13b02251 100644 --- a/smoker_status_prediction/README.md +++ b/smoker_status_prediction/README.md @@ -34,7 +34,7 @@ Assumes familiarity with Python and basic ML concepts (binary classification, tr ## What's included -- **Model**: `model/` -- the deployed model: concepts and splits (`schema.py`, `source.py`), the graph, the feature types, and the GNN with its predictions (`reasoning.py`) +- **Model**: `model/` -- the deployed model: concepts and splits (`schema.py`, `source.py`), the graph, the feature types, and the GNN with its predictions (`smoker_gnn.py`), and the table counts and test-set metrics (`prediction_metrics.py`) - **Training**: `train.py` -- trains the GNN over the deployed splits and registers its version - **Query**: `queries/smoker_report.py` -- prints the data summary, a sample of predictions, and the test-set metrics from the deployed model - **Runbook**: `runbook.md` — a paste-testable walkthrough that reproduces the template step by step with the RAI skills; as important a reference as the code itself. @@ -125,7 +125,7 @@ Use this sequence to deploy the model, train the GNN, and query its predictions: predictive: name: smoker_status_prediction_gnn # created on first use if it doesn't exist gnns: - smoker_status: # the GNN's name in model/reasoning.py + smoker_status: # the GNN's name in model/smoker_gnn.py registry: .SMOKER_STATUS_PREDICTION model: SMOKER_STATUS version: V1 # train.py registers this version @@ -223,7 +223,8 @@ Use this sequence to deploy the model, train the GNN, and query its predictions: │ ├── __init__.py # exports for train.py and the query │ ├── schema.py # concepts and the Train/Validation/Test task relationships │ ├── source.py # bundled CSVs bound to the schema -│ └── reasoning.py # graph, feature types, the GNN and its predictions +│ ├── smoker_gnn.py # graph, feature types, the GNN and its predictions +│ └── prediction_metrics.py # table counts, test-set accuracy, ROC-AUC, class shares ├── train.py # trains the GNN and registers its version ├── queries/ │ └── smoker_report.py # data summary, prediction sample, and test-set metrics @@ -279,7 +280,7 @@ The pipeline turns the `PEOPLE` table into graph nodes and the `RELATED` pairs i 4. **Train and predict.** The GNN is instantiated with the graph, the transformer, and the train/validation relationships, fit, then used to attach predictions over the held-out test cohort back onto each `People` node. 5. **Register and predict.** `train.py` registers the trained run as a version in the Snowflake Model Registry, and every refresh of the deployed model scores the test cohort with that version, so predictions need no retraining. -See `model/reasoning.py` for the graph and the GNN, `queries/smoker_report.py` for the metrics, and `runbook.md` for the skill-driven reproduction. +See `model/smoker_gnn.py` for the graph and the GNN, `model/prediction_metrics.py` for the metrics, `queries/smoker_report.py` for the report, and `runbook.md` for the skill-driven reproduction. ## Customize this template @@ -300,7 +301,7 @@ For the full hyperparameter list, see the [Configure a GNN](https://docs.relatio ### Extend the model - **Add categorical demographics** (e.g. occupation, income bracket): list them under `category=[...]` in the `PropertyTransformer`. -- **Try a multiclass task**: if your label has more than two values (e.g. never / light / heavy smoker), change `task_type="multiclass_classification"` and use `eval_metric="macro_f1"` or `"accuracy"`. The published prediction then carries per-class scores rather than one probability, so update `SmokerPrediction` in `model/reasoning.py` and replace the report's binary ROC-AUC and its fixed classes `0` and `1` with a multiclass metric. +- **Try a multiclass task**: if your label has more than two values (e.g. never / light / heavy smoker), change `task_type="multiclass_classification"` and use `eval_metric="macro_f1"` or `"accuracy"`. The published prediction then carries per-class scores rather than one probability, so update `SmokerPrediction` in `model/smoker_gnn.py` and replace the binary ROC-AUC and the fixed classes `0` and `1` in `model/prediction_metrics.py` with a multiclass metric. - **Train a new version**: the registry refuses to overwrite a version, so set a new `version` under `reasoners.predictive.gnns.smoker_status` in `raiconfig.yaml`, then run `python train.py` and the refresh call again. ### Scale up / productionize @@ -331,7 +332,7 @@ data: Importing Snowflake tables requires change tracking on them: without `ensure_change_tracking: true`, the SDK warns that GNN workflows using Snowflake tables will fail. If your role cannot enable tracking on the five source tables, have their owner run `ALTER TABLE
SET CHANGE_TRACKING = TRUE` on each. -The tables carry the same columns as the CSVs, created with quoted names so Snowflake keeps their case and matching the names the model uses: `PEOPLE` with `"Id"` and the lowercase feature names that `model/reasoning.py` reads (`"height_cm"`, `"fasting_blood_sugar"`, ...), `RELATED` with `"person1"` and `"person2"`, and `TRAIN`, `VALIDATION`, and `TEST` with `"Id"` and `"smoking"`. +The tables carry the same columns as the CSVs, created with quoted names so Snowflake keeps their case and matching the names the model uses: `PEOPLE` with `"Id"` and the lowercase feature names that `model/smoker_gnn.py` reads (`"height_cm"`, `"fasting_blood_sugar"`, ...), `RELATED` with `"person1"` and `"person2"`, and `TRAIN`, `VALIDATION`, and `TEST` with `"Id"` and `"smoking"`. ## Troubleshooting diff --git a/smoker_status_prediction/model/__init__.py b/smoker_status_prediction/model/__init__.py index c60d3df1..8a1e97ca 100644 --- a/smoker_status_prediction/model/__init__.py +++ b/smoker_status_prediction/model/__init__.py @@ -1,20 +1,29 @@ """Smoker-status model: people, their connections, and a binary-classification GNN. -`rai models deploy --path model` deploys everything this package declares. +`rai models deploy --path model` deploys everything this package declares. `smoker_gnn.py` holds +the graph, the GNN, and the published predictions; `prediction_metrics.py` holds the table row +counts and the test-set accuracy, ROC-AUC, and class shares, and imports the module whose +declarations it reads. """ from .schema import People, Related, TestTable, TrainTable, ValidationTable, model from .source import DATA_DIR # isort: split -# The reasoning declares the graph and the GNN over the facts loaded above. -from .reasoning import SmokerPrediction, gnn +# The graph, the GNN, and the metrics are declared over the facts loaded above. +from .prediction_metrics import ClassShare, DataSummary, TestAccuracy, TestAuc, TestCohort +from .smoker_gnn import SmokerPrediction, gnn __all__ = [ "DATA_DIR", + "ClassShare", + "DataSummary", "People", "Related", "SmokerPrediction", + "TestAccuracy", + "TestAuc", + "TestCohort", "TestTable", "TrainTable", "ValidationTable", diff --git a/smoker_status_prediction/model/prediction_metrics.py b/smoker_status_prediction/model/prediction_metrics.py new file mode 100644 index 00000000..74e2a624 --- /dev/null +++ b/smoker_status_prediction/model/prediction_metrics.py @@ -0,0 +1,129 @@ +"""Prediction metrics: the row counts of the loaded tables, and the test-set accuracy, ROC-AUC, and +class distributions of the published predictions against the held-out labels.""" + +from relationalai.semantics import Float, Integer +from relationalai.semantics.std import aggregates as aggs +from relationalai.semantics.std import floats + +from .schema import People, Related, TestTable, TrainTable, ValidationTable, model + +# Declares SmokerPrediction, the published predictions these metrics score. +from .smoker_gnn import SmokerPrediction + +# The number of rows in each loaded table. +DataSummary = model.Relationship( + f"the data has {Integer:people} people, {Integer:related} related pairs, and " + f"{Integer:train} train, {Integer:validation} validation, {Integer:test} test rows" +) +model.define( + DataSummary( + aggs.count(People), + aggs.count(Related), + aggs.count(TrainTable), + aggs.count(ValidationTable), + aggs.count(TestTable), + ) +) + +# A scored observation is a prediction joined to a held-out test row of the same person, so a +# person with several test rows is scored once per row. The scored cohort is those observations, +# and how many of them the prediction matches. +_scored = SmokerPrediction.person_id == TestTable.Id +_actual = TestTable.smoking +TestCohort = model.Relationship( + f"the test cohort has {Integer:n_test} scored predictions, {Integer:n_correct} of them correct" +) +model.define( + TestCohort( + aggs.count(SmokerPrediction, TestTable).where(_scored), + aggs.count(SmokerPrediction, TestTable).where( + _scored, SmokerPrediction.predicted_label == _actual + ) + | 0, + ) +) +_n_test, _n_correct = Integer.ref(), Integer.ref() +TestAccuracy = model.Relationship(f"the test accuracy is {Float:accuracy}") +model.where(TestCohort(_n_test, _n_correct), _n_test > 0).define( + TestAccuracy(floats.float(_n_correct) / floats.float(_n_test)) +) + +# The share of the scored cohort in each class of the binary task, by held-out label and by +# predicted label (zero for a class that never occurs). +ClassShare = model.Concept("ClassShare", identify_by={"label": Integer}) +ClassShare.n_actual = model.Property(f"{ClassShare} has {Integer:n_actual} held-out labels") +ClassShare.n_predicted = model.Property(f"{ClassShare} has {Integer:n_predicted} predicted labels") +ClassShare.actual_share = model.Property(f"{ClassShare} has held-out share {Float:actual_share}") +ClassShare.predicted_share = model.Property( + f"{ClassShare} has predicted share {Float:predicted_share}" +) +model.define(ClassShare.new(label=0), ClassShare.new(label=1)) +model.define( + ClassShare.n_actual( + aggs.count(SmokerPrediction, TestTable) + .per(ClassShare) + .where(_scored, _actual == ClassShare.label) + | 0 + ), + ClassShare.n_predicted( + aggs.count(SmokerPrediction, TestTable) + .per(ClassShare) + .where(_scored, SmokerPrediction.predicted_label == ClassShare.label) + | 0 + ), +) +model.where(TestCohort(_n_test, _n_correct), _n_test > 0).define( + ClassShare.actual_share(floats.float(ClassShare.n_actual) / floats.float(_n_test)), + ClassShare.predicted_share(floats.float(ClassShare.n_predicted) / floats.float(_n_test)), +) + +# Rank-based ROC-AUC: (sum of the positives' ranks - n_pos * (n_pos + 1) / 2) / (n_pos * n_neg), +# where tied probabilities share the average of their ranks. A level is one distinct probability +# among the scored observations; its observations occupy ranks n_up_to - n_scored + 1 through +# n_up_to, so they share the average rank n_up_to - (n_scored - 1) / 2. +ScoreLevel = model.Concept("ScoreLevel", identify_by={"probability": Float}) +ScoreLevel.n_scored = model.Property(f"{ScoreLevel} has {Integer:n_scored} scored observations") +ScoreLevel.n_positive = model.Property(f"{ScoreLevel} has {Integer:n_positive} positives") +ScoreLevel.n_up_to = model.Property(f"{ScoreLevel} has {Integer:n_up_to} observations up to it") +ScoreLevel.mean_rank = model.Property(f"{ScoreLevel} has average rank {Float:mean_rank}") +model.where(_scored).define(ScoreLevel.new(probability=SmokerPrediction.probability)) +_at_level = SmokerPrediction.probability == ScoreLevel.probability +model.define( + ScoreLevel.n_scored( + aggs.count(SmokerPrediction, TestTable).per(ScoreLevel).where(_scored, _at_level) + ), + ScoreLevel.n_positive( + aggs.count(SmokerPrediction, TestTable) + .per(ScoreLevel) + .where(_scored, _at_level, _actual == 1) + | 0 + ), +) +model.define(ScoreLevel.n_up_to(aggs.cumsum_asc(ScoreLevel.probability, ScoreLevel.n_scored))) +model.define( + ScoreLevel.mean_rank( + floats.float(ScoreLevel.n_up_to) - (floats.float(ScoreLevel.n_scored) - 1.0) / 2.0 + ) +) + +# The ROC-AUC is defined when the scored cohort has both classes; its positives are the +# held-out class-1 count. +PositiveRankSum = model.Relationship(f"the scored positives have rank sum {Float:rank_sum}") +model.define( + PositiveRankSum(aggs.sum(ScoreLevel, ScoreLevel.n_positive * ScoreLevel.mean_rank)) +) +TestAuc = model.Relationship(f"the test ROC-AUC is {Float:auc}") +_n_positive, _rank_sum = Integer.ref(), Float.ref() +model.where( + PositiveRankSum(_rank_sum), + TestCohort(_n_test, _n_correct), + ClassShare.label == 1, + ClassShare.n_actual(_n_positive), + _n_positive > 0, + _n_test > _n_positive, +).define( + TestAuc( + (_rank_sum - floats.float(_n_positive) * (floats.float(_n_positive) + 1.0) / 2.0) + / (floats.float(_n_positive) * floats.float(_n_test - _n_positive)) + ) +) diff --git a/smoker_status_prediction/model/reasoning.py b/smoker_status_prediction/model/smoker_gnn.py similarity index 100% rename from smoker_status_prediction/model/reasoning.py rename to smoker_status_prediction/model/smoker_gnn.py diff --git a/smoker_status_prediction/queries/smoker_report.py b/smoker_status_prediction/queries/smoker_report.py index eed67989..925a8a75 100644 --- a/smoker_status_prediction/queries/smoker_report.py +++ b/smoker_status_prediction/queries/smoker_report.py @@ -7,27 +7,37 @@ the test-set ROC-AUC, accuracy, and class distributions. """ -from model import People, Related, SmokerPrediction, TestTable, TrainTable, ValidationTable -from relationalai.semantics import count, select +from model import ( + ClassShare, + DataSummary, + SmokerPrediction, + TestAccuracy, + TestAuc, + TestCohort, + TestTable, +) +from relationalai.semantics import Float, Integer, select def main() -> None: + people, related, train, validation, test = (Integer.ref() for _ in range(5)) counts = ( select( - count(People).alias("people"), - count(Related).alias("related"), - count(TrainTable).alias("train"), - count(ValidationTable).alias("val"), - count(TestTable).alias("test"), + people.alias("people"), + related.alias("related"), + train.alias("train"), + validation.alias("val"), + test.alias("test"), ) + .where(DataSummary(people, related, train, validation, test)) .to_df() .iloc[0] ) print(f"People: {counts['people']:,} Related: {counts['related']:,}") print(f"Splits: train={counts['train']:,} val={counts['val']:,} test={counts['test']:,}") - # Pull per-person predictions joined to the held-out actual labels in a - # single query, so we can score the GNN on the test cohort. + # Pull per-person predictions joined to the held-out actual labels, so the sample shows the + # GNN's test-cohort scores next to the truth. predictions_df = ( select( SmokerPrediction.person_id.alias("Id"), @@ -53,27 +63,32 @@ def main() -> None: .to_string(index=False) ) - # Test-set metrics. Rank-based ROC-AUC keeps the script sklearn-free: - # AUC = (sum_of_ranks_of_positives - n_pos*(n_pos+1)/2) / (n_pos * n_neg). - n_test = len(predictions_df) - accuracy = float( - (predictions_df["predicted_label"] == predictions_df["actual_smoking"]).mean() + # Test-set metrics, as the model publishes them. ROC-AUC is rank-based (ties share the + # average rank), so the script stays sklearn-free. It is undefined when the scored cohort + # has one class only. + n_test_ref, n_correct_ref, accuracy_ref, auc_ref = ( + Integer.ref(), + Integer.ref(), + Float.ref(), + Float.ref(), ) - ranks = predictions_df["prob"].rank(method="average") - pos_mask = predictions_df["actual_smoking"] == 1 - n_pos = int(pos_mask.sum()) - n_neg = int((~pos_mask).sum()) - test_auc = ( - float((ranks[pos_mask].sum() - n_pos * (n_pos + 1) / 2) / (n_pos * n_neg)) - if n_pos > 0 and n_neg > 0 - else float("nan") + n_test = int( + select(n_test_ref).where(TestCohort(n_test_ref, n_correct_ref)).to_df().iloc[0, 0] ) - actual_dist = ( - predictions_df["actual_smoking"].value_counts(normalize=True).sort_index().to_dict() - ) - predicted_dist = ( - predictions_df["predicted_label"].value_counts(normalize=True).sort_index().to_dict() + accuracy = float(select(accuracy_ref).where(TestAccuracy(accuracy_ref)).to_df().iloc[0, 0]) + auc_values = select(auc_ref).where(TestAuc(auc_ref)).to_df().iloc[:, 0].tolist() + test_auc = float(auc_values[0]) if auc_values else float("nan") + shares = ( + select( + ClassShare.label.alias("label"), + ClassShare.actual_share.alias("actual"), + ClassShare.predicted_share.alias("predicted"), + ) + .to_df() + .set_index("label") ) + actual_dist = shares["actual"].to_dict() + predicted_dist = shares["predicted"].to_dict() print(f"\n=== Test-set metrics (n={n_test}) ===") if n_test < counts["test"]: diff --git a/sprint_scheduling/README.md b/sprint_scheduling/README.md index 7cd5bf6c..689cd16d 100644 --- a/sprint_scheduling/README.md +++ b/sprint_scheduling/README.md @@ -39,7 +39,7 @@ Built using **prescriptive reasoning** (mixed-integer programming solved with Hi ## What's included -- **Model**: developers, sprints, issues, and skill mappings as concepts, plus a cross-product `Assignment` decision concept with binary assignment variables, capacity and once-per-issue constraints, and a weighted-completion-time objective, in the `model/` package (`schema.py` declares the concepts, `source.py` loads the sample data and applies the planning horizon, `reasoning.py` states one decision problem per capacity scenario), which `rai models deploy --path model` deploys to your Snowflake account, where each refresh runs the solves. +- **Model**: developers, sprints, issues, and skill mappings as concepts, plus a cross-product `Assignment` decision concept with binary assignment variables, capacity and once-per-issue constraints, and a weighted-completion-time objective, in the `model/` package (`schema.py` declares the concepts, `source.py` loads the sample data and applies the planning horizon, `sprint_assignment.py` maps each issue to its target sprint and states one decision problem per capacity scenario), which `rai models deploy --path model` deploys to your Snowflake account, where each refresh runs the solves. - **Query**: `queries/sprint_plan.py`, which prints the report from the deployed model. - **Runbook**: `runbook.md` -- a paste-testable walkthrough that reproduces the template step by step with the RAI skills; as important a reference as the script itself. - **Sample data**: four CSVs under `data/` describing 8 developers, 4 sprints, 30 backlog issues, and developer-team skills. See *Sample data* below. @@ -239,7 +239,7 @@ Use this sequence to deploy the model and query it: │ ├── __init__.py # exports of the deployed model │ ├── schema.py # concepts and properties │ ├── source.py # sample data, planning horizon, epoch filter -│ └── reasoning.py # assignment domain, constraints, objective, one solve per scenario +│ └── sprint_assignment.py # target sprints, assignment domain, constraints, objective, one solve per scenario ├── queries/ │ └── sprint_plan.py # report from the deployed model └── data/ @@ -286,7 +286,7 @@ CSV inputs → epoch filter → target-sprint mapping → assignment domain → **5. Weighted completion time objective.** The objective minimizes a weighted sum where higher-priority issues (lower priority number) cost more when placed in later sprints -- with `max_priority = 3`, a priority-1 issue in Sprint 4 costs `(3+1-1) * 4 = 12` and a priority-3 issue in Sprint 4 costs `(3+1-3) * 4 = 4`. This pushes the most urgent work into the earliest sprints. -For the implementation, see `model/reasoning.py`; to reproduce it step by step with the RAI skills, follow `runbook.md`. +For the implementation, see `model/sprint_assignment.py`; to reproduce it step by step with the RAI skills, follow `runbook.md`. ## Customize this template @@ -295,14 +295,14 @@ Focus on the first changes most users will make. ### Use your own data - Replace the four CSVs in `data/` with your own, keeping the column names listed in *Sample data* above. `developers.csv`, `sprints.csv`, `issues.csv`, and `skills.csv` each map directly to a concept. -- `sprints.csv` and `issues.csv` use Unix epoch seconds for dates; convert your date strings to epochs before loading, or adapt the epoch-mapping helper. +- `sprints.csv` and `issues.csv` use Unix epoch seconds for dates; convert your date strings to epochs before loading, or adapt the target-sprint rule in `model/sprint_assignment.py`. - Make sure every team present in `issues.csv` has at least one skilled developer in `skills.csv`: an issue with no eligible developer gets no assignment constraint, so it is left out of the plan rather than making the model infeasible. ### Tune parameters - **Planning horizon** -- edit `planning_start` and `planning_end` in `model/source.py` to include more or fewer sprints, and add matching rows to `sprints.csv`. -- **Capacity** -- modify `capacity_points_per_sprint` in `developers.csv`, or edit `SCENARIO_VALUES` in `model/reasoning.py` to sweep different `capacity_multiplier` levels (default `[0.35, 0.5, 1.0]`). -- **Priority scheme** -- adjust `max_priority` and the weight formula in the objective in `model/reasoning.py` to match your team's priority scale. +- **Capacity** -- modify `capacity_points_per_sprint` in `developers.csv`, or edit `SCENARIO_VALUES` in `model/sprint_assignment.py` to sweep different `capacity_multiplier` levels (default `[0.35, 0.5, 1.0]`). +- **Priority scheme** -- adjust `max_priority` and the weight formula in the objective in `model/sprint_assignment.py` to match your team's priority scale. ### Extend the model diff --git a/sprint_scheduling/model/__init__.py b/sprint_scheduling/model/__init__.py index d5617d84..e30efe2c 100644 --- a/sprint_scheduling/model/__init__.py +++ b/sprint_scheduling/model/__init__.py @@ -5,8 +5,10 @@ - Load sample CSVs describing developers, sprints, issues, and developer-team skills. - Model those entities as *concepts* with typed properties. -- Filter issues by epoch timestamp (created_at) to scope the planning horizon. -- Map each issue's created_at epoch to a target sprint via epoch-to-period mapping. +- Filter issues by epoch timestamp (created_at) to scope the planning horizon + (`source.py`). +- Map each issue's created_at epoch to a target sprint via epoch-to-period mapping + (`sprint_assignment.py`). - Assign each issue to exactly one developer in one sprint (binary variables). - Enforce developer capacity per sprint and skill-matching constraints. - Minimize weighted completion time (high-priority issues penalized more for delay). @@ -15,19 +17,23 @@ Temporal filtering pattern (epoch integers -- Pattern B): - Convert date-range boundaries to Unix epoch seconds. -- Filter event rows by epoch BEFORE loading into the model. +- Filter event rows by epoch as they load into the model. - Map epochs to categorical periods (sprints) by comparing against sprint start/end epochs. - Compare with Pattern A (native date strings) in the demand_planning_temporal template. +The target sprints and the sprint assignment problem are in `sprint_assignment.py`. + Run: `rai models deploy --path model` deploys this package to the schemas in raiconfig.yaml and waits for its first refresh, which runs the solves. `python -m queries.sprint_plan` then prints the report from the deployed model. """ -from .reasoning import ( +from .schema import Assignment, Developer, Issue, Skill, Sprint, model +from .source import DATA_DIR, PlanningHorizon +from .sprint_assignment import ( SCENARIO_PARAM, SCENARIO_VALUES, Assigned, @@ -35,8 +41,6 @@ WeightedCompletion, problems, ) -from .schema import Assignment, Developer, Issue, Skill, Sprint, model -from .source import DATA_DIR, PlanningHorizon __all__ = [ "DATA_DIR", diff --git a/sprint_scheduling/model/source.py b/sprint_scheduling/model/source.py index 48eeb969..a850b37e 100644 --- a/sprint_scheduling/model/source.py +++ b/sprint_scheduling/model/source.py @@ -35,35 +35,14 @@ issues_df = read_csv(DATA_DIR / "issues.csv") -# EPOCH FILTERING: Only load issues created within the planning horizon -# This is the key epoch pattern — filter event rows by epoch BEFORE they enter the model -filtered_issues = issues_df[ - (issues_df["created_at"] >= start_epoch) & (issues_df["created_at"] <= end_epoch) -].copy() - -# EPOCH-TO-PERIOD MAPPING: Map each issue to its target sprint based on created_at epoch -# Issues created during a sprint -> assigned to that sprint (earliest eligible) - - -def map_to_sprint(created_at_epoch): - """Map an issue's created_at epoch to its target sprint number.""" - for _, sprint in sprints_csv.iterrows(): - if created_at_epoch < sprint["startdate"]: - # Created before this sprint starts -> eligible from this sprint - return int(sprint["number"]) - if sprint["startdate"] <= created_at_epoch < sprint["enddate"]: - # Created during this sprint -> target this sprint - return int(sprint["number"]) - # Created after all sprints -> last sprint - return int(sprints_csv["number"].max()) - - -filtered_issues["target_sprint_number"] = filtered_issues["created_at"].apply( - map_to_sprint -) - -issue_data = model.data(filtered_issues) -model.define( +# EPOCH FILTERING: every row of the CSV is embedded as data, and the rule below makes an Issue +# only of a row created within the planning horizon -- the key epoch pattern. The +# epoch-to-period mapping is in `sprint_assignment.py`. +issue_data = model.data(issues_df) +model.where( + issue_data.created_at >= start_epoch, + issue_data.created_at <= end_epoch, +).define( i := Issue.new(id=issue_data.id), i.key(issue_data.key), i.summary(issue_data.summary), @@ -71,7 +50,6 @@ def map_to_sprint(created_at_epoch): i.created_at(issue_data.created_at), i.priority(issue_data.priority), i.team(issue_data.team), - i.target_sprint_number(issue_data.target_sprint_number), ) skills_csv = read_csv(DATA_DIR / "skills.csv") diff --git a/sprint_scheduling/model/reasoning.py b/sprint_scheduling/model/sprint_assignment.py similarity index 86% rename from sprint_scheduling/model/reasoning.py rename to sprint_scheduling/model/sprint_assignment.py index 1e6e4d05..e05f412e 100644 --- a/sprint_scheduling/model/reasoning.py +++ b/sprint_scheduling/model/sprint_assignment.py @@ -1,10 +1,23 @@ -"""Sprint assignment decision problems: one weighted-completion-time problem per capacity scenario.""" +"""Sprint assignment: the first sprint each issue can be assigned to, and one +weighted-completion-time decision problem per capacity scenario.""" from relationalai.semantics import Float, String, sum from relationalai.semantics.reasoners.prescriptive import Problem +from relationalai.semantics.std import aggregates as aggs from .schema import Assignment, Developer, Issue, Skill, Sprint, model +# EPOCH-TO-PERIOD MAPPING: an issue created before a sprint starts is eligible from that sprint, +# and one created during a sprint targets it, so the target is the first sprint that ends after +# the issue was created. An issue created after the last sprint ended targets the last sprint. +_ending_after, _last = Sprint.ref(), Sprint.ref() +model.define( + Issue.target_sprint_number( + aggs.min(_ending_after.number).per(Issue).where(Issue.created_at < _ending_after.enddate) + | aggs.max(_last.number) + ) +) + # Build assignment domain: developer can work on issue if they have the matching skill, # and the sprint is >= the issue's target sprint (can't assign to earlier sprints) model.define(Assignment.new(developer=Developer, issue=Issue, sprint=Sprint)).where( diff --git a/sprint_scheduling/runbook.md b/sprint_scheduling/runbook.md index 6ffae5a3..3b95d850 100644 --- a/sprint_scheduling/runbook.md +++ b/sprint_scheduling/runbook.md @@ -39,7 +39,7 @@ Each prompt is pasted into a fresh agent session loaded with the named `/rai-*` **Prompt:** /rai-prescriptive-problem Assign each in-scope issue to exactly one developer in one sprint to minimize weighted completion time — where an urgent (low-priority-number) issue costs more the later its sprint. A developer can only take an issue if their team matches the issue's team and the sprint is at or after the issue's target sprint, and each developer's assigned story points per sprint can't exceed their capacity. Solve three capacity scenarios — scaling every developer's capacity to 35%, 50%, and 100% — and persist the assignment. -**Response:** The decision is a binary assignment over the 259 valid (developer, issue, sprint) combinations, with 57 constraints per scenario (HiGHS). At **0.35x capacity the problem is INFEASIBLE** — the backlog can't fit — while **0.5x and 1.0x are both OPTIMAL with objective 112.0**. The assignment is read back per scenario from the solved decision. In `model/reasoning.py` each scenario's solve is declared with `problem.configure(...)`, so each refresh of the deployed model runs them. +**Response:** The decision is a binary assignment over the 259 valid (developer, issue, sprint) combinations, with 57 constraints per scenario (HiGHS). At **0.35x capacity the problem is INFEASIBLE** — the backlog can't fit — while **0.5x and 1.0x are both OPTIMAL with objective 112.0**. The assignment is read back per scenario from the solved decision. In `model/sprint_assignment.py` each scenario's solve is declared with `problem.configure(...)`, so each refresh of the deployed model runs them. ## 4. Read the plan diff --git a/subscriber_retention/README.md b/subscriber_retention/README.md index ff2c0fe9..070b7b56 100644 --- a/subscriber_retention/README.md +++ b/subscriber_retention/README.md @@ -37,14 +37,14 @@ This template scores the held-out test subscribers for churn risk using both the - A per-subscriber churn-risk score, predicted by a **graph neural network (GNN) regression head** (the predictive reasoner) from plan attributes, demographics, and call-network features. - Call-network features enriched onto each subscriber by the **graph reasoner** -- a PageRank "social influence" score plus aggregate-derived `outgoing_calls` / `incoming_calls` counts -- so the GNN sees who each subscriber talks to. -- A retention-ready report of the top-N highest-predicted-risk subscribers per segment: the deployed model publishes each test subscriber's predicted risk, and the report ranks and truncates it per segment. +- A retention-ready report of the top-N highest-predicted-risk subscribers per segment: the deployed model publishes each test subscriber's predicted risk and its rank within its segment, and the report prints the first N of each segment. - A pipeline that runs end-to-end on the small bundled telco dataset (~1,200 subscribers, ~6,000 calls) with no Snowflake source-data setup and no GPU. Built using the **graph reasoner** (PageRank on the call graph) and the **predictive reasoner** (GNN regression scored per subscriber). ## What's included -- **Model**: `model/` — the deployed model: concepts, data and splits (`schema.py`, `source.py`), the call graph, the features and the GNN (`reasoning.py`) +- **Model**: `model/` — the deployed model: concepts, data and splits (`schema.py`, `source.py`), the call graph and call features (`call_signals.py`), the GNN and its published predictions (`churn_predictor.py`), and the counts, score range, per-segment ranks and RMSE the report prints (`data_profile.py`, `prediction_summary.py`) - **Training**: `train.py` — trains the GNN over the deployed splits and registers its version - **Query**: `queries/churn_report.py` — prints the top-N highest-predicted-risk subscribers per segment from the deployed model - **Runbook**: `runbook.md` — a paste-testable walkthrough that reproduces the template step by step with the RAI skills; as important a reference as the code itself. @@ -134,7 +134,7 @@ Use this sequence to deploy the model, train the GNN, and query the churn report predictive: name: subscriber_retention_gnn # created on first use if it doesn't exist gnns: - churn_risk: # the GNN's name in model/reasoning.py + churn_risk: # the GNN's name in model/churn_predictor.py registry: .SUBSCRIBER_RETENTION model: CHURN_RISK version: V1 # train.py registers this version @@ -237,8 +237,11 @@ Use this sequence to deploy the model, train the GNN, and query the churn report ├── model/ │ ├── __init__.py # exports for train.py and the query │ ├── schema.py # concepts and the Train/Val/Test task relationships -│ ├── source.py # bundled CSVs and the stratified split -│ └── reasoning.py # call graph, PageRank, call-volume features, the GNN +│ ├── source.py # bundled CSVs, plan attributes, and the stratified split +│ ├── call_signals.py # call graph, PageRank, call-volume features +│ ├── churn_predictor.py # the GNN and the published predicted risk +│ ├── data_profile.py # subscriber, call, and split counts; churn-risk score range +│ └── prediction_summary.py # rank within segment, scored subscribers per segment, RMSE ├── train.py # trains the GNN and registers its version ├── queries/ │ └── churn_report.py # top-N highest-predicted-risk subscribers per segment @@ -298,9 +301,9 @@ Subscribers + Plans + Call records (bundled CSVs, denormalized to Subscriber) **4. Train and predict.** The split is stratified by `SEGMENT` so each segment's risk distribution carries through train/val/test. The GNN trains as a regression head evaluated with RMSE, then scores the held-out test subscribers; predictions bind back as `Subscriber.predictions`, and a rule publishes each one on its own `ChurnRiskPrediction` concept for downstream queries. -**5. Top-N per segment.** A query joins the published predicted risk to subscriber metadata, and the report ranks it within each segment (ties by subscriber ID), surfacing the highest-predicted-risk subscribers a retention team should act on first. +**5. Top-N per segment.** A rule links each published prediction to its subscriber and ranks it within the subscriber's segment (ties by subscriber ID), and the report prints the first N of each segment: the highest-predicted-risk subscribers a retention team should act on first. -For the implementation, see `model/reasoning.py` and `queries/churn_report.py`; to reproduce it step by step with the RAI skills, follow `runbook.md`. +For the implementation, see `model/call_signals.py`, `model/churn_predictor.py`, `model/prediction_summary.py`, and `queries/churn_report.py`; to reproduce it step by step with the RAI skills, follow `runbook.md`. ## Customize this template @@ -316,7 +319,7 @@ For the implementation, see `model/reasoning.py` and `queries/churn_report.py`; - **Switch to binary churn classification** — change `task_type="regression"` → `"binary_classification"` and set the train/val target to a Boolean churn outcome instead of a continuous risk score. The graph + rules stages stay identical. - **Add weights to the call graph** — set `weighted=True` on the `Graph(...)` call and add an aggregated edge-weight property (e.g. total call-duration or call-count per pair). The PageRank scores will reflect call intensity, not just topology. -- **Bring more features in** — the bundled `billing_events.csv` is not used by the default pipeline. To wire it in as a billing-driven feature, declare a `BillingEvent` concept in `model/schema.py`, load it in `model/source.py`, derive a `Subscriber.late_payment_count` rule from `PAYMENT_STATUS = "OVERDUE"` in `model/reasoning.py`, then add it to the integer features in `PropertyTransformer`: +- **Bring more features in** — the bundled `billing_events.csv` is not used by the default pipeline. To wire it in as a billing-driven feature, declare a `BillingEvent` concept in `model/schema.py`, load it in `model/source.py`, derive a `Subscriber.late_payment_count` rule from `PAYMENT_STATUS = "OVERDUE"` in a new `model/billing_signals.py` that `model/churn_predictor.py` imports as it imports `call_signals.py`, then add it to the integer features in `PropertyTransformer`: ```python billing_df = pd.read_csv(DATA_DIR / "billing_events.csv") diff --git a/subscriber_retention/model/__init__.py b/subscriber_retention/model/__init__.py index a2649f51..14ef1db6 100644 --- a/subscriber_retention/model/__init__.py +++ b/subscriber_retention/model/__init__.py @@ -1,20 +1,35 @@ """Subscriber-retention model: telco call data, PageRank and call-volume features, and a churn-risk GNN. -`rai models deploy --path model` deploys everything this package declares. +`rai models deploy --path model` deploys everything this package declares. The model is split by +stage, and each module imports the modules whose declarations it reads: + +- `call_signals.py`: the call graph, PageRank, and the call-volume features. +- `churn_predictor.py`: the churn-risk GNN and the predicted risk it publishes. +- `data_profile.py`: the data and split counts and the churn-risk score range. +- `prediction_summary.py`: each prediction's rank within its segment, the scored subscribers per + segment, and the root mean squared error. """ -from .reasoning import ChurnRiskPrediction, gnn +from .call_signals import call_graph +from .churn_predictor import ChurnRiskPrediction, gnn +from .data_profile import ChurnRiskRange, DataCounts +from .prediction_summary import ScoredPerSegment, TestRmse from .schema import Call, Subscriber, TestTable, TrainTable, ValTable, model from .source import DATA_DIR __all__ = [ "Call", "ChurnRiskPrediction", + "ChurnRiskRange", "DATA_DIR", + "DataCounts", + "ScoredPerSegment", "Subscriber", + "TestRmse", "TestTable", "TrainTable", "ValTable", + "call_graph", "gnn", "model", ] diff --git a/subscriber_retention/model/call_signals.py b/subscriber_retention/model/call_signals.py new file mode 100644 index 00000000..78c01bfb --- /dev/null +++ b/subscriber_retention/model/call_signals.py @@ -0,0 +1,57 @@ +"""Call signals for the churn-risk model: the call graph, each subscriber's PageRank, and each +subscriber's counts of outgoing and incoming calls.""" + +from relationalai.semantics import Float, Integer, count +from relationalai.semantics.reasoners.graph import Graph + +# Loads Call and Subscriber from the CSVs, declaring the call and subscriber columns read here. +from . import source # noqa: F401 +from .schema import Call, Subscriber, model + +# -------------------------------------------------- +# Graph: PageRank on the call graph +# -------------------------------------------------- +# Build a directed Subscriber -> Subscriber graph with one edge per call. +# PageRank scores act as a "social influence" continuous feature. + +call_graph = Graph( + model, + name="call_graph", + directed=True, + weighted=False, + node_concept=Subscriber, + aggregator="sum", +) +caller = Subscriber.ref() +callee = Subscriber.ref() +call_ref = Call.ref() +model.define(call_graph.Edge.new(src=caller, dst=callee)).where( + call_ref.caller_sub_id == caller.sub_id, + call_ref.callee_sub_id == callee.sub_id, +) + +pagerank_rel = call_graph.pagerank() +Subscriber.pagerank = model.Property(f"{Subscriber} has {Float:pagerank}") +sub_pr = Subscriber.ref() +score_pr = Float.ref() +model.define(sub_pr.pagerank(score_pr)).where(pagerank_rel(sub_pr, score_pr)) + +# -------------------------------------------------- +# Call-volume features (count-based rules) +# -------------------------------------------------- +# count(Call).per(Subscriber) aggregates derive integer features alongside +# the PageRank score. + +Subscriber.outgoing_calls = model.Property( + f"{Subscriber} has {Integer:outgoing_calls}" +) +model.define( + Subscriber.outgoing_calls(count(Call).per(Subscriber)) +).where(Call.caller_sub_id == Subscriber.sub_id) + +Subscriber.incoming_calls = model.Property( + f"{Subscriber} has {Integer:incoming_calls}" +) +model.define( + Subscriber.incoming_calls(count(Call).per(Subscriber)) +).where(Call.callee_sub_id == Subscriber.sub_id) diff --git a/subscriber_retention/model/reasoning.py b/subscriber_retention/model/churn_predictor.py similarity index 58% rename from subscriber_retention/model/reasoning.py rename to subscriber_retention/model/churn_predictor.py index f160e5a9..6eba5e47 100644 --- a/subscriber_retention/model/reasoning.py +++ b/subscriber_retention/model/churn_predictor.py @@ -1,62 +1,16 @@ -"""The call graph and its PageRank, the call-volume features, and the churn-risk GNN.""" +"""Churn-risk predictor: the GNN that scores each test subscriber's churn risk, and the predicted +risk it publishes.""" -from relationalai.semantics import Float, Integer, String, count -from relationalai.semantics.reasoners.graph import Graph +from relationalai.semantics import Float, String from relationalai.semantics.reasoners.predictive import GNN, PropertyTransformer -from .schema import Call, Subscriber, Test, Train, Val, model +# Declares Subscriber.pagerank, outgoing_calls and incoming_calls, the GNN's rule-derived features. +from .call_signals import call_graph +from .schema import Subscriber, Test, Train, Val, model from .source import SEED STREAM_LOGS = False -# -------------------------------------------------- -# Graph: PageRank on the call graph -# -------------------------------------------------- -# Build a directed Subscriber -> Subscriber graph with one edge per call. -# PageRank scores act as a "social influence" continuous feature. - -call_graph = Graph( - model, - name="call_graph", - directed=True, - weighted=False, - node_concept=Subscriber, - aggregator="sum", -) -caller = Subscriber.ref() -callee = Subscriber.ref() -call_ref = Call.ref() -model.define(call_graph.Edge.new(src=caller, dst=callee)).where( - call_ref.caller_sub_id == caller.sub_id, - call_ref.callee_sub_id == callee.sub_id, -) - -pagerank_rel = call_graph.pagerank() -Subscriber.pagerank = model.Property(f"{Subscriber} has {Float:pagerank}") -sub_pr = Subscriber.ref() -score_pr = Float.ref() -model.define(sub_pr.pagerank(score_pr)).where(pagerank_rel(sub_pr, score_pr)) - -# -------------------------------------------------- -# Call-volume features (count-based rules) -# -------------------------------------------------- -# count(Call).per(Subscriber) aggregates derive integer features alongside -# the PageRank score. - -Subscriber.outgoing_calls = model.Property( - f"{Subscriber} has {Integer:outgoing_calls}" -) -model.define( - Subscriber.outgoing_calls(count(Call).per(Subscriber)) -).where(Call.caller_sub_id == Subscriber.sub_id) - -Subscriber.incoming_calls = model.Property( - f"{Subscriber} has {Integer:incoming_calls}" -) -model.define( - Subscriber.incoming_calls(count(Call).per(Subscriber)) -).where(Call.callee_sub_id == Subscriber.sub_id) - # -------------------------------------------------- # PropertyTransformer -- declare feature types # -------------------------------------------------- @@ -122,8 +76,10 @@ ChurnRiskPrediction.predicted_risk = model.Property( f"{ChurnRiskPrediction} has predicted churn risk {Float:predicted_risk}" ) +ChurnRiskPrediction.subscriber = model.Property(f"{ChurnRiskPrediction} is for {Subscriber}") predicted_risk = Float.ref() model.where(Subscriber.predictions.predicted_value(predicted_risk)).define( prediction := ChurnRiskPrediction.new(sub_id=Subscriber.sub_id), prediction.predicted_risk(predicted_risk), + prediction.subscriber(Subscriber), ) diff --git a/subscriber_retention/model/data_profile.py b/subscriber_retention/model/data_profile.py new file mode 100644 index 00000000..a7e5376f --- /dev/null +++ b/subscriber_retention/model/data_profile.py @@ -0,0 +1,36 @@ +"""Data profile: how many subscribers, calls, and split subscribers the model holds, and the range of +the churn-risk scores.""" + +from relationalai.semantics import Float, Integer +from relationalai.semantics.std import aggregates as aggs + +# Loads the subscribers, calls, and split tables, declaring Subscriber.churn_risk_score. +from . import source # noqa: F401 +from .schema import Call, Subscriber, TestTable, TrainTable, ValTable, model + +# The size of each loaded table and of the three split tables. +DataCounts = model.Relationship( + f"the data has {Integer:subscribers} subscribers, {Integer:calls} calls, and splits of " + f"{Integer:train} training, {Integer:val} validation, and {Integer:test} test subscribers" +) +model.define( + DataCounts( + aggs.count(Subscriber), + aggs.count(Call), + aggs.count(TrainTable), + aggs.count(ValTable), + aggs.count(TestTable), + ) +) + +# The churn-risk score range over the subscribers that have a score. +ChurnRiskRange = model.Relationship( + f"churn risk scores have minimum {Float:minimum}, mean {Float:mean}, and maximum {Float:maximum}" +) +model.define( + ChurnRiskRange( + aggs.min(Subscriber.churn_risk_score), + aggs.avg(Subscriber, Subscriber.churn_risk_score), + aggs.max(Subscriber.churn_risk_score), + ) +) diff --git a/subscriber_retention/model/prediction_summary.py b/subscriber_retention/model/prediction_summary.py new file mode 100644 index 00000000..10145d8e --- /dev/null +++ b/subscriber_retention/model/prediction_summary.py @@ -0,0 +1,33 @@ +"""Prediction summary: each scored subscriber's rank by predicted risk within its segment, the scored +subscribers per segment, and the root mean squared error of the predictions.""" + +from relationalai.semantics import Float, Integer, String +from relationalai.semantics.std import aggregates as aggs +from relationalai.semantics.std import math + +from .churn_predictor import ChurnRiskPrediction +from .schema import model + +# The retention queue order within a segment: highest predicted risk first, ties broken by the +# lower subscriber id. The risk is negated so both keys sort ascending, a form every backend ranks. +ChurnRiskPrediction.segment_rank = model.Property( + f"{ChurnRiskPrediction} has {Integer:segment_rank} in its segment" +) +segment = String.ref() +model.where( + ChurnRiskPrediction.subscriber.segment == segment, + segment_rank := aggs.rank(-ChurnRiskPrediction.predicted_risk, ChurnRiskPrediction.sub_id).per(segment), +).define(ChurnRiskPrediction.segment_rank(segment_rank)) + +# The number of scored subscribers in each segment. +ScoredPerSegment = model.Relationship(f"segment {String:segment} has {Integer:n_scored} scored subscribers") +model.where(ChurnRiskPrediction.subscriber.segment == segment).define( + ScoredPerSegment(segment, aggs.count(ChurnRiskPrediction).per(segment)) +) + +# The root mean squared error of the predicted risk against the subscribers' actual risk score. +TestRmse = model.Relationship(f"the predicted churn risk has a root mean squared error of {Float:rmse}") +error = ChurnRiskPrediction.predicted_risk - ChurnRiskPrediction.subscriber.churn_risk_score +model.where(mean_squared_error := aggs.avg(ChurnRiskPrediction, error * error)).define( + TestRmse(math.sqrt(mean_squared_error)) +) diff --git a/subscriber_retention/model/schema.py b/subscriber_retention/model/schema.py index 701bc30d..4d0abfec 100644 --- a/subscriber_retention/model/schema.py +++ b/subscriber_retention/model/schema.py @@ -1,12 +1,18 @@ """Semantic schema for subscriber retention: subscribers, calls, and the churn-risk task.""" -from relationalai.semantics import Float, Model, String +from relationalai.semantics import Boolean, Float, Integer, Model, String model = Model("subscriber_retention") -Concept, Relationship = model.Concept, model.Relationship +Concept, Property, Relationship = model.Concept, model.Property, model.Relationship # Subscriber concept: one row per subscriber with denormalized plan attrs. Subscriber = Concept("Subscriber", identify_by={"sub_id": String}) +Subscriber.plan_type = Property(f"{Subscriber} has {String:plan_type}") +Subscriber.monthly_rate_usd = Property(f"{Subscriber} has {Float:monthly_rate_usd}") +Subscriber.data_limit_gb = Property(f"{Subscriber} has {Integer:data_limit_gb}") +Subscriber.term_months = Property(f"{Subscriber} has {Integer:term_months}") +Subscriber.auto_renew = Property(f"{Subscriber} has {Boolean:auto_renew}") +Subscriber.early_termination_fee_usd = Property(f"{Subscriber} has {Integer:early_termination_fee_usd}") # Call concept: edge-intermediary for the Subscriber -> Subscriber call # graph. No identify_by (the CDR_ID is irrelevant downstream); the edges are diff --git a/subscriber_retention/model/source.py b/subscriber_retention/model/source.py index d3499cde..d678fcc7 100644 --- a/subscriber_retention/model/source.py +++ b/subscriber_retention/model/source.py @@ -24,11 +24,19 @@ VAL_FRAC = 0.15 # TEST_FRAC = 0.15 (remainder) -# Load and denormalize source data into a single Subscriber feature table. +# Load the subscribers, their plan contracts, and the calls. sub_df = pd.read_csv(DATA_DIR / "subscribers.csv", parse_dates=["SIGNUP_DATE"]) plan_df = pd.read_csv( DATA_DIR / "plans_contracts.csv", - parse_dates=["CONTRACT_START_DATE", "CONTRACT_END_DATE"], + usecols=[ + "SUB_ID", + "PLAN_TYPE", + "MONTHLY_RATE_USD", + "DATA_LIMIT_GB", + "TERM_MONTHS", + "AUTO_RENEW", + "EARLY_TERMINATION_FEE_USD", + ], ) calls_df = pd.read_csv( DATA_DIR / "call_detail_records.csv", parse_dates=["CALL_START_TIME"] @@ -40,31 +48,29 @@ columns=["FIRST_NAME", "LAST_NAME", "EMAIL", "PHONE"], errors="ignore" ) -# Each subscriber has exactly one active contract; left-join plan attrs onto -# the subscriber row (1:1 denormalization). -plan_keep = plan_df[ - [ - "SUB_ID", - "PLAN_TYPE", - "MONTHLY_RATE_USD", - "DATA_LIMIT_GB", - "TERM_MONTHS", - "AUTO_RENEW", - "EARLY_TERMINATION_FEE_USD", - ] -] -features_df = sub_df.merge(plan_keep, on="SUB_ID", how="left") - -model.define(Subscriber.new(model.data(features_df).to_schema())) +model.define(Subscriber.new(model.data(sub_df).to_schema())) model.define(Call.new(model.data(calls_df).to_schema())) +# Each subscriber has exactly one active contract (1:1 denormalization): bind its plan +# attributes onto the subscriber. A subscriber without a contract has no plan attributes. +plan_data = model.data(plan_df) +model.where(Subscriber.sub_id == plan_data.SUB_ID).define( + Subscriber.plan_type(plan_data.PLAN_TYPE), + Subscriber.monthly_rate_usd(plan_data.MONTHLY_RATE_USD), + Subscriber.data_limit_gb(plan_data.DATA_LIMIT_GB), + Subscriber.term_months(plan_data.TERM_MONTHS), + Subscriber.auto_renew(plan_data.AUTO_RENEW), + Subscriber.early_termination_fee_usd(plan_data.EARLY_TERMINATION_FEE_USD), +) + # -------------------------------------------------- # Train / Val / Test split # -------------------------------------------------- # Build train/val/test splits in pandas. Stratified by segment so each split -# preserves the segment mix; CHURN_RISK_SCORE distribution carries through. +# preserves the segment mix; CHURN_RISK_SCORE distribution carries through. The shuffle and +# the per-segment permutation are seeded, and PyRel has no seeded random primitive. rng = np.random.default_rng(SEED) -shuffled = features_df.sample(frac=1.0, random_state=SEED).reset_index(drop=True) +shuffled = sub_df.sample(frac=1.0, random_state=SEED).reset_index(drop=True) # Stratify split by segment to keep distribution stable across splits. train_idx, val_idx, test_idx = [], [], [] diff --git a/subscriber_retention/queries/churn_report.py b/subscriber_retention/queries/churn_report.py index eb96ee85..b25c48e4 100644 --- a/subscriber_retention/queries/churn_report.py +++ b/subscriber_retention/queries/churn_report.py @@ -8,39 +8,47 @@ """ from model import ( - Call, ChurnRiskPrediction, - Subscriber, - TestTable, - TrainTable, - ValTable, + ChurnRiskRange, + DataCounts, + ScoredPerSegment, + TestRmse, model, ) -from relationalai.semantics import count, select +from relationalai.semantics import Float, Integer, String TOP_N_PER_SEGMENT = 5 def main() -> None: + subscribers, calls, train, val, test = (Integer.ref() for _ in range(5)) counts = ( - select( - count(Subscriber).alias("subscribers"), - count(Call).alias("calls"), - count(TrainTable).alias("train"), - count(ValTable).alias("val"), - count(TestTable).alias("test"), + model.where(DataCounts(subscribers, calls, train, val, test)) + .select( + subscribers.alias("subscribers"), + calls.alias("calls"), + train.alias("train"), + val.alias("val"), + test.alias("test"), ) .to_df() .iloc[0] ) - risk = select(Subscriber.sub_id, Subscriber.churn_risk_score).to_df()["churn_risk_score"] - print(f"Subscribers: {counts['subscribers']} Calls: {counts['calls']}") + lowest, mean, highest = (Float.ref() for _ in range(3)) + risk = ( + model.where(ChurnRiskRange(lowest, mean, highest)) + .select(lowest.alias("min"), mean.alias("mean"), highest.alias("max")) + .to_df() + .iloc[0] + ) + print(f"Subscribers: {int(counts['subscribers'])} Calls: {int(counts['calls'])}") print( - f"Splits: train={counts['train']} val={counts['val']} test={counts['test']}" + f"Splits: train={int(counts['train'])} val={int(counts['val'])} test={int(counts['test'])}" " (stratified by SEGMENT)" ) print( - f"CHURN_RISK_SCORE: min={risk.min():.2f} mean={risk.mean():.2f} max={risk.max():.2f}" + f"CHURN_RISK_SCORE: min={float(risk['min']):.2f} mean={float(risk['mean']):.2f}" + f" max={float(risk['max']):.2f}" ) print("\n" + "=" * 60) @@ -48,14 +56,15 @@ def main() -> None: print("=" * 60) results_df = ( - model.where(ChurnRiskPrediction.sub_id == Subscriber.sub_id) + model.where(ChurnRiskPrediction.segment_rank <= TOP_N_PER_SEGMENT) .select( - Subscriber.sub_id.alias("sub_id"), - Subscriber.segment.alias("segment"), - Subscriber.subscriber_type.alias("type"), - Subscriber.lifetime_value_usd.alias("lifetime_value"), - Subscriber.churn_risk_score.alias("actual_risk"), + ChurnRiskPrediction.sub_id.alias("sub_id"), + ChurnRiskPrediction.subscriber.segment.alias("segment"), + ChurnRiskPrediction.subscriber.subscriber_type.alias("type"), + ChurnRiskPrediction.subscriber.lifetime_value_usd.alias("lifetime_value"), + ChurnRiskPrediction.subscriber.churn_risk_score.alias("actual_risk"), ChurnRiskPrediction.predicted_risk.alias("predicted_risk"), + ChurnRiskPrediction.segment_rank.alias("segment_rank"), ) .to_df() ) @@ -65,16 +74,23 @@ def main() -> None: else: results_df["predicted_risk"] = results_df["predicted_risk"].astype(float) results_df["actual_risk"] = results_df["actual_risk"].astype(float) - for seg, group in results_df.groupby("segment"): - top = group.sort_values( - ["predicted_risk", "sub_id"], ascending=[False, True] - ).head(TOP_N_PER_SEGMENT) - print(f"\n[{seg}] ({len(group)} test subscribers)") + segment, n_scored = String.ref(), Integer.ref() + scored = ( + model.where(ScoredPerSegment(segment, n_scored)) + .select(segment.alias("segment"), n_scored.alias("n_scored")) + .to_df() + .sort_values("segment") + ) + for seg, n in zip(scored["segment"], scored["n_scored"]): + top = ( + results_df[results_df["segment"] == seg] + .sort_values("segment_rank") + .drop(columns="segment_rank") + ) + print(f"\n[{seg}] ({int(n)} test subscribers)") print(top.to_string(index=False)) - rmse = float( - ((results_df["predicted_risk"] - results_df["actual_risk"]) ** 2).mean() ** 0.5 - ) + rmse = float(model.select(TestRmse).to_df().iloc[0, 0]) print(f"\nTest-set RMSE: {rmse:.4f}") diff --git a/supplier_reliability/README.md b/supplier_reliability/README.md index aa693141..20d1e9e1 100644 --- a/supplier_reliability/README.md +++ b/supplier_reliability/README.md @@ -37,7 +37,7 @@ This template answers all of those in one place: it finds the cost-minimizing so ## What's included -- `model/` -- the deployed model package, deployed with `rai models deploy --path model`: `schema.py` declares the `Supplier`, `Product`, `SupplyOption`, and `SupplyOrder` concepts, `source.py` loads the sample data, `reasoning.py` states the baseline sourcing problem with its sensitivity analysis and the disruption-scenario problems +- `model/` -- the deployed model package, deployed with `rai models deploy --path model`: `schema.py` declares the `Supplier`, `Product`, `SupplyOption`, and `SupplyOrder` concepts, `source.py` loads the sample data, `sourcing_plan.py` states the baseline sourcing problem with its sensitivity analysis, `plan_marginals.py` publishes the reduced costs, basis statuses, shadow prices, and the capacity ranking, and `disruption_scenarios.py` states the disruption-scenario problems - `queries/sourcing_report.py` -- the report from the deployed model: baseline plan, capacity and demand shadow prices, lane reduced costs and basis status, an order plan per scenario, and a scenario summary - **Runbook**: `runbook.md` -- a paste-testable walkthrough that reproduces the template step by step with the RAI skills; as important a reference as the code itself. - **Sample data**: three CSVs under `data/` describing suppliers, products, and per-supplier-product supply options. See *Sample data* below. @@ -282,7 +282,9 @@ Use this sequence to deploy the model and query it: │ ├── __init__.py # exports of the deployed model │ ├── schema.py # concepts and properties │ ├── source.py # sample data load -│ └── reasoning.py # baseline sensitivity solve, disruption scenarios, and their published status and objective +│ ├── sourcing_plan.py # baseline sensitivity solve and its published status, cost, and orders +│ ├── plan_marginals.py # published reduced costs, basis statuses, shadow prices, and capacity ranking +│ └── disruption_scenarios.py # disruption scenarios and their published status, cost, and orders ├── queries/ │ └── sourcing_report.py # baseline plan, marginals, and scenario report from the deployed model └── data/ @@ -336,7 +338,7 @@ Because each constraint carries an entity back-pointer, a marginal joins to that **5. Scenario analysis.** Each disruption scenario is a separate, named Problem that excludes one supplier via a filter on the decision variable and has its own solve, so one infeasible scenario leaves the others unaffected. This is a finite, structural change the marginals contextualize but do not by themselves predict -- removing all of a supplier's capacity can move cost further than the local shadow price suggests. -For the implementation, see `model/reasoning.py` and `queries/sourcing_report.py`; to reproduce it step by step with the RAI skills, follow `runbook.md`. +For the implementation, see `model/sourcing_plan.py`, `model/plan_marginals.py`, `model/disruption_scenarios.py`, and `queries/sourcing_report.py`; to reproduce it step by step with the RAI skills, follow `runbook.md`. ## Customize this template @@ -352,7 +354,7 @@ Focus on the first changes most users will make. - **Capacity and demand** -- edit `capacity` in `suppliers.csv` and `demand` in `products.csv` to change where the bottleneck lands; the shadow prices track which constraint binds. The report's marginal checks name the bundled suppliers (SupplierA and SupplierD priced out, SupplierC binding), so update them in `queries/sourcing_report.py` when the bottleneck moves. - **Costs** -- adjust `cost_per_unit` in `supply_options.csv` to shift the optimal sourcing mix and the reduced costs of unused lanes. -- **Scenarios** -- edit `EXCLUDED_SUPPLIERS` in `model/reasoning.py` to test different disruptions. +- **Scenarios** -- edit `EXCLUDED_SUPPLIERS` in `model/disruption_scenarios.py` to test different disruptions. ### Extend the model diff --git a/supplier_reliability/model/__init__.py b/supplier_reliability/model/__init__.py index be93a404..7dc864c1 100644 --- a/supplier_reliability/model/__init__.py +++ b/supplier_reliability/model/__init__.py @@ -39,6 +39,14 @@ separate Problem with a where= filter -- a FINITE structural change the local marginals contextualize but do not by themselves predict. +The model is split by stage, and each module imports the modules whose declarations it reads: + +- `sourcing_plan.py`: Phase A's baseline sourcing LP, its solve with sensitivity analysis, and the + published status, total cost, and order quantities. +- `plan_marginals.py`: the lane reduced costs and basis statuses, the capacity and demand shadow + prices, and the ranking of the capacities by shadow price magnitude. +- `disruption_scenarios.py`: Phase B's supplier-exclusion problems and their published results. + Run: `rai models deploy --path model` deploys this package to the schemas in raiconfig.yaml and waits for its first refresh, which runs all three solves. Then @@ -48,19 +56,17 @@ deployed model. """ -from .reasoning import ( - EXCLUDED_SUPPLIERS, - BaselineCost, - BaselineOrder, - BaselineStatus, +from .disruption_scenarios import EXCLUDED_SUPPLIERS, scenarios +from .plan_marginals import ( + CapacityPriceRank, CapacityShadowPrice, DemandShadowPrice, LaneBasisStatus, LaneReducedCost, - scenarios, ) from .schema import Product, Supplier, SupplyOption, SupplyOrder, model from .source import DATA_DIR +from .sourcing_plan import BaselineCost, BaselineOrder, BaselineStatus __all__ = [ "DATA_DIR", @@ -68,6 +74,7 @@ "BaselineCost", "BaselineOrder", "BaselineStatus", + "CapacityPriceRank", "CapacityShadowPrice", "DemandShadowPrice", "LaneBasisStatus", diff --git a/supplier_reliability/model/disruption_scenarios.py b/supplier_reliability/model/disruption_scenarios.py new file mode 100644 index 00000000..b37e5258 --- /dev/null +++ b/supplier_reliability/model/disruption_scenarios.py @@ -0,0 +1,74 @@ +"""Disruption scenarios: one sourcing problem per excluded supplier, with each scenario's published +solve status, total cost, and order quantity of each supply lane.""" + +from relationalai.semantics import Float, String, sum +from relationalai.semantics.reasoners.prescriptive import Problem + +# Declares SupplyOrder.x_quantity and the supplier, product, and unit cost of each order. +from . import sourcing_plan # noqa: F401 +from .schema import Product, Supplier, SupplyOrder, model + +# -------------------------------------------------- +# Phase B -- disruption scenarios (separate solves) +# -------------------------------------------------- +# Each scenario is its own Problem with a where= filter excluding one supplier -- a +# FINITE structural change (a supplier fully removed). A shadow price is a marginal at +# the current optimum, not an exclusion-impact ranking, so these re-solves are +# CONSISTENT WITH Phase A (SupplierC, the most valuable capacity, hurts most when +# excluded) without being predicted by the duals alone. One infeasible scenario leaves the +# others unaffected. + +EXCLUDED_SUPPLIERS = ["SupplierC", "SupplierB"] + + +def build_scenario(excluded): + """Build, configure, and publish the results of the scenario that excludes one supplier.""" + name = f"supplier_reliability_without_{excluded.lower()}" + problem = Problem(model, Float, name=name) + + # Exclude one supplier via where=; populate=False leaves SupplyOrder.x_quantity + # untouched so the Problems do not write the same property. + qty_scn = problem.solve_for( + SupplyOrder.x_quantity, + name=["qty", SupplyOrder.supplier.name, SupplyOrder.product.name], + lower=0, + where=[SupplyOrder.supplier.name != excluded], + populate=False, + ) + + # Capacity and demand over the remaining suppliers' orders: the excluded one's + # orders have no variables. + problem.satisfy( + model.where(SupplyOrder.supplier == Supplier, Supplier.name != excluded).require( + sum(SupplyOrder.x_quantity) + .where(SupplyOrder.supplier == Supplier) + .per(Supplier) + <= Supplier.capacity + ) + ) + problem.satisfy( + model.where(SupplyOrder.product == Product, SupplyOrder.supplier.name != excluded).require( + sum(SupplyOrder.x_quantity) + .where(SupplyOrder.product == Product) + .per(Product) + >= Product.demand + ) + ) + problem.minimize(sum(SupplyOrder.x_quantity * SupplyOrder.cost_per_unit)) + + # Each refresh of the deployed model runs this solve. + problem.configure("highs", time_limit_sec=60) + + # The solve's status and objective, which the deployed model publishes for the queries. + status = model.Relationship(f"{name} solve status is {String:status}") + cost = model.Relationship(f"{name} total cost is {Float:cost}") + model.define(status(problem.termination_status()), cost(problem.objective_value())) + + # The solved order quantity of each supply lane, which the deployed model publishes for the queries. + amount = Float.ref() + orders = model.Relationship(f"{name} orders {SupplyOrder} in quantity {Float:quantity}") + model.where(qty_scn.values(0, amount)).define(orders(qty_scn.supplyorder, amount)) + return status, cost, orders + + +scenarios = {excluded: build_scenario(excluded) for excluded in EXCLUDED_SUPPLIERS} diff --git a/supplier_reliability/model/plan_marginals.py b/supplier_reliability/model/plan_marginals.py new file mode 100644 index 00000000..e27a4678 --- /dev/null +++ b/supplier_reliability/model/plan_marginals.py @@ -0,0 +1,33 @@ +"""Plan marginals: each lane's reduced cost and basis status, each capacity's and demand's shadow +price, and the ranking of the supplier capacities by shadow price magnitude.""" + +from relationalai.semantics import Float, Integer, String +from relationalai.semantics.std import aggregates as aggs +from relationalai.semantics.std import math + +from .schema import Product, Supplier, SupplyOrder, model +from .sourcing_plan import cap, meet, qty_var + +# The sensitivity marginals, which the deployed model publishes for the queries: each lane's +# reduced cost and basis status, and each capacity's and demand's shadow price, keyed by the +# entity they belong to. +lane_reduced_cost, lane_basis, capacity_price, demand_price = Float.ref(), String.ref(), Float.ref(), Float.ref() +LaneReducedCost = model.Relationship(f"supplier_reliability_baseline {SupplyOrder} has reduced cost {Float:reduced_cost}") +LaneBasisStatus = model.Relationship(f"supplier_reliability_baseline {SupplyOrder} has basis status {String:basis_status}") +CapacityShadowPrice = model.Relationship(f"supplier_reliability_baseline {Supplier} has capacity shadow price {Float:shadow_price}") +DemandShadowPrice = model.Relationship(f"supplier_reliability_baseline {Product} has demand shadow price {Float:shadow_price}") +model.where(qty_var.reduced_cost(lane_reduced_cost)).define(LaneReducedCost(qty_var.supplyorder, lane_reduced_cost)) +model.where(qty_var.basis_status(lane_basis)).define(LaneBasisStatus(qty_var.supplyorder, lane_basis)) +model.where(cap.shadow_price(capacity_price)).define(CapacityShadowPrice(cap.supplier, capacity_price)) +model.where(meet.shadow_price(demand_price)).define(DemandShadowPrice(meet.product, demand_price)) + +# The supplier capacities ranked by the magnitude of their shadow price, largest first, ties +# broken by supplier name. The first is the capacity whose marginal unit moves the bill the +# most. The magnitude is negated so both keys sort ascending, a form every backend ranks. +CapacityPriceRank = model.Relationship( + f"supplier_reliability_baseline {Supplier} ranks {Integer:rank} by capacity shadow price magnitude" +) +model.where( + CapacityShadowPrice(Supplier, capacity_price), + capacity_rank := aggs.rank(-math.abs(capacity_price), Supplier.name), +).define(CapacityPriceRank(Supplier, capacity_rank)) diff --git a/supplier_reliability/model/reasoning.py b/supplier_reliability/model/reasoning.py deleted file mode 100644 index 8b871606..00000000 --- a/supplier_reliability/model/reasoning.py +++ /dev/null @@ -1,150 +0,0 @@ -"""Supplier reliability decision problems: a baseline sourcing plan with sensitivity, and supplier-disruption scenarios.""" - -from relationalai.semantics import Float, String, sum -from relationalai.semantics.reasoners.prescriptive import Problem - -from .schema import Product, Supplier, SupplyOption, SupplyOrder, model - -# -------------------------------------------------- -# Model the decision problem -# -------------------------------------------------- - -# Decision variable: units ordered through each supply option. -SupplyOrder.x_quantity = model.Property(f"{SupplyOrder} has {Float:quantity}") -model.define(SupplyOrder.new(option=SupplyOption)) - -model.define(SupplyOrder.supplier(Supplier)).where(SupplyOrder.option(SupplyOption), SupplyOption.supplier(Supplier)) -model.define(SupplyOrder.product(Product)).where(SupplyOrder.option(SupplyOption), SupplyOption.product(Product)) -model.define(SupplyOrder.cost_per_unit(SupplyOption.cost_per_unit)).where(SupplyOrder.option(SupplyOption)) - -# -------------------------------------------------- -# Phase A -- baseline solve with sensitivity analysis -# -------------------------------------------------- -# The marginals are read off this baseline Problem's captured variable and constraint -# handles. The disruption scenarios below are separate Problems with their own variables. - -baseline = Problem(model, Float, name="supplier_reliability_baseline") - -# Variable: order quantity per supply lane (continuous, non-negative). -qty_var = baseline.solve_for( - SupplyOrder.x_quantity, - name=["qty", SupplyOrder.supplier.name, SupplyOrder.product.name], - lower=0, - populate=False, -) - -# Constraints, captured as handles. ``keyed_by`` declares each instance's ENTITY KEY, -# so its marginal reads back through that key (cap.supplier / meet.product), never by -# parsing the constraint name string; the per-entity name is a readable label. -cap = baseline.satisfy( - model.where(SupplyOrder.supplier == Supplier).require( - sum(SupplyOrder.x_quantity) - .where(SupplyOrder.supplier == Supplier) - .per(Supplier) - <= Supplier.capacity - ), - name=["cap", Supplier.name], - keyed_by={"supplier": Supplier}, -) -meet = baseline.satisfy( - model.where(SupplyOrder.product == Product).require( - sum(SupplyOrder.x_quantity).where(SupplyOrder.product == Product).per(Product) - >= Product.demand - ), - name=["demand", Product.name], - keyed_by={"product": Product}, -) - -# Objective: minimize total sourcing cost. -baseline.minimize(sum(SupplyOrder.x_quantity * SupplyOrder.cost_per_unit)) - -# Each refresh of the deployed model runs this solve, with sensitivity analysis. -baseline.configure("highs", time_limit_sec=60, sensitivity=True) - -# The solve's status and objective, which the deployed model publishes for the queries. -BaselineStatus = model.Relationship(f"supplier_reliability_baseline solve status is {String:status}") -BaselineCost = model.Relationship(f"supplier_reliability_baseline total cost is {Float:cost}") -model.define(BaselineStatus(baseline.termination_status()), BaselineCost(baseline.objective_value())) - -# The solved order quantity of each supply lane, which the deployed model publishes for the queries. -baseline_amount = Float.ref() -BaselineOrder = model.Relationship(f"supplier_reliability_baseline orders {SupplyOrder} in quantity {Float:quantity}") -model.where(qty_var.values(0, baseline_amount)).define(BaselineOrder(qty_var.supplyorder, baseline_amount)) - -# The sensitivity marginals, which the deployed model publishes for the queries: each lane's -# reduced cost and basis status, and each capacity's and demand's shadow price, keyed by the -# entity they belong to. -lane_reduced_cost, lane_basis, capacity_price, demand_price = Float.ref(), String.ref(), Float.ref(), Float.ref() -LaneReducedCost = model.Relationship(f"supplier_reliability_baseline {SupplyOrder} has reduced cost {Float:reduced_cost}") -LaneBasisStatus = model.Relationship(f"supplier_reliability_baseline {SupplyOrder} has basis status {String:basis_status}") -CapacityShadowPrice = model.Relationship(f"supplier_reliability_baseline {Supplier} has capacity shadow price {Float:shadow_price}") -DemandShadowPrice = model.Relationship(f"supplier_reliability_baseline {Product} has demand shadow price {Float:shadow_price}") -model.where(qty_var.reduced_cost(lane_reduced_cost)).define(LaneReducedCost(qty_var.supplyorder, lane_reduced_cost)) -model.where(qty_var.basis_status(lane_basis)).define(LaneBasisStatus(qty_var.supplyorder, lane_basis)) -model.where(cap.shadow_price(capacity_price)).define(CapacityShadowPrice(cap.supplier, capacity_price)) -model.where(meet.shadow_price(demand_price)).define(DemandShadowPrice(meet.product, demand_price)) - -# -------------------------------------------------- -# Phase B -- disruption scenarios (separate solves) -# -------------------------------------------------- -# Each scenario is its own Problem with a where= filter excluding one supplier -- a -# FINITE structural change (a supplier fully removed). A shadow price is a marginal at -# the current optimum, not an exclusion-impact ranking, so these re-solves are -# CONSISTENT WITH Phase A (SupplierC, the most valuable capacity, hurts most when -# excluded) without being predicted by the duals alone. One infeasible scenario leaves the -# others unaffected. - -EXCLUDED_SUPPLIERS = ["SupplierC", "SupplierB"] - - -def build_scenario(excluded): - """Build, configure, and publish the results of the scenario that excludes one supplier.""" - name = f"supplier_reliability_without_{excluded.lower()}" - problem = Problem(model, Float, name=name) - - # Exclude one supplier via where=; populate=False leaves SupplyOrder.x_quantity - # untouched so the Problems do not write the same property. - qty_scn = problem.solve_for( - SupplyOrder.x_quantity, - name=["qty", SupplyOrder.supplier.name, SupplyOrder.product.name], - lower=0, - where=[SupplyOrder.supplier.name != excluded], - populate=False, - ) - - # Capacity and demand over the remaining suppliers' orders: the excluded one's - # orders have no variables. - problem.satisfy( - model.where(SupplyOrder.supplier == Supplier, Supplier.name != excluded).require( - sum(SupplyOrder.x_quantity) - .where(SupplyOrder.supplier == Supplier) - .per(Supplier) - <= Supplier.capacity - ) - ) - problem.satisfy( - model.where(SupplyOrder.product == Product, SupplyOrder.supplier.name != excluded).require( - sum(SupplyOrder.x_quantity) - .where(SupplyOrder.product == Product) - .per(Product) - >= Product.demand - ) - ) - problem.minimize(sum(SupplyOrder.x_quantity * SupplyOrder.cost_per_unit)) - - # Each refresh of the deployed model runs this solve. - problem.configure("highs", time_limit_sec=60) - - # The solve's status and objective, which the deployed model publishes for the queries. - status = model.Relationship(f"{name} solve status is {String:status}") - cost = model.Relationship(f"{name} total cost is {Float:cost}") - model.define(status(problem.termination_status()), cost(problem.objective_value())) - - # The solved order quantity of each supply lane, which the deployed model publishes for the queries. - amount = Float.ref() - orders = model.Relationship(f"{name} orders {SupplyOrder} in quantity {Float:quantity}") - model.where(qty_scn.values(0, amount)).define(orders(qty_scn.supplyorder, amount)) - return status, cost, orders - - -scenarios = {excluded: build_scenario(excluded) for excluded in EXCLUDED_SUPPLIERS} diff --git a/supplier_reliability/model/schema.py b/supplier_reliability/model/schema.py index cd1e5b7c..79c49499 100644 --- a/supplier_reliability/model/schema.py +++ b/supplier_reliability/model/schema.py @@ -7,7 +7,7 @@ # Concept: suppliers with capacity and a reliability score. (reliability is carried as # data only -- it is NOT priced into the cost objective and does NOT drive the hard-coded -# disruption scenarios in `model/reasoning.py`; it is here for you to extend, see "Customize".) +# disruption scenarios in `model/disruption_scenarios.py`; it is here for you to extend, see "Customize".) Supplier = Concept("Supplier", identify_by={"id": Integer}) Supplier.name = Property(f"{Supplier} has {String:name}") Supplier.reliability = Property(f"{Supplier} has {Float:reliability}") @@ -28,7 +28,7 @@ SupplyOrder = Concept("SupplyOrder") SupplyOrder.option = Property(f"{SupplyOrder} uses {SupplyOption}", short_name="option") -# Derived relationships for direct access (avoids multi-hop traversals); `model/reasoning.py` +# Derived relationships for direct access (avoids multi-hop traversals); `model/sourcing_plan.py` # defines them. SupplyOrder.supplier = Property(f"{SupplyOrder} has {Supplier}", short_name="supplier") SupplyOrder.product = Property(f"{SupplyOrder} has {Product}", short_name="product") diff --git a/supplier_reliability/model/sourcing_plan.py b/supplier_reliability/model/sourcing_plan.py new file mode 100644 index 00000000..85905fad --- /dev/null +++ b/supplier_reliability/model/sourcing_plan.py @@ -0,0 +1,73 @@ +"""Sourcing plan: the baseline min-cost sourcing LP, solved with sensitivity analysis, and the +published solve status, total cost, and order quantity of each supply lane.""" + +from relationalai.semantics import Float, String, sum +from relationalai.semantics.reasoners.prescriptive import Problem + +from .schema import Product, Supplier, SupplyOption, SupplyOrder, model + +# -------------------------------------------------- +# Model the decision problem +# -------------------------------------------------- + +# Decision variable: units ordered through each supply option. +SupplyOrder.x_quantity = model.Property(f"{SupplyOrder} has {Float:quantity}") +model.define(SupplyOrder.new(option=SupplyOption)) + +model.define(SupplyOrder.supplier(Supplier)).where(SupplyOrder.option(SupplyOption), SupplyOption.supplier(Supplier)) +model.define(SupplyOrder.product(Product)).where(SupplyOrder.option(SupplyOption), SupplyOption.product(Product)) +model.define(SupplyOrder.cost_per_unit(SupplyOption.cost_per_unit)).where(SupplyOrder.option(SupplyOption)) + +# -------------------------------------------------- +# Phase A -- baseline solve with sensitivity analysis +# -------------------------------------------------- +# The marginals are read off this baseline Problem's captured variable and constraint +# handles. The disruption scenarios are separate Problems with their own variables. + +baseline = Problem(model, Float, name="supplier_reliability_baseline") + +# Variable: order quantity per supply lane (continuous, non-negative). +qty_var = baseline.solve_for( + SupplyOrder.x_quantity, + name=["qty", SupplyOrder.supplier.name, SupplyOrder.product.name], + lower=0, + populate=False, +) + +# Constraints, captured as handles. ``keyed_by`` declares each instance's ENTITY KEY, +# so its marginal reads back through that key (cap.supplier / meet.product), never by +# parsing the constraint name string; the per-entity name is a readable label. +cap = baseline.satisfy( + model.where(SupplyOrder.supplier == Supplier).require( + sum(SupplyOrder.x_quantity) + .where(SupplyOrder.supplier == Supplier) + .per(Supplier) + <= Supplier.capacity + ), + name=["cap", Supplier.name], + keyed_by={"supplier": Supplier}, +) +meet = baseline.satisfy( + model.where(SupplyOrder.product == Product).require( + sum(SupplyOrder.x_quantity).where(SupplyOrder.product == Product).per(Product) + >= Product.demand + ), + name=["demand", Product.name], + keyed_by={"product": Product}, +) + +# Objective: minimize total sourcing cost. +baseline.minimize(sum(SupplyOrder.x_quantity * SupplyOrder.cost_per_unit)) + +# Each refresh of the deployed model runs this solve, with sensitivity analysis. +baseline.configure("highs", time_limit_sec=60, sensitivity=True) + +# The solve's status and objective, which the deployed model publishes for the queries. +BaselineStatus = model.Relationship(f"supplier_reliability_baseline solve status is {String:status}") +BaselineCost = model.Relationship(f"supplier_reliability_baseline total cost is {Float:cost}") +model.define(BaselineStatus(baseline.termination_status()), BaselineCost(baseline.objective_value())) + +# The solved order quantity of each supply lane, which the deployed model publishes for the queries. +baseline_amount = Float.ref() +BaselineOrder = model.Relationship(f"supplier_reliability_baseline orders {SupplyOrder} in quantity {Float:quantity}") +model.where(qty_var.values(0, baseline_amount)).define(BaselineOrder(qty_var.supplyorder, baseline_amount)) diff --git a/supplier_reliability/queries/sourcing_report.py b/supplier_reliability/queries/sourcing_report.py index 8d59c996..3e928395 100644 --- a/supplier_reliability/queries/sourcing_report.py +++ b/supplier_reliability/queries/sourcing_report.py @@ -13,6 +13,7 @@ BaselineCost, BaselineOrder, BaselineStatus, + CapacityPriceRank, CapacityShadowPrice, DemandShadowPrice, LaneBasisStatus, @@ -23,7 +24,7 @@ model, scenarios, ) -from relationalai.semantics import Float, String +from relationalai.semantics import Float, Integer, String def solve_result(status_rel, cost_rel): @@ -154,13 +155,22 @@ def solve_result(status_rel, cost_rel): # --- Acting on it: which supplier capacity is the bottleneck? ------------------- # The largest-magnitude capacity shadow price is the capacity whose marginal unit - # moves the bill the most -- the supplier to expand (or protect) first. - bottleneck = max( - zip(cap_sp_df["supplier"], cap_sp_df["shadow_price"]), - key=lambda sp: abs(sp[1]), + # moves the bill the most -- the supplier to expand (or protect) first. The model ranks + # the capacities by that magnitude; the bottleneck is the first. + price_rank = Integer.ref() + bottleneck = ( + model.select(Supplier.name.alias("supplier"), shadow_price.alias("shadow_price")) + .where( + CapacityShadowPrice(Supplier, shadow_price), + CapacityPriceRank(Supplier, price_rank), + price_rank == 1, + ) + .to_df() + .iloc[0] ) print( - f"\nMost cost-sensitive capacity: {bottleneck[0]} (d cost / d capacity = {bottleneck[1]:+.2f})" + f"\nMost cost-sensitive capacity: {bottleneck['supplier']} " + f"(d cost / d capacity = {float(bottleneck['shadow_price']):+.2f})" ) # -------------------------------------------------- diff --git a/supplier_reliability/runbook.md b/supplier_reliability/runbook.md index 131b6732..afdfc218 100644 --- a/supplier_reliability/runbook.md +++ b/supplier_reliability/runbook.md @@ -54,4 +54,4 @@ Each prompt is pasted into a fresh agent session loaded with the named `/rai-*` ## Data -Bundled CSVs in `data/`: 4 suppliers, 3 products, 10 supply options. The disruption scenarios (remove SupplierC, SupplierB) are defined in `model/reasoning.py`. Full model in `model/`. +Bundled CSVs in `data/`: 4 suppliers, 3 products, 10 supply options. The disruption scenarios (remove SupplierC, SupplierB) are defined in `model/disruption_scenarios.py`. Full model in `model/`. diff --git a/supply_chain_resilience/README.md b/supply_chain_resilience/README.md index 09aef59c..766d6411 100644 --- a/supply_chain_resilience/README.md +++ b/supply_chain_resilience/README.md @@ -40,7 +40,7 @@ Supply chain networks route goods from suppliers through factories and distribut ## What's included -- **Model**: concepts for sites, businesses, SKUs, operations, demand, shipments, and delay predictions, the graph, rules, and risk-adjusted network flow problems, in the `model/` package (`schema.py` declares the concepts, `source.py` loads the sample data, `reasoning.py` states the graphs, rules, and decision problems), which `rai models deploy --path model` deploys to your Snowflake account, where each refresh runs the graph analysis and the solves. +- **Model**: concepts for sites, businesses, SKUs, operations, demand, shipments, and delay predictions, the graph, rules, and risk-adjusted network flow problems, in the `model/` package (`schema.py` declares the concepts, `source.py` loads the sample data, `blast_radius.py`, `network_criticality.py`, `supplier_risk.py`, and `risk_adjusted_flows.py` state the graphs, rules, and decision problems, one module per stage), which `rai models deploy --path model` deploys to your Snowflake account, where each refresh runs the graph analysis and the solves. - **Query**: `queries/resilience_report.py`, which prints the report from the deployed model. - `runbook.md` -- a paste-testable walkthrough that reproduces the template step by step with the RAI skills; as important a reference as the script itself - `data/site.csv` -- 31 sites (factories, distribution centers, offices, stores) across multiple regions @@ -233,7 +233,10 @@ Use this sequence to deploy the model and query it: │ ├── __init__.py # exports of the deployed model │ ├── schema.py # concepts and properties │ ├── source.py # sample data -│ └── reasoning.py # graphs, risk rules, and the network flow problems +│ ├── blast_radius.py # Stage 0: Business graph, high-priority customers, upstream suppliers +│ ├── network_criticality.py # Stage 1: site graph, components, centrality +│ ├── supplier_risk.py # Stage 2: risk flags and classes, late shipments, escalated demand +│ └── risk_adjusted_flows.py # Stage 3: network flow problems and scenario cost change ├── queries/ │ └── resilience_report.py # report from the deployed model └── data/ @@ -278,21 +281,21 @@ One shared ontology threads a pre-analysis and three chained reasoning stages -- CSV inputs → blast-radius reachability → Graph criticality → Rules risk classification → Prescriptive risk-adjusted flow → scenario re-solves ``` -**Configure inputs.** A handful of parameters at the top of `model/reasoning.py` control the run: risk thresholds (`RELIABILITY_THRESHOLD`, `DELAY_PROB_THRESHOLD`), objective penalties (`UNMET_PENALTY`, `RISK_SURCHARGE`, `CENTRALITY_WEIGHT`), and which quarter's delay predictions to use (`PREDICTION_QUARTER`). +**Configure inputs.** A handful of parameters at the top of the module that uses them control the run: risk thresholds (`RELIABILITY_THRESHOLD`, `DELAY_PROB_THRESHOLD`) and which quarter's delay predictions to use (`PREDICTION_QUARTER`) in `model/supplier_risk.py`, and objective penalties (`UNMET_PENALTY`, `RISK_SURCHARGE`, `CENTRALITY_WEIGHT`) and the solver-noise cutoff `FLOW_TOLERANCE` in `model/risk_adjusted_flows.py`. **Define concepts and load data.** The seven source concepts load from CSV (`model/schema.py` and `model/source.py`). A derived `Operation.source_business` relationship links each operation to its source business by matching the operation's source site to the business's site, avoiding an explicit join table. -**Stage 0 -- blast-radius pre-analysis.** A directed `Business` graph is built from the derived supplier-to-customer `ships_to` edges. Upstream reachability from each high-priority customer traces every supplier it transitively depends on, making the exposure footprint explicit so the later scenario results can be read in context. +**Stage 0 -- blast-radius pre-analysis.** A directed `Business` graph is built from the derived supplier-to-customer `ships_to` edges. Upstream reachability from each high-priority customer traces every supplier it transitively depends on, making the exposure footprint explicit so the later scenario results can be read in context. The `SUPPLIER`-type businesses a customer reaches are published as `Business.upstream_supplier`. -**Stage 1 -- Graph, network criticality.** An undirected graph with sites as nodes and SHIP operations as edges captures the physical shipping network. Weakly connected components reveal whether the network is fragmented or unified; eigenvector centrality scores each site by its structural influence. Scores are normalized by the largest score and stored as `Site.centrality` for the optimizer to penalize; the site with the largest score (the lowest site ID among ties) is flagged `Site.is_most_critical`. +**Stage 1 -- Graph, network criticality.** An undirected graph with sites as nodes and SHIP operations as edges captures the physical shipping network. Weakly connected components reveal whether the network is fragmented or unified; eigenvector centrality scores each site by its structural influence. Scores are normalized by the largest score and stored as `Site.centrality` for the optimizer to penalize. Each site's rank by centrality (`Site.centrality_rank`, ties broken by site ID) is published, and the first-ranked site is flagged `Site.is_most_critical`. Each component's site count and regions (`SiteCluster`) are published too. -**Stage 2 -- Rules, supplier risk classification.** Derived relationships flag suppliers below the reliability threshold and suppliers with high predicted delay probability. Suppliers with both flags are classified "avoid" (blocked from flow); suppliers with either flag are "watch" (allowed but surcharged). A further rule flags `HIGH`-priority demand as escalated. These classifications feed the optimizer as hard constraints and cost surcharges. +**Stage 2 -- Rules, supplier risk classification.** Derived relationships flag suppliers below the reliability threshold and suppliers with high predicted delay probability. Suppliers with both flags are classified "avoid" (blocked from flow); suppliers with either flag are "watch" (allowed but surcharged). Each business with a reliability score gets one risk class (`Business.risk_class`: avoid, watch, or reliable). A shipment with a recorded delay over zero days is late (`Shipment.is_late`), with late counts per supplier and in total, and a further rule flags `HIGH`-priority demand as escalated. These classifications feed the optimizer as hard constraints and cost surcharges. **Stage 3 -- Prescriptive, risk-adjusted network flow.** Two continuous decision variables drive the solve: `x_flow` per operation (bounded by capacity) and `x_unmet` slack per order. A demand-satisfaction constraint requires inbound flow at each customer's site for the demanded SKU, plus slack, to cover the order. Each order is checked against the whole inbound flow for its site and SKU, so several orders for the same site and SKU can count the same units, and an order with no inbound operation for its site and SKU gets no constraint; "All demand satisfied" means every constrained order is covered by that inbound flow, not that the orders are fulfilled separately. Operations from "avoid" suppliers are pinned to zero flow. The objective minimizes four components: base transport cost, a surcharge on flow through "watch" suppliers, a centrality penalty that discourages over-reliance on bottleneck sites, and a high penalty on unmet demand. -**Solve and run scenarios.** The baseline solves with HiGHS. Two disruption scenarios are their own problems with modified constraints -- taking the most critical site offline, and downgrading all "watch" suppliers to "avoid" -- so one infeasible scenario never affects the others, and the cost increase across scenarios quantifies the network's resilience to each type of disruption. The report assembles the scenario comparison from each problem's published status and objective. +**Solve and run scenarios.** The baseline solves with HiGHS. Two disruption scenarios are their own problems with modified constraints -- taking the most critical site offline, and downgrading all "watch" suppliers to "avoid" -- so one infeasible scenario never affects the others, and the cost increase across scenarios quantifies the network's resilience to each type of disruption. Each problem also publishes its count of active flows and unmet orders and units, and `CostChangePct` publishes each scenario's cost change against the baseline, so the report assembles the scenario comparison from published values. -For the implementation, see `model/reasoning.py`; to reproduce it step by step with the RAI skills, follow `runbook.md`. +For the implementation, see `model/blast_radius.py`, `model/network_criticality.py`, `model/supplier_risk.py`, and `model/risk_adjusted_flows.py`; to reproduce it step by step with the RAI skills, follow `runbook.md`. ## Customize this template @@ -314,7 +317,7 @@ Focus on the first changes most users will make. ### Extend the model -- Add new scenarios by calling `build_flow()` in `model/reasoning.py` with a new problem name and different `exclude_critical_site` or `block_watch_level` arguments, then report the new problem in `queries/resilience_report.py`. +- Add new scenarios by calling `build_flow()` in `model/risk_adjusted_flows.py` with a new problem name and different `exclude_critical_site` or `block_watch_level` arguments, then report the new problem in `queries/resilience_report.py`. - Add rows to the CSV files -- more sites, operations, or demand orders scale the network flow problem. - Swap eigenvector centrality for another graph algorithm (e.g. betweenness) to surface a different notion of structural criticality without changing the optimizer. diff --git a/supply_chain_resilience/model/__init__.py b/supply_chain_resilience/model/__init__.py index e8e70ea5..40fde717 100644 --- a/supply_chain_resilience/model/__init__.py +++ b/supply_chain_resilience/model/__init__.py @@ -21,38 +21,61 @@ - Scenario analysis: re-solve with disruptions (critical site offline, supplier downgrade) to quantify resilience costs. Each scenario is its own problem. +Modules, one per stage (each module imports the modules whose declarations +it reads): + +- ``blast_radius.py``: Stage 0, the Business graph, the high-priority + customers, and their upstream suppliers. +- ``network_criticality.py``: Stage 1, the site graph, its components, and + centrality. +- ``supplier_risk.py``: Stage 2, the risk flags and classes, late shipments, + and escalated demand. +- ``risk_adjusted_flows.py``: Stage 3 and the scenarios, the network flow + problems and the scenario cost comparison. + Run: `rai models deploy --path model` deploys this package to the schemas in raiconfig.yaml and waits for its first refresh, which runs the solves. `python -m queries.resilience_report` then prints the report from the deployed model. """ -from .reasoning import ( - baseline, +from .blast_radius import ( biz_graph, biz_num_edges, biz_num_nodes, + reachable_to, + target_customer, +) +from .network_criticality import ( + SiteCluster, eigenvector, graph, + num_components, num_edges, num_nodes, - reachable_to, + wcc, +) +from .risk_adjusted_flows import ( + CostChangePct, + baseline, + num_source_links, site_offline, - target_customer, watch_avoid, - wcc, ) from .schema import Business, DelayPrediction, Demand, Operation, Shipment, Site, model from .source import DATA_DIR +from .supplier_risk import num_escalated, num_late_shipments, num_shipments __all__ = [ "DATA_DIR", "Business", + "CostChangePct", "DelayPrediction", "Demand", "Operation", "Shipment", "Site", + "SiteCluster", "baseline", "biz_graph", "biz_num_edges", @@ -60,8 +83,13 @@ "eigenvector", "graph", "model", + "num_components", "num_edges", + "num_escalated", + "num_late_shipments", "num_nodes", + "num_shipments", + "num_source_links", "reachable_to", "site_offline", "target_customer", diff --git a/supply_chain_resilience/model/blast_radius.py b/supply_chain_resilience/model/blast_radius.py new file mode 100644 index 00000000..9fcbc1eb --- /dev/null +++ b/supply_chain_resilience/model/blast_radius.py @@ -0,0 +1,67 @@ +"""Blast radius: the directed graph of who ships to whom, the high-priority customers, and the +suppliers each of them transitively depends on.""" + +from relationalai.semantics import Integer +from relationalai.semantics.reasoners.graph import Graph + +from .schema import Business, Demand, Shipment, model + +# Derived ships_to: supplier -> customer (collapses many shipments into edges). +Business.ships_to = model.Relationship( + f"{Business:supplier} ships to {Business:customer}" +) +b_from, b_to = Business.ref(), Business.ref() +model.define(Business.ships_to(b_from, b_to)).where( + Shipment.supplier(b_from), + Shipment.customer(b_to), +) + +# Flag businesses that hold at least one HIGH-priority demand — they are +# the customers whose blast-radius we care about most. +Business.is_high_priority_customer = model.Relationship( + f"{Business} is a high-priority customer" +) +model.where( + Demand.business(Business), + Demand.priority == "HIGH", +).define(Business.is_high_priority_customer()) + +# -------------------------------------------------- +# Stage 0: Blast-radius pre-analysis (directed Business graph) +# -------------------------------------------------- +# Trace every supplier each high-priority customer transitively depends on. +# This surfaces the exposure footprint BEFORE the MILP runs, so the +# scenario analysis in Stage 3 can be read in context: "if supplier X is +# downgraded, the optimizer is rerouting around the demands listed here." + +biz_graph = Graph(model, directed=True, weighted=False, node_concept=Business, name="business_graph") +b_src, b_dst = Business.ref(), Business.ref() +model.where(Business.ships_to(b_src, b_dst)).define( + biz_graph.Edge.new(src=b_src, dst=b_dst) +) + +# The business graph's size, which the deployed model publishes for the queries. +biz_node_count, biz_edge_count = Integer.ref(), Integer.ref() +biz_num_nodes = model.Relationship(f"the business graph has {Integer:num_nodes} nodes") +biz_num_edges = model.Relationship(f"the business graph has {Integer:num_edges} edges") +model.where(biz_graph.num_nodes()(biz_node_count)).define(biz_num_nodes(biz_node_count)) +model.where(biz_graph.num_edges()(biz_edge_count)).define(biz_num_edges(biz_edge_count)) + +# Upstream reachability: which suppliers do high-priority customers depend on? +target_customer = model.Relationship(f"target customer {Business}") +model.where(Business.is_high_priority_customer()).define(target_customer(Business)) + +reachable_to = biz_graph.reachable(to=target_customer) +# Attach it to Business, so the deployed model publishes it for the queries. +Business.reaches_target_customer = reachable_to + +# Each high-priority customer's upstream suppliers: the SUPPLIER-type businesses that reach it +# through shipments. +Business.upstream_supplier = model.Relationship( + f"{Business:customer} depends on supplier {Business:supplier}" +) +customer_node, supplier_node = Business.ref(), Business.ref() +model.where( + reachable_to(supplier_node, customer_node), + supplier_node.business_type == "SUPPLIER", +).define(Business.upstream_supplier(customer_node, supplier_node)) diff --git a/supply_chain_resilience/model/network_criticality.py b/supply_chain_resilience/model/network_criticality.py new file mode 100644 index 00000000..e0b14bec --- /dev/null +++ b/supply_chain_resilience/model/network_criticality.py @@ -0,0 +1,98 @@ +"""Network criticality: the site shipping graph, its connected components, and each site's +eigenvector centrality, rank, and the most critical site.""" + +from relationalai.semantics import Float, Integer, String +from relationalai.semantics.reasoners.graph import Graph +from relationalai.semantics.std import aggregates as aggs + +from .schema import Operation, Site, model + +# -------------------------------------------------- +# Stage 1: Graph -- network criticality +# -------------------------------------------------- + +# Build undirected unweighted graph: Sites as nodes, SHIP operations as edges. +graph = Graph( + model, directed=False, weighted=False, node_concept=Site, aggregator="sum", name="shipping_network" +) + +s1, s2, op_ref = Site.ref(), Site.ref(), Operation.ref() +model.define( + graph.Edge.new(src=s1, dst=s2) +).where( + op_ref.source_site(s1), + op_ref.output_site(s2), + op_ref.op_type == "SHIP", +) + +# The site graph's size, which the deployed model publishes for the queries. +node_count, edge_count = Integer.ref(), Integer.ref() +num_nodes = model.Relationship(f"the site graph has {Integer:num_nodes} nodes") +num_edges = model.Relationship(f"the site graph has {Integer:num_edges} edges") +model.where(graph.num_nodes()(node_count)).define(num_nodes(node_count)) +model.where(graph.num_edges()(edge_count)).define(num_edges(edge_count)) + +# Weakly connected components. +wcc = graph.weakly_connected_component() + +# Eigenvector centrality: identify most critical sites. +eigenvector = graph.eigenvector_centrality() + +# Attach both results to Site, so the deployed model publishes them for the queries. +Site.component = wcc +Site.eigenvector_centrality = eigenvector + +# Store centrality on Site for use in optimization objective: the eigenvector score +# of each site other than stores and offices, divided by the largest such score. When +# the largest score is 0, every score is 0 and is kept as is. +Site.centrality = model.Property(f"{Site} has centrality {Float:centrality}") +MaxCentrality = model.Relationship(f"max eigenvector centrality is {Float:max_score}") +site_max, score_max = Site.ref(), Float.ref() +model.define(MaxCentrality(aggs.max(score_max))).where( + eigenvector(site_max, score_max), + site_max.site_type != "STORE", + site_max.site_type != "OFFICE", +) +site_eig, score_eig, max_score = Site.ref(), Float.ref(), Float.ref() +model.where( + eigenvector(site_eig, score_eig), + site_eig.site_type != "STORE", + site_eig.site_type != "OFFICE", + MaxCentrality(max_score), + max_score > 0, +).define(site_eig.centrality(score_eig / max_score)) +model.where( + eigenvector(site_eig, score_eig), + site_eig.site_type != "STORE", + site_eig.site_type != "OFFICE", + MaxCentrality(0.0), +).define(site_eig.centrality(score_eig)) + +# Each scored site's rank by centrality, highest first, ties broken by site id. The score is +# negated so both keys sort ascending. +Site.centrality_rank = model.Property(f"{Site} has centrality rank {Integer:centrality_rank}") +model.define(Site.centrality_rank(aggs.rank(-Site.centrality, Site.id))) + +# The site ranked first, the lowest ID among those with the highest centrality; the +# site-offline scenario takes this one site offline. +Site.is_most_critical = model.Relationship(f"{Site} is the most critical site") +model.where(Site.centrality_rank == 1).define(Site.is_most_critical()) + +# Each weakly connected component, keyed by the id of its representative site, with its site +# count and the sorted distinct regions its sites span. +SiteCluster = model.Concept("SiteCluster", identify_by={"id": String}) +SiteCluster.n_sites = model.Property(f"{SiteCluster} has {Integer:n_sites} sites") +SiteCluster.regions = model.Property(f"{SiteCluster} spans regions {String:regions}") +cluster_site, cluster_root = Site.ref(), Site.ref() +model.define(SiteCluster.new(id=cluster_root.id)).where(wcc(cluster_site, cluster_root)) +_in_cluster = (wcc(cluster_site, cluster_root), cluster_root.id == SiteCluster.id) +model.define( + SiteCluster.n_sites(aggs.count(cluster_site).per(SiteCluster).where(*_in_cluster)), + SiteCluster.regions( + aggs.string_join(cluster_site.region, sep=", ").per(SiteCluster).where(*_in_cluster) + ), +) + +# The number of components (zero for an empty graph). +num_components = model.Relationship(f"the site graph has {Integer:num_components} connected components") +model.define(num_components(aggs.count(cluster_root).where(wcc(cluster_site, cluster_root)) | 0)) diff --git a/supply_chain_resilience/model/reasoning.py b/supply_chain_resilience/model/reasoning.py deleted file mode 100644 index e1ae3567..00000000 --- a/supply_chain_resilience/model/reasoning.py +++ /dev/null @@ -1,365 +0,0 @@ -"""Supply chain reasoning: dependency graphs, supplier risk rules, and risk-adjusted network flow problems.""" - -from typing import Any, NamedTuple - -from relationalai.semantics import Float, Integer, String, sum -from relationalai.semantics.reasoners.graph import Graph -from relationalai.semantics.reasoners.prescriptive import Problem -from relationalai.semantics.std import aggregates as aggs - -from .schema import ( - Business, - DelayPrediction, - Demand, - Operation, - Shipment, - Site, - model, -) - -# -------------------------------------------------- -# Configure inputs -# -------------------------------------------------- - -UNMET_PENALTY = 100.0 # penalty for unmet demand (kept moderate so routing costs are visible) -RISK_SURCHARGE = 5.0 # cost multiplier for "watch" supplier operations -CENTRALITY_WEIGHT = 2.0 # multiplier for bottleneck site penalty -DELAY_PROB_THRESHOLD = 0.15 # above this = high delay risk -RELIABILITY_THRESHOLD = 0.80 # below this = unreliable supplier -PREDICTION_QUARTER = "Q1-2025" # which quarter's predictions to use - -# Derived relationship: Operation's source business (via shared site). -Operation.source_business = model.Relationship( - f"{Operation} sourced from {Business}" -) -model.define(Operation.source_business(Operation, Business)).where( - Operation.source_site == Business.site -) - -# Derived ships_to: supplier -> customer (collapses many shipments into edges). -Business.ships_to = model.Relationship( - f"{Business:supplier} ships to {Business:customer}" -) -b_from, b_to = Business.ref(), Business.ref() -model.define(Business.ships_to(b_from, b_to)).where( - Shipment.supplier(b_from), - Shipment.customer(b_to), -) - -# Flag businesses that hold at least one HIGH-priority demand — they are -# the customers whose blast-radius we care about most. -Business.is_high_priority_customer = model.Relationship( - f"{Business} is a high-priority customer" -) -model.where( - Demand.business(Business), - Demand.priority == "HIGH", -).define(Business.is_high_priority_customer()) - -# -------------------------------------------------- -# Stage 0: Blast-radius pre-analysis (directed Business graph) -# -------------------------------------------------- -# Trace every supplier each high-priority customer transitively depends on. -# This surfaces the exposure footprint BEFORE the MILP runs, so the -# scenario analysis in Stage 3 can be read in context: "if supplier X is -# downgraded, the optimizer is rerouting around the demands listed here." - -biz_graph = Graph(model, directed=True, weighted=False, node_concept=Business, name="business_graph") -b_src, b_dst = Business.ref(), Business.ref() -model.where(Business.ships_to(b_src, b_dst)).define( - biz_graph.Edge.new(src=b_src, dst=b_dst) -) - -# The business graph's size, which the deployed model publishes for the queries. -biz_node_count, biz_edge_count = Integer.ref(), Integer.ref() -biz_num_nodes = model.Relationship(f"the business graph has {Integer:num_nodes} nodes") -biz_num_edges = model.Relationship(f"the business graph has {Integer:num_edges} edges") -model.where(biz_graph.num_nodes()(biz_node_count)).define(biz_num_nodes(biz_node_count)) -model.where(biz_graph.num_edges()(biz_edge_count)).define(biz_num_edges(biz_edge_count)) - -# Upstream reachability: which suppliers do high-priority customers depend on? -target_customer = model.Relationship(f"target customer {Business}") -model.where(Business.is_high_priority_customer()).define(target_customer(Business)) - -reachable_to = biz_graph.reachable(to=target_customer) -# Attach it to Business, so the deployed model publishes it for the queries. -Business.reaches_target_customer = reachable_to - -# -------------------------------------------------- -# Stage 1: Graph -- network criticality -# -------------------------------------------------- - -# Build undirected unweighted graph: Sites as nodes, SHIP operations as edges. -graph = Graph( - model, directed=False, weighted=False, node_concept=Site, aggregator="sum", name="shipping_network" -) - -s1, s2, op_ref = Site.ref(), Site.ref(), Operation.ref() -model.define( - graph.Edge.new(src=s1, dst=s2) -).where( - op_ref.source_site(s1), - op_ref.output_site(s2), - op_ref.op_type == "SHIP", -) - -# The site graph's size, which the deployed model publishes for the queries. -node_count, edge_count = Integer.ref(), Integer.ref() -num_nodes = model.Relationship(f"the site graph has {Integer:num_nodes} nodes") -num_edges = model.Relationship(f"the site graph has {Integer:num_edges} edges") -model.where(graph.num_nodes()(node_count)).define(num_nodes(node_count)) -model.where(graph.num_edges()(edge_count)).define(num_edges(edge_count)) - -# Weakly connected components. -wcc = graph.weakly_connected_component() - -# Eigenvector centrality: identify most critical sites. -eigenvector = graph.eigenvector_centrality() - -# Attach both results to Site, so the deployed model publishes them for the queries. -Site.component = wcc -Site.eigenvector_centrality = eigenvector - -# Store centrality on Site for use in optimization objective: the eigenvector score -# of each site other than stores and offices, divided by the largest such score. When -# the largest score is 0, every score is 0 and is kept as is. -Site.centrality = model.Property(f"{Site} has centrality {Float:centrality}") -MaxCentrality = model.Relationship(f"max eigenvector centrality is {Float:max_score}") -site_max, score_max = Site.ref(), Float.ref() -model.define(MaxCentrality(aggs.max(score_max))).where( - eigenvector(site_max, score_max), - site_max.site_type != "STORE", - site_max.site_type != "OFFICE", -) -site_eig, score_eig, max_score = Site.ref(), Float.ref(), Float.ref() -model.where( - eigenvector(site_eig, score_eig), - site_eig.site_type != "STORE", - site_eig.site_type != "OFFICE", - MaxCentrality(max_score), - max_score > 0, -).define(site_eig.centrality(score_eig / max_score)) -model.where( - eigenvector(site_eig, score_eig), - site_eig.site_type != "STORE", - site_eig.site_type != "OFFICE", - MaxCentrality(0.0), -).define(site_eig.centrality(score_eig)) - -# The site with the highest centrality, the lowest ID among ties; the site-offline -# scenario takes this one site offline. -MostCriticalSiteId = model.Relationship(f"the most critical site has id {String:site_id}") -site_top, score_top = Site.ref(), Float.ref() -model.define(MostCriticalSiteId(aggs.min(site_top.id))).where( - eigenvector(site_top, score_top), - site_top.site_type != "STORE", - site_top.site_type != "OFFICE", - MaxCentrality(score_top), -) -Site.is_most_critical = model.Relationship(f"{Site} is the most critical site") -model.where(MostCriticalSiteId(Site.id)).define(Site.is_most_critical()) - -# -------------------------------------------------- -# Stage 2: Rules -- supplier risk classification -# -------------------------------------------------- - -# Rule 2: Business is unreliable when reliability_score < threshold. -Business.is_unreliable = model.Relationship(f"{Business} is unreliable") -model.where( - Business.reliability_score < RELIABILITY_THRESHOLD -).define(Business.is_unreliable()) - -# Rule 3: Business has high delay risk from ML predictions. -Business.has_high_delay_risk = model.Relationship( - f"{Business} has high delay risk" -) -dp_ref = DelayPrediction.ref() -model.where( - dp_ref.supplier_business(Business), - dp_ref.fiscal_quarter == PREDICTION_QUARTER, - dp_ref.predicted_delay_prob > DELAY_PROB_THRESHOLD, -).define(Business.has_high_delay_risk()) - -# Rule: Business is watch-level when it has either risk flag. -# "Avoid" businesses (both flags) are hard-blocked in Stage 3; watch-level -# businesses get a soft risk surcharge in the objective. -Business.is_watch_level = model.Relationship(f"{Business} is watch level") -model.where(Business.is_unreliable()).define(Business.is_watch_level()) -model.where(Business.has_high_delay_risk()).define(Business.is_watch_level()) - -# Rule: Business is avoid when BOTH unreliable AND high delay risk fire. -Business.is_avoid = model.Relationship(f"{Business} is avoid") -model.define(Business.is_avoid()).where( - Business.is_unreliable(), - Business.has_high_delay_risk(), -) - -# Rule 4: Demand is escalated when priority is HIGH. -Demand.is_escalated = model.Relationship(f"{Demand} is escalated") -model.where(Demand.priority == "HIGH").define(Demand.is_escalated()) - -# -------------------------------------------------- -# Stage 3: Prescriptive -- risk-adjusted network flow -# -------------------------------------------------- - -# Define decision variable properties once, outside build_flow(). -Operation.x_flow = model.Property(f"{Operation} has {Float:flow}") -Demand.x_unmet = model.Property(f"{Demand} has {Float:unmet}") - - -class Flow(NamedTuple): - """One network flow problem, its decision variables, and its published result.""" - - name: str - problem: Any - routes: Any - unmet: Any - status: Any - cost: Any - - -def build_flow(name, exclude_critical_site=False, block_watch_level=False): - """Define a network flow problem named `name`, optionally disabling the most critical site or blocking more suppliers. - - Args: - name: Problem name, which also prefixes the problem's published status and cost. - exclude_critical_site: If True, all operations from the most critical site - (Site.is_most_critical) get zero flow. - block_watch_level: If True, operations sourced from every watch-level - business (unreliable or high delay risk) get zero flow, in place of the - Business.is_avoid() block that the other problems use. - """ - problem = Problem(model, Float, name=name) - - # Decision variable: flow on each operation. - flow_var = problem.solve_for( - Operation.x_flow, - name=["x_flow", Operation.id], - lower=0, - upper=Operation.capacity_per_day, - populate=False, - ) - - # Slack variable: unmet demand per demand order. - unmet_var = problem.solve_for( - Demand.x_unmet, - name=["x_unmet", Demand.id], - lower=0, - populate=False, - ) - - # Constraint: demand satisfaction. - # For each demand, inbound flow at the customer's site for the demanded - # SKU, plus unmet slack, must cover the quantity. - D = Demand.ref() - Op = Operation.ref() - B = Business.ref() - problem.satisfy( - model.require( - sum(Op.x_flow).per(D) + D.x_unmet >= D.quantity - ).where( - D.business(B), - B.site == Op.output_site, - D.sku == Op.output_sku, - ), - name=["demand_sat", D.id], - ) - - if block_watch_level: - # Constraint: block operations sourced from watch-level businesses (a strict - # superset of the avoid businesses). - biz_block = Business.ref() - op_block = Operation.ref() - problem.satisfy( - model.require(op_block.x_flow == 0).where( - op_block.source_business(biz_block), - biz_block.is_watch_level(), - ), - name=["block_watch", op_block.id], - ) - else: - # Constraint: block operations sourced from "avoid" businesses, read - # directly from the ontology Business.is_avoid() Relationship. - biz_avoid = Business.ref() - op_avoid = Operation.ref() - problem.satisfy( - model.require(op_avoid.x_flow == 0).where( - op_avoid.source_business(biz_avoid), - biz_avoid.is_avoid(), - ), - name=["block_avoid", op_avoid.id], - ) - - # Constraint (scenario): disable operations from the most critical site. - if exclude_critical_site: - excl_site = Site.ref() - op_excl = Operation.ref() - problem.satisfy( - model.require(op_excl.x_flow == 0).where( - op_excl.source_site(excl_site), - excl_site.is_most_critical(), - ), - name=["site_offline", op_excl.id], - ) - - # Objective: minimize transport cost + risk surcharge + centrality penalty - # + unmet demand penalty. - transport_cost = sum(Operation.cost_per_unit * Operation.x_flow) - - # Risk surcharge: extra cost for "watch"-level supplier operations - # (unreliable or high delay risk, but not necessarily blocked). - op_watch = Operation.ref() - biz_watch = Business.ref() - risk_cost = RISK_SURCHARGE * sum(op_watch.x_flow).where( - op_watch.source_business(biz_watch), - biz_watch.is_watch_level(), - ) - - # Centrality penalty: discourage over-reliance on bottleneck sites. - op_cent = Operation.ref() - site_cent = Site.ref() - cent_val = Float.ref() - centrality_cost = CENTRALITY_WEIGHT * sum( - op_cent.x_flow * cent_val - ).where( - op_cent.output_site(site_cent), - site_cent.centrality(cent_val), - ) - - unmet_cost = UNMET_PENALTY * sum(Demand.x_unmet) - - # The risk sum is empty with no watch-level supplier, and the centrality sum - # with no operation into a scored site (stores and offices are unscored); - # `| 0.0` makes an empty sum zero. - problem.minimize( - transport_cost + (risk_cost | 0.0) + (centrality_cost | 0.0) + unmet_cost - ) - - # Each refresh of the deployed model runs this solve. - problem.configure("highs", time_limit_sec=120) - - # The solve's status and objective, which the deployed model publishes for the queries. - status = model.Relationship(f"{name} solve status is {String:status}") - cost = model.Relationship(f"{name} total cost is {Float:cost}") - model.define(status(problem.termination_status()), cost(problem.objective_value())) - - # The solved flows and unmet demand, which the deployed model publishes for the queries. - routes = model.Relationship(f"{name} routes {Float:flow} on operation {String:operation_id}") - unmet = model.Relationship(f"{name} leaves {Float:unmet} unmet for demand {String:demand_id}") - value = Float.ref() - model.where(flow_var.values(0, value)).define(routes(value, flow_var.operation.id)) - model.where(unmet_var.values(0, value)).define(unmet(value, unmet_var.demand.id)) - - return Flow(name, problem, routes, unmet, status, cost) - - -# Baseline solve: block only "avoid" suppliers (both unreliable AND high delay) -# via the Business.is_avoid() Relationship from the ontology. -baseline = build_flow("supply_chain_resilience_baseline") - -# Scenario 1: Take the highest-centrality site offline. -site_offline = build_flow("supply_chain_resilience_site_offline", exclude_critical_site=True) - -# Scenario 2: Downgrade all "watch" suppliers to "avoid" — block any -# supplier that is unreliable OR has high delay risk. -watch_avoid = build_flow("supply_chain_resilience_watch_avoid", block_watch_level=True) diff --git a/supply_chain_resilience/model/risk_adjusted_flows.py b/supply_chain_resilience/model/risk_adjusted_flows.py new file mode 100644 index 00000000..d3b16b76 --- /dev/null +++ b/supply_chain_resilience/model/risk_adjusted_flows.py @@ -0,0 +1,240 @@ +"""Risk-adjusted network flow: the baseline routing problem, the disruption scenarios, and what each +solve publishes.""" + +from typing import Any, NamedTuple + +from relationalai.semantics import Float, Integer, String, sum +from relationalai.semantics.reasoners.prescriptive import Problem +from relationalai.semantics.std import aggregates as aggs + +# Declare Site.centrality and Site.is_most_critical, and the Business risk flags, that the +# objective and the constraints read. +from . import network_criticality, supplier_risk # noqa: F401 +from .schema import Business, Demand, Operation, Site, model + +# -------------------------------------------------- +# Configure inputs +# -------------------------------------------------- + +UNMET_PENALTY = 100.0 # penalty for unmet demand (kept moderate so routing costs are visible) +RISK_SURCHARGE = 5.0 # cost multiplier for "watch" supplier operations +CENTRALITY_WEIGHT = 2.0 # multiplier for bottleneck site penalty +FLOW_TOLERANCE = 0.001 # solved flows and unmet quantities at or below this are solver noise + +# Derived relationship: Operation's source business (via shared site). +Operation.source_business = model.Relationship( + f"{Operation} sourced from {Business}" +) +model.define(Operation.source_business(Operation, Business)).where( + Operation.source_site == Business.site +) + +# How many source links that relationship holds. +num_source_links = model.Relationship(f"there are {Integer:num_source_links} operation source links") +op_linked, biz_linked = Operation.ref(), Business.ref() +model.define(num_source_links( + aggs.count(op_linked, biz_linked).where(Operation.source_business(op_linked, biz_linked)) | 0 +)) + +# -------------------------------------------------- +# Stage 3: Prescriptive -- risk-adjusted network flow +# -------------------------------------------------- + +# Define decision variable properties once, outside build_flow(). +Operation.x_flow = model.Property(f"{Operation} has {Float:flow}") +Demand.x_unmet = model.Property(f"{Demand} has {Float:unmet}") + + +class Flow(NamedTuple): + """One network flow problem, its decision variables, and its published result.""" + + name: str + problem: Any + routes: Any + unmet: Any + status: Any + cost: Any + active_flows: Any + unmet_orders: Any + unmet_units: Any + + +def build_flow(name, exclude_critical_site=False, block_watch_level=False): + """Define a network flow problem named `name`, optionally disabling the most critical site or blocking more suppliers. + + Args: + name: Problem name, which also prefixes the problem's published status and cost. + exclude_critical_site: If True, all operations from the most critical site + (Site.is_most_critical) get zero flow. + block_watch_level: If True, operations sourced from every watch-level + business (unreliable or high delay risk) get zero flow, in place of the + Business.is_avoid() block that the other problems use. + """ + problem = Problem(model, Float, name=name) + + # Decision variable: flow on each operation. + flow_var = problem.solve_for( + Operation.x_flow, + name=["x_flow", Operation.id], + lower=0, + upper=Operation.capacity_per_day, + populate=False, + ) + + # Slack variable: unmet demand per demand order. + unmet_var = problem.solve_for( + Demand.x_unmet, + name=["x_unmet", Demand.id], + lower=0, + populate=False, + ) + + # Constraint: demand satisfaction. + # For each demand, inbound flow at the customer's site for the demanded + # SKU, plus unmet slack, must cover the quantity. + D = Demand.ref() + Op = Operation.ref() + B = Business.ref() + problem.satisfy( + model.require( + sum(Op.x_flow).per(D) + D.x_unmet >= D.quantity + ).where( + D.business(B), + B.site == Op.output_site, + D.sku == Op.output_sku, + ), + name=["demand_sat", D.id], + ) + + if block_watch_level: + # Constraint: block operations sourced from watch-level businesses (a strict + # superset of the avoid businesses). + biz_block = Business.ref() + op_block = Operation.ref() + problem.satisfy( + model.require(op_block.x_flow == 0).where( + op_block.source_business(biz_block), + biz_block.is_watch_level(), + ), + name=["block_watch", op_block.id], + ) + else: + # Constraint: block operations sourced from "avoid" businesses, read + # directly from the ontology Business.is_avoid() Relationship. + biz_avoid = Business.ref() + op_avoid = Operation.ref() + problem.satisfy( + model.require(op_avoid.x_flow == 0).where( + op_avoid.source_business(biz_avoid), + biz_avoid.is_avoid(), + ), + name=["block_avoid", op_avoid.id], + ) + + # Constraint (scenario): disable operations from the most critical site. + if exclude_critical_site: + excl_site = Site.ref() + op_excl = Operation.ref() + problem.satisfy( + model.require(op_excl.x_flow == 0).where( + op_excl.source_site(excl_site), + excl_site.is_most_critical(), + ), + name=["site_offline", op_excl.id], + ) + + # Objective: minimize transport cost + risk surcharge + centrality penalty + # + unmet demand penalty. + transport_cost = sum(Operation.cost_per_unit * Operation.x_flow) + + # Risk surcharge: extra cost for "watch"-level supplier operations + # (unreliable or high delay risk, but not necessarily blocked). + op_watch = Operation.ref() + biz_watch = Business.ref() + risk_cost = RISK_SURCHARGE * sum(op_watch.x_flow).where( + op_watch.source_business(biz_watch), + biz_watch.is_watch_level(), + ) + + # Centrality penalty: discourage over-reliance on bottleneck sites. + op_cent = Operation.ref() + site_cent = Site.ref() + cent_val = Float.ref() + centrality_cost = CENTRALITY_WEIGHT * sum( + op_cent.x_flow * cent_val + ).where( + op_cent.output_site(site_cent), + site_cent.centrality(cent_val), + ) + + unmet_cost = UNMET_PENALTY * sum(Demand.x_unmet) + + # The risk sum is empty with no watch-level supplier, and the centrality sum + # with no operation into a scored site (stores and offices are unscored); + # `| 0.0` makes an empty sum zero. + problem.minimize( + transport_cost + (risk_cost | 0.0) + (centrality_cost | 0.0) + unmet_cost + ) + + # Each refresh of the deployed model runs this solve. + problem.configure("highs", time_limit_sec=120) + + # The solve's status and objective, which the deployed model publishes for the queries. + status = model.Relationship(f"{name} solve status is {String:status}") + cost = model.Relationship(f"{name} total cost is {Float:cost}") + model.define(status(problem.termination_status()), cost(problem.objective_value())) + + # The solved flows and unmet demand, which the deployed model publishes for the queries. + routes = model.Relationship(f"{name} routes {Float:flow} on operation {String:operation_id}") + unmet = model.Relationship(f"{name} leaves {Float:unmet} unmet for demand {String:demand_id}") + value = Float.ref() + model.where(flow_var.values(0, value)).define(routes(value, flow_var.operation.id)) + model.where(unmet_var.values(0, value)).define(unmet(value, unmet_var.demand.id)) + + # The solve's active flows, unmet orders, and unmet units, which the deployed model + # publishes for the queries; each is zero when nothing exceeds FLOW_TOLERANCE. + active_flows = model.Relationship(f"{name} has {Integer:active_flows} active flows") + unmet_orders = model.Relationship(f"{name} leaves {Integer:unmet_orders} orders unmet") + unmet_units = model.Relationship(f"{name} leaves {Float:unmet_units} units unmet") + route_value, route_op = Float.ref(), String.ref() + unmet_value, unmet_demand = Float.ref(), String.ref() + model.define(active_flows( + aggs.count(route_op).where(routes(route_value, route_op), route_value > FLOW_TOLERANCE) | 0 + )) + model.define(unmet_orders( + aggs.count(unmet_demand).where(unmet(unmet_value, unmet_demand), unmet_value > FLOW_TOLERANCE) + | 0 + )) + model.define(unmet_units( + aggs.sum(unmet_demand, unmet_value).where( + unmet(unmet_value, unmet_demand), unmet_value > FLOW_TOLERANCE + ) + | 0.0 + )) + + return Flow(name, problem, routes, unmet, status, cost, active_flows, unmet_orders, unmet_units) + + +# Baseline solve: block only "avoid" suppliers (both unreliable AND high delay) +# via the Business.is_avoid() Relationship from the ontology. +baseline = build_flow("supply_chain_resilience_baseline") + +# Scenario 1: Take the highest-centrality site offline. +site_offline = build_flow("supply_chain_resilience_site_offline", exclude_critical_site=True) + +# Scenario 2: Downgrade all "watch" suppliers to "avoid" — block any +# supplier that is unreliable OR has high delay risk. +watch_avoid = build_flow("supply_chain_resilience_watch_avoid", block_watch_level=True) + +# How much more each scenario costs than the baseline, in percent; there is none when +# the baseline cost is zero. +CostChangePct = model.Relationship( + f"scenario {String:scenario} costs {Float:pct_change} percent more than the baseline" +) +baseline_cost, scenario_cost = Float.ref(), Float.ref() +for scenario in (site_offline, watch_avoid): + model.where( + baseline.cost(baseline_cost), + scenario.cost(scenario_cost), + baseline_cost != 0, + ).define(CostChangePct(scenario.name, (scenario_cost - baseline_cost) / baseline_cost * 100)) diff --git a/supply_chain_resilience/model/source.py b/supply_chain_resilience/model/source.py index 21f74ba1..7c1455da 100644 --- a/supply_chain_resilience/model/source.py +++ b/supply_chain_resilience/model/source.py @@ -82,17 +82,22 @@ ) # Shipment data: only the columns the graph and the late-shipment statistics need. -# Shipments still in transit have no delay yet, so they count as 0 days late. shipments_csv = read_csv(DATA_DIR / "shipment.csv") -ship_cols = ["ID", "SUPPLIER_BUSINESS_ID", "CUSTOMER_BUSINESS_ID", "SKU_ID", "QUANTITY", "DELAY_DAYS"] -ship_data = model.data(shipments_csv[ship_cols].fillna({"DELAY_DAYS": 0})) +ship_cols = ["ID", "SUPPLIER_BUSINESS_ID", "CUSTOMER_BUSINESS_ID", "SKU_ID", "QUANTITY"] +ship_data = model.data(shipments_csv[ship_cols]) model.define( sh := Shipment.new(id=ship_data["ID"]), sh.supplier(Business.lookup(id=ship_data["SUPPLIER_BUSINESS_ID"])), sh.customer(Business.lookup(id=ship_data["CUSTOMER_BUSINESS_ID"])), sh.sku_id(ship_data["SKU_ID"]), sh.quantity(ship_data["QUANTITY"]), - sh.delay_days(ship_data["DELAY_DAYS"]), +) + +# A shipment's delay is recorded once it has arrived; a shipment still in transit has none. +delay_data = model.data(shipments_csv.dropna(subset=["DELAY_DAYS"])[["ID", "DELAY_DAYS"]]) +model.define( + sh_delay := Shipment.new(id=delay_data["ID"]), + sh_delay.delay_days(delay_data["DELAY_DAYS"]), ) pred_data = model.data(read_csv(DATA_DIR / "delay_prediction.csv")) diff --git a/supply_chain_resilience/model/supplier_risk.py b/supply_chain_resilience/model/supplier_risk.py new file mode 100644 index 00000000..0e881997 --- /dev/null +++ b/supply_chain_resilience/model/supplier_risk.py @@ -0,0 +1,103 @@ +"""Supplier risk: reliability and delay-risk flags, the avoid, watch, and reliable classes, late +shipments, and escalated demand.""" + +from relationalai.semantics import Float, Integer, String +from relationalai.semantics.std import aggregates as aggs + +from .schema import Business, DelayPrediction, Demand, Shipment, model + +# -------------------------------------------------- +# Configure inputs +# -------------------------------------------------- + +DELAY_PROB_THRESHOLD = 0.15 # above this = high delay risk +RELIABILITY_THRESHOLD = 0.80 # below this = unreliable supplier +PREDICTION_QUARTER = "Q1-2025" # which quarter's predictions to use + +# -------------------------------------------------- +# Stage 2: Rules -- supplier risk classification +# -------------------------------------------------- + +# Rule 2: Business is unreliable when reliability_score < threshold. +Business.is_unreliable = model.Relationship(f"{Business} is unreliable") +model.where( + Business.reliability_score < RELIABILITY_THRESHOLD +).define(Business.is_unreliable()) + +# Rule 3: Business has high delay risk from ML predictions. +Business.has_high_delay_risk = model.Relationship( + f"{Business} has high delay risk" +) +dp_ref = DelayPrediction.ref() +model.where( + dp_ref.supplier_business(Business), + dp_ref.fiscal_quarter == PREDICTION_QUARTER, + dp_ref.predicted_delay_prob > DELAY_PROB_THRESHOLD, +).define(Business.has_high_delay_risk()) + +# Rule: Business is watch-level when it has either risk flag. +# "Avoid" businesses (both flags) are hard-blocked in Stage 3; watch-level +# businesses get a soft risk surcharge in the objective. +Business.is_watch_level = model.Relationship(f"{Business} is watch level") +model.where(Business.is_unreliable()).define(Business.is_watch_level()) +model.where(Business.has_high_delay_risk()).define(Business.is_watch_level()) + +# Rule: Business is avoid when BOTH unreliable AND high delay risk fire. +Business.is_avoid = model.Relationship(f"{Business} is avoid") +model.define(Business.is_avoid()).where( + Business.is_unreliable(), + Business.has_high_delay_risk(), +) + +# Rule 4: Demand is escalated when priority is HIGH. +Demand.is_escalated = model.Relationship(f"{Demand} is escalated") +model.where(Demand.priority == "HIGH").define(Demand.is_escalated()) + +# Supplier risk class, for each business that has a reliability score: avoid, else watch +# (watch level without avoid), else reliable. +Business.risk_class = model.Property(f"{Business} has risk class {String:risk_class}") +rated_score = Float.ref() +model.where(Business.reliability_score(rated_score), Business.is_avoid()).define( + Business.risk_class("avoid") +) +model.where( + Business.reliability_score(rated_score), + Business.is_watch_level(), + model.not_(Business.is_avoid()), +).define(Business.risk_class("watch")) +model.where( + Business.reliability_score(rated_score), + model.not_(Business.is_watch_level()), +).define(Business.risk_class("reliable")) + +# Late shipments: a shipment with a recorded delay over 0 days. A shipment still in transit +# has no recorded delay and is not late. +Shipment.is_late = model.Relationship(f"{Shipment} is late") +model.where(Shipment.delay_days > 0).define(Shipment.is_late()) + +# Shipments from a supplier, and how many of them are late. +num_shipments = model.Relationship(f"there are {Integer:num_shipments} shipments from a supplier") +num_late_shipments = model.Relationship( + f"there are {Integer:num_late_shipments} late shipments from a supplier" +) +shipper = Business.ref() +model.define(num_shipments(aggs.count(Shipment).where(Shipment.supplier(shipper)) | 0)) +model.define(num_late_shipments( + aggs.count(Shipment).where(Shipment.supplier(shipper), Shipment.is_late()) | 0 +)) + +# Late shipments per supplier (a supplier with none has no count) and each supplier's rank by +# them, most first, ties broken by business id. The count is negated so both keys sort +# ascending. +Business.late_shipment_count = model.Property( + f"{Business} has {Integer:late_shipment_count} late shipments" +) +model.define(Business.late_shipment_count( + aggs.count(Shipment).per(Business).where(Shipment.supplier(Business), Shipment.is_late()) +)) +Business.late_rank = model.Property(f"{Business} has late-shipment rank {Integer:late_rank}") +model.define(Business.late_rank(aggs.rank(-Business.late_shipment_count, Business.id))) + +# Escalated demand orders. +num_escalated = model.Relationship(f"there are {Integer:num_escalated} escalated demands") +model.define(num_escalated(aggs.count(Demand).where(Demand.is_escalated()) | 0)) diff --git a/supply_chain_resilience/queries/resilience_report.py b/supply_chain_resilience/queries/resilience_report.py index ee3da512..c8b62ce6 100644 --- a/supply_chain_resilience/queries/resilience_report.py +++ b/supply_chain_resilience/queries/resilience_report.py @@ -8,27 +8,31 @@ from model import ( Business, - Demand, + CostChangePct, Operation, - Shipment, Site, + SiteCluster, baseline, - biz_graph, biz_num_edges, biz_num_nodes, eigenvector, graph, model, + num_components, num_edges, + num_escalated, + num_late_shipments, num_nodes, - reachable_to, + num_shipments, + num_source_links, site_offline, - target_customer, watch_avoid, - wcc, ) -from relationalai.semantics import Float, String, where -from relationalai.semantics.std import aggregates as aggs +from relationalai.semantics import Float, where + +# How many of the top-ranked sites and late-shipment suppliers the report lists. +TOP_SITES = 8 +TOP_LATE_SUPPLIERS = 5 def report_flow(flow, label): @@ -40,28 +44,11 @@ def report_flow(flow, label): print(f"• objective: {round(cost[0], 9)}\n") obj = cost[0] if cost and status in ("OPTIMAL", "LOCALLY_SOLVED") else None - # Extract active flows. + # The published count of active flows and the unmet orders and units. if obj is not None: - value_ref, op_ref, demand_ref = Float.ref(), String.ref(), String.ref() - flow_df = ( - model.select( - op_ref.alias("operation_id"), - value_ref.alias("flow"), - ) - .where(flow.routes(value_ref, op_ref), value_ref > 0.001) - .to_df() - ) - unmet_df = ( - model.select( - demand_ref.alias("demand_id"), - value_ref.alias("unmet"), - ) - .where(flow.unmet(value_ref, demand_ref), value_ref > 0.001) - .to_df() - ) - n_active = len(flow_df) - n_unmet = len(unmet_df) - total_unmet = unmet_df["unmet"].sum() if len(unmet_df) > 0 else 0.0 + n_active = int(model.select(flow.active_flows).to_df().iloc[0, 0]) + n_unmet = int(model.select(flow.unmet_orders).to_df().iloc[0, 0]) + total_unmet = float(model.select(flow.unmet_units).to_df().iloc[0, 0]) else: n_active, n_unmet, total_unmet = 0, 0, None @@ -75,20 +62,27 @@ def report_flow(flow, label): else: print(" All demand satisfied") - return {"label": label, "status": status, "objective": obj, "unmet": total_unmet} + return { + "label": label, + "problem": flow.name, + "status": status, + "objective": obj, + "unmet": total_unmet, + } if __name__ == "__main__": # Verify source_business derived relationship populates correctly. - sb_df = ( - model.select(Operation.id.alias("op"), Business.id.alias("biz")) - .where(Operation.source_business(Operation, Business)) - .to_df() - ) - print(f"Source-business links: {len(sb_df)}") - if len(sb_df) == 0: + n_links = int(model.select(num_source_links).to_df().iloc[0, 0]) + print(f"Source-business links: {n_links}") + if n_links == 0: print("WARNING: source_business derived relationship is empty!") else: + sb_df = ( + model.select(Operation.id.alias("op"), Business.id.alias("biz")) + .where(Operation.source_business(Operation, Business)) + .to_df() + ) print(f" Sample: {sb_df.head(5).to_string(index=False)}") # -------------------------------------------------- @@ -102,20 +96,21 @@ def report_flow(flow, label): biz_num_nodes.inspect() biz_num_edges.inspect() - supplier_node = biz_graph.Node.ref() + customer, supplier = Business.ref(), Business.ref() blast_df = ( - where( - reachable_to(supplier_node, target_customer), - supplier_node.business_type == "SUPPLIER", - ) - .select( - target_customer.name.alias("customer"), - supplier_node.id.alias("supplier_id"), - supplier_node.name.alias("supplier"), - supplier_node.reliability_score.alias("supplier_reliability"), + model.select( + customer.name.alias("customer"), + supplier.id.alias("supplier_id"), + supplier.name.alias("supplier"), ) + .where(Business.upstream_supplier(customer, supplier)) .to_df() ) + reliability_df = model.select( + Business.id.alias("supplier_id"), + Business.reliability_score.alias("supplier_reliability"), + ).to_df() + blast_df = blast_df.merge(reliability_df, on="supplier_id", how="left") print("\nUpstream supplier dependencies for high-priority customers:") if blast_df.empty: @@ -140,31 +135,17 @@ def report_flow(flow, label): num_nodes.inspect() num_edges.inspect() - node_ref = graph.Node.ref("n") - comp_ref = graph.Node.ref("comp") - - wcc_df = ( - where(wcc(node_ref, comp_ref)) - .select( - node_ref.id.alias("site_id"), - node_ref.name.alias("site_name"), - node_ref.site_type.alias("site_type"), - node_ref.region.alias("region"), - comp_ref.id.alias("component_id"), - aggs.count(node_ref).per(comp_ref).alias("cluster_size"), - ) - .to_df() - ) - - num_components = wcc_df["component_id"].nunique() - print(f"\nConnected components: {num_components}") - if num_components == 1: + n_clusters = int(model.select(num_components).to_df().iloc[0, 0]) + print(f"\nConnected components: {n_clusters}") + if n_clusters == 1: print("UNIFIED NETWORK: All sites in a single connected component") - for comp_id in sorted(wcc_df["component_id"].unique()): - comp_df = wcc_df[wcc_df["component_id"] == comp_id] - size = int(comp_df["cluster_size"].iloc[0]) - regions = ", ".join(sorted(comp_df["region"].unique())) - print(f" Component {comp_id}: {size} sites ({regions})") + cluster_df = model.select( + SiteCluster.id.alias("component_id"), + SiteCluster.n_sites.alias("n_sites"), + SiteCluster.regions.alias("regions"), + ).to_df() + for _, row in cluster_df.sort_values("component_id").iterrows(): + print(f" Component {row['component_id']}: {int(row['n_sites'])} sites ({row['regions']})") node_eig = graph.Node.ref("ne") eig_score = Float.ref("es") @@ -172,8 +153,7 @@ def report_flow(flow, label): eig_df = ( where( eigenvector(node_eig, eig_score), - node_eig.site_type != "STORE", - node_eig.site_type != "OFFICE", + node_eig.centrality_rank <= TOP_SITES, ) .select( node_eig.id.alias("site_id"), @@ -181,14 +161,14 @@ def report_flow(flow, label): node_eig.site_type.alias("site_type"), node_eig.region.alias("region"), eig_score.alias("centrality_score"), + node_eig.centrality_rank.alias("rank"), ) .to_df() - .sort_values("centrality_score", ascending=False) - .reset_index(drop=True) + .sort_values("rank") ) print("\nTop critical sites (eigenvector centrality):") - for _, row in eig_df.head(8).iterrows(): + for _, row in eig_df.iterrows(): print( f" {row['site_id']} {row['site_name']} ({row['site_type']}, {row['region']}): " f"centrality={row['centrality_score']:.4f}" @@ -203,29 +183,22 @@ def report_flow(flow, label): print("=" * 70) # Late shipment analysis. - supplier_ref = Business.ref() - shipments_df = ( - model.select( - Shipment.id.alias("id"), - supplier_ref.id.alias("supplier_id"), - Shipment.delay_days.alias("delay_days"), - ) - .where(Shipment.supplier(supplier_ref)) - .to_df() - ) - late_shipments = shipments_df[shipments_df["delay_days"] > 0] - total_n = len(shipments_df) - late_n = len(late_shipments) + total_n = int(model.select(num_shipments).to_df().iloc[0, 0]) + late_n = int(model.select(num_late_shipments).to_df().iloc[0, 0]) late_pct = f" ({100 * late_n / total_n:.0f}%)" if total_n else "" print(f"\nLate shipments: {late_n} of {total_n}{late_pct}") late_by_supplier = ( - late_shipments.groupby("supplier_id") - .size() - .reset_index(name="late_count") - .sort_values("late_count", ascending=False) + model.select( + Business.id.alias("supplier_id"), + Business.late_shipment_count.alias("late_count"), + Business.late_rank.alias("rank"), + ) + .where(Business.late_rank <= TOP_LATE_SUPPLIERS) + .to_df() + .sort_values("rank") ) - for _, row in late_by_supplier.head(5).iterrows(): - print(f" {row['supplier_id']}: {row['late_count']} late shipments") + for _, row in late_by_supplier.iterrows(): + print(f" {row['supplier_id']}: {int(row['late_count'])} late shipments") # Read the risk classes from the same rules the solves block and surcharge on: # avoid (both flags) and watch level (either flag, a superset of avoid). @@ -242,26 +215,18 @@ def report_flow(flow, label): .to_df() ) + risk_df = model.select(Business.id.alias("id"), Business.risk_class.alias("risk_class")).to_df() + all_biz_df = all_biz_df.merge(risk_df, on="id", how="left") + markers = {"avoid": "[X]", "watch": "[!]", "reliable": "[ ]"} + print("\nSupplier risk classification:") for _, row in all_biz_df.sort_values("reliability").iterrows(): - biz_id = row["id"] - if biz_id in avoid_ids: - rc, marker = "avoid", "[X]" - elif biz_id in watch_ids: - rc, marker = "watch", "[!]" - else: - rc, marker = "reliable", "[ ]" print( - f" {marker} {biz_id} {row['name']}: " - f"reliability={row['reliability']:.2f}, class={rc}" + f" {markers[row['risk_class']]} {row['id']} {row['name']}: " + f"reliability={row['reliability']:.2f}, class={row['risk_class']}" ) - esc_df = ( - model.select(aggs.count(Demand).alias("count")) - .where(Demand.is_escalated()) - .to_df() - ) - esc_n = int(esc_df["count"].iloc[0]) if len(esc_df) > 0 else 0 + esc_n = int(model.select(num_escalated).to_df().iloc[0, 0]) print(f"\nEscalated demands (HIGH priority): {esc_n}") # -------------------------------------------------- @@ -321,6 +286,7 @@ def report_flow(flow, label): print(f" {'-' * 65}") baseline_obj = results[0]["objective"] + pct_ref = Float.ref() for r in results: name = canonical_names[r["label"]] # A scenario with no solution has no cost or unmet demand to compare. @@ -329,7 +295,12 @@ def report_flow(flow, label): delta = "" if r["label"] != "Baseline": if baseline_obj and r["objective"] is not None: - pct = (r["objective"] - baseline_obj) / baseline_obj * 100 + pct = float( + model.where(CostChangePct(r["problem"], pct_ref)) + .select(pct_ref) + .to_df() + .iloc[0, 0] + ) delta = f" (+{pct:.1f}%)" if pct > 0 else f" ({pct:.1f}%)" else: delta = " (N/A)" diff --git a/supply_chain_resilience/runbook.md b/supply_chain_resilience/runbook.md index 0842017e..bf65ea80 100644 --- a/supply_chain_resilience/runbook.md +++ b/supply_chain_resilience/runbook.md @@ -145,7 +145,7 @@ Baseline OPTIMAL $1,865 / 8 flows / 0 unmet; S004 offline +88.5%; watch->avoid + **Response** -Each solve is its own problem in `model/reasoning.py` and publishes its own status and objective, so one infeasible scenario never affects the others; the report assembles the table. Baseline OPTIMAL 1,865.00, 0 unmet; S004-offline OPTIMAL 3,515.00 (+88.5%), 0 unmet; Watch-Avoid OPTIMAL 1,865.00 (0.0%), 0 unmet. +Each solve is its own problem in `model/risk_adjusted_flows.py` and publishes its own status and objective, so one infeasible scenario never affects the others; the report assembles the table. Baseline OPTIMAL 1,865.00, 0 unmet; S004-offline OPTIMAL 3,515.00 (+88.5%), 0 unmet; Watch-Avoid OPTIMAL 1,865.00 (0.0%), 0 unmet. ## Data diff --git a/synthetic_eligibility_records/README.md b/synthetic_eligibility_records/README.md index e99e997a..e61595ce 100644 --- a/synthetic_eligibility_records/README.md +++ b/synthetic_eligibility_records/README.md @@ -45,7 +45,7 @@ The rule structure here is a synthetic fixture policy modeled on the public [CMS ## What's included -- `model/` -- `schema.py` (ontology), `source.py` (reference data and its pre-solve checks), and `reasoning.py` (decisions, constraints, and solver configuration); `rai models deploy --path model` deploys the package to your Snowflake account, where each refresh runs the solve +- `model/` -- `schema.py` (ontology), `source.py` (reference data and its pre-solve checks), and `member_records.py` (decisions, constraints, solver configuration, and the published records); `rai models deploy --path model` deploys the package to your Snowflake account, where each refresh runs the solve - `queries/eligibility_records.py` -- prints the report from the deployed model: the solve status, the number of solutions, and every generated member record - `data/age_buckets.csv` -- 4 representative ages spanning the adult/senior split (2 under 65, 2 at or above) - `data/plans.csv` -- 3 plans (PPO, HMO, MedicareAdvantage) each on its own network @@ -201,9 +201,9 @@ Use this sequence to deploy the model and query it: ├── pyproject.toml ├── model/ │ ├── __init__.py +│ ├── member_records.py │ ├── schema.py -│ ├── source.py -│ └── reasoning.py +│ └── source.py ├── queries/ │ └── eligibility_records.py └── data/ @@ -380,6 +380,6 @@ To extend to a fleet of N members, reintroduce a `Member` concept inside the mod - `model.where(...)` filters at relational time only -- decision variables are not legal inside it. The rewriter raises this error when it encounters a decision-valued comparison in a `where` clause. - Move the decision condition into `implies` and use a tautological relational filter (or a real one) to scope any reference-data Concepts the IC needs. For example, replace `model.where(Plan.id == plan_id).require(num_dependents <= Plan.max_dependents)` with `model.where(Plan.max_dependents >= 0).require(implies(plan_id == Plan.id, num_dependents <= Plan.max_dependents))`. -- See the three constraint definitions in `model/reasoning.py` (`network_match_ic`, `senior_must_medicare_ic`, `non_senior_no_medicare_ic`) for the canonical idiom. +- See the three constraint definitions in `model/member_records.py` (`network_match_ic`, `senior_must_medicare_ic`, `non_senior_no_medicare_ic`) for the canonical idiom. diff --git a/synthetic_eligibility_records/model/__init__.py b/synthetic_eligibility_records/model/__init__.py index 5f0378d0..a8f3d00f 100644 --- a/synthetic_eligibility_records/model/__init__.py +++ b/synthetic_eligibility_records/model/__init__.py @@ -11,13 +11,16 @@ (test-data generation, claim-engine fuzzing, RegTech rules certification) want a batch of records per solve, not one. +The decision problem, its constraints and the published records are declared in +`member_records.py`; `source.py` loads and checks the reference data. + Run: `rai models deploy --path model` deploys this package to the schemas in raiconfig.yaml and waits for its first refresh, which runs the solve. `python -m queries.eligibility_records` then prints the report from the deployed model. """ -from .reasoning import ( +from .member_records import ( MAX_RECORDS, SENIOR_THRESHOLD_YEARS, MemberRecord, diff --git a/synthetic_eligibility_records/model/reasoning.py b/synthetic_eligibility_records/model/member_records.py similarity index 93% rename from synthetic_eligibility_records/model/reasoning.py rename to synthetic_eligibility_records/model/member_records.py index d294dfe0..ddac89b8 100644 --- a/synthetic_eligibility_records/model/reasoning.py +++ b/synthetic_eligibility_records/model/member_records.py @@ -2,9 +2,9 @@ from relationalai.semantics import Integer, String from relationalai.semantics.reasoners.prescriptive import Problem, implies +from relationalai.semantics.std import aggregates as aggs from .schema import AgeBucket, Plan, Provider, model -from .source import age_buckets_csv, plans_csv, providers_csv # Senior status (age >= 65) drives the Medicare-Advantage CFD. SENIOR_THRESHOLD_YEARS = 65 @@ -33,29 +33,30 @@ problem = Problem(model, Integer, name="synthetic_eligibility_records") # The report reads every record through `Variable.values(sol_idx, value)`, so the -# variables skip the write-back of the first solution (`populate=False`). +# variables skip the write-back of the first solution (`populate=False`). Each +# variable ranges over the smallest to the largest reference ID. age_bucket_var = problem.solve_for( age_bucket_id, type="int", name="age_bucket", - lower=int(age_buckets_csv["id"].min()), - upper=int(age_buckets_csv["id"].max()), + lower=aggs.min(AgeBucket.id), + upper=aggs.max(AgeBucket.id), populate=False, ) plan_id_var = problem.solve_for( plan_id, type="int", name="plan_id", - lower=int(plans_csv["id"].min()), - upper=int(plans_csv["id"].max()), + lower=aggs.min(Plan.id), + upper=aggs.max(Plan.id), populate=False, ) provider_id_var = problem.solve_for( provider_id, type="int", name="provider_id", - lower=int(providers_csv["id"].min()), - upper=int(providers_csv["id"].max()), + lower=aggs.min(Provider.id), + upper=aggs.max(Provider.id), populate=False, ) diff --git a/synthetic_order_lifecycle/README.md b/synthetic_order_lifecycle/README.md index dea143b5..b4c6664e 100644 --- a/synthetic_order_lifecycle/README.md +++ b/synthetic_order_lifecycle/README.md @@ -44,7 +44,7 @@ The same pattern applies to any test-data-generation problem where rows have to ## What's included -- `model/` -- the deployed model: ontology, decisions, constraints, and solver configuration, as a package (`schema.py` declares the concepts, `source.py` loads the sample data, `reasoning.py` states the decision problem). `rai models deploy --path model` deploys it to your Snowflake account, where each refresh runs the solve. +- `model/` -- the deployed model: ontology, decisions, constraints, and solver configuration, as a package (`schema.py` declares the concepts, `source.py` loads the sample data, `lifecycle_trace.py` states the decision problem and totals each order's fills). `rai models deploy --path model` deploys it to your Snowflake account, where each refresh runs the solve. - `queries/order_trace.py` -- the report, which prints the trace from the deployed model - `data/symbols.csv` -- 5 tradable symbols (AAPL, MSFT, GOOG, NVDA, TSLA) - `data/venues.csv` -- 5 trading venues (NYSE, NASDAQ, ARCA, BATS, IEX) @@ -212,7 +212,7 @@ Use this sequence to deploy the model and query it: │ ├── __init__.py # exports of the deployed model │ ├── schema.py # symbol, venue, order, and event concepts; the event-type vocabulary │ ├── source.py # loads the sample CSVs and derives the disallowed venue pairs -│ └── reasoning.py # event decisions, sequencing rules, solve +│ └── lifecycle_trace.py # event decisions, sequencing rules, solve, filled quantity per order ├── queries/ │ └── order_trace.py └── data/ @@ -319,7 +319,7 @@ model.define(SolveStatus(problem.termination_status())) ).require(implies(a_modify_ind + b_fill_ind == 2, A.ts_ms < B.ts_ms)) problem.satisfy(no_modify_after_fill_ic) ``` -- **Replace the synthetic time horizon** by reading `ts_ms` bounds from your real session schedule (market open / market close) and updating `TS_MIN` / `TS_MAX` in `model/reasoning.py`. +- **Replace the synthetic time horizon** by reading `ts_ms` bounds from your real session schedule (market open / market close) and updating `TS_MIN` / `TS_MAX` in `model/lifecycle_trace.py`. ## Troubleshooting diff --git a/synthetic_order_lifecycle/model/__init__.py b/synthetic_order_lifecycle/model/__init__.py index 17507030..1f7b7935 100644 --- a/synthetic_order_lifecycle/model/__init__.py +++ b/synthetic_order_lifecycle/model/__init__.py @@ -15,6 +15,9 @@ All decisions are integer: prices are integer ticks (1c, so 17500 reads as $175.00), times are integer milliseconds, quantities are integer shares. +The decision problem, and each order's filled quantity in the returned trace, are +in `lifecycle_trace.py`. + Run: `rai models deploy --path model` deploys this package to the schemas in raiconfig.yaml and waits for its first refresh, which runs the solve. @@ -22,8 +25,17 @@ model. """ -from .reasoning import SolveStatus, problem +from .lifecycle_trace import OrderFill, SolveStatus, problem from .schema import Order, OrderEvent, Venue, model from .source import DATA_DIR -__all__ = ["DATA_DIR", "Order", "OrderEvent", "SolveStatus", "Venue", "model", "problem"] +__all__ = [ + "DATA_DIR", + "Order", + "OrderEvent", + "OrderFill", + "SolveStatus", + "Venue", + "model", + "problem", +] diff --git a/synthetic_order_lifecycle/model/reasoning.py b/synthetic_order_lifecycle/model/lifecycle_trace.py similarity index 89% rename from synthetic_order_lifecycle/model/reasoning.py rename to synthetic_order_lifecycle/model/lifecycle_trace.py index a990c70f..73709e95 100644 --- a/synthetic_order_lifecycle/model/reasoning.py +++ b/synthetic_order_lifecycle/model/lifecycle_trace.py @@ -1,4 +1,5 @@ -"""Order lifecycle decision problem: one valid event trace for the pre-allocated slots.""" +"""Lifecycle trace: the decision problem that yields one valid event trace for the pre-allocated slots, +and each order's filled quantity in that trace.""" from relationalai.semantics import Integer, String from relationalai.semantics import sum as rai_sum @@ -172,3 +173,17 @@ # The solve's status, which the deployed model publishes for the queries. SolveStatus = model.Relationship(f"synthetic order lifecycle solve status is {String:status}") model.define(SolveStatus(problem.termination_status())) + +# The quantity filled across each order's events in the trace. The total lives on a concept of +# its own, not on Order: a value computed from the solution on a concept the solve reads fails +# the deploy. An order with no event has no fill total. +OrderFill = model.Concept("OrderFill", identify_by={"order_id": Integer}) +OrderFill.filled_qty = model.Property(f"{OrderFill} has filled qty {Integer:filled_qty}") +model.where(OrderEvent.order(Order)).define(OrderFill.new(order_id=Order.id)) +model.define( + OrderFill.filled_qty( + rai_sum(OrderEvent, OrderEvent.fill_qty) + .per(OrderFill) + .where(OrderEvent.order.id == OrderFill.order_id) + ) +) diff --git a/synthetic_order_lifecycle/model/schema.py b/synthetic_order_lifecycle/model/schema.py index 50b26cad..39eaea65 100644 --- a/synthetic_order_lifecycle/model/schema.py +++ b/synthetic_order_lifecycle/model/schema.py @@ -12,8 +12,11 @@ Venue = model.Concept("Venue", identify_by={"id": Integer}) Venue.name = model.Property(f"{Venue} has {String:name}") +# The (symbol, venue) pairs a symbol may trade on, loaded from symbol_venues.csv. +AllowedSymbolVenue = model.Relationship(f"{Symbol} trades on {Venue}") + # NotAllowedSymbolVenue (encoding artifact, not a domain concept): the -# disallowed dual of the allowed (symbol, venue) pairs in symbol_venues.csv. +# disallowed dual of the allowed (symbol, venue) pairs. # The CSP supports only the arithmetic operators !=, *, +, -, so the rule # is encoded as "forbid these pairs" rather than "require an allowed pair". NotAllowedSymbolVenue = model.Concept( diff --git a/synthetic_order_lifecycle/model/source.py b/synthetic_order_lifecycle/model/source.py index e0663b1b..a5e1b259 100644 --- a/synthetic_order_lifecycle/model/source.py +++ b/synthetic_order_lifecycle/model/source.py @@ -2,9 +2,18 @@ from pathlib import Path -from pandas import DataFrame, read_csv - -from .schema import NotAllowedSymbolVenue, Order, OrderEvent, Symbol, Venue, model +from pandas import read_csv +from relationalai.semantics import not_ + +from .schema import ( + AllowedSymbolVenue, + NotAllowedSymbolVenue, + Order, + OrderEvent, + Symbol, + Venue, + model, +) DATA_DIR = Path(__file__).resolve().parents[1] / "data" @@ -14,21 +23,16 @@ venues_csv = read_csv(DATA_DIR / "venues.csv") model.define(Venue.new(model.data(venues_csv).to_schema())) -# NotAllowedSymbolVenue rows: every (symbol, venue) pair not listed in symbol_venues.csv. -sv_csv = read_csv(DATA_DIR / "symbol_venues.csv") -all_pairs = [(int(s), int(v)) for s in symbols_csv["id"] for v in venues_csv["id"]] -allowed_pairs = {(int(r.symbol_id), int(r.venue_id)) for r in sv_csv.itertuples()} -disallowed_csv = DataFrame( - [ - {"symbol_id": s, "venue_id": v} - for (s, v) in all_pairs - if (s, v) not in allowed_pairs - ] +# The allowed pairs from symbol_venues.csv, and NotAllowedSymbolVenue: every (symbol, venue) +# pair that is not allowed. With full venue coverage there are no disallowed pairs. +sv_data = model.data(read_csv(DATA_DIR / "symbol_venues.csv")) +model.define(AllowedSymbolVenue(Symbol, Venue)).where( + Symbol.id == sv_data.symbol_id, + Venue.id == sv_data.venue_id, +) +model.where(Symbol, Venue, not_(AllowedSymbolVenue(Symbol, Venue))).define( + NotAllowedSymbolVenue.new(symbol_id=Symbol.id, venue_id=Venue.id) ) - -# With full venue coverage there are no disallowed pairs and nothing to load. -if not disallowed_csv.empty: - model.define(NotAllowedSymbolVenue.new(model.data(disallowed_csv).to_schema())) orders_csv = read_csv(DATA_DIR / "orders.csv") orders_data = model.data(orders_csv) diff --git a/synthetic_order_lifecycle/queries/order_trace.py b/synthetic_order_lifecycle/queries/order_trace.py index 4a1f68b9..c8b9a5b0 100644 --- a/synthetic_order_lifecycle/queries/order_trace.py +++ b/synthetic_order_lifecycle/queries/order_trace.py @@ -5,8 +5,7 @@ filled-quantity totals. """ -from model import Order, OrderEvent, SolveStatus, Venue, model -from relationalai.semantics import sum as rai_sum +from model import Order, OrderEvent, OrderFill, SolveStatus, Venue, model if __name__ == "__main__": status = model.select(SolveStatus).to_df().iloc[:, 0].tolist() @@ -37,5 +36,5 @@ model.select( Order.id.alias("order_id"), Order.original_qty.alias("original_qty"), - rai_sum(OrderEvent.fill_qty).per(Order).alias("filled_qty"), - ).where(OrderEvent.order(Order)).inspect() + OrderFill.filled_qty.alias("filled_qty"), + ).where(OrderFill.order_id == Order.id).inspect() diff --git a/telco_network_recovery/README.md b/telco_network_recovery/README.md index ea11cd5c..9d6b8a44 100644 --- a/telco_network_recovery/README.md +++ b/telco_network_recovery/README.md @@ -44,7 +44,7 @@ Built using **predictive reasoning** (GNN on a heterogeneous graph), **rules-bas ## What's included -- **Model**: a 5-stage pipeline (predictive, then rules, then graph, then paths, then prescriptive) on a single shared ontology, in the `model/` package (`schema.py` declares the 8 source-data concepts and the GNN task relationships, `source.py` loads the bundled CSVs and the equipment split, `reasoning.py` states the GNN, rules, graphs, and the upgrade MIP). `rai models deploy --path model` deploys it to your Snowflake account, where each refresh scores the equipment, derives the critical towers, and solves the upgrade MIP. +- **Model**: a 5-stage pipeline (predictive, then rules, then graph, then paths, then prescriptive) on a single shared ontology, in the `model/` package (`schema.py` declares the 8 source-data concepts and the GNN task relationships, `source.py` loads the bundled CSVs, the equipment split and the most severe advisory per MODEL, and a module per stage states its rules: `equipment_failure.py` the GNN (with `advisory_signals.py` for the advisory coverage figures), `critical_towers.py` the critical-tower rules, `customer_impact.py` the PageRank and customer impact, `call_paths.py` the call paths, and `tower_upgrades.py` the upgrade MIP). `rai models deploy --path model` deploys it to your Snowflake account, where each refresh scores the equipment, derives the critical towers, and solves the upgrade MIP. - **Training**: `train.py` — trains the equipment-failure GNN over the deployed splits and registers its version. - **Query**: `queries/recovery_report.py` — prints the per-stage diagnostics and the plan from the deployed model. - **Runbook**: `runbook.md` — a paste-testable walkthrough that reproduces the template step by step with the RAI skills; as important a reference as the code itself. @@ -154,7 +154,7 @@ Use this sequence to deploy the model, train the GNN, and query the recovery pla predictive: name: telco_failure_gnn # created on first use if it doesn't exist gnns: - equipment_failure: # the GNN's name in model/reasoning.py + equipment_failure: # the GNN's name in model/equipment_failure.py registry: .TELCO_NETWORK_RECOVERY model: EQUIPMENT_FAILURE version: V1 # train.py registers this version @@ -286,7 +286,12 @@ Use this sequence to deploy the model, train the GNN, and query the recovery pla │ ├── __init__.py # exports for train.py and the query │ ├── schema.py # concepts, GNN task relationships, plan relationships │ ├── source.py # bundled CSVs and the equipment split -│ └── reasoning.py # GNN, rules, graph analysis, and the upgrade MIP +│ ├── equipment_failure.py # at-risk label, GNN, tower failure intensity, training and score figures +│ ├── advisory_signals.py # advisory counts and the equipment the advised MODELs cover +│ ├── critical_towers.py # tower averages, the three restore branches, branch and region counts +│ ├── customer_impact.py # PageRank, customer value, per-tower impact +│ ├── call_paths.py # call-path enumeration from the seed hub +│ └── tower_upgrades.py # upgrade MIP, plan summary, and rationale tally ├── train.py # trains the GNN and registers its version ├── queries/ │ └── recovery_report.py # per-stage diagnostics and the plan @@ -356,7 +361,7 @@ For the full concept and property definitions, see `model/`; `runbook.md` builds After the solve, a `RestorePlan` singleton is populated and each selected option is tagged `is_selected_upgrade`. Every selected tower carries a `rationale` tag in the printed plan noting which upstream signal(s) drove its inclusion: `operational` (Stage 2 Branch 1 or 2 fired), `advisory/predicted` (Branch 3 fired), `high-value` (weighted impact in the top quartile of critical towers). -For the implementation, see `model/reasoning.py`; to reproduce it step by step with the RAI skills, follow `runbook.md`. +For the implementation, see the stage modules in `model/`; to reproduce it step by step with the RAI skills, follow `runbook.md`. ## Customize this template @@ -367,8 +372,8 @@ Focus on the first changes most users will make. - Replace the CSVs in `data/` with your own; keep the column names listed in *Sample data* above. - Regenerate the synthetic corpus: run `python _synthesize_advisory_data.py` in `data/`, then deploy again and train a new version. The generator uses a fixed seed, so it reproduces the bundled files; change its `SEED` for a different corpus. - The subscriber `STATUS` column is enum-mapped: values must exactly match the `SubscriberStatus` member names (`ACTIVE` / `SUSPENDED`). `lookup()` cannot validate values that arrive from data columns — unrecognized values silently map to a nonexistent member, and those subscribers drop out of the Stage 3 customer-impact aggregates. Extend the enum if your feed has more statuses. -- For Snowflake-backed runs, replace the CSV reads in `model/source.py` with Snowflake reads that return pandas DataFrames: the label derivation, the seeded train/validation/test split and the advisory selection there run in pandas. -- The model derives `Subscriber.customer_value` from `lifetime_value` and `churn_risk_score` in `model/reasoning.py`, so a subscriber feed needs both `LIFETIME_VALUE_USD` and `CHURN_RISK_SCORE`. +- For Snowflake-backed runs, replace the CSV reads in `model/source.py` with Snowflake reads that return pandas DataFrames: the seeded train/validation/test split and the advisory selection there run in pandas. The equipment frame needs its `STATUS` column, which the model turns into the `at_risk` label. +- The model derives `Subscriber.customer_value` from `lifetime_value` and `churn_risk_score` in `model/customer_impact.py`, so a subscriber feed needs both `LIFETIME_VALUE_USD` and `CHURN_RISK_SCORE`. ### Tune parameters @@ -380,7 +385,7 @@ Focus on the first changes most users will make. - **Add more advisories** — extend `data/model_advisories.csv` with new advisory types and severities; the GNN picks them up on the next training run. - **Add a fourth GNN edge** — e.g., `NetworkEquipment -> SimilarEquipment` via shared `FIRMWARE_VERSION` or `MANUFACTURER` to test other heterogeneous-neighborhood patterns. -- **Add SLA-tier weighting** — add `SLA_TIER` / `is_emergency_service` columns to `subscribers.csv` and fold them into the `customer_value` rule in `model/reasoning.py`; the rest of the chain is unchanged. +- **Add SLA-tier weighting** — add `SLA_TIER` / `is_emergency_service` columns to `subscribers.csv` and fold them into the `customer_value` rule in `model/customer_impact.py`; the rest of the chain is unchanged. - **Add backhaul coupling** — model `BackhaulPath` / `AggregationNode` as Concepts and add a per-node capacity constraint to Stage 5 (`aggs.sum(selected * capacity).per(AggregationNode) <= node_headroom`). - **Swap PageRank for another graph algorithm** — `weighted_pagerank` is the secondary network-effect signal; replace `call_graph.pagerank()` with `betweenness_centrality()` or `eigenvector_centrality()` to surface different structural roles without changing the optimizer. @@ -427,7 +432,7 @@ The bundled subscriber data has 50 enterprise (~$300K LTV avg) vs. 1,150 consume
Using Gurobi instead of HiGHS -The model solves with HiGHS, an open-source solver that needs no license. Where Gurobi is licensed, change `problem.configure("highs", ...)` in `model/reasoning.py` to `problem.configure("gurobi", ...)` and deploy again. +The model solves with HiGHS, an open-source solver that needs no license. Where Gurobi is licensed, change `problem.configure("highs", ...)` in `model/tower_upgrades.py` to `problem.configure("gurobi", ...)` and deploy again.
diff --git a/telco_network_recovery/model/__init__.py b/telco_network_recovery/model/__init__.py index 611a0a42..5e78d5a7 100644 --- a/telco_network_recovery/model/__init__.py +++ b/telco_network_recovery/model/__init__.py @@ -8,8 +8,9 @@ by manufacturer advisories (captured by a GNN). Neither signal is recoverable from the other alone, so the chain integrates both. -- Stage 1 -- Predictive: a binary classification GNN on - NetworkEquipment.STATUS over a heterogeneous *undirected* graph +- Stage 1 -- Predictive (`equipment_failure.py`, with `advisory_signals.py` for how much of the + equipment the advisories cover): a binary classification GNN on + NetworkEquipment.at_risk (status FAILING or WARNING) over a heterogeneous *undirected* graph that includes EquipmentHealth <-> NetworkEquipment, NetworkEquipment <-> CellTower, and ModelAdvisory <-> NetworkEquipment (the recall/defect edge). The undirected setting enables 2-hop message @@ -17,27 +18,27 @@ that a piece of equipment is at elevated risk when its tower-mate sits on a recalled MODEL. Per-equipment predicted-failure probability is summed per tower into `TowerFailureScore.failure_intensity`. -- Stage 2 -- Rules: derive per-tower averages from NetworkPerformance +- Stage 2 -- Rules (`critical_towers.py`): derive per-tower averages from NetworkPerformance and EquipmentHealth, then flag `CellTower.is_critical_restore` via three branches: WEST + DEGRADED + low equipment health; WEST + high packet loss + low health; or `failure_intensity > threshold` (any region). The third branch broadens upgrade scope beyond WEST when the GNN flags concentrated equipment failure elsewhere. -- Stage 3 -- Graph: Customer impact analysis. PageRank on a directed +- Stage 3 -- Graph (`customer_impact.py`): Customer impact analysis. PageRank on a directed Subscriber -> Subscriber call graph (caller -> callee) is the graph-reasoner signal. Per-critical-tower `weighted_impact` aggregates the *customer value* (revenue weighted by churn risk) of the distinct ACTIVE subscribers whose calls route through the tower; PageRank-weighted impact is exposed alongside as a secondary network-effect signal. -- Stage 4 -- Paths (PREVIEW): the arity-3 +- Stage 4 -- Paths (PREVIEW, `call_paths.py`): the arity-3 `{Subscriber} via {CellTower} calls {Subscriber}` edge; the model enumerates caller -> callee call paths over it (<=3 hops, simple, from the highest-PageRank subscriber), counts the paths and the routing towers on each hop via `relationship_fields`, keeps the highest influence load (PageRank summed along a path), and publishes that winning route with its routing towers. -- Stage 5 -- Prescriptive: tower-upgrade MIP. Decision variable +- Stage 5 -- Prescriptive (`tower_upgrades.py`): tower-upgrade MIP. Decision variable `TowerUpgradeOption.selected` is binary (one of three tiers per tower). Constraints: at most one tier per tower, total cost <= budget, total install crew-weeks <= 200. Objective maximizes @@ -45,7 +46,7 @@ Each stage enriches the shared ontology, and downstream stages consume those enrichments as first-class properties -- the accretive enrichment -pattern. +pattern. Each module imports the modules whose declarations it reads. Subscriber account status is modelled as a `model.Enum`: CSV strings map to members by name on load, and the @@ -60,19 +61,29 @@ diagnostics and the plan. """ -from .reasoning import ( - FAILURE_INTENSITY_THRESHOLD, +from .advisory_signals import AdvisedEquipmentCount, AdvisedModelEquipment, AdvisoryCount +from .call_paths import ( PATH_MAX_HOPS, - RestorePlan, RoutingTowerCount, SimplePathCount, - SolveObjective, - SolveStatus, TopCallPathHop, TopCallPathStep, +) +from .critical_towers import ( + FAILURE_INTENSITY_THRESHOLD, + CriticalRegionCount, + IntenseTowerCount, + RestoreBranchCounts, +) +from .equipment_failure import ( + POSITIVE_PROBABILITY_CUTOFF, + AtRiskBalance, + EquipmentSplitSize, + FailureIntensitySpread, + GnnRecallCounts, + PositiveProbabilitySpread, TowerFailureScore, gnn, - problem, ) from .schema import ( CallDetailRecord, @@ -90,27 +101,49 @@ model, ) from .source import DATA_DIR +from .tower_upgrades import ( + RationaleTally, + RestorePlan, + SelectedRegionCount, + SolveObjective, + SolveStatus, + problem, +) __all__ = [ "DATA_DIR", "FAILURE_INTENSITY_THRESHOLD", + "PATH_MAX_HOPS", + "POSITIVE_PROBABILITY_CUTOFF", + "AdvisedEquipmentCount", + "AdvisedModelEquipment", + "AdvisoryCount", + "AtRiskBalance", "CallDetailRecord", "CellTower", + "CriticalRegionCount", "EquipmentHealth", + "EquipmentSplitSize", + "FailureIntensitySpread", + "GnnRecallCounts", + "IntenseTowerCount", "ModelAdvisory", "NetworkEquipment", "NetworkPerformance", - "PATH_MAX_HOPS", + "PositiveProbabilitySpread", + "RationaleTally", + "RestoreBranchCounts", "RestorePlan", "RoutingTowerCount", + "SelectedRegionCount", "SimplePathCount", "SolveObjective", "SolveStatus", - "TopCallPathHop", - "TopCallPathStep", "Subscriber", "SubscriberStatus", "TestEqTable", + "TopCallPathHop", + "TopCallPathStep", "TowerFailureScore", "TowerUpgradeOption", "TrainEqTable", diff --git a/telco_network_recovery/model/advisory_signals.py b/telco_network_recovery/model/advisory_signals.py new file mode 100644 index 00000000..849b4062 --- /dev/null +++ b/telco_network_recovery/model/advisory_signals.py @@ -0,0 +1,31 @@ +"""Advisory signals: how many advisories the model keeps, and how much of the equipment the advised +models cover.""" + +from relationalai.semantics import Integer, String, distinct +from relationalai.semantics.std import aggregates as aggs + +from .schema import ModelAdvisory, NetworkEquipment, model + +# How many advisories the model keeps, and on how many distinct MODELs. +AdvisoryCount = model.Relationship(f"the model keeps {Integer:advisories} advisories on {Integer:models} distinct models") +model.define(AdvisoryCount(aggs.count(ModelAdvisory) | 0, aggs.count(distinct(ModelAdvisory.model)) | 0)) + +# The equipment items on each advised MODEL. +AdvisedModelEquipment = model.Relationship( + f"advised model {String:eqp_model} sits on {Integer:equipment_items} equipment items" +) +_advised_model = String.ref() +model.where(ModelAdvisory.model == _advised_model).define( + AdvisedModelEquipment( + _advised_model, + aggs.count(NetworkEquipment).per(_advised_model).where(NetworkEquipment.eqp_model == _advised_model) | 0, + ) +) + +# The equipment items that sit on any advised MODEL. +AdvisedEquipmentCount = model.Relationship(f"{Integer:equipment_items} equipment items sit on an advised model") +model.define( + AdvisedEquipmentCount( + aggs.count(NetworkEquipment).where(NetworkEquipment.eqp_model == ModelAdvisory.model) | 0 + ) +) diff --git a/telco_network_recovery/model/call_paths.py b/telco_network_recovery/model/call_paths.py new file mode 100644 index 00000000..80084acf --- /dev/null +++ b/telco_network_recovery/model/call_paths.py @@ -0,0 +1,117 @@ +"""Call paths: the simple call routes from the highest-PageRank subscriber, the routing towers on them, +and the top route by influence load.""" + +from relationalai.semantics import Float, Hash, Integer, not_, where +from relationalai.semantics.std import aggregates as aggs +from relationalai.semantics.std import math + +# Declares Subscriber.influence_score, the PageRank the paths are ranked by. +from . import customer_impact # noqa: F401 +from .schema import CallDetailRecord, CellTower, Subscriber, model + +# -------------------------------------------------- +# Stage 4: Paths -- Call-path enumeration through critical towers +# PREVIEW capability. +# -------------------------------------------------- +# Composes on Stage 3's Subscriber.influence_score (PageRank). Where +# PageRank scores a *node*, paths scores the *call route*: the model +# enumerates caller -> ... -> callee chains from the top-PageRank +# subscriber, recovers the routing tower on each hop, and ranks each +# route by total influence summed along the chain. The routing tower +# is the auxiliary middle field of an arity-3 edge, so each enumerated +# path also tells us which towers the influence flows through. + +# Arity-3 call edge: {Subscriber:caller} via {CellTower:tower} calls {Subscriber:callee}. +# First/last fields (caller/callee) are the path endpoints; the tower is the +# auxiliary middle field (field_index 1), recoverable per hop via +# relationship_fields. Derived from CallDetailRecord's caller/callee/routed_through. +Subscriber.calls_via = model.Relationship( + f"{Subscriber:caller} via {CellTower:tower} calls {Subscriber:callee}", + short_name="calls_via", +) +cdr_edge = CallDetailRecord.ref() +caller_sub, callee_sub, via_tower = Subscriber.ref(), Subscriber.ref(), CellTower.ref() +model.where( + cdr_edge.caller(caller_sub), + cdr_edge.callee(callee_sub), + cdr_edge.routed_through(via_tower), +).define(caller_sub.calls_via(via_tower, callee_sub)) + +# Path enumeration is declared here, in the model: a deployed model only has the +# path tables its own rules ask for, so a query cannot enumerate new paths. The +# scope is a deterministic seed -- the highest-PageRank subscriber, the smallest +# ID on an exact tie -- and call paths of up to PATH_MAX_HOPS hops, keeping +# simple paths only (the call graph is cyclic, so the negated existential drops +# walks that revisit a node). Both rank keys sort ascending, with the score +# negated, because the rules that read graph results run on the Logic engine, +# whose rank does not mix ascending and descending keys. +PATH_MAX_HOPS = 3 + +Subscriber.is_seed_hub = model.Relationship(f"{Subscriber} is the seed hub") +model.define(Subscriber.is_seed_hub()).where( + aggs.rank(-Subscriber.influence_score, Subscriber.id) == 1 +) + +seed = Subscriber.ref() +i, j = Integer.ref(), Integer.ref() +call_path = model.path(seed, Subscriber.calls_via.repeat(1, PATH_MAX_HOPS)).all().paths() +simple_hub_path = (seed.is_seed_hub(), call_path, not_(where(i < j, call_path.nodes(i) == call_path.nodes(j)))) + +SimplePathCount = model.Relationship(f"simple call paths from the seed hub number {Integer:paths}") +model.define(SimplePathCount(aggs.count(call_path).where(*simple_hub_path))) + +# The routing tower on each hop is field_index 1 of the arity-3 edge +# (caller=0, tower=1, callee=2). +routing_tower = CellTower.ref() +RoutingTowerCount = model.Relationship(f"routing towers on those paths number {Integer:towers}") +model.define( + RoutingTowerCount( + aggs.count(routing_tower).where( + *simple_hub_path, + call_path.relationship_fields["field_index"] == 1, + routing_tower == CellTower(call_path.relationship_fields["field"]), + ) + ) +) + +# Rank the simple paths by influence load, the PageRank summed along each path's +# nodes and rounded to six decimals, so paths whose printed loads agree tie, and +# keep the seed hub's highest. +def path_influence_load(): + return math.round(aggs.sum(Subscriber(call_path.nodes).influence_score).per(call_path), 6) + + +Subscriber.top_call_path_influence = model.Property(f"{Subscriber} has {Float:top_call_path_influence}") +model.where( + *simple_hub_path, + load := path_influence_load(), + top := aggs.max(load).per(seed), +).define(seed.top_call_path_influence(top)) + +# The winning route: the simple path with the highest influence load (on a tie, +# the smallest path ID), published step by step with the tower on each hop. +TopCallPath = model.Relationship(f"{Hash:path} is the seed hub's top call path") +model.where( + *simple_hub_path, + load := path_influence_load(), + aggs.rank(-load, call_path) == 1, +).define(TopCallPath(call_path)) +TopCallPathStep = model.Relationship( + f"the top call path visits {Subscriber:subscriber} at step {Integer:step}" +) +model.where(*simple_hub_path, TopCallPath(call_path)).define( + TopCallPathStep(Subscriber(call_path.nodes), call_path.nodes["index"]) +) +TopCallPathHop = model.Relationship( + f"the top call path routes hop {Integer:hop} through {CellTower:tower}" +) +model.where( + *simple_hub_path, + TopCallPath(call_path), + call_path.relationship_fields["field_index"] == 1, +).define( + TopCallPathHop( + call_path.relationship_fields["index"], + CellTower(call_path.relationship_fields["field"]), + ) +) diff --git a/telco_network_recovery/model/critical_towers.py b/telco_network_recovery/model/critical_towers.py new file mode 100644 index 00000000..c2ab0a37 --- /dev/null +++ b/telco_network_recovery/model/critical_towers.py @@ -0,0 +1,134 @@ +"""Critical towers: each tower's measured averages, the three restore branches that flag it critical, and +the counts of towers per branch and region and of scored towers above the threshold.""" + +from relationalai.semantics import Float, Integer, String, not_ +from relationalai.semantics.std import aggregates as aggs + +from .equipment_failure import TowerFailureScore +from .schema import CellTower, EquipmentHealth, NetworkEquipment, NetworkPerformance, model + +# Threshold for the predictive-driven critical-restore branch. +# failure_intensity is the per-tower SUM of equipment failure probs -- +# effectively expected count of at-risk equipment items on the tower. +# 1.5 means "the GNN is confident at least ~2 pieces are at risk." +FAILURE_INTENSITY_THRESHOLD = 1.5 + +# -------------------------------------------------- +# Stage 2: Rules -- flag is_critical_restore towers +# -------------------------------------------------- + +# Per-tower averages from NetworkPerformance (one row per measurement). +CellTower.avg_packet_loss = model.Property(f"{CellTower} has {Float:avg_packet_loss}") +CellTower.avg_latency_ms = model.Property(f"{CellTower} has {Float:avg_latency_ms}") +CellTower.avg_error_rate = model.Property(f"{CellTower} has {Float:avg_error_rate}") + +model.define( + CellTower.avg_packet_loss( + aggs.avg(NetworkPerformance.packet_loss_pct) + .where(NetworkPerformance.for_tower(CellTower)) + .per(CellTower) + ) +) +model.define( + CellTower.avg_latency_ms( + aggs.avg(NetworkPerformance.latency_ms) + .where(NetworkPerformance.for_tower(CellTower)) + .per(CellTower) + ) +) +model.define( + CellTower.avg_error_rate( + aggs.avg(NetworkPerformance.error_rate) + .where(NetworkPerformance.for_tower(CellTower)) + .per(CellTower) + ) +) + +# Per-tower equipment-health average (two-hop join via property +# equality: EquipmentHealth -> NetworkEquipment -> CellTower). +CellTower.avg_health_score = model.Property(f"{CellTower} has {Float:avg_health_score}") +model.define( + CellTower.avg_health_score( + aggs.avg(EquipmentHealth.health_score) + .where( + EquipmentHealth.equipment_id_fk == NetworkEquipment.id, + NetworkEquipment.tower_id_fk == CellTower.id, + ) + .per(CellTower) + ) +) + +# is_critical_restore flag, three branches (OR semantics): +# 1. WEST + DEGRADED status + low equipment health (operational) +# 2. WEST + high packet loss + low equipment health (ACTIVE-but-failing) +# 3. failure_intensity > threshold (predictive, any region) +# Each branch is published on its own, so the report can say which ones fired. +CellTower.fires_degraded_branch = model.Relationship(f"{CellTower} fires the degraded-status restore branch") +CellTower.fires_packet_loss_branch = model.Relationship(f"{CellTower} fires the packet-loss restore branch") +CellTower.fires_predictive_branch = model.Relationship(f"{CellTower} fires the predictive restore branch") +CellTower.is_critical_restore = model.Relationship(f"{CellTower} is critical restore") + +model.where( + CellTower.region == "WEST", + CellTower.status == "DEGRADED", + CellTower.avg_health_score < 0.85, +).define(CellTower.fires_degraded_branch()) + +model.where( + CellTower.region == "WEST", + CellTower.avg_packet_loss > 5.0, + CellTower.avg_health_score < 0.85, +).define(CellTower.fires_packet_loss_branch()) + +model.where( + TowerFailureScore.tower_id == CellTower.id, + TowerFailureScore.failure_intensity > FAILURE_INTENSITY_THRESHOLD, +).define(CellTower.fires_predictive_branch()) + +model.where(CellTower.fires_degraded_branch()).define(CellTower.is_critical_restore()) +model.where(CellTower.fires_packet_loss_branch()).define(CellTower.is_critical_restore()) +model.where(CellTower.fires_predictive_branch()).define(CellTower.is_critical_restore()) + +# The operational branches together, and the predictive branch with no operational one. +CellTower.fires_operational_branch = model.Relationship(f"{CellTower} fires an operational restore branch") +CellTower.fires_only_predictive_branch = model.Relationship( + f"{CellTower} fires the predictive restore branch and no operational one" +) +model.where(CellTower.fires_degraded_branch()).define(CellTower.fires_operational_branch()) +model.where(CellTower.fires_packet_loss_branch()).define(CellTower.fires_operational_branch()) +model.where(CellTower.fires_predictive_branch(), not_(CellTower.fires_operational_branch())).define( + CellTower.fires_only_predictive_branch() +) + +# How many towers are critical, how many fire each branch (a tower can fire several), and +# how many fire only the predictive branch. +RestoreBranchCounts = model.Relationship( + f"{Integer:critical} towers are critical restore; {Integer:degraded} fire the degraded-status branch, " + f"{Integer:packet_loss} the packet-loss branch and {Integer:predictive} the predictive branch, " + f"and {Integer:only_predictive} fire only the predictive branch" +) +model.define( + RestoreBranchCounts( + aggs.count(CellTower).where(CellTower.is_critical_restore()) | 0, + aggs.count(CellTower).where(CellTower.fires_degraded_branch()) | 0, + aggs.count(CellTower).where(CellTower.fires_packet_loss_branch()) | 0, + aggs.count(CellTower).where(CellTower.fires_predictive_branch()) | 0, + aggs.count(CellTower).where(CellTower.fires_only_predictive_branch()) | 0, + ) +) + +# How many scored towers have a failure intensity above the threshold, counted over the scores +# whether or not a CellTower carries the tower id. +IntenseTowerCount = model.Relationship(f"{Integer:towers} scored towers have a failure intensity above the threshold") +model.define( + IntenseTowerCount( + aggs.count(TowerFailureScore).where(TowerFailureScore.failure_intensity > FAILURE_INTENSITY_THRESHOLD) | 0 + ) +) + +# The critical towers in each region. +CriticalRegionCount = model.Relationship(f"{Integer:towers} critical-restore towers lie in region {String:region}") +_region = String.ref() +model.where(CellTower.is_critical_restore(), CellTower.region == _region).define( + CriticalRegionCount(aggs.count(CellTower).per(_region), _region) +) diff --git a/telco_network_recovery/model/customer_impact.py b/telco_network_recovery/model/customer_impact.py new file mode 100644 index 00000000..ee411420 --- /dev/null +++ b/telco_network_recovery/model/customer_impact.py @@ -0,0 +1,97 @@ +"""Customer impact: subscriber PageRank, each subscriber's customer value, and each critical tower's +impact on customers.""" + +from relationalai.semantics import Float, distinct +from relationalai.semantics.reasoners.graph import Graph +from relationalai.semantics.std import aggregates as aggs + +# Declares CellTower.is_critical_restore, the towers whose impact matters. +from . import critical_towers # noqa: F401 +from .schema import CallDetailRecord, CellTower, Subscriber, SubscriberStatus, model + +# -------------------------------------------------- +# Stage 3: Graph -- Customer impact analysis +# (PageRank as graph-reasoner signal; per-tower weighted_impact from +# customer_value (revenue x churn). PageRank-weighted impact retained +# as a secondary network-effect signal alongside the headline measure.) +# -------------------------------------------------- + +call_graph = Graph( + model, + name="call_graph", + directed=True, + weighted=False, + node_concept=Subscriber, + edge_concept=CallDetailRecord, + edge_src_relationship=CallDetailRecord.caller, + edge_dst_relationship=CallDetailRecord.callee, + aggregator="sum", +) +call_graph.Node.influence_score = call_graph.pagerank() + +# Per-subscriber customer_value = lifetime value weighted by churn risk: +# at-risk subscribers (high churn_risk_score) get up to ~1.9x the weight +# of stable ones. Possible refinements: SLA-tier and emergency-service +# multipliers; NPS-deterioration weighting; log-scaling to compress the +# enterprise-vs-consumer LTV gap (~130x in the bundled corpus). +model.define(Subscriber.customer_value(Subscriber.lifetime_value * (1.0 + Subscriber.churn_risk_score))) + +CellTower.impact_count = model.Property(f"{CellTower} has {Float:impact_count}") +# weighted_impact is the headline per-tower customer-impact score: the +# sum of customer_value (revenue x churn) over the distinct ACTIVE +# subscribers whose calls route through the tower. The Stage 5 MIP +# objective consumes this directly to prioritize towers by +# revenue-at-risk weighted by churn urgency. +# +# The sum is keyed by subscriber, so a subscriber's value counts once per +# tower however many of their calls it carries: revenue at risk does not +# grow with call volume. +CellTower.weighted_impact = model.Property(f"{CellTower} has {Float:weighted_impact}") +# Secondary signal: PageRank-weighted impact retained so the graph +# reasoner's network-effect view is still queryable alongside the +# revenue-based headline. Not consumed by the Stage 5 objective. +CellTower.weighted_pagerank = model.Property(f"{CellTower} has {Float:weighted_pagerank}") + +model.define( + CellTower.impact_count( + aggs.count(distinct(Subscriber)) + .where( + CallDetailRecord.routed_through(CellTower), + CallDetailRecord.caller(Subscriber), + Subscriber.status == SubscriberStatus.ACTIVE, + ) + .per(CellTower) + ) +) +model.define( + CellTower.weighted_impact( + aggs.sum(Subscriber.customer_value) + .where( + CallDetailRecord.routed_through(CellTower), + CallDetailRecord.caller(Subscriber), + Subscriber.status == SubscriberStatus.ACTIVE, + ) + .per(CellTower) + ) +) +model.define( + CellTower.weighted_pagerank( + aggs.sum(Subscriber.influence_score) + .where( + CallDetailRecord.routed_through(CellTower), + CallDetailRecord.caller(Subscriber), + Subscriber.status == SubscriberStatus.ACTIVE, + ) + .per(CellTower) + ) +) + +# A critical tower is high-value when its weighted_impact reaches the 75th +# percentile of the critical towers' (interpolated linearly between ranks). +peer = CellTower.ref() +CellTower.is_high_value = model.Relationship(f"{CellTower} is a high-value critical tower") +model.where( + CellTower.is_critical_restore(), + CellTower.weighted_impact + >= aggs.percentile(75, peer, peer.weighted_impact).where(peer.is_critical_restore()), +).define(CellTower.is_high_value()) diff --git a/telco_network_recovery/model/equipment_failure.py b/telco_network_recovery/model/equipment_failure.py new file mode 100644 index 00000000..a06dc532 --- /dev/null +++ b/telco_network_recovery/model/equipment_failure.py @@ -0,0 +1,237 @@ +"""Equipment failure: the GNN that scores each equipment item's failure risk, each tower's summed failure +intensity, and the figures that profile the training data and the scores.""" + +from relationalai.semantics import Float, Integer, String, not_ +from relationalai.semantics.reasoners.graph import Graph +from relationalai.semantics.reasoners.predictive import GNN, PropertyTransformer +from relationalai.semantics.std import aggregates as aggs + +from .schema import ( + CellTower, + EquipmentHealth, + ModelAdvisory, + NetworkEquipment, + Test, + TestEqTable, + Train, + TrainEqTable, + Val, + ValEqTable, + model, +) +from .source import SEED + +GNN_EPOCHS = 80 +GNN_LR = 0.002 + +# Equipment with one of these statuses is at risk: the positive class of the GNN's +# binary label. +AT_RISK_STATUSES = ("FAILING", "WARNING") + +# The standard probability cutoff for reading a positive prediction. +POSITIVE_PROBABILITY_CUTOFF = 0.5 + +# -------------------------------------------------- +# Stage 1: Predictive -- equipment-failure binary GNN +# -------------------------------------------------- + +# The GNN's label: 1 for an at-risk status, 0 otherwise, including equipment without a status. +for _status in AT_RISK_STATUSES: + model.where(NetworkEquipment.status == _status).define(NetworkEquipment.at_risk(1)) +model.where(*(not_(NetworkEquipment.status == _status) for _status in AT_RISK_STATUSES)).define( + NetworkEquipment.at_risk(0) +) + +# Heterogeneous graph with three FK / shared-MODEL edges: +# 1. EquipmentHealth <-> NetworkEquipment (per-equipment health features) +# 2. NetworkEquipment <-> CellTower (tower-context features) +# 3. ModelAdvisory <-> NetworkEquipment (recall/defect signal via MODEL) +# We use `directed=False` (undirected, bidirectional message passing) +# so the GNN can propagate signal across multi-hop paths: a piece of +# equipment whose own MODEL has no advisory can still inherit risk +# from a tower-mate whose MODEL does, via the path +# ModelAdvisory -> tower_mate -> CellTower -> this_equipment. +gnn_graph = Graph(model, name="equipment_graph", directed=False, weighted=False) + +model.define(gnn_graph.Edge.new(src=EquipmentHealth, dst=NetworkEquipment)).where( + EquipmentHealth.equipment_id_fk == NetworkEquipment.id, +) +model.define(gnn_graph.Edge.new(src=NetworkEquipment, dst=CellTower)).where( + NetworkEquipment.tower_id_fk == CellTower.id, +) +model.define(gnn_graph.Edge.new(src=ModelAdvisory, dst=NetworkEquipment)).where( + ModelAdvisory.model == NetworkEquipment.eqp_model, +) + +# Feature configuration. Drop identifier / FK columns, the label and the status it +# derives from, and high-cardinality free-text fields. Pull every other ontology +# property as a typed feature. +pt = PropertyTransformer( + drop=[ + CellTower.id, + CellTower.name, + NetworkEquipment.id, + NetworkEquipment.tower_id_fk, + # The GNN target is at_risk, derived from status -- keeping either as a + # feature would leak. + NetworkEquipment.status, + NetworkEquipment.at_risk, + EquipmentHealth.id, + EquipmentHealth.equipment_id_fk, + ModelAdvisory.model, + ], + category=[ + NetworkEquipment.equipment_type, + NetworkEquipment.manufacturer, + NetworkEquipment.eqp_model, + NetworkEquipment.firmware_version, + CellTower.tower_type, + CellTower.status, + CellTower.region, + ModelAdvisory.advisory_type, + ], + continuous=[ + EquipmentHealth.failure_rate, + EquipmentHealth.temperature_avg_c, + EquipmentHealth.power_consumption_kw, + EquipmentHealth.health_score, + ModelAdvisory.severity, + ], + integer=[ + EquipmentHealth.mtbf_hours, + CellTower.capacity_gbps, + ], + datetime=[ + NetworkEquipment.install_date, + EquipmentHealth.last_failure_date, + EquipmentHealth.measurement_date, + CellTower.install_date, + ModelAdvisory.issued_date, + ], +) + +# `name` ties this GNN to the registered model and version that +# `reasoners.predictive.gnns.equipment_failure` names in raiconfig.yaml: +# train.py registers the trained run there, and every refresh scores all +# equipment with it. +gnn = GNN( + name="equipment_failure", + graph=gnn_graph, + property_transformer=pt, + train=Train, + validation=Val, + task_type="binary_classification", + eval_metric="roc_auc", + has_time_column=False, + stream_logs=False, + seed=SEED, + n_epochs=GNN_EPOCHS, + lr=GNN_LR, +) +NetworkEquipment.predictions = gnn.predictions(domain=Test) + +# TowerFailureScore concept: bridge concept holding the per-tower SUM of +# the equipment failure probabilities (= expected count of at-risk +# equipment on the tower), joined onto CellTower by tower id. SUM (not max) +# preserves per-tower differentiation when individual predictions saturate +# near 0 or 1. It is a concept of its own, not a CellTower property: the +# GNN reads the CellTower table, so a CellTower property derived from the +# predictions would make the predictions depend on themselves. +TowerFailureScore = model.Concept("TowerFailureScore", identify_by={"tower_id": String}) +TowerFailureScore.failure_intensity = model.Property(f"{TowerFailureScore} has {Float:failure_intensity}") +model.define(TowerFailureScore.new(tower_id=NetworkEquipment.tower_id_fk)).where( + NetworkEquipment.predictions, +) +model.define( + TowerFailureScore.failure_intensity( + aggs.sum(NetworkEquipment, NetworkEquipment.predictions.probs) + .where(NetworkEquipment.tower_id_fk == TowerFailureScore.tower_id) + .per(TowerFailureScore) + ) +) + +# -------------------------------------------------- +# What the GNN trains on +# -------------------------------------------------- + +# How many equipment items each split holds. +EquipmentSplitSize = model.Relationship( + f"the equipment split has {Integer:train_items} train, {Integer:validation_items} validation " + f"and {Integer:test_items} test items" +) +model.define(EquipmentSplitSize(aggs.count(TrainEqTable), aggs.count(ValEqTable), aggs.count(TestEqTable))) + +# The label's balance over all equipment: how many items, how many at risk, and the at-risk rate. +AtRiskBalance = model.Relationship( + f"the equipment has {Integer:items} items, {Integer:at_risk_items} of them at risk, " + f"an at-risk rate of {Float:at_risk_rate}" +) +model.define( + AtRiskBalance( + aggs.count(NetworkEquipment), + aggs.sum(NetworkEquipment, NetworkEquipment.at_risk), + aggs.avg(NetworkEquipment, NetworkEquipment.at_risk), + ) +) + +# -------------------------------------------------- +# What the GNN predicts +# -------------------------------------------------- + +# Towers ranked by failure intensity, highest first, ties broken by tower id. The +# intensity is negated so both keys sort ascending: the Logic engine's rank does not +# mix ascending and descending keys. +TowerFailureScore.failure_rank = model.Property(f"{TowerFailureScore} has {Integer:failure_rank}") +model.define( + TowerFailureScore.failure_rank(aggs.rank(-TowerFailureScore.failure_intensity, TowerFailureScore.tower_id)) +) + +# The scored towers and the spread of their failure intensities. +FailureIntensitySpread = model.Relationship( + f"{Integer:scored_towers} towers have failure intensities from {Float:minimum} " + f"to {Float:maximum} with median {Float:median}" +) +model.define( + FailureIntensitySpread( + aggs.count(TowerFailureScore), + aggs.min(TowerFailureScore.failure_intensity), + aggs.max(TowerFailureScore.failure_intensity), + aggs.median(TowerFailureScore, TowerFailureScore.failure_intensity), + ) +) + +# How many at-risk equipment items the GNN catches: by its predicted label and by the +# probability cutoff. +GnnRecallCounts = model.Relationship( + f"the GNN catches {Integer:by_label} at-risk equipment items by predicted label " + f"and {Integer:by_cutoff} by the probability cutoff" +) +_scored_at_risk = (NetworkEquipment.predictions, NetworkEquipment.at_risk == 1) +model.define( + GnnRecallCounts( + aggs.count(NetworkEquipment).where( + *_scored_at_risk, NetworkEquipment.predictions.predicted_labels == 1 + ) + | 0, + aggs.count(NetworkEquipment).where( + *_scored_at_risk, NetworkEquipment.predictions.probs >= POSITIVE_PROBABILITY_CUTOFF + ) + | 0, + ) +) + +# The scored equipment items and the spread of their positive-class probabilities. +PositiveProbabilitySpread = model.Relationship( + f"{Integer:scored_items} equipment items have positive probabilities from {Float:minimum} " + f"to {Float:maximum} with median {Float:median}, and {Integer:at_cutoff} reach the cutoff" +) +model.define( + PositiveProbabilitySpread( + aggs.count(NetworkEquipment).where(NetworkEquipment.predictions), + aggs.min(NetworkEquipment.predictions.probs), + aggs.max(NetworkEquipment.predictions.probs), + aggs.median(NetworkEquipment, NetworkEquipment.predictions.probs), + aggs.count(NetworkEquipment).where(NetworkEquipment.predictions.probs >= POSITIVE_PROBABILITY_CUTOFF) + | 0, + ) +) diff --git a/telco_network_recovery/model/reasoning.py b/telco_network_recovery/model/reasoning.py deleted file mode 100644 index 283e6e54..00000000 --- a/telco_network_recovery/model/reasoning.py +++ /dev/null @@ -1,561 +0,0 @@ -"""Telco reasoning chain: equipment-failure GNN, critical-tower rules, customer-impact graph, call paths, and the upgrade MIP.""" - -from relationalai.semantics import Float, Hash, Integer, String, distinct, not_, where -from relationalai.semantics.reasoners.graph import Graph -from relationalai.semantics.reasoners.predictive import GNN, PropertyTransformer -from relationalai.semantics.reasoners.prescriptive import Problem -from relationalai.semantics.std import aggregates as aggs -from relationalai.semantics.std import math - -from .schema import ( - CallDetailRecord, - CellTower, - EquipmentHealth, - ModelAdvisory, - NetworkEquipment, - NetworkPerformance, - Subscriber, - SubscriberStatus, - Test, - TowerUpgradeOption, - Train, - Val, - model, -) -from .source import SEED - -GNN_EPOCHS = 80 -GNN_LR = 0.002 - -# Stage 5 budget envelope. -BUDGET_USD = 5_000_000 -INSTALL_WEEKS_BUDGET = 200 - -# Stage 2 threshold for the predictive-driven critical-restore branch. -# failure_intensity is the per-tower SUM of equipment failure probs -- -# effectively expected count of at-risk equipment items on the tower. -# 1.5 means "the GNN is confident at least ~2 pieces are at risk." -FAILURE_INTENSITY_THRESHOLD = 1.5 - -# -------------------------------------------------- -# Stage 1: Predictive -- equipment-failure binary GNN -# -------------------------------------------------- - -# Heterogeneous graph with three FK / shared-MODEL edges: -# 1. EquipmentHealth <-> NetworkEquipment (per-equipment health features) -# 2. NetworkEquipment <-> CellTower (tower-context features) -# 3. ModelAdvisory <-> NetworkEquipment (recall/defect signal via MODEL) -# We use `directed=False` (undirected, bidirectional message passing) -# so the GNN can propagate signal across multi-hop paths: a piece of -# equipment whose own MODEL has no advisory can still inherit risk -# from a tower-mate whose MODEL does, via the path -# ModelAdvisory -> tower_mate -> CellTower -> this_equipment. -gnn_graph = Graph(model, name="equipment_graph", directed=False, weighted=False) - -model.define(gnn_graph.Edge.new(src=EquipmentHealth, dst=NetworkEquipment)).where( - EquipmentHealth.equipment_id_fk == NetworkEquipment.id, -) -model.define(gnn_graph.Edge.new(src=NetworkEquipment, dst=CellTower)).where( - NetworkEquipment.tower_id_fk == CellTower.id, -) -model.define(gnn_graph.Edge.new(src=ModelAdvisory, dst=NetworkEquipment)).where( - ModelAdvisory.model == NetworkEquipment.eqp_model, -) - -# Feature configuration. Drop identifier / FK columns, the label, and -# high-cardinality free-text fields. Pull every other ontology property -# as a typed feature. -pt = PropertyTransformer( - drop=[ - CellTower.id, - CellTower.name, - NetworkEquipment.id, - NetworkEquipment.tower_id_fk, - # The GNN target is at_risk -- keeping it as a feature would leak. - NetworkEquipment.at_risk, - EquipmentHealth.id, - EquipmentHealth.equipment_id_fk, - ModelAdvisory.model, - ], - category=[ - NetworkEquipment.equipment_type, - NetworkEquipment.manufacturer, - NetworkEquipment.eqp_model, - NetworkEquipment.firmware_version, - CellTower.tower_type, - CellTower.status, - CellTower.region, - ModelAdvisory.advisory_type, - ], - continuous=[ - EquipmentHealth.failure_rate, - EquipmentHealth.temperature_avg_c, - EquipmentHealth.power_consumption_kw, - EquipmentHealth.health_score, - ModelAdvisory.severity, - ], - integer=[ - EquipmentHealth.mtbf_hours, - CellTower.capacity_gbps, - ], - datetime=[ - NetworkEquipment.install_date, - EquipmentHealth.last_failure_date, - EquipmentHealth.measurement_date, - CellTower.install_date, - ModelAdvisory.issued_date, - ], -) - -# `name` ties this GNN to the registered model and version that -# `reasoners.predictive.gnns.equipment_failure` names in raiconfig.yaml: -# train.py registers the trained run there, and every refresh scores all -# equipment with it. -gnn = GNN( - name="equipment_failure", - graph=gnn_graph, - property_transformer=pt, - train=Train, - validation=Val, - task_type="binary_classification", - eval_metric="roc_auc", - has_time_column=False, - stream_logs=False, - seed=SEED, - n_epochs=GNN_EPOCHS, - lr=GNN_LR, -) -NetworkEquipment.predictions = gnn.predictions(domain=Test) - -# TowerFailureScore concept: bridge concept holding the per-tower SUM of -# the equipment failure probabilities (= expected count of at-risk -# equipment on the tower), joined onto CellTower by tower id. SUM (not max) -# preserves per-tower differentiation when individual predictions saturate -# near 0 or 1. It is a concept of its own, not a CellTower property: the -# GNN reads the CellTower table, so a CellTower property derived from the -# predictions would make the predictions depend on themselves. -TowerFailureScore = model.Concept("TowerFailureScore", identify_by={"tower_id": String}) -TowerFailureScore.failure_intensity = model.Property(f"{TowerFailureScore} has {Float:failure_intensity}") -model.define(TowerFailureScore.new(tower_id=NetworkEquipment.tower_id_fk)).where( - NetworkEquipment.predictions, -) -model.define( - TowerFailureScore.failure_intensity( - aggs.sum(NetworkEquipment, NetworkEquipment.predictions.probs) - .where(NetworkEquipment.tower_id_fk == TowerFailureScore.tower_id) - .per(TowerFailureScore) - ) -) - -# -------------------------------------------------- -# Stage 2: Rules -- flag is_critical_restore towers -# -------------------------------------------------- - -# Per-tower averages from NetworkPerformance (one row per measurement). -CellTower.avg_packet_loss = model.Property(f"{CellTower} has {Float:avg_packet_loss}") -CellTower.avg_latency_ms = model.Property(f"{CellTower} has {Float:avg_latency_ms}") -CellTower.avg_error_rate = model.Property(f"{CellTower} has {Float:avg_error_rate}") - -model.define( - CellTower.avg_packet_loss( - aggs.avg(NetworkPerformance.packet_loss_pct) - .where(NetworkPerformance.for_tower(CellTower)) - .per(CellTower) - ) -) -model.define( - CellTower.avg_latency_ms( - aggs.avg(NetworkPerformance.latency_ms) - .where(NetworkPerformance.for_tower(CellTower)) - .per(CellTower) - ) -) -model.define( - CellTower.avg_error_rate( - aggs.avg(NetworkPerformance.error_rate) - .where(NetworkPerformance.for_tower(CellTower)) - .per(CellTower) - ) -) - -# Per-tower equipment-health average (two-hop join via property -# equality: EquipmentHealth -> NetworkEquipment -> CellTower). -CellTower.avg_health_score = model.Property(f"{CellTower} has {Float:avg_health_score}") -model.define( - CellTower.avg_health_score( - aggs.avg(EquipmentHealth.health_score) - .where( - EquipmentHealth.equipment_id_fk == NetworkEquipment.id, - NetworkEquipment.tower_id_fk == CellTower.id, - ) - .per(CellTower) - ) -) - -# is_critical_restore flag, three branches (OR semantics): -# 1. WEST + DEGRADED status + low equipment health (operational) -# 2. WEST + high packet loss + low equipment health (ACTIVE-but-failing) -# 3. failure_intensity > threshold (predictive, any region) -# Each branch is published on its own, so the report can say which ones fired. -CellTower.fires_degraded_branch = model.Relationship(f"{CellTower} fires the degraded-status restore branch") -CellTower.fires_packet_loss_branch = model.Relationship(f"{CellTower} fires the packet-loss restore branch") -CellTower.fires_predictive_branch = model.Relationship(f"{CellTower} fires the predictive restore branch") -CellTower.is_critical_restore = model.Relationship(f"{CellTower} is critical restore") - -model.where( - CellTower.region == "WEST", - CellTower.status == "DEGRADED", - CellTower.avg_health_score < 0.85, -).define(CellTower.fires_degraded_branch()) - -model.where( - CellTower.region == "WEST", - CellTower.avg_packet_loss > 5.0, - CellTower.avg_health_score < 0.85, -).define(CellTower.fires_packet_loss_branch()) - -model.where( - TowerFailureScore.tower_id == CellTower.id, - TowerFailureScore.failure_intensity > FAILURE_INTENSITY_THRESHOLD, -).define(CellTower.fires_predictive_branch()) - -model.where(CellTower.fires_degraded_branch()).define(CellTower.is_critical_restore()) -model.where(CellTower.fires_packet_loss_branch()).define(CellTower.is_critical_restore()) -model.where(CellTower.fires_predictive_branch()).define(CellTower.is_critical_restore()) - -# -------------------------------------------------- -# Stage 3: Graph -- Customer impact analysis -# (PageRank as graph-reasoner signal; per-tower weighted_impact from -# customer_value (revenue x churn). PageRank-weighted impact retained -# as a secondary network-effect signal alongside the headline measure.) -# -------------------------------------------------- - -call_graph = Graph( - model, - name="call_graph", - directed=True, - weighted=False, - node_concept=Subscriber, - edge_concept=CallDetailRecord, - edge_src_relationship=CallDetailRecord.caller, - edge_dst_relationship=CallDetailRecord.callee, - aggregator="sum", -) -call_graph.Node.influence_score = call_graph.pagerank() - -# Per-subscriber customer_value = lifetime value weighted by churn risk: -# at-risk subscribers (high churn_risk_score) get up to ~1.9x the weight -# of stable ones. Possible refinements: SLA-tier and emergency-service -# multipliers; NPS-deterioration weighting; log-scaling to compress the -# enterprise-vs-consumer LTV gap (~130x in the bundled corpus). -model.define(Subscriber.customer_value(Subscriber.lifetime_value * (1.0 + Subscriber.churn_risk_score))) - -CellTower.impact_count = model.Property(f"{CellTower} has {Float:impact_count}") -# weighted_impact is the headline per-tower customer-impact score: the -# sum of customer_value (revenue x churn) over the distinct ACTIVE -# subscribers whose calls route through the tower. The Stage 5 MIP -# objective consumes this directly to prioritize towers by -# revenue-at-risk weighted by churn urgency. -# -# The sum is keyed by subscriber, so a subscriber's value counts once per -# tower however many of their calls it carries: revenue at risk does not -# grow with call volume. -CellTower.weighted_impact = model.Property(f"{CellTower} has {Float:weighted_impact}") -# Secondary signal: PageRank-weighted impact retained so the graph -# reasoner's network-effect view is still queryable alongside the -# revenue-based headline. Not consumed by the Stage 5 objective. -CellTower.weighted_pagerank = model.Property(f"{CellTower} has {Float:weighted_pagerank}") - -model.define( - CellTower.impact_count( - aggs.count(distinct(Subscriber)) - .where( - CallDetailRecord.routed_through(CellTower), - CallDetailRecord.caller(Subscriber), - Subscriber.status == SubscriberStatus.ACTIVE, - ) - .per(CellTower) - ) -) -model.define( - CellTower.weighted_impact( - aggs.sum(Subscriber.customer_value) - .where( - CallDetailRecord.routed_through(CellTower), - CallDetailRecord.caller(Subscriber), - Subscriber.status == SubscriberStatus.ACTIVE, - ) - .per(CellTower) - ) -) -model.define( - CellTower.weighted_pagerank( - aggs.sum(Subscriber.influence_score) - .where( - CallDetailRecord.routed_through(CellTower), - CallDetailRecord.caller(Subscriber), - Subscriber.status == SubscriberStatus.ACTIVE, - ) - .per(CellTower) - ) -) - -# A critical tower is high-value when its weighted_impact reaches the 75th -# percentile of the critical towers' (interpolated linearly between ranks). -peer = CellTower.ref() -CellTower.is_high_value = model.Relationship(f"{CellTower} is a high-value critical tower") -model.where( - CellTower.is_critical_restore(), - CellTower.weighted_impact - >= aggs.percentile(75, peer, peer.weighted_impact).where(peer.is_critical_restore()), -).define(CellTower.is_high_value()) - -# -------------------------------------------------- -# Stage 4: Paths -- Call-path enumeration through critical towers -# PREVIEW capability. -# -------------------------------------------------- -# Composes on Stage 3's Subscriber.influence_score (PageRank). Where -# PageRank scores a *node*, paths scores the *call route*: the model -# enumerates caller -> ... -> callee chains from the top-PageRank -# subscriber, recovers the routing tower on each hop, and ranks each -# route by total influence summed along the chain. The routing tower -# is the auxiliary middle field of an arity-3 edge, so each enumerated -# path also tells us which towers the influence flows through. - -# Arity-3 call edge: {Subscriber:caller} via {CellTower:tower} calls {Subscriber:callee}. -# First/last fields (caller/callee) are the path endpoints; the tower is the -# auxiliary middle field (field_index 1), recoverable per hop via -# relationship_fields. Derived from CallDetailRecord's caller/callee/routed_through. -Subscriber.calls_via = model.Relationship( - f"{Subscriber:caller} via {CellTower:tower} calls {Subscriber:callee}", - short_name="calls_via", -) -cdr_edge = CallDetailRecord.ref() -caller_sub, callee_sub, via_tower = Subscriber.ref(), Subscriber.ref(), CellTower.ref() -model.where( - cdr_edge.caller(caller_sub), - cdr_edge.callee(callee_sub), - cdr_edge.routed_through(via_tower), -).define(caller_sub.calls_via(via_tower, callee_sub)) - -# Path enumeration is declared here, in the model: a deployed model only has the -# path tables its own rules ask for, so a query cannot enumerate new paths. The -# scope is a deterministic seed -- the highest-PageRank subscriber, the smallest -# ID on an exact tie -- and call paths of up to PATH_MAX_HOPS hops, keeping -# simple paths only (the call graph is cyclic, so the negated existential drops -# walks that revisit a node). Both rank keys sort ascending, with the score -# negated, because the rules that read graph results run on the Logic engine, -# whose rank does not mix ascending and descending keys. -PATH_MAX_HOPS = 3 - -Subscriber.is_seed_hub = model.Relationship(f"{Subscriber} is the seed hub") -model.define(Subscriber.is_seed_hub()).where( - aggs.rank(-Subscriber.influence_score, Subscriber.id) == 1 -) - -seed = Subscriber.ref() -i, j = Integer.ref(), Integer.ref() -call_path = model.path(seed, Subscriber.calls_via.repeat(1, PATH_MAX_HOPS)).all().paths() -simple_hub_path = (seed.is_seed_hub(), call_path, not_(where(i < j, call_path.nodes(i) == call_path.nodes(j)))) - -SimplePathCount = model.Relationship(f"simple call paths from the seed hub number {Integer:paths}") -model.define(SimplePathCount(aggs.count(call_path).where(*simple_hub_path))) - -# The routing tower on each hop is field_index 1 of the arity-3 edge -# (caller=0, tower=1, callee=2). -routing_tower = CellTower.ref() -RoutingTowerCount = model.Relationship(f"routing towers on those paths number {Integer:towers}") -model.define( - RoutingTowerCount( - aggs.count(routing_tower).where( - *simple_hub_path, - call_path.relationship_fields["field_index"] == 1, - routing_tower == CellTower(call_path.relationship_fields["field"]), - ) - ) -) - -# Rank the simple paths by influence load, the PageRank summed along each path's -# nodes and rounded to six decimals, so paths whose printed loads agree tie, and -# keep the seed hub's highest. -def path_influence_load(): - return math.round(aggs.sum(Subscriber(call_path.nodes).influence_score).per(call_path), 6) - - -Subscriber.top_call_path_influence = model.Property(f"{Subscriber} has {Float:top_call_path_influence}") -model.where( - *simple_hub_path, - load := path_influence_load(), - top := aggs.max(load).per(seed), -).define(seed.top_call_path_influence(top)) - -# The winning route: the simple path with the highest influence load (on a tie, -# the smallest path ID), published step by step with the tower on each hop. -TopCallPath = model.Relationship(f"{Hash:path} is the seed hub's top call path") -model.where( - *simple_hub_path, - load := path_influence_load(), - aggs.rank(-load, call_path) == 1, -).define(TopCallPath(call_path)) -TopCallPathStep = model.Relationship( - f"the top call path visits {Subscriber:subscriber} at step {Integer:step}" -) -model.where(*simple_hub_path, TopCallPath(call_path)).define( - TopCallPathStep(Subscriber(call_path.nodes), call_path.nodes["index"]) -) -TopCallPathHop = model.Relationship( - f"the top call path routes hop {Integer:hop} through {CellTower:tower}" -) -model.where( - *simple_hub_path, - TopCallPath(call_path), - call_path.relationship_fields["field_index"] == 1, -).define( - TopCallPathHop( - call_path.relationship_fields["index"], - CellTower(call_path.relationship_fields["field"]), - ) -) - -# -------------------------------------------------- -# Stage 5: Prescriptive -- tower upgrade MIP -# -------------------------------------------------- - -TowerUpgradeOption.selected = model.Property(f"{TowerUpgradeOption} has {Float:selected}") - -problem = Problem(model, Float, name="telco_network_recovery") - -# Decision variable: binary 0/1 per (critical tower, tier). -problem.solve_for( - TowerUpgradeOption.selected, - where=[ - TowerUpgradeOption.for_tower(CellTower), - CellTower.is_critical_restore(), - ], - name=["tower_id", "tier"], - type="bin", -) - -# Constraint 1: at most one tier selected per tower. -problem.satisfy( - model.where( - TowerUpgradeOption.for_tower(CellTower), - CellTower.is_critical_restore(), - ).require( - aggs.sum(TowerUpgradeOption.selected).per(CellTower) <= 1 - ) -) - -# Constraint 2: total upgrade cost <= BUDGET_USD. -problem.satisfy( - model.where( - TowerUpgradeOption.for_tower(CellTower), - CellTower.is_critical_restore(), - ).require( - aggs.sum(TowerUpgradeOption.selected * TowerUpgradeOption.cost) <= BUDGET_USD - ) -) - -# Constraint 3: total install crew-weeks <= INSTALL_WEEKS_BUDGET. -problem.satisfy( - model.where( - TowerUpgradeOption.for_tower(CellTower), - CellTower.is_critical_restore(), - ).require( - aggs.sum(TowerUpgradeOption.selected * TowerUpgradeOption.install_weeks) - <= INSTALL_WEEKS_BUDGET - ) -) - -# Objective: three-factor weighted capacity gain. Each factor comes -# from a different upstream stage; the third is the GNN's per-tower -# failure_intensity (TowerFailureScore). -problem.maximize( - aggs.sum( - TowerUpgradeOption.selected - * TowerUpgradeOption.capacity_increase_gbps - * CellTower.weighted_impact - * TowerFailureScore.failure_intensity - ).where( - TowerUpgradeOption.for_tower(CellTower), - CellTower.is_critical_restore(), - TowerFailureScore.tower_id == CellTower.id, - ) -) - -# Each refresh of the deployed model runs this solve. HiGHS is the bundled -# open-source solver; use solver "gurobi" where it is licensed. -problem.configure("highs") - -# The solve's status and objective, which the deployed model publishes for the queries. -SolveStatus = model.Relationship(f"telco recovery solve status is {String:status}") -SolveObjective = model.Relationship(f"telco recovery objective is {Float:objective}") -model.define(SolveStatus(problem.termination_status()), SolveObjective(problem.objective_value())) - -TowerUpgradeOption.is_selected_upgrade = model.Relationship( - f"{TowerUpgradeOption} is selected upgrade" -) -model.where(TowerUpgradeOption.selected > 0.5).define( - TowerUpgradeOption.is_selected_upgrade() -) - -# -------------------------------------------------- -# Plan summary: the RestorePlan singleton publishes the headline metrics -# (total cost, install weeks, capacity, tier mix, binding constraint). -# -------------------------------------------------- - -# RestorePlan concept: singleton holding the headline plan metrics -# (cost, install-weeks, capacity restored, tier mix, towers covered, -# binding constraint) -- the prescriptive output materialized as -# queryable ontology. -RESTORE_PLAN_ID = "TELCO_RECOVERY_2024Q4" -RestorePlan = model.Concept("RestorePlan", identify_by={"id": String}) -RestorePlan.total_cost = model.Property(f"{RestorePlan} has {Float:total_cost}") -RestorePlan.total_install_weeks = model.Property(f"{RestorePlan} has {Integer:total_install_weeks}") -RestorePlan.capacity_restored_gbps = model.Property(f"{RestorePlan} has {Integer:capacity_restored_gbps}") -RestorePlan.gold_count = model.Property(f"{RestorePlan} has {Integer:gold_count}") -RestorePlan.silver_count = model.Property(f"{RestorePlan} has {Integer:silver_count}") -RestorePlan.bronze_count = model.Property(f"{RestorePlan} has {Integer:bronze_count}") -RestorePlan.towers_covered = model.Property(f"{RestorePlan} has {Integer:towers_covered}") -RestorePlan.binding_constraint = model.Property(f"{RestorePlan} has {String:binding_constraint}") - -model.define(RestorePlan.new(id=RESTORE_PLAN_ID)) - -selected_option = TowerUpgradeOption.is_selected_upgrade() -model.where(RestorePlan.id == RESTORE_PLAN_ID).define( - RestorePlan.total_cost( - aggs.sum(TowerUpgradeOption, TowerUpgradeOption.cost).where(selected_option) - ), - RestorePlan.total_install_weeks( - aggs.sum(TowerUpgradeOption, TowerUpgradeOption.install_weeks).where(selected_option) - ), - RestorePlan.capacity_restored_gbps( - aggs.sum(TowerUpgradeOption, TowerUpgradeOption.capacity_increase_gbps).where(selected_option) - ), - RestorePlan.gold_count( - aggs.count(TowerUpgradeOption).where(selected_option, TowerUpgradeOption.tier == "GOLD") - ), - RestorePlan.silver_count( - aggs.count(TowerUpgradeOption).where(selected_option, TowerUpgradeOption.tier == "SILVER") - ), - RestorePlan.bronze_count( - aggs.count(TowerUpgradeOption).where(selected_option, TowerUpgradeOption.tier == "BRONZE") - ), - RestorePlan.towers_covered(aggs.count(TowerUpgradeOption).where(selected_option)), -) - -# 0.995: residual headroom below ~0.5% is too small to fit another -# whole-tier upgrade (cheapest BRONZE > $25k vs $25k of slack), so -# the cap is effectively hit. -BINDING_COST = BUDGET_USD * 0.995 -model.where(RestorePlan.total_cost > BINDING_COST).define( - RestorePlan.binding_constraint("budget") -) -model.where( - RestorePlan.total_cost <= BINDING_COST, - RestorePlan.total_install_weeks >= INSTALL_WEEKS_BUDGET - 1, -).define(RestorePlan.binding_constraint("install_weeks")) -model.where( - RestorePlan.total_cost <= BINDING_COST, - RestorePlan.total_install_weeks < INSTALL_WEEKS_BUDGET - 1, -).define(RestorePlan.binding_constraint("none")) diff --git a/telco_network_recovery/model/schema.py b/telco_network_recovery/model/schema.py index bd8226a6..f0bef264 100644 --- a/telco_network_recovery/model/schema.py +++ b/telco_network_recovery/model/schema.py @@ -23,8 +23,9 @@ # target. tower_id_fk is an explicit FK property used by the GNN # graph via property equality, so heterogeneous edges are expressed as # property-level equality conditions rather than `Relationship` -# traversal. at_risk is the label (1 if STATUS is FAILING or WARNING); -# the GNN drops it from the features to prevent leakage. +# traversal. at_risk is the label (1 if status is FAILING or WARNING, +# derived in equipment_failure.py); the GNN drops both status and at_risk +# from the features to prevent leakage. NetworkEquipment = Concept("NetworkEquipment", identify_by={"id": String}) NetworkEquipment.equipment_type = Property(f"{NetworkEquipment} has {String:equipment_type}") NetworkEquipment.manufacturer = Property(f"{NetworkEquipment} has {String:manufacturer}") @@ -32,6 +33,7 @@ NetworkEquipment.firmware_version = Property(f"{NetworkEquipment} has {String:firmware_version}") NetworkEquipment.install_date = Property(f"{NetworkEquipment} has {DateTime:install_date}") NetworkEquipment.tower_id_fk = Property(f"{NetworkEquipment} has {String:tower_id_fk}") +NetworkEquipment.status = Property(f"{NetworkEquipment} has {String:status}") NetworkEquipment.at_risk = Property(f"{NetworkEquipment} has {Integer:at_risk}") # EquipmentHealth concept: per-equipment health snapshot (MTBF, failure @@ -60,9 +62,9 @@ ModelAdvisory.issued_date = Property(f"{ModelAdvisory} has {DateTime:issued_date}") # TrainEqTable / ValEqTable / TestEqTable concepts: GNN task tables -# holding (equipment_id, at_risk) pairs for training / validation / -# inference. Test = all equipment so every NetworkEquipment receives -# a prediction, independent of train/val split. +# holding the equipment_id of each item used for training / validation / +# inference, labeled by NetworkEquipment.at_risk. Test = all equipment so +# every NetworkEquipment receives a prediction, independent of train/val split. TrainEqTable = Concept("TrainEqTable") ValEqTable = Concept("ValEqTable") TestEqTable = Concept("TestEqTable") @@ -101,7 +103,7 @@ class SubscriberStatus(model.Enum): Subscriber.churn_risk_score = Property(f"{Subscriber} has {Float:churn_risk_score}") Subscriber.status = Property(f"{Subscriber} has {SubscriberStatus:status}") # Composite revenue-at-risk signal (LTV * (1 + churn)), derived in -# reasoning.py; this is the per-subscriber weight that sums into +# customer_impact.py; this is the per-subscriber weight that sums into # `CellTower.weighted_impact` and drives the upgrade objective. Subscriber.customer_value = Property(f"{Subscriber} has {Float:customer_value}") diff --git a/telco_network_recovery/model/source.py b/telco_network_recovery/model/source.py index b1bd25ea..90f624cf 100644 --- a/telco_network_recovery/model/source.py +++ b/telco_network_recovery/model/source.py @@ -39,30 +39,19 @@ upgrade_options_df = pd.read_csv(DATA_DIR / "tower_upgrade_options.csv") advisories_df = pd.read_csv(DATA_DIR / "model_advisories.csv", parse_dates=["ISSUED_DATE"]) -# Binary at_risk label for the GNN: STATUS in {FAILING, WARNING} are -# the positive class (597 of 1,500 equipment items in the bundled data). OPERATIONAL is the negative -# class. STATUS itself is never loaded, and at_risk is dropped from the -# feature set to prevent leakage. -network_equipment_df["AT_RISK"] = ( - network_equipment_df["STATUS"].isin(["FAILING", "WARNING"]).astype(int) -) - # Train/val/test split. Train + val carry labels for fit + evaluation; # test = ALL equipment so every item receives a prediction (inference -# domain) for the chain's per-tower aggregation. +# domain) for the chain's per-tower aggregation. The shuffle runs in pandas +# because PyRel 2.3.0 has no seeded random shuffle. eq_shuf = network_equipment_df.sample(frac=1, random_state=SEED).reset_index(drop=True) n = len(eq_shuf) train_n = int(n * 0.70) val_n = int(n * 0.15) -# reset_index(drop=True) on every split: model.data() infers column -# types via df[col][0], a 0-based label lookup. An .iloc slice keeps -# the parent index (val/test start mid-frame), so without this reset -# the val split has no row labeled 0 -> KeyError: 0. -train_eq_df = eq_shuf.iloc[:train_n][["EQUIPMENT_ID", "AT_RISK"]].rename( - columns={"EQUIPMENT_ID": "equipment_id", "AT_RISK": "at_risk"} +train_eq_df = eq_shuf.iloc[:train_n][["EQUIPMENT_ID"]].rename( + columns={"EQUIPMENT_ID": "equipment_id"} ).reset_index(drop=True) -val_eq_df = eq_shuf.iloc[train_n:train_n + val_n][["EQUIPMENT_ID", "AT_RISK"]].rename( - columns={"EQUIPMENT_ID": "equipment_id", "AT_RISK": "at_risk"} +val_eq_df = eq_shuf.iloc[train_n:train_n + val_n][["EQUIPMENT_ID"]].rename( + columns={"EQUIPMENT_ID": "equipment_id"} ).reset_index(drop=True) test_eq_df = network_equipment_df[["EQUIPMENT_ID"]].rename( columns={"EQUIPMENT_ID": "equipment_id"} @@ -88,7 +77,7 @@ firmware_version=src.FIRMWARE_VERSION, install_date=src.INSTALL_DATE, tower_id_fk=src.TOWER_ID, - at_risk=src.AT_RISK, + status=src.STATUS, )) src = model.data(equipment_health_df) @@ -104,6 +93,8 @@ equipment_id_fk=src.EQUIPMENT_ID, )) +# The most severe advisory per MODEL is picked in pandas: the advisory rows carry no id, so a +# rule could not tell apart two notices with the same MODEL and type. adv_collapsed = ( advisories_df.sort_values("SEVERITY", ascending=False) .drop_duplicates(subset=["MODEL"], keep="first") @@ -120,10 +111,10 @@ model.define(ValEqTable.new(model.data(val_eq_df).to_schema())) model.define(TestEqTable.new(model.data(test_eq_df).to_schema())) -model.define(Train(NetworkEquipment, TrainEqTable.at_risk)).where( +model.define(Train(NetworkEquipment, NetworkEquipment.at_risk)).where( NetworkEquipment.id == TrainEqTable.equipment_id, ) -model.define(Val(NetworkEquipment, ValEqTable.at_risk)).where( +model.define(Val(NetworkEquipment, NetworkEquipment.at_risk)).where( NetworkEquipment.id == ValEqTable.equipment_id, ) model.define(Test(NetworkEquipment)).where( diff --git a/telco_network_recovery/model/tower_upgrades.py b/telco_network_recovery/model/tower_upgrades.py new file mode 100644 index 00000000..2e58484f --- /dev/null +++ b/telco_network_recovery/model/tower_upgrades.py @@ -0,0 +1,192 @@ +"""Tower upgrades: the upgrade MIP over the critical towers, the plan it yields, and how many selected +upgrades each restore signal flagged.""" + +from relationalai.semantics import Float, Integer, String +from relationalai.semantics.reasoners.prescriptive import Problem +from relationalai.semantics.std import aggregates as aggs + +# Declare CellTower.is_critical_restore and the branch flags, and CellTower.weighted_impact and +# CellTower.is_high_value: the decision scope, the objective's weight and the signals the tally counts. +from . import critical_towers, customer_impact # noqa: F401 +from .equipment_failure import TowerFailureScore +from .schema import CellTower, TowerUpgradeOption, model + +# Stage 5 budget envelope. +BUDGET_USD = 5_000_000 +INSTALL_WEEKS_BUDGET = 200 + +# -------------------------------------------------- +# Stage 5: Prescriptive -- tower upgrade MIP +# -------------------------------------------------- + +TowerUpgradeOption.selected = model.Property(f"{TowerUpgradeOption} has {Float:selected}") + +problem = Problem(model, Float, name="telco_network_recovery") + +# Decision variable: binary 0/1 per (critical tower, tier). +problem.solve_for( + TowerUpgradeOption.selected, + where=[ + TowerUpgradeOption.for_tower(CellTower), + CellTower.is_critical_restore(), + ], + name=["tower_id", "tier"], + type="bin", +) + +# Constraint 1: at most one tier selected per tower. +problem.satisfy( + model.where( + TowerUpgradeOption.for_tower(CellTower), + CellTower.is_critical_restore(), + ).require( + aggs.sum(TowerUpgradeOption.selected).per(CellTower) <= 1 + ) +) + +# Constraint 2: total upgrade cost <= BUDGET_USD. +problem.satisfy( + model.where( + TowerUpgradeOption.for_tower(CellTower), + CellTower.is_critical_restore(), + ).require( + aggs.sum(TowerUpgradeOption.selected * TowerUpgradeOption.cost) <= BUDGET_USD + ) +) + +# Constraint 3: total install crew-weeks <= INSTALL_WEEKS_BUDGET. +problem.satisfy( + model.where( + TowerUpgradeOption.for_tower(CellTower), + CellTower.is_critical_restore(), + ).require( + aggs.sum(TowerUpgradeOption.selected * TowerUpgradeOption.install_weeks) + <= INSTALL_WEEKS_BUDGET + ) +) + +# Objective: three-factor weighted capacity gain. Each factor comes +# from a different upstream stage; the third is the GNN's per-tower +# failure_intensity (TowerFailureScore). +problem.maximize( + aggs.sum( + TowerUpgradeOption.selected + * TowerUpgradeOption.capacity_increase_gbps + * CellTower.weighted_impact + * TowerFailureScore.failure_intensity + ).where( + TowerUpgradeOption.for_tower(CellTower), + CellTower.is_critical_restore(), + TowerFailureScore.tower_id == CellTower.id, + ) +) + +# Each refresh of the deployed model runs this solve. HiGHS is the bundled +# open-source solver; use solver "gurobi" where it is licensed. +problem.configure("highs") + +# The solve's status and objective, which the deployed model publishes for the queries. +SolveStatus = model.Relationship(f"telco recovery solve status is {String:status}") +SolveObjective = model.Relationship(f"telco recovery objective is {Float:objective}") +model.define(SolveStatus(problem.termination_status()), SolveObjective(problem.objective_value())) + +TowerUpgradeOption.is_selected_upgrade = model.Relationship( + f"{TowerUpgradeOption} is selected upgrade" +) +model.where(TowerUpgradeOption.selected > 0.5).define( + TowerUpgradeOption.is_selected_upgrade() +) + +# -------------------------------------------------- +# Plan summary: the RestorePlan singleton publishes the headline metrics +# (total cost, install weeks, capacity, tier mix, binding constraint). +# -------------------------------------------------- + +# RestorePlan concept: singleton holding the headline plan metrics +# (cost, install-weeks, capacity restored, tier mix, towers covered, +# binding constraint) -- the prescriptive output materialized as +# queryable ontology. +RESTORE_PLAN_ID = "TELCO_RECOVERY_2024Q4" +RestorePlan = model.Concept("RestorePlan", identify_by={"id": String}) +RestorePlan.total_cost = model.Property(f"{RestorePlan} has {Float:total_cost}") +RestorePlan.total_install_weeks = model.Property(f"{RestorePlan} has {Integer:total_install_weeks}") +RestorePlan.capacity_restored_gbps = model.Property(f"{RestorePlan} has {Integer:capacity_restored_gbps}") +RestorePlan.gold_count = model.Property(f"{RestorePlan} has {Integer:gold_count}") +RestorePlan.silver_count = model.Property(f"{RestorePlan} has {Integer:silver_count}") +RestorePlan.bronze_count = model.Property(f"{RestorePlan} has {Integer:bronze_count}") +RestorePlan.towers_covered = model.Property(f"{RestorePlan} has {Integer:towers_covered}") +RestorePlan.binding_constraint = model.Property(f"{RestorePlan} has {String:binding_constraint}") + +model.define(RestorePlan.new(id=RESTORE_PLAN_ID)) + +selected_option = TowerUpgradeOption.is_selected_upgrade() +model.where(RestorePlan.id == RESTORE_PLAN_ID).define( + RestorePlan.total_cost( + aggs.sum(TowerUpgradeOption, TowerUpgradeOption.cost).where(selected_option) + ), + RestorePlan.total_install_weeks( + aggs.sum(TowerUpgradeOption, TowerUpgradeOption.install_weeks).where(selected_option) + ), + RestorePlan.capacity_restored_gbps( + aggs.sum(TowerUpgradeOption, TowerUpgradeOption.capacity_increase_gbps).where(selected_option) + ), + RestorePlan.gold_count( + aggs.count(TowerUpgradeOption).where(selected_option, TowerUpgradeOption.tier == "GOLD") + ), + RestorePlan.silver_count( + aggs.count(TowerUpgradeOption).where(selected_option, TowerUpgradeOption.tier == "SILVER") + ), + RestorePlan.bronze_count( + aggs.count(TowerUpgradeOption).where(selected_option, TowerUpgradeOption.tier == "BRONZE") + ), + RestorePlan.towers_covered(aggs.count(TowerUpgradeOption).where(selected_option)), +) + +# 0.995: residual headroom below ~0.5% is too small to fit another +# whole-tier upgrade (cheapest BRONZE > $25k vs $25k of slack), so +# the cap is effectively hit. +BINDING_COST = BUDGET_USD * 0.995 +model.where(RestorePlan.total_cost > BINDING_COST).define( + RestorePlan.binding_constraint("budget") +) +model.where( + RestorePlan.total_cost <= BINDING_COST, + RestorePlan.total_install_weeks >= INSTALL_WEEKS_BUDGET - 1, +).define(RestorePlan.binding_constraint("install_weeks")) +model.where( + RestorePlan.total_cost <= BINDING_COST, + RestorePlan.total_install_weeks < INSTALL_WEEKS_BUDGET - 1, +).define(RestorePlan.binding_constraint("none")) + +# -------------------------------------------------- +# Why each upgrade was selected +# -------------------------------------------------- + +# How many selected upgrades each signal that flags a critical tower fired on: an operational +# branch, the predictive branch, and a high-value tower (an upgrade can fire on several). +RationaleTally = model.Relationship( + f"selected upgrades fire {Integer:operational} operational, {Integer:predictive} advisory/predicted " + f"and {Integer:high_value} high-value signals" +) +model.define( + RationaleTally( + *( + aggs.count(TowerUpgradeOption).where( + selected_option, TowerUpgradeOption.for_tower(CellTower), signal() + ) + | 0 + for signal in ( + CellTower.fires_operational_branch, + CellTower.fires_predictive_branch, + CellTower.is_high_value, + ) + ) + ) +) + +# The selected upgrades in each region. +SelectedRegionCount = model.Relationship(f"{Integer:upgrades} selected upgrades lie in region {String:region}") +_region = String.ref() +model.where(selected_option, TowerUpgradeOption.for_tower(CellTower), CellTower.region == _region).define( + SelectedRegionCount(aggs.count(TowerUpgradeOption).per(_region), _region) +) diff --git a/telco_network_recovery/queries/recovery_report.py b/telco_network_recovery/queries/recovery_report.py index 8ca3ee21..adc81b4f 100644 --- a/telco_network_recovery/queries/recovery_report.py +++ b/telco_network_recovery/queries/recovery_report.py @@ -15,46 +15,81 @@ from model import ( FAILURE_INTENSITY_THRESHOLD, PATH_MAX_HOPS, + POSITIVE_PROBABILITY_CUTOFF, + AdvisedEquipmentCount, + AdvisedModelEquipment, + AdvisoryCount, + AtRiskBalance, CellTower, + CriticalRegionCount, + EquipmentSplitSize, + FailureIntensitySpread, + GnnRecallCounts, + IntenseTowerCount, ModelAdvisory, NetworkEquipment, + PositiveProbabilitySpread, + RationaleTally, + RestoreBranchCounts, RestorePlan, RoutingTowerCount, + SelectedRegionCount, SimplePathCount, SolveObjective, SolveStatus, Subscriber, - TestEqTable, TopCallPathHop, TopCallPathStep, TowerFailureScore, TowerUpgradeOption, - TrainEqTable, - ValEqTable, model, ) -from relationalai.semantics import Integer, count, select +from relationalai.semantics import Float, Integer, String, select pd.set_option("display.float_format", lambda v: f"{v:,.4f}") +TOP_TOWERS = 10 +TOP_SUBSCRIBERS = 10 -def stage_1_predictive() -> bool: +def published_row(relationship, **field_types) -> dict: + """The one row a global-summary relationship publishes, by field name; the field types name its + fields in order.""" + refs = {name: kind.ref() for name, kind in field_types.items()} + df = model.where(relationship(*refs.values())).select(*(ref.alias(name) for name, ref in refs.items())).to_df() + return {name: df[name].iloc[0] for name in refs} + + +def restore_branch_counts() -> dict: + return published_row( + RestoreBranchCounts, + critical=Integer, + degraded=Integer, + packet_loss=Integer, + predictive=Integer, + only_predictive=Integer, + ) + + +def region_counts(relationship, first_seen: pd.Series) -> pd.Series: + """A relationship's towers per region, most first; ties keep the order in which their regions + first appear in `first_seen`. A tower without a region is not counted.""" + towers, region = Integer.ref(), String.ref() counts = ( - select( - count(TrainEqTable).alias("train"), - count(ValEqTable).alias("val"), - count(TestEqTable).alias("test"), - ) + model.where(relationship(towers, region)) + .select(region.alias("region"), towers.alias("towers")) .to_df() - .iloc[0] + .set_index("region")["towers"] ) - equipment_df = select( - NetworkEquipment.id.alias("equipment_id"), - NetworkEquipment.eqp_model.alias("MODEL"), - NetworkEquipment.tower_id_fk.alias("TOWER_ID"), - NetworkEquipment.at_risk.alias("AT_RISK"), - ).to_df() + order = pd.Index(first_seen.dropna().drop_duplicates(), name="region") + return counts.reindex(order).astype(int).sort_values(ascending=False, kind="stable") + + +def stage_1_predictive() -> bool: + split = published_row(EquipmentSplitSize, train_items=Integer, validation_items=Integer, test_items=Integer) + balance = published_row(AtRiskBalance, items=Integer, at_risk_items=Integer, at_risk_rate=Float) + advisories = published_row(AdvisoryCount, advisories=Integer, models=Integer) + n_items = int(balance["items"]) advisories_df = select( ModelAdvisory.model.alias("MODEL"), ModelAdvisory.advisory_type.alias("ADVISORY_TYPE"), @@ -62,67 +97,73 @@ def stage_1_predictive() -> bool: ModelAdvisory.issued_date.alias("ISSUED_DATE"), ).to_df() - print(f"Equipment split: train={counts['train']} val={counts['val']} test={counts['test']} (all)") - print(f"Label distribution: at_risk=1 {equipment_df['AT_RISK'].sum()} / " - f"{len(equipment_df)} ({equipment_df['AT_RISK'].mean():.1%})") - print(f"Advisories: {len(advisories_df)} on {advisories_df['MODEL'].nunique()} distinct models") + print( + f"Equipment split: train={int(split['train_items'])} val={int(split['validation_items'])} " + f"test={int(split['test_items'])} (all)" + ) + print(f"Label distribution: at_risk=1 {int(balance['at_risk_items'])} / " + f"{n_items} ({float(balance['at_risk_rate']):.1%})") + print(f"Advisories: {int(advisories['advisories'])} on {int(advisories['models'])} distinct models") # Descriptive: advisory landscape -- which MODELs are affected, severity, # and how many equipment items sit on each. This is the relational # neighbor signal the GNN propagates in Stage 1. print("\n Advisory landscape -- equipment count per advised MODEL:") + advised_model, advised_items = String.ref(), Integer.ref() + eq_counts = ( + model.where(AdvisedModelEquipment(advised_model, advised_items)) + .select(advised_model.alias("MODEL"), advised_items.alias("eq_count")) + .to_df() + ) adv_landscape = ( advisories_df - .merge(equipment_df.groupby("MODEL").size().rename("eq_count").reset_index(), on="MODEL", how="left") + .merge(eq_counts, on="MODEL", how="left") .sort_values("SEVERITY", ascending=False) [["MODEL", "ADVISORY_TYPE", "SEVERITY", "ISSUED_DATE", "eq_count"]] ) print(adv_landscape.to_string(index=False)) - n_on_advised = int(equipment_df["MODEL"].isin(set(advisories_df["MODEL"])).sum()) - print(f" Equipment on an advised MODEL: {n_on_advised} / {len(equipment_df)} " - f"({n_on_advised / len(equipment_df):.1%})") + n_on_advised = int(published_row(AdvisedEquipmentCount, equipment_items=Integer)["equipment_items"]) + print(f" Equipment on an advised MODEL: {n_on_advised} / {n_items} " + f"({n_on_advised / n_items:.1%})") print(f"\n{'=' * 60}") print("STAGE 1: PREDICTIVE -- equipment-failure binary classification GNN") print("=" * 60) - pred_df = ( - select( - NetworkEquipment.id.alias("equipment_id"), - NetworkEquipment.predictions.probs.alias("pos_prob"), - NetworkEquipment.predictions.predicted_labels.alias("predicted_label"), - ) - .where(NetworkEquipment.predictions) - .to_df() - ) + pred_df = select(NetworkEquipment.id.alias("equipment_id")).where(NetworkEquipment.predictions).to_df() if pred_df.empty: print("(no predictions returned)") return False - pred_df["pos_prob"] = pred_df["pos_prob"].astype(float) # Per-tower SUM of positive probabilities (= expected count of at-risk # equipment on the tower), published by the model as - # TowerFailureScore.failure_intensity. + # TowerFailureScore.failure_intensity and ranked by TowerFailureScore.failure_rank. per_tower = ( select( TowerFailureScore.tower_id.alias("TOWER_ID"), TowerFailureScore.failure_intensity.alias("FAILURE_INTENSITY"), + TowerFailureScore.failure_rank.alias("failure_rank"), ) + .where(TowerFailureScore.failure_rank <= TOP_TOWERS) .to_df() - .sort_values("FAILURE_INTENSITY", ascending=False) + .sort_values("failure_rank") + .drop(columns="failure_rank") ) per_tower["FAILURE_INTENSITY"] = per_tower["FAILURE_INTENSITY"].astype(float) - print("\n Top 10 towers by predicted failure intensity (sum of equipment failure probs):") - print(per_tower.head(10).to_string(index=False)) + print(f"\n Top {TOP_TOWERS} towers by predicted failure intensity (sum of equipment failure probs):") + print(per_tower.to_string(index=False)) + spread = published_row( + FailureIntensitySpread, scored_towers=Integer, minimum=Float, maximum=Float, median=Float + ) print( f"\n failure_intensity distribution: " - f"min={per_tower['FAILURE_INTENSITY'].min():.2f}, " - f"median={per_tower['FAILURE_INTENSITY'].median():.2f}, " - f"max={per_tower['FAILURE_INTENSITY'].max():.2f}" + f"min={float(spread['minimum']):.2f}, " + f"median={float(spread['median']):.2f}, " + f"max={float(spread['maximum']):.2f}" ) print( f" Towers with failure_intensity > {FAILURE_INTENSITY_THRESHOLD}: " - f"{int((per_tower['FAILURE_INTENSITY'] > FAILURE_INTENSITY_THRESHOLD).sum())} / {len(per_tower)}" + f"{int(published_row(IntenseTowerCount, towers=Integer)['towers'])} / {int(spread['scored_towers'])}" ) # GNN end-to-end recall on at-risk items. Two views: @@ -132,37 +173,35 @@ def stage_1_predictive() -> bool: # answers "what a downstream rule would catch using the GNN's calibrated # probability." They can diverge if the model's calibration is shifted # (the argmax can be conservative even when probs are well-separated). - total_atrisk = int(equipment_df["AT_RISK"].sum()) + total_atrisk = int(balance["at_risk_items"]) if total_atrisk == 0: print("\n GNN recall: no at-risk items in the labels, so recall is undefined.") else: - gnn_flagged_atrisk = pred_df.merge(equipment_df[["equipment_id", "AT_RISK"]], on="equipment_id", how="left") - gnn_recall_argmax = int( - gnn_flagged_atrisk[ - (gnn_flagged_atrisk["AT_RISK"] == 1) - & (gnn_flagged_atrisk["predicted_label"] == 1) - ].shape[0] - ) - gnn_recall_p05 = int( - gnn_flagged_atrisk[ - (gnn_flagged_atrisk["AT_RISK"] == 1) - & (gnn_flagged_atrisk["pos_prob"] >= 0.5) - ].shape[0] - ) + recall = published_row(GnnRecallCounts, by_label=Integer, by_cutoff=Integer) + gnn_recall_argmax = int(recall["by_label"]) + gnn_recall_p05 = int(recall["by_cutoff"]) print( f"\n GNN recall on {total_atrisk} true at-risk items:" f"\n argmax (predicted_label == 1): " f"{gnn_recall_argmax:>4} ({gnn_recall_argmax / total_atrisk:>5.1%})" - f"\n p>=0.5 (probabilistic threshold): " + f"\n p>={POSITIVE_PROBABILITY_CUTOFF} (probabilistic threshold): " f"{gnn_recall_p05:>4} ({gnn_recall_p05 / total_atrisk:>5.1%})" ) # Per-equipment positive-prediction distribution for transparency. + probs = published_row( + PositiveProbabilitySpread, + scored_items=Integer, + minimum=Float, + maximum=Float, + median=Float, + at_cutoff=Integer, + ) print( f"\n GNN per-equipment positive-prob distribution: " - f"min={pred_df['pos_prob'].min():.3f}, " - f"median={pred_df['pos_prob'].median():.3f}, " - f"max={pred_df['pos_prob'].max():.3f}; " - f"items with pos_prob>=0.5: {int((pred_df['pos_prob'] >= 0.5).sum())} / {len(pred_df)}" + f"min={float(probs['minimum']):.3f}, " + f"median={float(probs['median']):.3f}, " + f"max={float(probs['maximum']):.3f}; " + f"items with pos_prob>={POSITIVE_PROBABILITY_CUTOFF}: {int(probs['at_cutoff'])} / {int(probs['scored_items'])}" ) return True @@ -206,22 +245,23 @@ def stage_2_rules() -> pd.DataFrame: ]: fired = set(model.where(branch()).select(CellTower.id).to_df().iloc[:, 0]) flagged_df[column] = flagged_df["tower_id"].isin(fired) - print(f"\n Flagged critical_restore towers: {len(flagged_df)}") + branches = restore_branch_counts() + n_critical = int(branches["critical"]) + print(f"\n Flagged critical_restore towers: {n_critical}") print(" Breakdown by region:") - print(flagged_df["region"].value_counts().to_string()) + print(region_counts(CriticalRegionCount, flagged_df["region"]).to_string()) - # Per-branch contribution, from the branch flags the model publishes. - _b1 = flagged_df["branch_degraded"] - _b2 = flagged_df["branch_packet_loss"] - _b3 = flagged_df["branch_predictive"] + # Per-branch contribution, from the branch counts the model publishes. + only_predictive = int(branches["only_predictive"]) + # With no critical towers the share is undefined and prints as nan%. + only_predictive_share = only_predictive / n_critical if n_critical else float("nan") print("\n Per-branch contribution (a tower can fire on multiple branches):") - print(f" Branch 1 (WEST + DEGRADED + low health): {int(_b1.sum())} towers") - print(f" Branch 2 (WEST + high packet loss + low health): {int(_b2.sum())} towers") + print(f" Branch 1 (WEST + DEGRADED + low health): {int(branches['degraded'])} towers") + print(f" Branch 2 (WEST + high packet loss + low health): {int(branches['packet_loss'])} towers") print(f" Branch 3 (failure_intensity > {FAILURE_INTENSITY_THRESHOLD}, any region): " - f"{int(_b3.sum())} towers") - _only_predictive = (_b3 & ~_b1 & ~_b2).sum() - print(f" Towers flagged ONLY by the predictive branch: {int(_only_predictive)} " - f"({_only_predictive / len(flagged_df):.0%} of flagged set)") + f"{int(branches['predictive'])} towers") + print(f" Towers flagged ONLY by the predictive branch: {only_predictive} " + f"({only_predictive_share:.0%} of flagged set)") print("\n Top 20 by predicted failure intensity:") print(flagged_df.head(20).to_string(index=False)) @@ -244,10 +284,11 @@ def stage_3_graph() -> pd.DataFrame: Subscriber.influence_score.alias("pagerank"), ) .to_df() - .sort_values("customer_value", ascending=False) - .head(10) + # Ties on customer value list the lower subscriber id first. + .sort_values(["customer_value", "sub_id"], ascending=[False, True]) + .head(TOP_SUBSCRIBERS) ) - print("\n Top 10 subscribers by customer_value (PageRank shown for reference):") + print(f"\n Top {TOP_SUBSCRIBERS} subscribers by customer_value (PageRank shown for reference):") print(top_subs.to_string(index=False)) blast_df = critical_tower_measures( @@ -337,54 +378,31 @@ def stage_5_prescriptive(flagged_df: pd.DataFrame, blast_df: pd.DataFrame) -> No selected_df["cost"] = selected_df["cost"].astype(float) selected_df = selected_df.merge( - flagged_df[["tower_id", "region", "status", "failure_intensity", + flagged_df[["tower_id", "region", "failure_intensity", "branch_degraded", "branch_packet_loss", "branch_predictive", "high_value"]], on="tower_id", how="left", ).sort_values(["region", "tier"]) - # Per-tower selection rationale: the upstream signals that flagged the - # tower, OR-combined, from the flags the model publishes: - # - operational : Stage 2 branch 1 (degraded) or 2 (packet loss) - # - advisory/predicted: Stage 2 branch 3 (GNN failure intensity) - # - high-value : weighted_impact in the top quartile of critical towers selected_df = selected_df.merge( blast_df[["tower_id", "weighted_impact", "weighted_pagerank"]], on="tower_id", how="left", ) - selected_df["sig_operational"] = selected_df["branch_degraded"] | selected_df["branch_packet_loss"] - selected_df["sig_predictive"] = selected_df["branch_predictive"] - selected_df["sig_high_value"] = selected_df["high_value"] + # Per-tower selection rationale: the upstream signals that flagged the + # tower, OR-combined, from the flags the model publishes. A selected tower is + # critical, so it fires an operational or the predictive branch. def _rationale(row): - sigs = [] - if row["sig_operational"]: - sigs.append("operational") - if row["sig_predictive"]: - sigs.append("advisory/predicted") - if row["sig_high_value"]: - sigs.append("high-value") - return ", ".join(sigs) if sigs else "(low signal)" + signals = ( + ("operational", row["branch_degraded"] or row["branch_packet_loss"]), # Stage 2 branch 1 or 2 + ("advisory/predicted", row["branch_predictive"]), # Stage 2 branch 3 (GNN failure intensity) + ("high-value", row["high_value"]), # weighted_impact in the top quartile of critical towers + ) + return ", ".join(name for name, fired in signals if fired) selected_df["rationale"] = selected_df.apply(_rationale, axis=1) - print(f"\n Selected upgrades: {len(selected_df)}") - print( - selected_df[ - ["tower_id", "region", "tier", "capacity_gbps", "cost", - "install_weeks", "failure_intensity", "weighted_impact", - "rationale"] - ].to_string(index=False) - ) - print( - f"\n Rationale tally: " - f"operational={int(selected_df['sig_operational'].sum())}, " - f"advisory/predicted={int(selected_df['sig_predictive'].sum())}, " - f"high-value={int(selected_df['sig_high_value'].sum())} " - f"(towers can fire on multiple signals)" - ) - # The plan headline, published by the model as ontology. plan_df = ( model.select( @@ -400,21 +418,42 @@ def _rationale(row): ) .to_df() ) + n_selected = len(selected_df) + + print(f"\n Selected upgrades: {n_selected}") + print( + selected_df[ + ["tower_id", "region", "tier", "capacity_gbps", "cost", + "install_weeks", "failure_intensity", "weighted_impact", + "rationale"] + ].to_string(index=False) + ) + tally = published_row(RationaleTally, operational=Integer, predictive=Integer, high_value=Integer) + print( + f"\n Rationale tally: " + f"operational={int(tally['operational'])}, " + f"advisory/predicted={int(tally['predictive'])}, " + f"high-value={int(tally['high_value'])} " + f"(towers can fire on multiple signals)" + ) + if len(plan_df) > 0: plan = plan_df.iloc[0] print(f"\n Total cost: ${float(plan['total_cost']):,.0f}") print(f" Total install crew-weeks: {int(plan['install_weeks'])}") print(f" Capacity restored: {int(plan['capacity_gbps'])} Gbps") print(f" Tier mix: {{'GOLD': {plan['gold']}, 'SILVER': {plan['silver']}, 'BRONZE': {plan['bronze']}}}") - print(f" Towers covered: {plan['towers']} of {len(flagged_df)} critical") - print(f" Region breakdown: {selected_df['region'].value_counts().to_dict()}") + print(f" Towers covered: {plan['towers']} of {int(restore_branch_counts()['critical'])} critical") + by_region = region_counts(SelectedRegionCount, selected_df["region"]) + region_mix = {region: int(n) for region, n in by_region.items()} + print(f" Region breakdown: {region_mix}") print("\n Plan (queryable as ontology):") print(plan_df.to_string(index=False)) print(f"\n{'=' * 60}") print("PIPELINE COMPLETE: 5 stages read from the deployed Telco ontology") - print(f"Plan headline + {len(selected_df)}-row SelectedUpgrade view are queryable") + print(f"Plan headline + {n_selected}-row SelectedUpgrade view are queryable") print("as ontology -- RestorePlan and TowerUpgradeOption.is_selected_upgrade.") print("=" * 60) diff --git a/telco_network_recovery/runbook.md b/telco_network_recovery/runbook.md index 9b24edaa..edc0277c 100644 --- a/telco_network_recovery/runbook.md +++ b/telco_network_recovery/runbook.md @@ -71,7 +71,7 @@ Concepts: `CellTower`, `NetworkEquipment` (with `tower_id_fk` FK property), `Equ **Response** -8 source-data concepts wired to the bundled CSVs: 250 `CellTower`, 1,500 `NetworkEquipment`, 1,500 `EquipmentHealth`, 5,000 `NetworkPerformance`, 1,200 `Subscriber`, 6,000 `CallDetailRecord`, 750 `TowerUpgradeOption` (3 tiers × 250 towers), 8 `ModelAdvisory` rows on 7 distinct MODELs (severities `0.50–0.95`). 572 of 1,500 equipment items (38.1%) sit on an advised MODEL — the relational-neighbor signal the GNN's `ModelAdvisory → NetworkEquipment` edge propagates; 597 (39.8%) carry the binary `AT_RISK` label (`STATUS in FAILING / WARNING`) — the GNN's prediction target, distinct from advised-MODEL coverage. +8 source-data concepts wired to the bundled CSVs: 250 `CellTower`, 1,500 `NetworkEquipment`, 1,500 `EquipmentHealth`, 5,000 `NetworkPerformance`, 1,200 `Subscriber`, 6,000 `CallDetailRecord`, 750 `TowerUpgradeOption` (3 tiers × 250 towers), 8 advisories on 7 distinct MODELs (severities `0.50–0.95`), loaded as 7 `ModelAdvisory` rows, the most severe per MODEL. 572 of 1,500 equipment items (38.1%) sit on an advised MODEL — the relational-neighbor signal the GNN's `ModelAdvisory → NetworkEquipment` edge propagates; 597 (39.8%) carry the binary `AT_RISK` label (`STATUS in FAILING / WARNING`) — the GNN's prediction target, distinct from advised-MODEL coverage. ### 3. Discover reasoner questions @@ -171,4 +171,4 @@ Ontology gains a singleton `RestorePlan` Concept with `total_cost`, `total_insta ## Data -Bundled CSVs in `data/`: 250 cell towers (15 WEST DEGRADED), 1,500 `NetworkEquipment` items across 18 consolidated MODELs, 1,500 `EquipmentHealth` snapshots, 5,000 `NetworkPerformance` measurements, 1,200 subscribers, 6,000 CDRs, 750 `TowerUpgradeOption` rows (3 tiers × 250 towers), 8 `ModelAdvisory` rows on 7 distinct MODELs (severities 0.50–0.95). `data/_synthesize_advisory_data.py` regenerates the equipment / health / advisory / upgrade-option CSVs deterministically from a seed. The chain's stages are declared in `model/` (`schema.py`, `source.py`, `reasoning.py`), trained with `train.py`, and read by `queries/recovery_report.py`. +Bundled CSVs in `data/`: 250 cell towers (15 WEST DEGRADED), 1,500 `NetworkEquipment` items across 18 consolidated MODELs, 1,500 `EquipmentHealth` snapshots, 5,000 `NetworkPerformance` measurements, 1,200 subscribers, 6,000 CDRs, 750 `TowerUpgradeOption` rows (3 tiers × 250 towers), 8 advisories on 7 distinct MODELs (severities 0.50–0.95). `data/_synthesize_advisory_data.py` regenerates the equipment / health / advisory / upgrade-option CSVs deterministically from a seed. The chain's stages are declared in `model/` (`schema.py`, `source.py`, and the stage modules `equipment_failure.py`, `advisory_signals.py`, `critical_towers.py`, `customer_impact.py`, `call_paths.py`, `tower_upgrades.py`), trained with `train.py`, and read by `queries/recovery_report.py`. diff --git a/test_data_generation/README.md b/test_data_generation/README.md index 730235fa..3c4adcab 100644 --- a/test_data_generation/README.md +++ b/test_data_generation/README.md @@ -20,7 +20,7 @@ Generating realistic test databases requires careful coordination of row counts This template uses **Prescriptive** reasoning to find optimal row counts for each table in a test database. It encodes referential integrity constraints, cardinality bounds, mandatory participation rules, and coverage requirements as a linear program, then minimizes weighted deviation from target row counts. Higher-priority tables stay closer to their targets. -After determining row counts, the report generates sample test records with realistic values -- emails, dates, prices, and foreign key references drawn from each parent table's ID range. The solved row counts satisfy the constraints; the model treats them as continuous and the report rounds each to a whole number, so on a custom schema with tight ratios the rounded counts can miss a bound, and a parent table that rounds to zero rows leaves its children's references with no parent row. The generated records are illustrative: each foreign key is drawn at random, so per-parent bounds and coverage are not guaranteed row by row, and the generator fills a few columns of the six bundled tables rather than every column in `testgen_schema.csv`. +After determining row counts, the report generates sample test records with realistic values -- emails, dates, prices, and foreign key references drawn from each parent table's ID range. The solved row counts satisfy the constraints; the solve treats them as continuous and the report rounds each to a whole number, so on a custom schema with tight ratios the rounded counts can miss a bound, and a parent table that rounds to zero rows leaves its children's references with no parent row. The generated records are illustrative: each foreign key is drawn at random, so per-parent bounds and coverage are not guaranteed row by row, and the generator fills a few columns of the six bundled tables rather than every column in `testgen_schema.csv`. ## Who this is for @@ -37,7 +37,7 @@ After determining row counts, the report generates sample test records with real ## What's included -- `model/` -- Row count optimization model, as a package (`schema.py` declares the concepts, `source.py` loads the sample data, `reasoning.py` states the decision problem); `rai models deploy --path model` deploys it to your Snowflake account, where each refresh runs the solve +- `model/` -- Row count optimization model, as a package (`schema.py` declares the concepts, `source.py` loads the sample data, `row_count_plan.py` states the decision problem); `rai models deploy --path model` deploys it to your Snowflake account, where each refresh runs the solve - `queries/test_data_plan.py` -- Prints the report from the deployed model: the optimal row counts and the generated test data - `data/testgen_schema.csv` -- Table and column definitions with types and foreign keys - `data/testgen_constraints.csv` -- Cardinality bounds, coverage, and participation rules @@ -216,9 +216,9 @@ Use this sequence to deploy the model and query it: ├── pyproject.toml ├── model/ │ ├── __init__.py # exports of the deployed model -│ ├── schema.py # the table concept +│ ├── schema.py # the table and foreign-key concepts │ ├── source.py # loads the CSVs and extracts the foreign keys -│ └── reasoning.py # decision variables, constraints, objective, solve +│ └── row_count_plan.py # decision variables, constraints, objective, solve ├── queries/ │ └── test_data_plan.py └── data/ @@ -256,20 +256,14 @@ problem.solve_for(Table.x_deviation, name=["dev", Table.table_name], lower=0) Foreign key relationships impose bounds linking child and parent row counts. For example, if each order has 1-3 order lines, the OrderLine count must be between 1x and 3x the Order count: ```python -ParentTable = Table.ref() -problem.satisfy(model.require( - Table.x_actual_rows <= ParentTable.x_actual_rows * fk_info['max'] -).where( - Table.table_name == child_name, - ParentTable.table_name == parent_name +ChildTable, ParentTable = Table.ref(), Table.ref() +foreign_key = [ForeignKey.child == ChildTable, ForeignKey.parent == ParentTable] +problem.satisfy(model.where(*foreign_key).require( + ChildTable.x_actual_rows <= ParentTable.x_actual_rows * ForeignKey.max_per +)) +problem.satisfy(model.where(*foreign_key, ForeignKey.min_per > 0).require( + ChildTable.x_actual_rows >= ParentTable.x_actual_rows * ForeignKey.min_per )) -if fk_info['min'] > 0: - problem.satisfy(model.require( - Table.x_actual_rows >= ParentTable.x_actual_rows * fk_info['min'] - ).where( - Table.table_name == child_name, - ParentTable.table_name == parent_name - )) ``` ### 4. Minimize weighted deviation diff --git a/test_data_generation/model/__init__.py b/test_data_generation/model/__init__.py index 98f308b4..a2297c3d 100644 --- a/test_data_generation/model/__init__.py +++ b/test_data_generation/model/__init__.py @@ -14,7 +14,7 @@ `python -m queries.test_data_plan` then prints the report from the deployed model. """ -from .reasoning import SolveStatus, TotalDeviation, problem +from .row_count_plan import SolveStatus, TotalDeviation, problem from .schema import Table, model from .source import DATA_DIR diff --git a/test_data_generation/model/reasoning.py b/test_data_generation/model/row_count_plan.py similarity index 56% rename from test_data_generation/model/reasoning.py rename to test_data_generation/model/row_count_plan.py index 5224823a..a1903499 100644 --- a/test_data_generation/model/reasoning.py +++ b/test_data_generation/model/row_count_plan.py @@ -1,11 +1,10 @@ -"""Test data generation decision problem: row counts closest to the targets, within the bounds.""" +"""Row-count plan: the decision problem for row counts closest to the targets within the bounds.""" from relationalai.semantics import Float, String from relationalai.semantics import sum as rai_sum from relationalai.semantics.reasoners.prescriptive import Problem -from .schema import Property, Table, model -from .source import fk_objs +from .schema import ForeignKey, Property, Table, model # Decision variable properties Table.x_actual_rows = Property(f"{Table} has actual {Float:actual_rows}") @@ -33,41 +32,26 @@ problem.satisfy(model.where(Table).require(Table.x_deviation >= Table.target_rows - Table.x_actual_rows)) # Constraint: referential integrity - child rows bounded by parent capacity -# These constraints link specific table pairs via their actual_rows variables -ParentTable = Table.ref() -for fk_info in fk_objs: - child_name = fk_info['child'] - parent_name = fk_info['parent'] +# These constraints link each foreign key's child and parent tables via their actual_rows +# variables. +ChildTable, ParentTable = Table.ref(), Table.ref() +foreign_key = [ForeignKey.child == ChildTable, ForeignKey.parent == ParentTable] - # Upper bound: can't have more children than max per parent - problem.satisfy(model.require( - Table.x_actual_rows <= ParentTable.x_actual_rows * fk_info['max'] - ).where( - Table.table_name == child_name, - ParentTable.table_name == parent_name - )) +# Upper bound: can't have more children than max per parent +problem.satisfy(model.where(*foreign_key).require( + ChildTable.x_actual_rows <= ParentTable.x_actual_rows * ForeignKey.max_per +)) - # Lower bound: at least the declared minimum of children per parent (cardinality, - # frequency, or mandatory participation) - if fk_info['min'] > 0: - problem.satisfy(model.require( - Table.x_actual_rows >= ParentTable.x_actual_rows * fk_info['min'] - ).where( - Table.table_name == child_name, - ParentTable.table_name == parent_name - )) +# Lower bound: at least the declared minimum of children per parent (cardinality, +# frequency, or mandatory participation) +problem.satisfy(model.where(*foreign_key, ForeignKey.min_per > 0).require( + ChildTable.x_actual_rows >= ParentTable.x_actual_rows * ForeignKey.min_per +)) # Constraint: coverage requirements -for fk_info in fk_objs: - if fk_info['coverage'] > 0: - child_name = fk_info['child'] - parent_name = fk_info['parent'] - problem.satisfy(model.require( - Table.x_actual_rows >= fk_info['coverage'] * ParentTable.x_actual_rows - ).where( - Table.table_name == child_name, - ParentTable.table_name == parent_name - )) +problem.satisfy(model.where(*foreign_key, ForeignKey.coverage > 0).require( + ChildTable.x_actual_rows >= ForeignKey.coverage * ParentTable.x_actual_rows +)) # Objective: minimize weighted deviation from targets # Weight by priority (higher priority = more important to match target) diff --git a/test_data_generation/model/schema.py b/test_data_generation/model/schema.py index 8384b659..cb864d10 100644 --- a/test_data_generation/model/schema.py +++ b/test_data_generation/model/schema.py @@ -1,6 +1,6 @@ """Semantic schema for the test data generation template: tables with row-count targets.""" -from relationalai.semantics import Integer, Model, String +from relationalai.semantics import Float, Integer, Model, String model = Model("test_data_generation") Concept, Property = model.Concept, model.Property @@ -11,3 +11,11 @@ Table.min_rows = Property(f"{Table} has {Integer:min_rows}") Table.max_rows = Property(f"{Table} has {Integer:max_rows}") Table.priority = Property(f"{Table} has {Integer:priority}") + +# Concept: foreign keys, one per child-table column, with the children per parent row the +# schema and constraints allow and the share of parent rows that must have a child. +ForeignKey = Concept("ForeignKey", identify_by={"child": Table, "column_name": String}) +ForeignKey.parent = Property(f"{ForeignKey} references {Table}") +ForeignKey.min_per = Property(f"{ForeignKey} has at least {Integer:min_per} children per parent") +ForeignKey.max_per = Property(f"{ForeignKey} has at most {Integer:max_per} children per parent") +ForeignKey.coverage = Property(f"{ForeignKey} covers {Float:coverage} of its parent rows") diff --git a/test_data_generation/model/source.py b/test_data_generation/model/source.py index 4ab6d456..acd416d3 100644 --- a/test_data_generation/model/source.py +++ b/test_data_generation/model/source.py @@ -2,9 +2,10 @@ from pathlib import Path -from pandas import read_csv +from pandas import DataFrame, read_csv +from relationalai.semantics.std import math, numbers -from .schema import Table, model +from .schema import ForeignKey, Table, model DATA_DIR = Path(__file__).resolve().parents[1] / "data" scale_factor = 1.0 @@ -14,22 +15,17 @@ constraints_df = read_csv(DATA_DIR / "testgen_constraints.csv") targets_df = read_csv(DATA_DIR / "testgen_targets.csv") -# Scale targets -targets_df = targets_df.copy() -targets_df['target_rows'] = (targets_df['target_rows'] * scale_factor).astype(int) -targets_df['min_rows'] = (targets_df['min_rows'] * scale_factor).astype(int) -targets_df['max_rows'] = (targets_df['max_rows'] * scale_factor).astype(int) - +# Load the tables. Each count is scaled by scale_factor and truncated to a whole number. table_data = model.data(targets_df) model.define( t := Table.new(table_name=table_data.table_name), - t.target_rows(table_data.target_rows), - t.min_rows(table_data.min_rows), - t.max_rows(table_data.max_rows), + t.target_rows(numbers.integer(math.floor(table_data.target_rows * scale_factor))), + t.min_rows(numbers.integer(math.floor(table_data.min_rows * scale_factor))), + t.max_rows(numbers.integer(math.floor(table_data.max_rows * scale_factor))), t.priority(table_data.priority), ) -# Extract FK relationships from schema +# Extract FK relationships from schema, with the bounds each foreign key declares combined. fk_df = schema_df[schema_df['is_foreign_key']].copy() fk_objs = [] @@ -59,8 +55,22 @@ fk_objs.append({ 'child': child_table, + 'column_name': fk_row['column_name'], 'parent': parent_table, - 'min': min_per, - 'max': max_per, + 'min_per': min_per, + 'max_per': max_per, 'coverage': coverage_pct }) + +# Load the foreign keys with their combined bounds. +fk_data = model.data( + DataFrame(fk_objs, columns=['child', 'column_name', 'parent', 'min_per', 'max_per', 'coverage']) +) +child, parent = Table.ref(), Table.ref() +model.where(child.table_name == fk_data['child'], parent.table_name == fk_data['parent']).define( + fk := ForeignKey.new(child=child, column_name=fk_data['column_name']), + fk.parent(parent), + fk.min_per(fk_data['min_per']), + fk.max_per(fk_data['max_per']), + fk.coverage(fk_data['coverage']), +) diff --git a/test_data_generation/queries/test_data_plan.py b/test_data_generation/queries/test_data_plan.py index 2084d6ce..343a0d99 100644 --- a/test_data_generation/queries/test_data_plan.py +++ b/test_data_generation/queries/test_data_plan.py @@ -14,7 +14,10 @@ def generate_test_data(row_counts, seed=42): - """Generate actual test data records based on optimal row counts.""" + """Generate actual test data records based on optimal row counts. + + PyRel has no seeded random sampling, so the records are generated here. + """ random.seed(seed) def random_email(i): @@ -84,7 +87,11 @@ def random_float(min_val, max_val): # Extract row counts row_counts = {} - results_df = model.select(Table.table_name, Table.x_actual_rows, Table.target_rows).to_df() + results_df = ( + model.select(Table.table_name, Table.x_actual_rows, Table.target_rows) + .to_df() + .sort_values("table_name") + ) for _, row in results_df.iterrows(): actual = int(round(row['actual_rows'])) target = int(row['target_rows']) diff --git a/traveling_salesman/README.md b/traveling_salesman/README.md index 558d44e2..2dca933e 100644 --- a/traveling_salesman/README.md +++ b/traveling_salesman/README.md @@ -39,7 +39,7 @@ Built using **prescriptive reasoning** (mixed-integer programming with the HiGHS ## What's included -- `model/` -- ontology, MTZ formulation, and solver configuration, as a package (`schema.py` declares the concepts, `source.py` loads the sample data, `reasoning.py` states the decision problem); `rai models deploy --path model` deploys it to your Snowflake account, where each refresh runs the solve +- `model/` -- ontology, MTZ formulation, and solver configuration, as a package (`schema.py` declares the concepts, `source.py` loads the sample data, `shortest_tour.py` states the decision problem); `rai models deploy --path model` deploys it to your Snowflake account, where each refresh runs the solve - `queries/tour.py` -- prints the report from the deployed model: the solve status, the tour distance, and the tour edges - **Runbook**: `runbook.md` — a paste-testable walkthrough that reproduces the template step by step with the RAI skills; as important a reference as the script itself. - `data/edges.csv` -- 12 directed edges between 4 nodes with distances @@ -196,7 +196,7 @@ traveling_salesman/ │ ├── __init__.py # exports of the deployed model │ ├── schema.py # edge and node concepts │ ├── source.py # loads the distance matrix -│ └── reasoning.py # tour variables, MTZ constraints, objective, solve +│ └── shortest_tour.py # tour variables, MTZ constraints, objective, solve ├── queries/ │ └── tour.py # report from the deployed model └── data/ @@ -229,7 +229,7 @@ Two families of constraints shape the tour. Degree constraints require exactly o edges.csv → load edges → derive nodes → edge + ordering variables → degree + MTZ constraints → minimize distance → optimal tour ``` -See `model/reasoning.py` for the implementation, and `runbook.md` to reproduce it step by step with the RAI skills. +See `model/shortest_tour.py` for the implementation, and `runbook.md` to reproduce it step by step with the RAI skills. ## Customize this template diff --git a/traveling_salesman/model/__init__.py b/traveling_salesman/model/__init__.py index 1416f6f2..27ec324c 100644 --- a/traveling_salesman/model/__init__.py +++ b/traveling_salesman/model/__init__.py @@ -8,14 +8,16 @@ elimination formulation. - Solve for the shortest Hamiltonian cycle and print the selected edges. +The decision problem is in `shortest_tour.py`. + Run: `rai models deploy --path model` deploys this package to the schemas in raiconfig.yaml and waits for its first refresh, which runs the solve. `python -m queries.tour` then prints the report from the deployed model. """ -from .reasoning import NumMinObjectives, NumVariables, SolveStatus, TourDistance, problem from .schema import Edge, Node, model +from .shortest_tour import NumMinObjectives, NumVariables, SolveStatus, TourDistance, problem from .source import DATA_DIR __all__ = [ diff --git a/traveling_salesman/model/reasoning.py b/traveling_salesman/model/shortest_tour.py similarity index 97% rename from traveling_salesman/model/reasoning.py rename to traveling_salesman/model/shortest_tour.py index b7af3c22..c3a42459 100644 --- a/traveling_salesman/model/reasoning.py +++ b/traveling_salesman/model/shortest_tour.py @@ -1,4 +1,4 @@ -"""Traveling salesman decision problem: the shortest tour, with MTZ subtour elimination.""" +"""Shortest tour: the traveling salesman decision problem, with MTZ subtour elimination.""" from relationalai.semantics import Float, Integer, String, count, sum from relationalai.semantics.reasoners.prescriptive import Problem diff --git a/traveling_salesman/runbook.md b/traveling_salesman/runbook.md index 892a586d..7b686bd9 100644 --- a/traveling_salesman/runbook.md +++ b/traveling_salesman/runbook.md @@ -37,7 +37,7 @@ Each prompt is pasted into a fresh agent session loaded with the named `/rai-*` **Prompt:** /rai-prescriptive-problem What's the shortest round-trip that visits every node exactly once and returns to the start, as one connected tour with no disconnected subtours? Use a binary decision per edge for whether it's in the tour, require every node to have exactly one selected edge in and one out, and eliminate subtours with MTZ ordering variables — one integer position per node, anchored at node 1. Minimize total distance, and persist the edge selection to the ontology. -**Response:** OPTIMAL (HiGHS mixed-integer program), shortest tour distance **8.5** (relative gap 0.0). The model has 16 variables (12 binary edge selections + 4 integer MTZ positions) and 15 constraints; the edge decision is written back as `Edge.x` and the position as `Node.u`. In `model/reasoning.py` the solve is declared with `problem.configure(...)`, so each refresh of the deployed model runs it. +**Response:** OPTIMAL (HiGHS mixed-integer program), shortest tour distance **8.5** (relative gap 0.0). The model has 16 variables (12 binary edge selections + 4 integer MTZ positions) and 15 constraints; the edge decision is written back as `Edge.x` and the position as `Node.u`. In `model/shortest_tour.py` the solve is declared with `problem.configure(...)`, so each refresh of the deployed model runs it. ## 4. Read the optimal route diff --git a/underwriting_audit/README.md b/underwriting_audit/README.md index d5379caa..12cfc141 100644 --- a/underwriting_audit/README.md +++ b/underwriting_audit/README.md @@ -41,7 +41,7 @@ Built using **prescriptive reasoning** (constraint satisfaction with multi-solut ## What's included -- **Model**: the reference concepts, the scalar applicant decisions, the rule pack, the property catalog, and one counterexample search per property, in the `model/` package (`schema.py` declares the concepts, `source.py` loads the reference data, `reasoning.py` states the decisions, rules, and searches), which `rai models deploy --path model` deploys to your Snowflake account, where each refresh runs one search per property. +- **Model**: the reference concepts, the scalar applicant decisions, the rule pack, the property catalog, and one counterexample search per property, in the `model/` package (`schema.py` declares the concepts, `source.py` loads the reference data, `applicant_rules.py` states the decisions and rules, `property_audits.py` states the catalog and the searches, `audit_verdicts.py` classifies and tallies the verdicts), which `rai models deploy --path model` deploys to your Snowflake account, where each refresh runs one search per property. - **Query**: `queries/audit_report.py`, which prints each property's verdict and witness table and the verdict matrix from the deployed model. - **Runbook**: `runbook.md` — a paste-testable walkthrough that reproduces the template step by step with the RAI skills; as important a reference as the script itself. - `data/age_buckets.csv` -- 4 representative ages (28, 45, 55, 72) -- three under the 70 senior threshold, one above @@ -209,7 +209,9 @@ underwriting_audit/ │ ├── __init__.py # exports of the deployed model │ ├── schema.py # reference concepts │ ├── source.py # reference data and its checks -│ └── reasoning.py # scalar decisions, rule pack, property catalog, one search per property +│ ├── applicant_rules.py # scalar decisions, derived indicators, rule pack +│ ├── property_audits.py # property catalog, one search per property, published status and witnesses +│ └── audit_verdicts.py # verdict per property, witness-limit flag, verdict tallies ├── queries/ │ └── audit_report.py # verdicts, witness tables, and verdict matrix from the deployed model └── data/ @@ -236,11 +238,11 @@ Rather than a table of applicants, the model has one applicant slot described by - **Primary identifiers**: `AgeBucket` and `CoverageBand` are each identified by an integer `id`. - **Important invariants**: reference ids are dense and contiguous; the free decisions `age_bucket_id`, `has_chronic`, and `coverage_band_id` select one reference row (or a binary flag); the rule indicators `is_senior`, `is_frail`, and `is_manual_review` are binaries pinned to those decisions by the rule pack. -For the full concept and property definitions, see `model/schema.py` and `model/reasoning.py`; `runbook.md` builds them step by step with the RAI skills. +For the full concept and property definitions, see `model/schema.py`, `model/applicant_rules.py`, and `model/property_audits.py`; `runbook.md` builds them step by step with the RAI skills. ## How it works -The template factors the audit into three artifacts. The scalar decisions that describe an applicant and the rule pack are declared once in the model. A property catalog pairs each property's name and description with a builder for its counterexample constraints. And one `Problem` per property in the catalog attaches the rule pack and that property's counterexample constraints and solves in multi-solution mode on each refresh of the deployed model. The query classifies each verdict from the published status and number of witnesses, reads back the witnesses, and prints a verdict matrix at the end. +The template factors the audit into three artifacts. The scalar decisions that describe an applicant and the rule pack are declared once in the model. A property catalog pairs each property's name and description with a builder for its counterexample constraints. And one `Problem` per property in the catalog attaches the rule pack and that property's counterexample constraints and solves in multi-solution mode on each refresh of the deployed model. The model classifies each verdict from the published status and number of witnesses and tallies the verdicts; the query reads back the verdicts and witnesses and prints a verdict matrix at the end. An applicant is described entirely by free decisions the solver fills in — which age bucket they fall into, whether they have a chronic condition, which coverage band they sit in — rather than by a row in an applicant table. On top of those, three rule indicators (`is_senior`, `is_frail`, `is_manual_review`) are also modeled as decisions, so the property check can compare them directly. The rule pack pins each indicator to a function of the free decisions: the senior indicator turns on when the chosen age bucket is at or above the senior threshold; the frailty indicator is the logical OR of senior-or-chronic, encoded as the standard three-constraint arithmetic for OR over binaries; and the manual-review indicator is pinned by the bundled — deliberately buggy — rule to the senior indicator alone, omitting the chronic arm that the audit is designed to expose. @@ -250,7 +252,7 @@ Each property in the catalog is checked by asserting its logical negation and as reference CSVs → free decisions + rule indicators → rule pack → per-property: assert negation → solve → PASS/FAIL/INCONCLUSIVE + witnesses → verdict matrix ``` -See `model/reasoning.py` and `queries/audit_report.py` for the implementation, and `runbook.md` to reproduce it step by step with the RAI skills. +See `model/applicant_rules.py`, `model/property_audits.py`, `model/audit_verdicts.py`, and `queries/audit_report.py` for the implementation, and `runbook.md` to reproduce it step by step with the RAI skills. ## Customize this template @@ -261,15 +263,15 @@ See `model/reasoning.py` and `queries/audit_report.py` for the implementation, a ### Tune parameters -- Raise `MAX_WITNESSES` in `model/reasoning.py` to surface more counterexamples per failing property. Production audits typically want 50 to 500 witnesses per failure to cover the rule pack's failure modes. Raising it past the size of the feasible set makes the solver exhaust every distinct case. -- The solve time cap is `time_limit_sec` (default 60) in the `problem.configure("minizinc", ...)` call in `model/reasoning.py`. +- Raise `MAX_WITNESSES` in `model/property_audits.py` to surface more counterexamples per failing property. Production audits typically want 50 to 500 witnesses per failure to cover the rule pack's failure modes. Raising it past the size of the feasible set makes the solver exhaust every distinct case. +- The solve time cap is `time_limit_sec` (default 60) in the `problem.configure("minizinc", ...)` call in `model/property_audits.py`. ### Extend the model -- Add a property to the catalog by appending a `(name, description, counterexample_builder)` tuple to `PROPERTIES` in `model/reasoning.py`. The builder takes no arguments and returns the property's counterexample ICs — the logical negation of the property. For example, to audit "no senior is in the cheapest coverage band", add `("no_senior_cheap_band", "no senior is in the cheapest coverage band", lambda: [model.require(is_senior == 1), model.require(coverage_band_id == 1)])`. The loop below the catalog creates its `Problem`, and the query reports it; redeploy and no other code changes. +- Add a property to the catalog by appending a `(name, description, counterexample_builder)` tuple to `PROPERTIES` in `model/property_audits.py`. The builder takes no arguments and returns the property's counterexample ICs — the logical negation of the property. For example, to audit "no senior is in the cheapest coverage band", add `("no_senior_cheap_band", "no senior is in the cheapest coverage band", lambda: [model.require(is_senior == 1), model.require(coverage_band_id == 1)])`. The loop below the catalog creates its `Problem`, and the query reports it; redeploy and no other code changes. - Add a scoped property by adding a `model.where().require()` IC alongside the unconditional counterexample ICs. `chronic_under_50_implies_review` shows the pattern: the `where` iterates `AgeBucket` rows outside the scope (a pure data filter), and the `require` body forbids the applicant decision from picking those rows. PyRel rejects decision-variable expressions inside `where`, so the decision-variable constraint must live in `require`. -- Audit a corrected ruleset by changing the buggy rule in `model/reasoning.py`: the manual-review rule pins `is_manual_review == is_senior`; change the right-hand side to `is_frail`. With the fix in place, the failing verdicts in the bundled run turn to PASS and the verdict matrix reports 3 PASS, 0 FAIL. -- Add more rule indicators by introducing additional decisions and their defining ICs in `model/reasoning.py`, then appending them to `rule_pack`. A logical AND over binaries is encoded with the dual of the OR pattern used for `is_frail`. +- Audit a corrected ruleset by changing the buggy rule in `model/applicant_rules.py`: the manual-review rule pins `is_manual_review == is_senior`; change the right-hand side to `is_frail`. With the fix in place, the failing verdicts in the bundled run turn to PASS and the verdict matrix reports 3 PASS, 0 FAIL. +- Add more rule indicators by introducing additional decisions and their defining ICs in `model/applicant_rules.py`, appending them to `rule_pack`, and adding a `solve_for` for each new decision in `model/property_audits.py`. A logical AND over binaries is encoded with the dual of the OR pattern used for `is_frail`. - Switch from "any counterexample" to "worst counterexample" by adding a `problem.maximize(...)` over a violation-severity score and letting the solve finish `OPTIMAL`, when triage capacity is limited and you want the single most severe failure first; a time-limited solve returns only the most severe counterexample it found. ### Extend to many applicants diff --git a/underwriting_audit/model/__init__.py b/underwriting_audit/model/__init__.py index 92241504..0e290e24 100644 --- a/underwriting_audit/model/__init__.py +++ b/underwriting_audit/model/__init__.py @@ -36,8 +36,19 @@ add-only, so a previous property's counterexample ICs cannot be detached from a reused `Problem`. The deployed model publishes each solve's status, its number of witnesses, and every distinct witness, read from - `Variable.values(solution_index, value)`; `queries/audit_report.py` - classifies the verdict and prints the witnesses. + `Variable.values(solution_index, value)`. It also classifies each + property's verdict and tallies the verdicts; `queries/audit_report.py` + prints them with the witnesses. + +The model package has one module per stage, and each module imports the +modules whose declarations it reads: + +- `source.py` loads the reference data. +- `applicant_rules.py` declares the free decisions, the derived indicators, + and the rule pack. +- `property_audits.py` declares the property catalog and one search per + property. +- `audit_verdicts.py` classifies each property's verdict and tallies them. The bundled ruleset has a deliberate bug: `is_manual_review` is defined as "senior", but `is_frail` is defined as "senior OR has chronic condition". @@ -56,13 +67,8 @@ `python -m queries.audit_report` then prints the report from the deployed model. """ -from .reasoning import ( - MAX_WITNESSES, - PROPERTIES, - NumPoints, - SolveStatus, - Witness, -) +from .audit_verdicts import PropertyVerdict, VerdictTally +from .property_audits import MAX_WITNESSES, PROPERTIES, NumPoints, SolveStatus, Witness from .schema import AgeBucket, CoverageBand, model from .source import DATA_DIR @@ -73,7 +79,9 @@ "AgeBucket", "CoverageBand", "NumPoints", + "PropertyVerdict", "SolveStatus", + "VerdictTally", "Witness", "model", ] diff --git a/underwriting_audit/model/applicant_rules.py b/underwriting_audit/model/applicant_rules.py new file mode 100644 index 00000000..5ce37bc6 --- /dev/null +++ b/underwriting_audit/model/applicant_rules.py @@ -0,0 +1,83 @@ +"""Applicant rules: the free decisions that describe one applicant, the derived indicators, and the +rule pack that pins each indicator to the decisions.""" + +from relationalai.semantics import Integer +from relationalai.semantics.reasoners.prescriptive import implies + +from .schema import AgeBucket, model + +# -------------------------------------------------- +# Parameters +# -------------------------------------------------- + +# Senior threshold: applicants with bucket age_years >= 70 are flagged +# `is_senior`. Drives both the (correct) `is_frail` and (buggy) +# `is_manual_review` rules. +SENIOR_THRESHOLD_YEARS = 70 + +# -------------------------------------------------- +# Scalar decisions and the rule pack +# -------------------------------------------------- + +# Free decisions: applicant attributes the audit is allowed to +# vary. Each is a scalar `model.Relationship` (one Integer slot) -- +# the unparented scalar shape. No singleton Applicant concept is +# required because there is exactly one applicant slot; the solver +# picks values for these scalars on every solution. To extend to a +# fleet of N applicants, reintroduce +# an `Applicant` concept and lift each scalar to a +# `model.Property(f"{Applicant} has {Integer:foo}")`, then scope +# every IC below (including each property's counterexample ICs) +# with `model.where(Applicant)` (or a tighter filter). +age_bucket_id = model.Relationship(f"{Integer:age_bucket_id}") +has_chronic = model.Relationship(f"{Integer:has_chronic}") +coverage_band_id = model.Relationship(f"{Integer:coverage_band_id}") + +# Derived indicators: defined in terms of the free decisions via +# arithmetic-equivalence ICs below. These are also decision +# variables from the solver's point of view so that the +# property-entailment IC can compare them directly. +is_senior = model.Relationship(f"{Integer:is_senior}") +is_frail = model.Relationship(f"{Integer:is_frail}") +is_manual_review = model.Relationship(f"{Integer:is_manual_review}") + +# Rule: `is_senior` is 1 iff the applicant's age bucket has age >= 70. +# Encoded as a per-bucket iteration over AgeBucket: for each senior +# bucket, if the applicant picks it, is_senior must be 1; for each +# non-senior bucket, if the applicant picks it, is_senior must be 0. +senior_def_pos_ic = model.where(AgeBucket.age_years >= SENIOR_THRESHOLD_YEARS).require( + implies(age_bucket_id == AgeBucket.id, is_senior == 1) +) +senior_def_neg_ic = model.where(AgeBucket.age_years < SENIOR_THRESHOLD_YEARS).require( + implies(age_bucket_id == AgeBucket.id, is_senior == 0) +) + +# Rule: `is_frail` is 1 iff the applicant is senior OR has a chronic +# condition. Encoded as the standard OR-arithmetic equivalence on +# binaries (`y = a OR b` is `y >= a, y >= b, y <= a + b`) -- a +# single `==` constraint won't do here because `is_senior + +# has_chronic` can be 2 but `is_frail` is binary. Keep all three +# arms even when one looks redundant under the bundled +# counterexample ICs -- each arm is part of the definition of the +# OR rule, and dropping an arm silently weakens the ruleset against +# a future rule change (the exact silent-pass shape the audit warns +# against). +frail_lb_senior_ic = model.require(is_frail >= is_senior) +frail_lb_chronic_ic = model.require(is_frail >= has_chronic) +frail_ub_ic = model.require(is_frail <= is_senior + has_chronic) + +# Rule (BUGGY): `is_manual_review` is 1 iff the applicant is +# senior. The correct rule should also flag frail applicants +# (senior OR chronic), but this version misses the chronic arm -- +# which is exactly the bug the audit exposes. Encoded as a single +# equality constraint. +manual_review_eq_ic = model.require(is_manual_review == is_senior) + +rule_pack = [ + senior_def_pos_ic, + senior_def_neg_ic, + frail_lb_senior_ic, + frail_lb_chronic_ic, + frail_ub_ic, + manual_review_eq_ic, +] diff --git a/underwriting_audit/model/audit_verdicts.py b/underwriting_audit/model/audit_verdicts.py new file mode 100644 index 00000000..31f3d09d --- /dev/null +++ b/underwriting_audit/model/audit_verdicts.py @@ -0,0 +1,60 @@ +"""Audit verdicts: each property's PASS, FAIL, or INCONCLUSIVE verdict, and how many properties +received each verdict.""" + +from relationalai.semantics import Integer, String +from relationalai.semantics.std import aggregates as aggs + +from .property_audits import NumPoints, SolveStatus +from .schema import model + +# -------------------------------------------------- +# Verdict per property +# -------------------------------------------------- + +# A verdict is classified from the status and number of witnesses of the property's solve: +# - FAIL: at least one witness. A counterexample exists, which falsifies the property +# regardless of whether the search was exhaustive; the witness count is partial when the +# status is not OPTIMAL or SOLUTION_LIMIT, but the verdict itself is conclusive. +# - PASS: INFEASIBLE, or OPTIMAL with a published count of zero. The solver proved no +# counterexample exists (or exhausted the search and found none), so the property holds under +# the encoded rule pack. Soundness is bounded by encoding fidelity: missing rule arms can +# produce a silent pass. Local-only statuses (e.g. LOCALLY_SOLVED from an LP solver) do not +# count as exhaustion and are INCONCLUSIVE. +# - INCONCLUSIVE: anything else (TIME_LIMIT, MEMORY_LIMIT, OTHER_ERROR, ... with zero +# witnesses, or OPTIMAL with no published count). The audit did not finish or its count is +# missing, and no witness was found, so neither pass nor fail can be concluded. +PropertyVerdict = model.Relationship(f"property {String:property_name} has verdict {String:verdict}") + +_n_witnesses = Integer.ref() +for name in SolveStatus: + found = (NumPoints[name](_n_witnesses), _n_witnesses >= 1) + infeasible = SolveStatus[name]("INFEASIBLE") + exhausted = (SolveStatus[name]("OPTIMAL"), NumPoints[name](0)) + model.where(*found).define(PropertyVerdict(name, "FAIL")) + model.where(infeasible, model.not_(*found)).define(PropertyVerdict(name, "PASS")) + model.where(*exhausted).define(PropertyVerdict(name, "PASS")) + model.where( + model.not_(*found), model.not_(infeasible), model.not_(*exhausted) + ).define(PropertyVerdict(name, "INCONCLUSIVE")) + +# -------------------------------------------------- +# Verdict tallies +# -------------------------------------------------- + +# The number of properties with each verdict, zero when none has it. +VerdictTally = model.Concept("VerdictTally", identify_by={"verdict": String}) +VerdictTally.n_properties = model.Property(f"{VerdictTally} has {Integer:n_properties} properties") +model.define( + VerdictTally.new(verdict="PASS"), + VerdictTally.new(verdict="FAIL"), + VerdictTally.new(verdict="INCONCLUSIVE"), +) +_property_name = String.ref() +model.define( + VerdictTally.n_properties( + aggs.count(_property_name) + .per(VerdictTally) + .where(PropertyVerdict(_property_name, VerdictTally.verdict)) + | 0 + ) +) diff --git a/underwriting_audit/model/reasoning.py b/underwriting_audit/model/property_audits.py similarity index 69% rename from underwriting_audit/model/reasoning.py rename to underwriting_audit/model/property_audits.py index a412345f..e16fe12c 100644 --- a/underwriting_audit/model/reasoning.py +++ b/underwriting_audit/model/property_audits.py @@ -1,8 +1,18 @@ -"""Underwriting rule pack and property audits: one counterexample search per catalog property.""" +"""Property audits: the property catalog and one counterexample search per property, with each +search's status, number of witnesses, and witnesses.""" from relationalai.semantics import Integer, String -from relationalai.semantics.reasoners.prescriptive import Problem, implies - +from relationalai.semantics.reasoners.prescriptive import Problem + +from .applicant_rules import ( + age_bucket_id, + coverage_band_id, + has_chronic, + is_frail, + is_manual_review, + is_senior, + rule_pack, +) from .schema import AgeBucket, CoverageBand, model from .source import age_buckets_csv, coverage_bands_csv @@ -10,10 +20,6 @@ # Parameters # -------------------------------------------------- -# Senior threshold: applicants with bucket age_years >= 70 are flagged -# `is_senior`. Drives both the (correct) `is_frail` and (buggy) -# `is_manual_review` rules. -SENIOR_THRESHOLD_YEARS = 70 # `chronic_under_50_implies_review` scopes its counterexample to age # buckets under this threshold. The bundled CSV has two buckets under 50 # (28 and 45), so the property's witness set is 2 buckets * 4 coverage @@ -29,73 +35,6 @@ # witnesses may exist beyond the cap; raise it for production rule packs. MAX_WITNESSES = 16 -# -------------------------------------------------- -# Scalar decisions and the rule pack -# -------------------------------------------------- - -# Free decisions: applicant attributes the audit is allowed to -# vary. Each is a scalar `model.Relationship` (one Integer slot) -- -# the unparented scalar shape. No singleton Applicant concept is -# required because there is exactly one applicant slot; the solver -# picks values for these scalars on every solution. To extend to a -# fleet of N applicants, reintroduce -# an `Applicant` concept and lift each scalar to a -# `model.Property(f"{Applicant} has {Integer:foo}")`, then scope -# every IC below (including each property's counterexample ICs) -# with `model.where(Applicant)` (or a tighter filter). -age_bucket_id = model.Relationship(f"{Integer:age_bucket_id}") -has_chronic = model.Relationship(f"{Integer:has_chronic}") -coverage_band_id = model.Relationship(f"{Integer:coverage_band_id}") - -# Derived indicators: defined in terms of the free decisions via -# arithmetic-equivalence ICs below. These are also decision -# variables from the solver's point of view so that the -# property-entailment IC can compare them directly. -is_senior = model.Relationship(f"{Integer:is_senior}") -is_frail = model.Relationship(f"{Integer:is_frail}") -is_manual_review = model.Relationship(f"{Integer:is_manual_review}") - -# Rule: `is_senior` is 1 iff the applicant's age bucket has age >= 70. -# Encoded as a per-bucket iteration over AgeBucket: for each senior -# bucket, if the applicant picks it, is_senior must be 1; for each -# non-senior bucket, if the applicant picks it, is_senior must be 0. -senior_def_pos_ic = model.where(AgeBucket.age_years >= SENIOR_THRESHOLD_YEARS).require( - implies(age_bucket_id == AgeBucket.id, is_senior == 1) -) -senior_def_neg_ic = model.where(AgeBucket.age_years < SENIOR_THRESHOLD_YEARS).require( - implies(age_bucket_id == AgeBucket.id, is_senior == 0) -) - -# Rule: `is_frail` is 1 iff the applicant is senior OR has a chronic -# condition. Encoded as the standard OR-arithmetic equivalence on -# binaries (`y = a OR b` is `y >= a, y >= b, y <= a + b`) -- a -# single `==` constraint won't do here because `is_senior + -# has_chronic` can be 2 but `is_frail` is binary. Keep all three -# arms even when one looks redundant under the bundled -# counterexample ICs -- each arm is part of the definition of the -# OR rule, and dropping an arm silently weakens the ruleset against -# a future rule change (the exact silent-pass shape the audit warns -# against). -frail_lb_senior_ic = model.require(is_frail >= is_senior) -frail_lb_chronic_ic = model.require(is_frail >= has_chronic) -frail_ub_ic = model.require(is_frail <= is_senior + has_chronic) - -# Rule (BUGGY): `is_manual_review` is 1 iff the applicant is -# senior. The correct rule should also flag frail applicants -# (senior OR chronic), but this version misses the chronic arm -- -# which is exactly the bug the audit exposes. Encoded as a single -# equality constraint. -manual_review_eq_ic = model.require(is_manual_review == is_senior) - -rule_pack = [ - senior_def_pos_ic, - senior_def_neg_ic, - frail_lb_senior_ic, - frail_lb_chronic_ic, - frail_ub_ic, - manual_review_eq_ic, -] - # -------------------------------------------------- # Property catalog (the spec the rule pack must satisfy) # -------------------------------------------------- diff --git a/underwriting_audit/queries/audit_report.py b/underwriting_audit/queries/audit_report.py index 8775dfbf..feb8fadb 100644 --- a/underwriting_audit/queries/audit_report.py +++ b/underwriting_audit/queries/audit_report.py @@ -1,9 +1,9 @@ """Audit report: reads the deployed underwriting_audit model. Run `python -m queries.audit_report` after `rai models deploy --path model`. For each property -in the catalog, prints the verdict (PASS, FAIL, or INCONCLUSIVE) classified from the status and -number of witnesses of the latest refresh's solve and, for FAILs, the witness table, then a -verdict-matrix recap covering every property. +in the catalog, prints the verdict (PASS, FAIL, or INCONCLUSIVE) the model classifies from the +status and number of witnesses of the latest refresh's solve and, for FAILs, the witness table, +then a verdict-matrix recap covering every property. """ from model import ( @@ -12,7 +12,9 @@ AgeBucket, CoverageBand, NumPoints, + PropertyVerdict, SolveStatus, + VerdictTally, Witness, model, ) @@ -27,32 +29,6 @@ pd_set_option("display.width", 200) -def _classify_verdict(status, num_points): - """Map solver termination + witness count to an audit verdict. - - - Any status with num_points >= 1 -> FAIL: a counterexample exists, - which falsifies the property regardless of whether the search was - exhaustive. The witness count is partial when status is not - OPTIMAL/SOLUTION_LIMIT, but the verdict itself is conclusive. - - INFEASIBLE, or OPTIMAL with a published count of zero -> PASS: solver proved - no counterexample exists (or exhausted the search and found none), - so the property holds under the encoded rule pack. Soundness is - bounded by encoding fidelity: missing rule arms can produce a - silent pass. Local-only statuses (e.g. LOCALLY_SOLVED from an LP - solver) do not count as exhaustion and route to INCONCLUSIVE - below. - - Anything else (TIME_LIMIT, MEMORY_LIMIT, OTHER_ERROR, ... with - zero witnesses, or OPTIMAL with no published count) -> INCONCLUSIVE: - the audit did not finish or its count is missing, and no witness was - found, so neither pass nor fail can be concluded. - """ - if num_points is not None and num_points >= 1: - return "FAIL" - if status == "INFEASIBLE" or (status == "OPTIMAL" and num_points == 0): - return "PASS" - return "INCONCLUSIVE" - - def report_audit(name, description): """Print one property's verdict line and (on FAIL) its witness table. @@ -77,7 +53,13 @@ def report_audit(name, description): # An infeasible audit has no witness, and its solve publishes no count. if n_witnesses is None and status == "INFEASIBLE": n_witnesses = 0 - verdict = _classify_verdict(status, n_witnesses) + verdict_ref = String.ref() + verdict = ( + model.select(verdict_ref.alias("verdict")) + .where(PropertyVerdict(name, verdict_ref)) + .to_df()["verdict"] + .iloc[0] + ) count_text = "no count" if n_witnesses is None else str(n_witnesses) print(f"Verdict: {verdict} ({count_text} witness(es), status={status})") if verdict == "FAIL" and status == "SOLUTION_LIMIT": @@ -131,13 +113,15 @@ def report_audit(name, description): # values (e.g. all witnesses with `has_chronic=1`) usually surfaces the # common root cause; comparing witness counts across FAILs surfaces # which sub-populations the bug touches. - fail_count = sum(1 for r in results if r["verdict"] == "FAIL") - pass_count = sum(1 for r in results if r["verdict"] == "PASS") - incon_count = sum(1 for r in results if r["verdict"] == "INCONCLUSIVE") + tally = ( + model.select(VerdictTally.verdict.alias("verdict"), VerdictTally.n_properties.alias("n")) + .to_df() + .set_index("verdict")["n"] + ) print("\n" + "=" * 80) print( f"Audit report ({len(results)} properties: " - f"{pass_count} PASS, {fail_count} FAIL, {incon_count} INCONCLUSIVE)" + f"{tally['PASS']} PASS, {tally['FAIL']} FAIL, {tally['INCONCLUSIVE']} INCONCLUSIVE)" ) print("=" * 80) print(f" {'Property':<32} {'Verdict':<14} {'Witnesses':>10} Description") diff --git a/underwriting_audit/runbook.md b/underwriting_audit/runbook.md index 166be37c..7aa54d20 100644 --- a/underwriting_audit/runbook.md +++ b/underwriting_audit/runbook.md @@ -38,7 +38,7 @@ Each prompt is pasted into a fresh agent session loaded with the named `/rai-*` **Prompt:** /rai-prescriptive-problem Encode the underwriting rules as constraints over an applicant's attributes: an applicant is senior if their age is at least 70; frail if senior or chronically ill; and the ruleset flags an applicant for manual review if they are senior. Then audit three properties — (a) every senior is flagged for review, (b) every frail applicant is flagged for review, (c) every chronically-ill applicant under 50 is flagged for review — by searching for a counterexample for each: an applicant who satisfies the rules but violates the property. Enumerate up to 16 distinct counterexample applicants per property (multi-solution mode). A property passes only if no counterexample exists. -**Response:** Each property is audited as its own constraint problem (MiniZinc) over 6 applicant decision variables, declared in `model/reasoning.py` with `problem.configure(...)`, so each refresh of the deployed model runs the searches. A property with no feasible counterexample is INFEASIBLE — meaning it holds (PASS); a property with feasible counterexamples FAILS, and each witness is a concrete applicant exhibiting the gap. +**Response:** Each property is audited as its own constraint problem (MiniZinc) over 6 applicant decision variables, declared in `model/applicant_rules.py` and `model/property_audits.py` with `problem.configure(...)`, so each refresh of the deployed model runs the searches. A property with no feasible counterexample is INFEASIBLE — meaning it holds (PASS); a property with feasible counterexamples FAILS, and each witness is a concrete applicant exhibiting the gap. ## 4. Read the audit report diff --git a/warehouse_allocation/README.md b/warehouse_allocation/README.md index d210e86d..e1e0bbf7 100644 --- a/warehouse_allocation/README.md +++ b/warehouse_allocation/README.md @@ -40,7 +40,7 @@ Built using **graph analysis** (eigenvector centrality, weakly connected compone ## What's included -- **Model**: a two-stage pipeline (graph, then prescriptive) on a single shared ontology — `Site`, `Route`, and `Demand` concepts wired to the bundled CSVs, plus the centrality enrichment Stage 1 writes back — in the `model/` package (`schema.py` declares the concepts, `source.py` loads the sample data, `reasoning.py` holds both stages), which `rai models deploy --path model` deploys to your Snowflake account, where each refresh runs both stages. +- **Model**: a two-stage pipeline (graph, then prescriptive) on a single shared ontology — `Site`, `Route`, and `Demand` concepts wired to the bundled CSVs, plus the centrality enrichment Stage 1 writes back — in the `model/` package (`schema.py` declares the concepts, `source.py` loads the sample data, `network_analysis.py` holds the graph stage, `inventory_allocation.py` holds the prescriptive stage), which `rai models deploy --path model` deploys to your Snowflake account, where each refresh runs both stages. - **Query**: `queries/allocation_report.py`, which prints the report from the deployed model. - **Runbook**: `runbook.md` — a paste-testable walkthrough that reproduces the template step by step with the RAI skills; as important a reference as the code in `model/`. - **Sample data**: a small distribution network of warehouses and stores with routes and per-site demand. See *Sample data* below. @@ -205,7 +205,8 @@ warehouse_allocation/ __init__.py # exports of the deployed model schema.py # Site, Route, and Demand concepts source.py # loads the sample CSVs - reasoning.py # Stage 1 graph + Stage 2 prescriptive + network_analysis.py # Stage 1 graph: centrality, components, bridge routes + inventory_allocation.py # Stage 2 prescriptive: allocation problem queries/ allocation_report.py # report from the deployed model data/ @@ -253,7 +254,7 @@ Stage 1 characterizes the route topology three ways, then Stage 2 allocates inve sites/routes/demands CSVs → graph (centrality, components, bridges) → Site.centrality → optimizer (budget, demand, centrality floor) → allocation plan ``` -See `model/reasoning.py` for the implementation, and `runbook.md` to reproduce it step by step with the RAI skills. +See `model/network_analysis.py` and `model/inventory_allocation.py` for the implementation, and `runbook.md` to reproduce it step by step with the RAI skills. ## Customize this template diff --git a/warehouse_allocation/model/__init__.py b/warehouse_allocation/model/__init__.py index c1d46496..00279187 100644 --- a/warehouse_allocation/model/__init__.py +++ b/warehouse_allocation/model/__init__.py @@ -20,6 +20,9 @@ properties that the prescriptive reasoner references directly -- no manual data transfer between stages. +The graph stage is `network_analysis.py` and the prescriptive stage is +`inventory_allocation.py`, which imports the module whose centrality it reads. + Run: `rai models deploy --path model` deploys this package to the schemas in raiconfig.yaml and waits for its first refresh, which runs the graph analysis @@ -27,13 +30,22 @@ from the deployed model. """ -from .reasoning import SiteComponent, SolveStatus, TotalHoldingCost, graph, problem +from .inventory_allocation import SolveStatus, TotalHoldingCost, problem +from .network_analysis import ( + NetworkComponent, + NetworkState, + SiteComponent, + graph, + num_components, +) from .schema import Demand, Route, Site, model from .source import DATA_DIR __all__ = [ "DATA_DIR", "Demand", + "NetworkComponent", + "NetworkState", "Route", "Site", "SiteComponent", @@ -41,5 +53,6 @@ "TotalHoldingCost", "graph", "model", + "num_components", "problem", ] diff --git a/warehouse_allocation/model/reasoning.py b/warehouse_allocation/model/inventory_allocation.py similarity index 50% rename from warehouse_allocation/model/reasoning.py rename to warehouse_allocation/model/inventory_allocation.py index d4f73dba..4affc348 100644 --- a/warehouse_allocation/model/reasoning.py +++ b/warehouse_allocation/model/inventory_allocation.py @@ -1,54 +1,12 @@ -"""Graph analysis of the distribution network, then the inventory allocation problem.""" +"""Inventory allocation: the linear program that allocates inventory across sites at minimum holding +cost, with a centrality-proportional floor on the warehouses.""" from relationalai.semantics import Float, String, sum -from relationalai.semantics.reasoners.graph import Graph from relationalai.semantics.reasoners.prescriptive import Problem -from .schema import Demand, Property, Route, Site, model - -# -------------------------------------------------- -# Stage 1: Graph Analysis -- identify critical network hubs -# -------------------------------------------------- - -graph = Graph( - model, directed=False, weighted=True, node_concept=Site, aggregator="sum", name="warehouse_network" -) - -# Build edges from routes (undirected, weighted by capacity) -route_ref = Route.ref() -src, dst = Site.ref(), Site.ref() -model.where(route_ref.source(src), route_ref.dest(dst)).define( - graph.Edge.new(src=src, dst=dst, weight=route_ref.capacity), -) - -# Eigenvector centrality: stored directly on Site (via node_concept) -Site.centrality = graph.eigenvector_centrality() - -# -------------------------------------------------- -# Stage 1b: Weakly Connected Components -- surface fragmentation -# -------------------------------------------------- - -# Each site's component, named by one of its sites, which the deployed model publishes for the queries. -wcc = graph.weakly_connected_component() -SiteComponent = model.Relationship(f"{Site} is in the component of {Site:component}") -site_member, site_component = Site.ref(), Site.ref() -model.where(wcc(site_member, site_component)).define(SiteComponent(site_member, site_component)) - -# -------------------------------------------------- -# Stage 1c: Bridge Routes -- cross-region connectors -# -------------------------------------------------- -# Routes whose endpoints lie in different regions: the links that carry -# inter-region flow. This compares region labels only; it does not test -# whether removing a route disconnects the graph. - -route_ref = Route.ref() -src, dst = Site.ref(), Site.ref() -Route.is_cross_region = Property(f"{Route} is cross-region {Float:is_cross_region}") -model.where( - route_ref.source(src), - route_ref.dest(dst), - src.region != dst.region, -).define(Route.is_cross_region(route_ref, 1.0)) +# Declares Site.centrality, the eigenvector centrality the warehouse floors read. +from . import network_analysis # noqa: F401 +from .schema import Demand, Property, Site, model # -------------------------------------------------- # Stage 2: Prescriptive -- allocate inventory across sites diff --git a/warehouse_allocation/model/network_analysis.py b/warehouse_allocation/model/network_analysis.py new file mode 100644 index 00000000..012b0da6 --- /dev/null +++ b/warehouse_allocation/model/network_analysis.py @@ -0,0 +1,80 @@ +"""Network analysis: the distribution network graph, each site's eigenvector centrality, the weakly +connected components with their sizes and regions, and the cross-region bridge routes.""" + +from relationalai.semantics import Float, Integer, String +from relationalai.semantics.reasoners.graph import Graph +from relationalai.semantics.std import aggregates as aggs + +from .schema import Property, Route, Site, model + +# -------------------------------------------------- +# Stage 1: Graph Analysis -- identify critical network hubs +# -------------------------------------------------- + +graph = Graph( + model, directed=False, weighted=True, node_concept=Site, aggregator="sum", name="warehouse_network" +) + +# Build edges from routes (undirected, weighted by capacity) +route_ref = Route.ref() +src, dst = Site.ref(), Site.ref() +model.where(route_ref.source(src), route_ref.dest(dst)).define( + graph.Edge.new(src=src, dst=dst, weight=route_ref.capacity), +) + +# Eigenvector centrality: stored directly on Site (via node_concept) +Site.centrality = graph.eigenvector_centrality() + +# -------------------------------------------------- +# Stage 1b: Weakly Connected Components -- surface fragmentation +# -------------------------------------------------- + +# Each site's component, named by one of its sites, which the deployed model publishes for the queries. +wcc = graph.weakly_connected_component() +SiteComponent = model.Relationship(f"{Site} is in the component of {Site:component}") +site_member, site_component = Site.ref(), Site.ref() +model.where(wcc(site_member, site_component)).define(SiteComponent(site_member, site_component)) + +# Each component's number of sites and its regions in alphabetical order. A component is +# identified by the id of the site that names it. +NetworkComponent = model.Concept("NetworkComponent", identify_by={"component_id": Integer}) +NetworkComponent.n_sites = model.Property(f"{NetworkComponent} has {Integer:n_sites} sites") +NetworkComponent.regions = model.Property(f"{NetworkComponent} spans regions {String:regions}") +model.where(SiteComponent(site_member, site_component)).define( + NetworkComponent.new(component_id=site_component.id) +) +_in_component = ( + SiteComponent(site_member, site_component), + site_component.id == NetworkComponent.component_id, +) +model.define( + NetworkComponent.n_sites(aggs.count(site_member).per(NetworkComponent).where(*_in_component)), + NetworkComponent.regions( + aggs.string_join(site_member.region, sep=", ").per(NetworkComponent).where(*_in_component) + ), +) + +# The number of components, and whether the network is one component (UNIFIED) or several +# (FRAGMENTED). +num_components = model.Relationship(f"the network has {Integer:num_components} components") +model.define(num_components(aggs.count(NetworkComponent))) +NetworkState = model.Relationship(f"the network is {String:state}") +_n_components = Integer.ref() +model.where(num_components(_n_components), _n_components == 1).define(NetworkState("UNIFIED")) +model.where(num_components(_n_components), _n_components != 1).define(NetworkState("FRAGMENTED")) + +# -------------------------------------------------- +# Stage 1c: Bridge Routes -- cross-region connectors +# -------------------------------------------------- +# Routes whose endpoints lie in different regions: the links that carry +# inter-region flow. This compares region labels only; it does not test +# whether removing a route disconnects the graph. + +route_ref = Route.ref() +src, dst = Site.ref(), Site.ref() +Route.is_cross_region = Property(f"{Route} is cross-region {Float:is_cross_region}") +model.where( + route_ref.source(src), + route_ref.dest(dst), + src.region != dst.region, +).define(Route.is_cross_region(route_ref, 1.0)) diff --git a/warehouse_allocation/queries/allocation_report.py b/warehouse_allocation/queries/allocation_report.py index 5dcf86df..c3bb3e00 100644 --- a/warehouse_allocation/queries/allocation_report.py +++ b/warehouse_allocation/queries/allocation_report.py @@ -6,9 +6,16 @@ inventory allocation plan. """ -from model import Route, Site, SiteComponent, SolveStatus, TotalHoldingCost, model -from relationalai.semantics import where -from relationalai.semantics.std import aggregates as aggs +from model import ( + NetworkComponent, + NetworkState, + Route, + Site, + SolveStatus, + TotalHoldingCost, + model, + num_components, +) if __name__ == "__main__": # Display centrality scores @@ -23,35 +30,28 @@ Site.centrality.alias("centrality"), ).inspect() - # Stage 1b: connected components - site_ref = Site.ref("site") - comp_ref = Site.ref("component_id") - - wcc_df = ( - where(SiteComponent(site_ref, comp_ref)) - .select( - site_ref.id.alias("site_id"), - site_ref.name.alias("site"), - site_ref.region.alias("region"), - comp_ref.id.alias("component_id"), - aggs.count(site_ref).per(comp_ref).alias("component_size"), + # Stage 1b: connected components, as the model publishes them + components = ( + model.select( + NetworkComponent.component_id.alias("component_id"), + NetworkComponent.n_sites.alias("n_sites"), + NetworkComponent.regions.alias("regions"), ) .to_df() + .sort_values("component_id") ) + network_state = model.select(NetworkState).to_df().iloc[0, 0] + n_components = model.select(num_components).to_df().iloc[0, 0] print("\n" + "=" * 50) print("Stage 1b: Connected Components") print("=" * 50) - num_components = wcc_df["component_id"].nunique() - if num_components == 1: - print(f"UNIFIED NETWORK: all {len(wcc_df)} sites in a single component") + if network_state == "UNIFIED": + print(f"UNIFIED NETWORK: all {components['n_sites'].iloc[0]} sites in a single component") else: - print(f"FRAGMENTED NETWORK: {num_components} separate components detected") - for comp_id in sorted(wcc_df["component_id"].unique()): - comp_df = wcc_df[wcc_df["component_id"] == comp_id] - size = int(comp_df["component_size"].iloc[0]) - regions = ", ".join(sorted(comp_df["region"].unique())) - print(f" Component {comp_id}: {size} sites ({regions})") + print(f"FRAGMENTED NETWORK: {n_components} separate components detected") + for comp in components.itertuples(): + print(f" Component {comp.component_id}: {comp.n_sites} sites ({comp.regions})") # Stage 1c: bridge routes bridge_df = model.select( diff --git a/warehouse_allocation/runbook.md b/warehouse_allocation/runbook.md index 91915a35..d108498a 100644 --- a/warehouse_allocation/runbook.md +++ b/warehouse_allocation/runbook.md @@ -86,7 +86,7 @@ Eigenvector centrality (the "important neighbors make you important" measure) ra **Response** -OPTIMAL (HiGHS), total holding cost **$13,713.29**. 10 continuous allocation variables, 14 constraints (1 budget cap, 8 demand floors, 5 warehouse centrality floors); `Site.x_inventory` written back. In `model/reasoning.py` the solve is declared with `problem.configure(...)`, so each refresh of the deployed model runs the graph analysis, then the solve. +OPTIMAL (HiGHS), total holding cost **$13,713.29**. 10 continuous allocation variables, 14 constraints (1 budget cap, 8 demand floors, 5 warehouse centrality floors); `Site.x_inventory` written back. In `model/inventory_allocation.py` the solve is declared with `problem.configure(...)`, so each refresh of the deployed model runs the graph analysis, then the solve. ### 6. Read the allocation @@ -102,4 +102,4 @@ About **951 of the 2,000 units** are placed, so the **budget is slack** — it i ## Data -Bundled CSVs in `data/`: 10 sites, 14 routes, 8 demands; inventory budget (2,000) and the centrality-to-floor multiplier (200) are constants in `model/reasoning.py`. Full chain in `model/`; the report in `queries/allocation_report.py`. +Bundled CSVs in `data/`: 10 sites, 14 routes, 8 demands; inventory budget (2,000) and the centrality-to-floor multiplier (200) are constants in `model/inventory_allocation.py`. Full chain in `model/`; the report in `queries/allocation_report.py`. diff --git a/wildlife-conservation-network/README.md b/wildlife-conservation-network/README.md index 7991aa0e..47e59c47 100644 --- a/wildlife-conservation-network/README.md +++ b/wildlife-conservation-network/README.md @@ -36,7 +36,7 @@ Built using **graph analysis** (Louvain community detection and degree centralit ## What's included -- **Model**: a single shared ontology — `Organization` nodes and `Partnership` edges — plus the Louvain community and degree-centrality enrichment the graph reasoner writes back. Declared in the `model/` package (`schema.py` declares the concepts, `source.py` loads the sample data, `reasoning.py` builds the graph and its metrics), which `rai models deploy --path model` deploys to your Snowflake account, where each refresh computes the metrics. +- **Model**: a single shared ontology — `Organization` nodes and `Partnership` edges — plus the Louvain community and degree-centrality enrichment the graph reasoner writes back. Declared in the `model/` package (`schema.py` declares the concepts, `source.py` loads the sample data, `partnership_network.py` builds the graph and its metrics, `community_profiles.py` ranks each community's members, regions, species focuses, and organization types, `network_summary.py` computes the network-wide figures), which `rai models deploy --path model` deploys to your Snowflake account, where each refresh computes the metrics and the rules over them. - **Query and app**: `queries/community_report.py` (CLI report) and `app.py` (interactive Streamlit visualization), both querying the deployed model. - **Runbook**: `runbook.md` — a paste-testable walkthrough that reproduces the template step by step with the RAI skills; as important a reference as the script itself. - **Sample data**: a small network of conservation organizations and the partnerships between them. See *Sample data* below. @@ -196,7 +196,9 @@ wildlife-conservation-network/ __init__.py # Exports of the deployed model schema.py # Organization and partnership concepts source.py # Loads the sample CSVs - reasoning.py # Graph, communities, and centrality metrics + partnership_network.py # Graph, communities, and centrality metrics + community_profiles.py # Each community's members, hub, region, species, and types + network_summary.py # Network-wide counts and averages queries/ community_report.py # CLI report from the deployed model app.py # Optional Streamlit app (queries the deployed model) @@ -222,6 +224,7 @@ The bundled data is a small, illustrative conservation network — designed to t A single ontology (declared in `model/schema.py`) backs both the report and the app. The graph reasoner writes community and centrality results back onto the network. - **Key entities**: `Organization` (the network's nodes), `Partnership` (the collaboration edges). +- **Derived entities**: `Community` (a Louvain cluster, with its hub, primary region, and member order), `CommunityTrait` (a region, focus species, or organization type among a community's members, ranked), and `NetworkSummary` (the network-wide figures). - **Primary identifiers**: integer `id` on `Organization`; `Partnership` is identified by its two endpoint organizations. - **Important invariants**: every `Partnership` endpoint must reference a valid `Organization` id; the graph is undirected and unweighted, so a partnership counts once regardless of row order. @@ -233,13 +236,13 @@ For the full concept and property definitions, see `model/schema.py`; `runbook.m CSV files → model/ (deployed) → apply Louvain + degree centrality → analyze communities → display results ``` -Both the report and the app query one deployed model. The `model/` package builds the RelationalAI model container and defines the `Organization` concept and the `Partnership` edges (`schema.py`), loads them from CSV (`source.py`), and constructs the undirected, unweighted graph and declares the metrics (`reasoning.py`), and `rai models deploy --path model` deploys it. This keeps the CLI report and the Streamlit app in sync, since neither declares or redefines anything. +Both the report and the app query one deployed model. The `model/` package builds the RelationalAI model container and defines the `Organization` concept and the `Partnership` edges (`schema.py`), loads them from CSV (`source.py`), and constructs the undirected, unweighted graph and declares the metrics (`partnership_network.py`), ranks each community's members and traits (`community_profiles.py`), and computes the network-wide figures (`network_summary.py`), and `rai models deploy --path model` deploys it. This keeps the CLI report and the Streamlit app in sync, since neither declares or redefines anything. The graph reasoner then runs two algorithms over that graph. Louvain community detection partitions the network into collaboration clusters by optimizing modularity — iteratively grouping organizations to maximize connections within a cluster and minimize connections between clusters — and writes a community label onto each organization. Degree centrality normalizes each organization's partnership count to a 0-to-1 scale, which makes hubs comparable across clusters of different sizes; the highest-centrality organization inside a community is the one best placed to broker coordination there. -Reading those results back is a query joining the community label, centrality score, and raw partnership count per organization. `queries/community_report.py` renders a per-organization table, a per-community breakdown (size, region, species focus, hub), and network-wide summary statistics. The optional Streamlit app is a visualization layer over the same query: an interactive network graph colored by community, expandable per-cluster detail, and cross-community connector analysis. +Rules over those results rank each community's members by centrality and each community's regions, species focuses, and organization types by how many members hold them, and compute the network-wide counts and averages. `queries/community_report.py` reads them back with a query joining the community label, centrality score, and raw partnership count per organization, and renders a per-organization table, a per-community breakdown (size, region, species focus, hub), and network-wide summary statistics. The optional Streamlit app is a visualization layer over the same query: an interactive network graph colored by community, expandable per-cluster detail, and cross-community connector analysis. -See `model/reasoning.py` and `queries/community_report.py` for the implementation, and `runbook.md` to reproduce it step by step with the RAI skills. +See the `model/` modules and `queries/community_report.py` for the implementation, and `runbook.md` to reproduce it step by step with the RAI skills. ## Customize this template @@ -253,7 +256,7 @@ Focus on the first changes most users will make. ### Tune parameters -- The graph is built undirected and unweighted in `model/reasoning.py`. Adding edge weights (see *Extend the model*) is the main lever on how the community detection partitions the network. +- The graph is built undirected and unweighted in `model/partnership_network.py`. Adding edge weights (see *Extend the model*) is the main lever on how the community detection partitions the network. ### Extend the model diff --git a/wildlife-conservation-network/model/__init__.py b/wildlife-conservation-network/model/__init__.py index fedaa2f8..a351c966 100644 --- a/wildlife-conservation-network/model/__init__.py +++ b/wildlife-conservation-network/model/__init__.py @@ -6,10 +6,17 @@ - Load a network of conservation organizations and their partnerships from CSV. - Apply the Louvain algorithm to detect communities (clusters of closely collaborating orgs). - Calculate degree centrality and degree to identify hub organizations within each community. +- Profile each community (size, hub, primary region, species focus, organization types, member + order) and summarize the whole network, all as rules the report reads. The model uses RelationalAI's Graph API to define organizations as nodes and partnerships as edges. +Modules: `partnership_network.py` (the graph, Louvain communities, degree centrality, degree), +`community_profiles.py` (each community's members, hub, and trait rankings), and +`network_summary.py` (network-wide counts and averages). Each module imports the modules whose +declarations it reads. + Run: `rai models deploy --path model` deploys this package to the schemas in raiconfig.yaml and waits for its first refresh, which computes the graph metrics. @@ -17,12 +24,17 @@ `streamlit run app.py` starts the interactive app, both from the deployed model. """ -from .reasoning import degree, degree_centrality, graph, louvain_communities +from .community_profiles import Community, CommunityTrait +from .network_summary import NetworkSummary +from .partnership_network import degree, degree_centrality, graph, louvain_communities from .schema import Organization, Partnership, model from .source import DATA_DIR __all__ = [ "DATA_DIR", + "Community", + "CommunityTrait", + "NetworkSummary", "Organization", "Partnership", "degree", diff --git a/wildlife-conservation-network/model/community_profiles.py b/wildlife-conservation-network/model/community_profiles.py new file mode 100644 index 00000000..d72cafa6 --- /dev/null +++ b/wildlife-conservation-network/model/community_profiles.py @@ -0,0 +1,103 @@ +"""Community profiles: each Louvain community's size, member order, hub organization, primary +region, and the ranked regions, species focuses, and organization types of its members.""" + +from relationalai.semantics import Integer, String +from relationalai.semantics.std import aggregates as aggs + +# Declares Organization.community and Organization.degree_centrality, the graph results read here. +from . import partnership_network # noqa: F401 +from .schema import Organization, model + +# -------------------------------------------------- +# Communities, their members, and their hubs +# -------------------------------------------------- + +# One Community per Louvain community id. +Community = model.Concept("Community", identify_by={"id": Integer}) +model.define(Community.new(id=Organization.community)) + +Community.n_organizations = model.Property( + f"{Community} has {Integer:n_organizations} organizations" +) +model.define( + Community.n_organizations( + aggs.count(Organization).per(Community).where(Organization.community == Community.id) + ) +) + +# Member order within a community: highest degree centrality first, ties broken by the lower +# organization id. The centrality is negated so both keys sort ascending. +Community.member = model.Relationship( + f"{Community} has {Organization:org} at member rank {Integer:member_rank}" +) +model.where(Organization.community == Community.id).define( + Community.member( + Organization, + aggs.rank(-Organization.degree_centrality, Organization.id).per(Community), + ) +) + +# The hub is the top-ranked member: the organization best placed to coordinate its community. +Community.hub = model.Property(f"{Community} has hub {Organization:hub}") +_member_rank = Integer.ref() +model.where(Community.member(Organization, _member_rank), _member_rank == 1).define( + Community.hub(Organization) +) + +# -------------------------------------------------- +# Region, species focus, and organization types +# -------------------------------------------------- + +# One CommunityTrait per value of a trait among a community's members. The kind is `region`, +# `species` (focus species), or `type` (organization type). +CommunityTrait = model.Concept( + "CommunityTrait", + identify_by={"community": Community, "kind": String, "value": String}, +) +CommunityTrait.n_organizations = model.Property( + f"{CommunityTrait} is held by {Integer:n_organizations} organizations" +) +# The member rank of the most central organization holding the value. +CommunityTrait.first_member_rank = model.Property( + f"{CommunityTrait} is first held at member rank {Integer:first_member_rank}" +) +# Order among the community's values of the same kind: most organizations first; a tie goes to +# the value held by the more central member. The count is negated so both keys sort ascending. +CommunityTrait.rank = model.Property(f"{CommunityTrait} has trait rank {Integer:rank}") + +for kind, trait in ( + ("region", Organization.region), + ("species", Organization.focus_species), + ("type", Organization.type), +): + holders = ( + Community.member(Organization, _member_rank), + CommunityTrait.community == Community, + CommunityTrait.kind == kind, + CommunityTrait.value == trait, + ) + model.where(Community.member(Organization, _member_rank)).define( + CommunityTrait.new(community=Community, kind=kind, value=trait) + ) + model.define( + CommunityTrait.n_organizations(aggs.count(Organization).per(CommunityTrait).where(*holders)) + ) + model.define( + CommunityTrait.first_member_rank(aggs.min(_member_rank).per(CommunityTrait).where(*holders)) + ) + +model.define( + CommunityTrait.rank( + aggs.rank( + -CommunityTrait.n_organizations, CommunityTrait.first_member_rank + ).per(CommunityTrait.community, CommunityTrait.kind) + ) +) + +# The primary region is the top-ranked region. +Community.primary_region = model.Property(f"{Community} has primary region {String:primary_region}") +model.where( + CommunityTrait.community == Community, + CommunityTrait.kind == "region", + CommunityTrait.rank == 1, +).define(Community.primary_region(CommunityTrait.value)) diff --git a/wildlife-conservation-network/model/network_summary.py b/wildlife-conservation-network/model/network_summary.py new file mode 100644 index 00000000..cfd99904 --- /dev/null +++ b/wildlife-conservation-network/model/network_summary.py @@ -0,0 +1,57 @@ +"""Network summary: network-wide counts and averages over organizations, communities, and +partnerships, and the most connected organization.""" + +from relationalai.semantics import Float, Integer +from relationalai.semantics.std import aggregates as aggs + +from . import partnership_network # noqa: F401 +from .community_profiles import Community +from .schema import Organization, model + +# One NetworkSummary instance holds the network-wide figures. +NetworkSummary = model.Concept("NetworkSummary", identify_by={"id": Integer}) +NetworkSummary.n_organizations = model.Property( + f"{NetworkSummary} has {Integer:n_organizations} organizations" +) +NetworkSummary.n_communities = model.Property( + f"{NetworkSummary} has {Integer:n_communities} communities" +) +NetworkSummary.mean_community_size = model.Property( + f"{NetworkSummary} has mean community size {Float:mean_community_size}" +) +NetworkSummary.mean_partnerships = model.Property( + f"{NetworkSummary} has {Float:mean_partnerships} partnerships per organization" +) +NetworkSummary.n_partnerships = model.Property( + f"{NetworkSummary} has {Integer:n_partnerships} partnerships" +) +NetworkSummary.most_connected = model.Property( + f"{NetworkSummary} has most connected organization {Organization:most_connected}" +) + +model.define(NetworkSummary.new(id=1)) +model.define(NetworkSummary.n_organizations(aggs.count(Organization).per(NetworkSummary))) +model.define(NetworkSummary.n_communities(aggs.count(Community).per(NetworkSummary))) +model.define( + NetworkSummary.mean_community_size( + aggs.avg(Community, Community.n_organizations).per(NetworkSummary) + ) +) +model.define( + NetworkSummary.mean_partnerships( + aggs.avg(Organization, Organization.degree).per(NetworkSummary) + ) +) +# Each undirected partnership adds one to the degree of both partners, so the total is half the +# degree sum; rows listing the same pair in both directions are one partnership of the graph. +model.define( + NetworkSummary.n_partnerships( + aggs.sum(Organization, Organization.degree).per(NetworkSummary) // 2 + ) +) + +# The most connected organization has the highest degree centrality, ties broken by the lower id. +# The centrality is negated so both keys sort ascending. +model.where(aggs.rank(-Organization.degree_centrality, Organization.id) == 1).define( + NetworkSummary.most_connected(Organization) +) diff --git a/wildlife-conservation-network/model/reasoning.py b/wildlife-conservation-network/model/partnership_network.py similarity index 92% rename from wildlife-conservation-network/model/reasoning.py rename to wildlife-conservation-network/model/partnership_network.py index 5e23dd92..3026148d 100644 --- a/wildlife-conservation-network/model/reasoning.py +++ b/wildlife-conservation-network/model/partnership_network.py @@ -1,4 +1,5 @@ -"""Wildlife conservation graph: Louvain communities, degree centrality, and degree.""" +"""Partnership network: the undirected partnership graph with its Louvain communities, degree +centrality, and degree.""" from relationalai.semantics.reasoners.graph import Graph diff --git a/wildlife-conservation-network/queries/community_report.py b/wildlife-conservation-network/queries/community_report.py index 39f482ab..84c9a5b9 100644 --- a/wildlife-conservation-network/queries/community_report.py +++ b/wildlife-conservation-network/queries/community_report.py @@ -7,7 +7,16 @@ coordination, and organizations well-positioned for leadership roles. """ -from model import degree, degree_centrality, graph, louvain_communities +from model import ( + Community, + CommunityTrait, + NetworkSummary, + degree, + degree_centrality, + graph, + louvain_communities, + model, +) from relationalai.semantics import Float, Integer, where # Create variable references for use in queries. @@ -15,6 +24,11 @@ community_id = Integer.ref("community_id") centr_score = Float.ref("centr_score") partner_count = Integer.ref("partner_count") +member = graph.Node.ref("member") +member_rank = Integer.ref("member_rank") + +# The species focus lists the community's most common species, up to this many. +TOP_SPECIES = 3 if __name__ == "__main__": # Query the graph to retrieve: @@ -37,8 +51,10 @@ partner_count.alias("partnerships") ).to_df() - # Sort by community, then by centrality within each community - results = results.sort_values(["community", "degree_centrality"], ascending=[True, False]) + # Sort by community, then by centrality within each community, ties by organization id + results = results.sort_values( + ["community", "degree_centrality", "id"], ascending=[True, False, True] + ) # Display overall results print("=" * 110) @@ -62,54 +78,99 @@ print(display_df.to_string(index=False)) print("-" * 110) + # The model publishes the network totals, each community's profile, the ranked region, + # species, and organization-type values, and each community's member order. + summary = ( + model.select( + NetworkSummary.n_organizations.alias("n_organizations"), + NetworkSummary.n_communities.alias("n_communities"), + NetworkSummary.mean_community_size.alias("mean_community_size"), + NetworkSummary.mean_partnerships.alias("mean_partnerships"), + NetworkSummary.n_partnerships.alias("n_partnerships"), + NetworkSummary.most_connected.name.alias("most_connected"), + NetworkSummary.most_connected.degree.alias("most_connected_partnerships"), + ) + .to_df() + .iloc[0] + ) + communities = ( + model.select( + Community.id.alias("community"), + Community.n_organizations.alias("size"), + Community.primary_region.alias("primary_region"), + Community.hub.name.alias("hub"), + Community.hub.degree_centrality.alias("hub_centrality"), + ) + .to_df() + .sort_values("community") + ) + traits = ( + model.select( + CommunityTrait.community.id.alias("community"), + CommunityTrait.kind.alias("kind"), + CommunityTrait.value.alias("value"), + CommunityTrait.n_organizations.alias("n_organizations"), + CommunityTrait.rank.alias("rank"), + ) + .to_df() + .sort_values(["community", "rank"]) + ) + members = ( + model.where(Community.member(member, member_rank)) + .select( + Community.id.alias("community"), + member.name.alias("name"), + member_rank.alias("rank"), + ) + .to_df() + .sort_values(["community", "rank"]) + ) + # Analyze each community in detail - num_communities = results['community'].nunique() + num_communities = int(summary["n_communities"]) print(f"\n🌍 DETECTED {num_communities} CONSERVATION COMMUNITIES:") print() - for comm_id in sorted(results['community'].unique()): - community_orgs = results[results['community'] == comm_id] + for _, comm in communities.iterrows(): + comm_id = int(comm["community"]) + community_traits = traits[traits["community"] == comm_id] print(f" Community {comm_id}:") - print(f" Size: {len(community_orgs)} organizations") - - # Identify primary region - regions = community_orgs['region'].value_counts() - primary_region = regions.index[0] - print(f" Primary Region: {primary_region}") - - # Identify primary species focus - species = community_orgs['focus_species'].value_counts() - species_summary = ", ".join([f"{sp}" for sp in species.index[:3]]) + print(f" Size: {int(comm['size'])} organizations") + print(f" Primary Region: {comm['primary_region']}") + + # Most common species first + species = community_traits[ + (community_traits["kind"] == "species") & (community_traits["rank"] <= TOP_SPECIES) + ] + species_summary = ", ".join(species["value"]) print(f" Species Focus: {species_summary}") - # Identify organization types - types = community_orgs['type'].value_counts() - types_summary = ", ".join([f"{t} ({c})" for t, c in types.items()]) + # Most common organization types first, with their counts + types = community_traits[community_traits["kind"] == "type"] + types_summary = ", ".join( + f"{t} ({c})" for t, c in zip(types["value"], types["n_organizations"]) + ) print(f" Organization Types: {types_summary}") - # Identify hub organization (highest centrality) in this community + # Hub organization (highest centrality) in this community # Hub organizations are well-connected within their community and are ideal candidates for leadership, # coordination, and resource-sharing coordination roles - most_central = community_orgs.iloc[0] - print(f" Hub Organization: {most_central['name']} (centrality: {most_central['degree_centrality']:.4f})") + print(f" Hub Organization: {comm['hub']} (centrality: {comm['hub_centrality']:.4f})") - # List all members - member_names = ", ".join(community_orgs['name'].tolist()) + # List all members, most central first + member_names = ", ".join(members[members["community"] == comm_id]["name"]) print(f" Members: {member_names}") print() # Overall network statistics print("📊 NETWORK SUMMARY:") - print(f" • Total organizations: {len(results)}") + print(f" • Total organizations: {int(summary['n_organizations'])}") print(f" • Number of communities detected: {num_communities}") - print(f" • Average community size: {len(results) / num_communities:.1f} organizations") - print(f" • Average partnerships per organization: {results['partnerships'].mean():.1f}") - print(f" • Most connected organization: {results.loc[results['degree_centrality'].idxmax(), 'name']} " - f"({int(results['partnerships'].max())} partnerships)") - - # Calculate inter-community vs intra-community partnerships - total_partnerships = results['partnerships'].sum() // 2 # Divide by 2 for undirected graph - print(f" • Total partnerships in network: {total_partnerships}") + print(f" • Average community size: {summary['mean_community_size']:.1f} organizations") + print(f" • Average partnerships per organization: {summary['mean_partnerships']:.1f}") + print(f" • Most connected organization: {summary['most_connected']} " + f"({int(summary['most_connected_partnerships'])} partnerships)") + print(f" • Total partnerships in network: {int(summary['n_partnerships'])}") print("\n✅ Analysis complete!")