Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
81 commits
Select commit Hold shift + click to select a range
e5f03d7
fraud-detection: split reasoning into stage modules and compute repor…
chriscoey Nov 25, 2026
414e13d
commercial_underwriting: split rules into stage modules and compute t…
chriscoey Nov 25, 2026
d7924e1
defect_root_cause: split reasoning into stage modules and compute rep…
chriscoey Nov 25, 2026
8ac76be
Rank the exemplar's ordered lists with single-direction keys
chriscoey Nov 25, 2026
c2acec1
entity_resolution: split reasoning into domain modules and compute re…
chriscoey Nov 25, 2026
5026419
wildlife-conservation-network: compute report figures as rules in dom…
chriscoey Nov 25, 2026
8c4ca44
factory_production: split reasoning into domain modules and compute r…
chriscoey Nov 25, 2026
0d8fbda
subscriber_retention: split reasoning into stage modules and compute …
chriscoey Nov 25, 2026
bbfcea5
supplier_reliability: split reasoning into stage modules and compute …
chriscoey Nov 25, 2026
58b2dd5
datacenter_compute_allocation: split reasoning into stage modules and…
chriscoey Nov 25, 2026
3f8c1e3
disease-outbreak-prevention: name the model module for its domain and…
chriscoey Nov 25, 2026
aa3c1e0
retail_planning: split reasoning into stage modules and compute the t…
chriscoey Nov 25, 2026
d37ff07
portfolio_balancing: split reasoning into stage modules and compute r…
chriscoey Nov 25, 2026
375f5bd
memory_supply_allocation: split reasoning into stage modules and comp…
chriscoey Nov 25, 2026
034d819
product_configurator: name the model module for its domain and price …
chriscoey Nov 25, 2026
c998d62
telco_network_recovery: split reasoning into stage modules and comput…
chriscoey Nov 25, 2026
f04464d
synthetic_eligibility_records: rename reasoning to member_records and…
chriscoey Nov 25, 2026
137a803
financial_index_replication: split reasoning into domain modules and …
chriscoey Nov 25, 2026
f206822
demand_forecasting: split reasoning into domain modules and compute t…
chriscoey Nov 25, 2026
5a4d320
book_slate_recommendation: split reasoning into stage modules and pub…
chriscoey Nov 25, 2026
4c6059a
supply_chain_resilience: split reasoning into stage modules and compu…
chriscoey Nov 25, 2026
d26ddc2
energy_grid_planning: split reasoning into stage modules and compute …
chriscoey Nov 25, 2026
1575f21
humanitarian-aid-supply-chain: split reasoning into domain modules an…
chriscoey Nov 25, 2026
eb68531
underwriting_audit: name the model modules for their domain and compu…
chriscoey Nov 25, 2026
34c42c9
bom-reachability: name the model modules for their domain and compute…
chriscoey Nov 25, 2026
a7f71d8
planogram_optimization: name the model modules for their domain and c…
chriscoey Nov 25, 2026
17e50c1
pod_placement: name the model modules for their domain and compute sp…
chriscoey Nov 25, 2026
f9f6d29
sprint_scheduling: name the model modules for their domain and comput…
chriscoey Nov 25, 2026
8df1f5f
synthetic_order_lifecycle: name the model modules for their domain an…
chriscoey Nov 25, 2026
5f405e0
warehouse_allocation: name the model modules for their domain and com…
chriscoey Nov 25, 2026
5ef0f4f
traveling_salesman: name the model module for its domain
chriscoey Nov 25, 2026
1abac00
cell_tower_coverage: split reasoning into domain modules and compute …
chriscoey Nov 25, 2026
e7c349d
it-dependency-mapping: split reasoning into domain modules and comput…
chriscoey Nov 25, 2026
8c58466
smoker_status_prediction: split reasoning into domain modules and com…
chriscoey Nov 25, 2026
6b7002a
demand_planning_temporal: split reasoning into domain modules and com…
chriscoey Nov 25, 2026
4ec8786
cicd_runner_allocation: name the model module for its domain and comp…
chriscoey Nov 25, 2026
eacffb7
campaign_roi: name the model module for its domain and compute plan c…
chriscoey Nov 25, 2026
792eaca
cybersecurity-attack-paths: split reasoning into path modules and com…
chriscoey Nov 25, 2026
a0aaaec
hospital_staffing: split reasoning into solve and frontier modules an…
chriscoey Nov 25, 2026
7219f3e
test_data_generation: name the model module for its domain and comput…
chriscoey Nov 25, 2026
4cd380f
Say that a solution-derived property on a solved concept fails the de…
chriscoey Nov 25, 2026
6380eb2
it-dependency-mapping: count distinct owners on each path
chriscoey Nov 25, 2026
5d2b6b5
energy_grid_planning: import the model sum in the investment frontier
chriscoey Nov 25, 2026
e1fe2f7
datacenter_compute_allocation: declare the GNN before the gating score
chriscoey Nov 25, 2026
9418efd
telco_network_recovery: break seed and path ties by the smallest id a…
chriscoey Nov 25, 2026
b646119
campaign_roi: divide by current figures in the report
chriscoey Nov 25, 2026
7532f33
it-dependency-mapping: keep chains that share a label apart
chriscoey Nov 25, 2026
3fbd6cd
portfolio_balancing: pair base and crisis volatility in the report
chriscoey Nov 25, 2026
cbdef9b
supply_chain_resilience: count suppliers per printed customer group
chriscoey Nov 25, 2026
f2acd21
retail_planning: profile the training target in the report
chriscoey Nov 25, 2026
60a5602
cybersecurity-attack-paths: count routes and chains from their steps
chriscoey Nov 25, 2026
ff0982a
demand_planning_temporal: load due dates as yyyy-mm-dd strings
chriscoey Nov 25, 2026
e883a4d
demand_forecasting: start each forecast week at midnight
chriscoey Nov 25, 2026
d8fb582
financial_index_replication: compute the baseline in pandas again
chriscoey Nov 25, 2026
36a8374
wildlife-conservation-network: count partnerships from the degree sum
chriscoey Nov 25, 2026
cb0f57d
cicd_runner_allocation: list each runner's jobs in the report
chriscoey Nov 25, 2026
26e1a14
hospital_staffing: join the knee roster in the report
chriscoey Nov 25, 2026
539354c
bom-reachability: count printed chains from the listed paths
chriscoey Nov 25, 2026
fcb5c30
synthetic_order_lifecycle: merge order_fills into lifecycle_trace
chriscoey Nov 25, 2026
8448c29
sprint_scheduling: merge target_sprints into sprint_assignment
chriscoey Nov 25, 2026
8fbc020
underwriting_audit: read the witness limit and property count in Python
chriscoey Nov 25, 2026
f65ab33
energy_grid_planning: match the base contingency and frontier steps
chriscoey Nov 25, 2026
cf2eefd
memory_supply_allocation: keep zero-demand customers in service levels
chriscoey Nov 25, 2026
9de2f6d
test_data_generation: round the solved row counts in the report
chriscoey Nov 25, 2026
0c11d77
humanitarian-aid-supply-chain: rank and total the printed points
chriscoey Nov 25, 2026
2ed3b7e
telco_network_recovery: keep report results on sparse custom data
chriscoey Nov 25, 2026
2eb2c9e
datacenter_compute_allocation: keep report results on sparse custom data
chriscoey Nov 25, 2026
3391805
fraud-detection: ignore a loaded audit_cost and cost a missing amount
chriscoey Nov 25, 2026
daad129
entity_resolution: count party records once and inline stage functions
chriscoey Nov 25, 2026
b174e21
commercial_underwriting: flag underinsurance on the limit, not the ratio
chriscoey Nov 25, 2026
aaa8fae
book_slate_recommendation: read unread candidates as not is_read
chriscoey Nov 25, 2026
1f0fbed
defect_root_cause: format root-cause evidence and raw top-N in Python
chriscoey Nov 25, 2026
d6af592
cell_tower_coverage: keep tower loads on TowerSite as relationships
chriscoey Nov 25, 2026
2584649
smoker_status_prediction: score each prediction-test row pair
chriscoey Nov 25, 2026
ac12a04
telco_network_recovery: say ties between equal path loads go to the s…
chriscoey Nov 25, 2026
fbfa788
energy_grid_planning: drop the unused corridor step relationship
chriscoey Nov 25, 2026
3425ad6
book_slate_recommendation: name only the is_read flag in the README
chriscoey Nov 25, 2026
235f98e
Merge #111's head: fraud-detection refresh call text
chriscoey Nov 25, 2026
ebf7205
Merge #111's head: portfolio_balancing walkthrough order
chriscoey Nov 25, 2026
4ee8c80
financial_index_replication: keep a walkthrough link label on one line
chriscoey Nov 25, 2026
dbbd322
Merge remote-tracking branch 'origin/coey/templates-deploy-mode-2.1' …
chriscoey Nov 25, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions bom-reachability/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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/
Expand Down Expand Up @@ -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

Expand Down
14 changes: 8 additions & 6 deletions bom-reachability/model/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,29 +18,31 @@
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

__all__ = [
"DATA_DIR",
"MAX_ASSEMBLY_HOPS",
"AssemblyStep",
"ChainLength",
"MaximalChain",
"SKU",
"BillOfMaterials",
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -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))
65 changes: 65 additions & 0 deletions bom-reachability/model/dependency_graph.py
Original file line number Diff line number Diff line change
@@ -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)))
48 changes: 38 additions & 10 deletions bom-reachability/queries/dependency_report.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 ===")
Expand All @@ -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']})")

Expand Down Expand Up @@ -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.")

Expand All @@ -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()
Expand All @@ -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).")

Expand Down
Loading
Loading