Skip to content

Compute report figures in the deployed models and split model modules by domain - #112

Open
chriscoey wants to merge 81 commits into
coey/templates-deploy-mode-2.1from
coey/templates-rules
Open

chriscoey wants to merge 81 commits into
coey/templates-deploy-mode-2.1from
coey/templates-rules

Conversation

@chriscoey

@chriscoey chriscoey commented Nov 25, 2026 •

Copy link
Copy Markdown
Member

Stacked on #111 (review that first). Changes 39 of the 53 templates in one or both of two ways; the other 14 are unchanged:

  • Many figures computed in pandas, mostly in reports, are now rules in the deployed model: counts, totals, shares, rankings and graph summaries. The report reads them, so other readers of the deployment see the same values. Queries still sort, cut and format what they print.
  • model/reasoning.py becomes one or more modules named for their part of the domain, for example supplier_risk.py and network_criticality.py in supply_chain_resilience. model/__init__.py exports what the queries use.

Rules that replace pandas use patterns such as these:

  • Some counts and sums over a group that can be empty default with | 0.
  • Distinct values are counted with count(distinct(...)), since count(X.prop) counts the X entities that have the property.
  • Some rankings break ties by id.

Results

Each changed template was deployed and run on Snowflake, and its output compared with #111's run of the same template:

  • Same results (24 templates): bom-reachability, campaign_roi, cell_tower_coverage, commercial_underwriting, cybersecurity-attack-paths, defect_root_cause, demand_forecasting, demand_planning_temporal, disease-outbreak-prevention, energy_grid_planning, entity_resolution, factory_production, humanitarian-aid-supply-chain, it-dependency-mapping, planogram_optimization, portfolio_balancing, smoker_status_prediction, subscriber_retention, supply_chain_resilience, telco_network_recovery, test_data_generation, underwriting_audit, warehouse_allocation, wildlife-conservation-network.
  • Another equally valid result or ordering: cicd_runner_allocation (jobs split differently between two identical runner types), fraud-detection (one queued audit swaps for another with the same amount and cost), hospital_staffing (the best-service anchor's overtime cost is $2,268 instead of $1,932; that solve minimizes unmet demand only), memory_supply_allocation (the split across customers among plans with the same margin), pod_placement, retail_planning, sprint_scheduling and supplier_reliability (another optimal assignment), product_configurator, synthetic_eligibility_records and synthetic_order_lifecycle (another valid solution or numbering), and traveling_salesman (the same tour in the other direction).
  • A different time-limit incumbent, as in Run the templates as deployed models #111: book_slate_recommendation (TIME_LIMIT 603 instead of 577) and datacenter_compute_allocation (TIME_LIMIT 634,045,372 instead of 632,672,721).
  • financial_index_replication returns the same portfolio and objective, but its solve reports TIME_LIMIT where Run the templates as deployed models #111's reported OPTIMAL: in both runs on this branch, HiGHS did not prove optimality within the 300 s limit. The Problem is declared exactly as in Run the templates as deployed models #111.

Known limits

  • datacenter_compute_allocation declares its GNN before Workload.gating_score. Declaring that property earlier failed deploy with Column(s) gating_score of Workload have no semantic type.
  • On custom data that the bundled data does not exercise, a few figures differ from Run the templates as deployed models #111:
    • A row missing a display field (a campaign name, a customer industry, an organization region, a workload name) can count toward a total and be left out of a detail table.
    • smoker_status_prediction can count an unlabeled test row as scored.
    • energy_grid_planning treats corridor loads that round to the same six decimals as tied.
    • demand_planning_temporal reads due dates as dates. An order timestamped after midnight on a horizon's last day therefore falls inside that horizon, where Run the templates as deployed models #111 excluded it.
    • fraud-detection computes each audit's hours from the amount, so on Snowflake it ignores an audit_cost column in TRANSACTIONS.
    • supply_chain_resilience can list an unrated upstream supplier with reliability N/A, where Run the templates as deployed models #111 left it out.

…t figures as rules

Replace model/reasoning.py with one module per stage:
- account_signals.py: funds-flow PageRank and each account's sent-transfer count
- fraud_classifier.py: the GNN and the class balance of its training labels
- alert_scores.py: the alert score, the alert queue order, and expected loss
- investigation_queue.py: audit costs, the audit MILP, and the audit queues

Moved into rules (9 items):
- Transaction.audit_cost is a rule on the amount instead of a column the
  loaders computed; the Snowflake TRANSACTIONS table no longer needs it.
- TrainClassBalance publishes the training split's size, fraud count, and
  fraud rate.
- AuditCandidate.alert_rank orders the alert queue (score descending,
  transaction id ascending); the report's top 20 reads it.
- AuditCandidate.expected_loss (alert score times amount) is the objective's
  coefficient and the naive queue's captured loss.
- The naive sort-and-take queue is a cumulative sum over the alert queue
  order within the hour budget. AuditQueue summarizes it and the MILP's
  selection: audit count, hours used, expected loss captured, and audits per
  transaction type. AuditUplift is the MILP objective less the naive queue's
  captured loss.

The report reads these and keeps only formatting and display order. README,
runbook, and template-docs anchors point at the new modules.
…iers and premium as rules

Replace model/reasoning.py with one module per stage, each holding the
thresholds it uses:
- eligibility_flags.py: location and coverage flags
- underwriting_factors.py: entity flags and the decline and marginal rollups
- risk_tiers.py: the tier subtypes, tier labels, and premium by tier

Moved into rules (5 items):
- Coverage.insurance_to_value is the ITV ratio of a building coverage; the
  underinsured flag and the report's ITV column read it.
- InsuredEntity.tier labels each insured with its tier in priority order, or
  UNCLASSIFIED.
- InsuredEntity.premium sums an insured's policy premiums, zero without a
  policy.
- TierPremium publishes each tier's insured count, total premium, and mean
  premium; the tier counts and premium-by-tier tables read it.

The flag matrix stays a display pivot of the published flags, and the
unclassified and overlap checks stay in the report. README and runbook point
at the new modules.
…ort figures as rules

Replace model/reasoning.py with one module per stage or concern:
- failure_timeline.py: units and failure rate per build week, spike onset
- genealogy.py: the lot genealogy graph, backward reachability, incidence
- contrast_scoring.py: baseline, per-factor counts, lift, suspects, and the
  naive ranking by raw defect count
- diagnosis.py: the set-cover MILP, its formulation counts, and the headline
- root_cause_evidence.py: each suspect's defect signature and evidence

Moved into rules (6 items):
- BuildWeek publishes each week's units, defective units, and failure rate;
  SpikeOnset is the first week above twice the opening week's rate.
- num_incidence counts the (factor, unit) incidence facts.
- Factor.raw_defect_rank ranks factors by raw defect count, ties by id.
- Factor.signature_type and Factor.signature_share give each suspect's most
  frequent defect type and its share of the factor's defective units.
- Factor.evidence states the kind-specific evidence: supplier and receipt
  date for a lot, calibration age for a machine, the shift for a shift.
- The factor loader binds each kind's back-pointer with a rule on the kind
  instead of splitting the CSV in pandas.

The formulation audit stays in the report. README points at the new modules.
The Logic engine's rank refuses mixed ascending and descending keys; negating the numeric key keeps the same order (highest first, ties by id or name).
…port figures as rules

Replace model/reasoning.py with one module per concern, each holding the
thresholds it uses:
- match_graph.py: weakly connected components over the accepted match edges,
  the party key of each record, and the graph's size
- match_bands.py: confidence tiers of the accepted matches, band sizes, and the
  blocking reduction
- resolved_parties.py: resolved parties, their records and golden record,
  total exposure, accumulation-limit breaches, excess, and premium
- review_queue.py: the breach picture if the review queue were confirmed
- reinsurance_cessions.py: the cession knapsack, its status, and the ceded
  totals

Moved into rules (10 items):
- num_auto_merges and num_review_pairs publish the sizes of the two bands.
- num_all_pairs and comparison_reduction publish the possible record pairs and
  the share of them that blocking avoids.
- num_parties publishes the number of resolved parties.
- ResolvedParty.golden_record is the party's latest record by creation date,
  the higher record id breaking a tie; the report reads its name.
- ResolvedParty.n_records and is_multi_record publish party size. A party is
  multi-record when it holds a duplicate record, so one rule defines the
  threshold.
- ResolvedParty.total_exposure sums over the party's records rather than their
  distinct coverage amounts; the multi-record table reads it.
- num_record_breaches and num_party_breaches count the policies and the
  parties over the accumulation limit, zero when none are.
- ceded_excess and ceded_premium total the plan's cessions, zero for an empty
  plan.
- review_graph clusters the records over the accepted and review pairs;
  ConfirmedParty totals each confirmed party's exposure, and
  num_confirmed_breaches and num_surfaced_breaches count the breaches.

The report reads these and keeps formatting, the display sorts, and the
evaluation against the labels. The labels stay out of the deployed model, so
the label cleaning, the true, predicted and review pair sets, and precision,
recall, and F1 stay in the report, as does the label-coverage check. Candidate
blocking, the normalization helpers, and pair scoring stay in the loader:
scoring calls Jaro-Winkler, which PyRel has no primitive for, and the bands
and candidate count are computed from those scores. The runbook prompts point
at the new modules.
…ain modules

Replace model/reasoning.py with one module per concern:
- partnership_network.py: the undirected partnership graph, Louvain
  communities, degree centrality, and degree
- community_profiles.py: each community's size, member order, hub, primary
  region, and ranked regions, species focuses, and organization types
- network_summary.py: network-wide counts and averages and the most connected
  organization

Moved into rules (11 items):
- Community.n_organizations is each community's size, and
  NetworkSummary.n_communities counts the communities.
- Community.member orders each community's organizations by degree centrality
  (ties by organization id), and Community.hub is the top-ranked member.
- CommunityTrait counts the organizations that hold each region, focus
  species, and organization type in a community and ranks them: most
  organizations first, a tie to the value held by the more central member.
  Community.primary_region is the top-ranked region; the species focus and the
  organization types with counts read the ranks.
- NetworkSummary publishes the organization count, the mean community size,
  the mean partnerships per organization, and the partnership count, which is
  the number of Partnership rows instead of half the summed degrees.
- NetworkSummary.most_connected is the organization with the highest degree
  centrality (ties by id); the report reads its partnership count from that
  organization.

The report prints the same lines and keeps only formatting: the
per-organization table and its display sort (organization id now breaks
centrality ties), the three-species cut, the joined name lists, and the number
formats. The Streamlit app is unchanged. README points at the new modules.
…eport figures as rules

Replace model/reasoning.py with one module per concern:
- production_plan.py: the product-mix LP, its solve with sensitivity
  analysis, and the published solve status and total profit
- plan_marginals.py: capacity shadow prices, product reduced costs and basis
  statuses, and the capacity ranking by shadow price
- capacity_utilization.py: each factory's hours used and idle hours

Moved into rules (2 items):
- CapacityPriceRank ranks the factory capacities by shadow price, largest
  first, ties by factory name; the report's bottleneck line reads rank 1.
- FactoryHoursUsed sums quantity over rate across a factory's products, and
  FactoryIdleHours is the available hours less that sum. Both are
  relationships rather than Factory properties because the solve reads
  Factory. The capacity summary reads them.

The objective check, plan check, and marginal sign and basis status checks
stay in the report, as do the quantity cutoff for the produced list and the
data guards in source.py. README code map and structure tree point at the
new modules.
…report figures as rules

Replace model/reasoning.py with one module per stage:
- call_signals.py: the call graph, PageRank, and the call-volume features
- churn_predictor.py: the property transformer, the churn-risk GNN, and the
  published ChurnRiskPrediction
- data_profile.py: the data and split counts and the churn-risk score range
- prediction_summary.py: rank within segment, scored subscribers per segment,
  and the prediction error

Moved into rules (7 items):
- DataCounts publishes the subscriber, call, and train, validation, and test
  subscriber counts.
- ChurnRiskRange publishes the minimum, mean, and maximum churn-risk score.
- ChurnRiskPrediction.subscriber links each prediction to its subscriber, so
  the report reads segment, type, lifetime value, and actual risk through it
  instead of joining on sub_id.
- ChurnRiskPrediction.segment_rank ranks the predictions within each segment,
  highest predicted risk first, ties by subscriber id; the report prints
  ranks 1 to 5.
- ScoredPerSegment publishes the number of scored subscribers per segment.
- TestRmse publishes the root mean squared error of the predicted risk.
- The plan attributes (plan type, monthly rate, data limit, term, auto-renew,
  early termination fee) are properties declared in schema.py and bound by a
  rule on the subscriber id, replacing the pandas merge in the loader.

The stratified train, validation, and test split stays in pandas: PyRel has
no seeded shuffle primitive, and a different cut would change the trained
model. The report keeps the top-N cut, the formatting, and the display
order. README code map and structure tree point at the new modules.
…the bottleneck as a rule

Replace model/reasoning.py with one module per stage:
- sourcing_plan.py: the baseline sourcing LP with sensitivity analysis and
  its published status, total cost, and order quantities
- plan_marginals.py: lane reduced costs and basis statuses, capacity and
  demand shadow prices, and the capacity ranking
- disruption_scenarios.py: the supplier-exclusion problems and their
  published status, total cost, and order quantities

Moved into rules (1 item):
- CapacityPriceRank ranks the supplier capacities by the magnitude of their
  shadow price, largest first, ties by supplier name; the report's bottleneck
  line reads rank 1 and prints the signed price.

The lane, shadow price, and complementary slackness checks stay in the
report, as do the quantity cutoff for lanes in use and the scenario summary.
README code map, structure tree, and runbook point at the new modules.
… compute report figures as rules

Replace model/reasoning.py with one module per stage or concern:
- utilization_forecast.py: the utilization GNN, each workload's forecast
  probability and its rank, and the split at the high-utilization cutoff
- workload_eligibility.py: priority tiers and weights, hardware
  compatibility, and the workload count per tier
- gating_scores.py: the dependency PageRank and the gating ranking
- compute_allocation.py: the allocation MIP and its solve status, time,
  and objective
- allocation_outcomes.py: per-cell results, the headline plan and its
  chosen assignments, and the demand overlay

Moved into rules (8 items):
- UtilizationSplit publishes the workloads with a forecast, how many are at
  or above the cutoff, and how many are below.
- WorkloadForecast.high_rank and low_rank order the forecasts from either
  end (ties by workload id); the report's top 5 and bottom 5 read them.
- PriorityTierCount publishes the workload count per priority tier.
- GatingRank.gating_rank orders workloads by gating score (ties by workload
  id); the report's top 10 reads it. It lives on its own concept so the GNN
  does not take it as a Workload feature.
- ScenarioCell.n_by_type and n_by_tier carry a zero for every workload type
  and priority tier, so the report no longer fills missing kinds.
- CellStatusCount publishes the cells per status label.
- ScenarioCell.in_margin_sweep and in_diversity_sweep mark the two sweeps
  through the headline envelope, replacing the report's hard-coded filters.
- DemandScenarioOutlook.stranded_share is the stranded revenue over the
  plan's revenue, zero for a plan without revenue.

The report's scenario-cell count reads count(ScenarioCell) instead of the
product of the three axis counts. The entity counts, the compatibility pair
count, and the plan cross-check stay as report-side aggregates, and display
sorts, the pivot of per-kind counts, top-N sizes, the ordering of status
labels, and the percent scaling stay in the report. README points at the
new modules.
… rank facilities as rules

Replace model/reasoning.py with model/facility_network.py, which holds the
connection risk weight, the facility graph, the centrality and connection
counts, and two new rules:
- Facility.priority_rank orders the facilities by weighted degree centrality,
  highest first, ties by facility id. The report and the app read it instead
  of sorting and numbering rows in pandas, and the report's top three and
  highest-ranked facility follow the rank order.
- NetworkSummary publishes the facility count, the mean degree centrality,
  and the mean connections per facility; the report's network summary reads
  it.

The top-3 cut, the table layout, and the rounding stay in the report, and the
app's own figures stay in the app. README points at the new module.
…arget profile and horizon as rules

Replace model/reasoning.py with one module per stage or concern:
- sales_forecast.py: the transaction graph, the sales-regression GNN, and
  the profile of its training target
- article_demand.py: each article's demand summed from the predictions, and
  the planning articles that lack it
- planning_horizon.py: the number of planning weeks
- markdown_plan.py: the markdown MILP, its status and revenue, and the
  selected discounts
- demand_planning.py: the demand/inventory LP, its status and cost, and the
  plan

Moved into rules (2 items):
- TrainTargetProfile publishes the train split's label count, minimum,
  maximum, mean, and sample standard deviation; the report prints them and
  the baseline RMSE (the standard deviation) from it.
- The planning LP's week and inventory indices range over num_weeks, the
  count of Week rows, instead of a Python constant counted from the weeks
  CSV at load time. source.py no longer defines NUM_WEEKS.

The report keeps its formatting. README points at the new modules.
…eport figures as rules

Replace model/reasoning.py with one module per stage or concern:
- compliance_flags.py: holding value and share of balance, the
  overconcentrated holdings, sector exposure, and the high-risk traders
- correlation_clusters.py: volatility and correlation, the correlation graph,
  Louvain clusters, cluster representatives, and the clustering summaries
- regime_covariance.py: the base and crisis covariance
- efficient_frontier.py: the anchor, grid, adaptive, and dichotomic solves,
  the frontier points they publish, and allocation weights
- crisis_volatility.py: each frontier point's volatility and its base-versus-
  crisis gap

Moved into rules (13 items):
- Holding.share_of_balance is a holding's value over its account balance.
- SectorExposure publishes each account's exposure to each sector, its share
  of the account balance, and whether it is concentrated; the sector flag on
  holdings reads it, and the report lists the concentrated pairs directly.
- num_edges counts the correlation graph's edges, Cluster.size counts the
  stocks of each cluster, and num_clusters, num_stocks, and
  num_representatives give the totals the report prints.
- intra_cluster_correlation and inter_cluster_correlation are the average
  correlation of the stock pairs inside one cluster and across clusters.
- The reference scenario's budget is a rule on the scenario data; each return
  rate divides by it.
- FrontierPoint.volatility, vol_base, vol_crisis, vol_gap, and vol_gap_ratio
  publish a point's volatility and the volatility of the same solve at the
  same budget under the base and crisis regimes, paired by scenario budget and
  regime instead of the scenario name.
- FrontierPoint.weight is each allocated stock's amount over the scenario
  budget.
- The report drops a second clamp on the shadow price; the published value is
  already at least 0.

Stayed in Python: the frontier point dedupe, which compares each point with the
last one kept, and the positions, chord gaps, secants, knee, and Pareto check
built on its order; the scenario list order; the merge and zero-fill of the
marginal that the report checks read; the formatting and display sorts. README,
runbook, and template-docs anchors point at the new modules.
…ute report figures as rules

Replace model/reasoning.py with one module per stage:
- customer_dependencies.py: yield, floor, dependency edge, and SPOF rules
- capability_forecast.py: the GNN or the bundled snapshot, the forecast
- rolling_horizon.py: effective capacity, the three LPs, and the rules that
  publish their results
- dependency_chains.py: the 1-3 hop customer chains
- disruption_what_ifs.py: baseline capacity, the supplier-offline and
  input-shortage what-ifs

Moved into rules (12 items):
- NumForecastRows counts the forecast rows.
- EffectiveCapacityCells counts each iteration's effective-capacity cells.
- PlanDiff gives each customer's allocation change against the prior
  iteration's plan over the cells both plans cover, once the prior solve is
  OPTIMAL.
- CustomerService gives each customer's allocation, demand over the horizon,
  and service level per iteration.
- DependencyChain reads each chain as "A -> B -> C" in step order;
  NumDependencyChains counts the chains and MultiHopChain marks those with
  more than one hop.
- SupplierOfflineImpact.affected_products lists the products behind a
  supplier's affected cells in product id order.
- SupplierOfflineImpact.has_widest_impact and Input.has_widest_shortage_impact
  mark the supplier and the input with the most affected cells, the lowest id
  among ties; neither exists when no cell is affected.
- ShortageAverageDrop gives the mean drop per input and exposed product over
  the cells above the shortage threshold.
- IterationMargin publishes each iteration's margin with its horizon start;
  FirstSolvedIteration and LastSolvedIteration pick the first and last
  iteration with a margin for the headline.

Stayed in Python:
- The per-supplier forecast mean, minimum, and maximum: on the bundled
  snapshot one supplier's mean lies exactly on a 3-decimal rounding boundary,
  so an engine's summation order could change the printed digit.
- The shortage names and their percent formatting: Python rounds 24.5% and
  10.5% to even, an engine's round would not.
- Observation ids and the temporal split in source.py: the ids order the GNN's
  nodes, and train.py prints the split sizes from the same frames.
- The disruption schedule in source.py: the input capacity multiplier is a
  product over inputs, and the product aggregate computes exp(sum(log)), which
  would shift the multiplier in the last bits and with it the printed
  objective; the supplier overrides and input availability share that loop.
- Display sorts, unit scaling, rounding of printed values, and status gating.

README and train.py point at the new modules.
…each build as a rule

Replace model/reasoning.py with model/build_enumeration.py, which holds the
decision problem, the solve, and the published solve results.

Moved into rules (1 item):
- BuildTotal publishes each feasible build's total price in cents, the sum of
  its selected options' prices; the report reads it instead of summing the
  option prices in pandas.

The dollar scaling, the ascending sort by total price, and the pivot to one
column per slot stay in the report as display. The catalog check for the
target region stays in source.py, where it raises while the model loads.
README, runbook, and the source.py comment point at the new module.
…e report figures as rules

Replace model/reasoning.py with one module per stage:
- equipment_failure.py: the at-risk label, the GNN, TowerFailureScore, and
  the figures that profile the training data and the scores
- advisory_signals.py: the most severe advisory per MODEL and the equipment
  the advised models cover
- critical_towers.py: tower averages, the three restore branches, and the
  counts per branch and region
- customer_impact.py: subscriber PageRank, customer value and its rank, and
  per-tower impact
- call_paths.py: call-path enumeration from the seed hub
- tower_upgrades.py: the upgrade MIP, the plan summary, and the selection
  rationale

Moved into rules (19 items):
- NetworkEquipment.at_risk is derived from the loaded status (FAILING or
  WARNING); status is dropped from the GNN features with the label. The train
  and validation tables hold equipment ids and are labeled by at_risk.
- Advisory holds every advisory as issued; ModelAdvisory keeps the most
  severe one per MODEL, ties by advisory type.
- EquipmentSplitSize, AtRiskBalance and AdvisoryCount publish the split
  sizes, the label balance and the advisory counts.
- AdvisedModelEquipment (zero-filled) and AdvisedEquipmentCount publish the
  equipment on each advised MODEL and on any advised MODEL.
- TowerFailureScore.failure_rank orders towers by failure intensity (ties by
  tower id); FailureIntensitySpread publishes the scored-tower count and the
  minimum, median and maximum. The towers above the threshold read the
  predictive branch count.
- GnnRecallCounts and PositiveProbabilitySpread publish the at-risk items the
  GNN catches at the predicted label and at the probability cutoff, and the
  spread of the positive probabilities.
- CellTower.fires_only_predictive_branch and RestoreBranchCounts publish the
  critical-tower count and the towers per branch; CriticalRegionCount
  publishes the critical towers per region.
- Subscriber.customer_rank orders subscribers by customer value (ties by id).
- TowerUpgradeOption.rationale states each upgrade's signals in a fixed
  order, "(low signal)" when none; RationaleTally counts selected upgrades
  per signal; SelectedRegionCount counts them per region. The selected count
  reads RestorePlan.towers_covered.

Stayed in Python:
- The seeded train/validation/test shuffle: PyRel 2.3.0 has no seeded random
  shuffle.
- Percent shares of published counts (equipment on an advised MODEL, recall,
  towers flagged only by the predictive branch), the top-N cutoffs, display
  sorts, and the empty-predictions and no-at-risk-items gates.
- The critical-tower and selected-upgrade tables the report prints.

The report reads these and keeps formatting and display order. README and
runbook point at the new modules.
… bound the decisions with rules

Replace model/reasoning.py with member_records.py: the decision problem, its
three constraints, the solve configuration, and the published status,
solution count and member records. schema.py and source.py keep their roles.

Moved into rules (1 item):
- Each decision variable's lower and upper bound is the smallest and largest
  reference id read in the model (aggs.min and aggs.max over AgeBucket.id,
  Plan.id and Provider.id) instead of integers taken from the pandas frames
  in source.py. member_records.py no longer imports those frames.

Stayed in Python:
- The dense-id check and the orphan-network warnings in source.py are
  validation of the input files at load, not model logic.
- The report only reads the published records, sorts them for display and
  prints them.

README points at the new module.
…compute report figures as rules

Replace model/reasoning.py with one module per concern:
- portfolio_selection.py: the replication policy, its feasibility checks, the
  decision problem, the solve, and the universe size
- index_correlation.py: each stock's correlation with the index and its rank
- tracking_quality.py: monthly replica and baseline returns, their differences
  from the index, and the tracking errors
- portfolio_exposure.py: sector exposure and implied turnover

Moved into rules (11 items):
- num_stocks counts the universe.
- TrackingMonth.replica_return is the month's weighted sum of stock returns
  and replica_difference its gap to the index return; TrackingMonth is a
  concept of its own because the solve reads ReturnMonth.
- AnnualizedTrackingError and MeanAbsResidual summarize the replica's monthly
  differences.
- SectorExposure publishes each sector's solved weight, benchmark weight, and
  active weight.
- ImpliedTurnover sums the change from the previous weights.
- Stock.abs_index_correlation is the absolute Pearson correlation of a stock's
  returns with the index; Stock.correlation_rank orders the stocks by it.
- TrackingMonth.baseline_return is the month's mean return of the
  BASELINE_NAMES most correlated stocks, baseline_difference its gap to the
  index, and BaselineTrackingError the annualized error of those gaps.

The report reads these and keeps the formatting and display order. The
feasibility checks stay in portfolio_selection.py, and the held-stock return
check stays in the report, which still reads the return history for it. The
replica_returns.csv export reads TrackingMonth.replica_return. The runbook and
template-docs anchors point at the new modules.
…he split and rollup as rules

Replace model/reasoning.py with one module per concern:
- temporal_split.py: the validation and test cutoffs 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 city and item family, and the RMSEs
- sales_summary.py: record counts and the range of unit sales

Moved into rules (10 items):
- TestStart and ValStart derive the cutoffs from the latest sale date
  (LatestSale); Train, Val, and Test select the sales on each side of them
  directly, so the TrainTable, ValTable, and TestTable concepts and the
  pandas split are gone.
- SalesCounts publishes the store, item, and sale counts and the size of each
  split; UnitSales publishes the minimum, maximum, and mean of unit sales.
- SaleForecast holds each predicted sale's actual sales, forecast clipped at
  zero, error, week start, and its store city and item family when present;
  it is a concept of its own because the GNN reads Sale.
- WeeklyForecast rolls the forecasts up per (city, family, week start) with
  the weekly actual, forecast, and absolute error.
- SaleRmse and WeeklyRmse are the test-set RMSE per sale and per weekly
  rollup.

The report reads these and keeps the formatting and the display sort. The
warning for predictions without a city or family stays in the report; it
compares the prediction count with the labeled rows. The README and runbook
point at the new modules.
…lish unread candidates and slates as rules

Replace model/reasoning.py with one module per stage, each holding the
thresholds it uses:
- candidate_paths.py: the bounded knowledge-graph walks, the candidates they
  reach, their explanation path counts, and the read and unread flags
- book_embeddedness.py: the triangle count of each book over the similarity
  graph
- slate_selection.py: the slate size and constraint dials, the slot rows, the
  slot constraint program, its status and objective, and each user's slate

Moved into rules (4 items):
- Candidate.is_read and Candidate.is_unread flag the candidates a user has
  read and has not read. The already-read exclusion and the report's
  feasibility check read the same definition.
- The slot rows 1..K are a rule over the slate size instead of a column the
  loader built.
- Slate.picks lists each user's picked candidates (slots 1..K); the report's
  slate and explanation tables read it.
- Slate.picks_by_subject counts a user's picks per subject; the subject
  distribution table reads it.

Stayed in Python: the nine per-user feasibility checks and the gate that
stops the report, which only read the published unread flag now, and the
joins that attach book attributes, authors, and subjects to the unread
candidates for those checks.

README points at the new modules.
…te report figures as rules

Replace model/reasoning.py with one module per stage, each holding the
thresholds it uses:
- blast_radius.py: the Business graph, the high-priority customers, and their
  upstream suppliers
- network_criticality.py: the site graph, its components, centrality, and the
  most critical site
- supplier_risk.py: the reliability and delay-risk flags, the risk classes,
  late shipments, and escalated demand
- risk_adjusted_flows.py: the network flow problems, the scenarios, and the
  scenario cost change

Moved into rules (12 items):
- Each flow problem publishes its active flow count, unmet order count, and
  unmet units; flows and shortfalls at or below FLOW_TOLERANCE are solver noise.
- CostChangePct publishes each scenario's cost change against the baseline in
  percent.
- num_source_links counts the operation-to-business source links.
- Business.upstream_supplier lists the SUPPLIER businesses each high-priority
  customer depends on; Business.n_upstream_suppliers counts them.
- SiteCluster publishes each connected component's site count and sorted
  regions; num_components counts the components.
- Site.centrality_rank orders the scored sites by centrality.
- Shipment.is_late, num_shipments, and num_late_shipments publish the late
  shipment totals; Business.late_shipment_count and Business.late_rank order
  the suppliers by late shipments.
- Business.risk_class labels each rated business avoid, watch, or reliable.
- num_escalated counts the escalated demand orders.
- Shipment delays are loaded only for shipments that recorded one, so a
  shipment in transit has no delay and is not late; the loader no longer fills
  a zero.

The report keeps formatting, the display order, the cut of the top sites and
top late suppliers, and the status gates that decide when a solve is reported.
README and runbook point at the new modules.
…report figures as rules

Replace model/reasoning.py with one module per stage:
- load_forecast.py: predicted load, growth, first capacity breach
- grid_topology.py: components, Louvain communities, centrality, structural criticality
- corridor_fragility.py: corridor enumeration, most fragile routes, contingency
- interconnection_compliance.py: the three compliance checks and the composite flag
- investment_solve.py: the approval and upgrade solve, its status and objective
- investment_frontier.py: per-level portfolios, budget gains, marginal value, knee point

Moved into rules (12 inventory items):
- GridTopology publishes the substation, component, and community counts and
  CONNECTED or FRAGMENTED; GridRegion lists each community's members by id.
- SimpleCorridor marks the corridors that do not revisit a substation, and
  CorridorSummary counts them.
- Substation.fragility_rank orders the data center substations by fragility
  load; Substation.fragile_route is each one's most fragile route, with ties
  going to the smaller substation ids. Loads compare to three decimals.
- Substation.is_offline marks the highest-betweenness substation (ties to the
  smaller id), and Substation.contingency_route is each data center
  substation's most fragile route without it. CorridorSummary counts the
  substations served before and after, rerouted, and left with no corridor.
- ComplianceSummary counts requests, compliant requests, and flagged requests.
- InvestmentRange publishes the number of levels and the smallest and largest
  budget.
- DataCenterRequest.annual_revenue (megawatts times revenue per megawatt) is
  read by the objective, each portfolio's revenue, and the report.
- InvestmentPortfolio.value_gain, budget_gain, mw_gain, and dc_gain are the
  changes to the next level; marginal_per_m_to_next_level divides the first two.

The knee point's rank negates the marginal drop so both keys sort ascending.

Stayed in the report: the at-risk table and its display order (breach_period is
already published), the PASS/FAIL and Y/N columns (a pivot of published
flags), the approved-request and selected-upgrade lists, formatting, and the
solve-status gate. README and runbook point at the new modules.
…d compute report figures as rules

Replace model/reasoning.py with one module per concern:
- supply_network.py: route flow weight, the graph, PageRank, degree centrality, route counts
- point_rankings.py: influence rank and the most connected points
- strategic_categories.py: the percentile categories, their point counts, and the rank within each
- network_summary.py: network totals and per-region totals

Moved into rules (9 inventory items):
- DistributionPoint.influence_rank orders points by PageRank, then degree
  centrality, then id; the report's rank column and the first-ranked point read it.
- PointCategory.n_points counts the points in each category, and
  DistributionPoint.category_rank ranks a point within its category; the
  category sections list their top 5, 3, and 3 points from it.
- DistributionPoint.is_most_connected (most routes) and is_most_central
  (highest degree centrality) mark one point each; ties go to the more
  influential point.
- NetworkSummary publishes the point count, route count, mean routes per
  point, total population served, and total capacity.
- RegionSummary publishes each region's point count, capacity, population
  served, and average PageRank and degree centrality.

The report keeps formatting, display order, and the number of points each
category lists. The Streamlit app is unchanged. README points at the new
modules.
…te verdicts as rules

Replace model/reasoning.py with one module per stage:
- applicant_rules.py: the free applicant decisions, the derived indicators,
  and the rule pack.
- property_audits.py: the property catalog, one counterexample search per
  property, and each search's status, witness count, and witnesses.
- audit_verdicts.py: each property's verdict, the witness-limit flag, and the
  verdict tallies.

Moved into rules (3 items):
- PropertyVerdict gives each property PASS, FAIL, or INCONCLUSIVE from the
  solve status and witness count; a property with no published count is
  INCONCLUSIVE.
- HitWitnessLimit names the failing properties whose search stopped at the
  witness limit.
- VerdictTally publishes the number of properties with each verdict, zero
  when none has it, and NumProperties the number of properties.

The report reads these and keeps only formatting. The solver bounds on the age
bucket and coverage band stay computed from the reference CSVs, and the
dense-id check stays at load. README and runbook point at the new modules.
… report figures as rules

Replace model/reasoning.py with one module per stage:
- dependency_graph.py: the directed SKU graph, reachability, betweenness, and
  the dependency counts and bottleneck rank the report reads.
- assembly_chains.py: assembly chain enumeration, maximal chains, chain
  lengths and counts, and assembly depth.

Moved into rules (3 items):
- SKU.n_dependencies and SKU.n_dependencies_by_type count the other SKUs each
  SKU transitively depends on, in total and of each type.
- SKU.bottleneck_rank ranks the SKUs with a positive betweenness, highest
  first, ties by SKU id; the report's top bottleneck is rank 1.
- ChainLength gives each assembly chain's hops, and num_chains and
  num_maximal_chains count the enumerated and the maximal chains.

The dependency lists, the maximal-chain lookup, and the display sorts stay in
the report. README points at the new modules.
…ompute shelf and category usage as rules

Replace model/reasoning.py with two modules:
- facing_allocation.py: the facing, realized-demand, and active decisions, the
  lookup, capacity, and cardinality constraints, the objective, and the solve.
- allocation_usage.py: the totals the report prints for the chosen facings.

Moved into rules (2 items):
- ShelfUsage.used_cm is the length each shelf uses: facings times SKU width,
  summed over the SKUs on the shelf.
- CategoryUsage.active_skus is the number of active SKUs in each category.
Both live on concepts of their own, because a value computed from the solution
on Shelf or Category, which the solve reads, would leave the solution empty
after the first refresh.

The post-solve demand-lookup check and the load-time data checks stay in
Python (checks stay where they are). README and runbook point at the new
modules.
…read caps and node usage as rules

Replace model/reasoning.py with one module per stage:
- zone_spread.py: the zone count and each deployment's cap on replicas per
  zone.
- pod_assignment.py: the pod-to-node decisions, the constraints, the
  objective, and the solve.
- node_usage.py: the CPU, memory, and GPU each node carries under the chosen
  placement.

Moved into rules (3 items):
- Deployment.max_per_zone is the override when a deployment has one, otherwise
  ceil(replicas / zones) in integer arithmetic; num_zones counts the zones.
  The loader no longer computes the cap in pandas: the overrides load as a
  table of their own, because model.data drops rows holding a NaN.
- Zones, racks, and each rack's zone come straight from the node rows instead
  of three de-duplicated frames.
- NodeUsage.cpu_used, memory_used, and gpu_used sum the demand of the pods
  placed on each node. They live on a concept of their own, because a value
  computed from the solution on Node, which the solve reads, would leave the
  solution empty after the first refresh.

The empty-cluster load check stays in Python. README and runbook point at the
new modules.
…e issue scope and target sprints as rules

Replace model/reasoning.py with sprint_assignment.py (the assignment domain,
constraints, objective, and one solve per capacity scenario) and add
target_sprints.py.

Moved into rules (2 items):
- Issue.target_sprint_number is the lowest sprint number that ends after the
  issue was created, or the last sprint when the issue was created after every
  sprint ended. It no longer depends on the row order of sprints.csv, which is
  sorted and contiguous.
- The planning-horizon filter on created_at is a rule over the issue rows as
  they load, instead of a pandas filter before model.data.

Stayed in Python: the horizon dates parsed to epoch seconds and the count of
input issues, which is the row count of issues.csv (the model loads only the
in-scope rows). README and runbook point at the new modules.
…d compute fill totals and venue exclusions as rules

Replace model/reasoning.py with:
- lifecycle_trace.py: the event decisions, the sequencing and conservation
  constraints, the enum-typed event type, and the solve.
- order_fills.py: the quantity filled across each order's events.

Moved into rules (2 items):
- OrderFill.filled_qty publishes each order's filled quantity, which the
  report printed from a query of its own. It lives on a concept of its own,
  because a value computed from the solution on Order, which the solve reads,
  would leave the solution empty after the first refresh.
- NotAllowedSymbolVenue is a rule over the symbols and venues that are not in
  the loaded AllowedSymbolVenue pairs, instead of a Python cross product and
  an empty-frame guard.

Stayed in Python: the solver bounds on quantity, price, and venue id, read
from the CSV maxima (no run shows an aggregate accepted as a solve_for bound).
README points at the new modules.
…pute component summaries as rules

Replace model/reasoning.py with one module per stage:
- network_analysis.py: the distribution network graph, eigenvector
  centrality, the weakly connected components, and the cross-region bridge
  routes.
- inventory_allocation.py: the inventory allocation problem, which reads the
  centrality from the module above.

Moved into rules (3 items):
- NetworkComponent publishes each component's site count (n_sites) and its
  regions in alphabetical order (regions), instead of a count and a sorted
  join in the report.
- num_components counts the components.
- NetworkState is UNIFIED for one component and FRAGMENTED otherwise.

The report reads these and keeps only the printing. The allocation-plan cutoff
on the solved inventory stays in the report's select. README and runbook point
at the new modules.
order_fills.py held one concept and one rule. OrderFill and its filled
quantity rule live at the end of lifecycle_trace.py, which declares the
fill decisions they sum; the report query is unchanged. README and the
package docstring list the merged module.
target_sprints.py held one rule, read only by the assignment domain. The
target-sprint rule opens sprint_assignment.py. The loader comment says
that every CSV row is embedded as data and only in-horizon rows become
Issue entities. README and the package docstring list the merged module.
The witness-limit note and the number of audited properties are read from
the report's own results, as before the rules conversion: a FAIL with
status SOLUTION_LIMIT prints the note, and the summary counts the result
rows. HitWitnessLimit and NumProperties are removed; PropertyVerdict and
VerdictTally stay.
- Contingency: a corridor through the offline substation is dropped as a
  whole, as in the base. The offline test reads the node at its own
  index, as the simple-corridor test does, instead of the node the load
  sums range over; with that form the offline substation itself stayed
  served. The bundled grid should print 6 -> 5 served, 5 reroute and
  1 lost, as the base did.
- Most fragile route and DC order: loads compare to 6 decimals instead
  of 3. The tolerance still absorbs float noise from summation order,
  which ties exactly equal loads on the bundled grid, and loads that
  differ by more than 1e-6 rank by value as in the base.
- Marginal analysis: the value, budget, MW and request gains are the
  differences between consecutive printed levels, computed in the
  report, and a missing marginal value prints as 0. Equal budget caps
  no longer leave a step without gains. The four gain properties are
  removed and the marginal value rule reads the next level directly.
- Docs: the paths stage needs relationalai>=1.27 for the ordered
  string_join, and the contingency drops corridors rather than
  enumerating them again.
- CustomerService publishes each customer's allocation and demand,
  both summed over the cells the iteration allocates, and the report
  divides them. A customer whose allocated cells have zero demand keeps
  its row with a NaN service level, and a sparse solution sums demand
  over the same cells as the allocation.
- The headline's multi-hop chains filter the chains the report already
  fetched, so chains with the same route are not merged.
  MultiHopChain is removed.
- The headline's horizon margin line reads the first and last solved
  iterations from the solve results the report already holds.
  IterationMargin, FirstSolvedIteration and LastSolvedIteration are
  removed.
The report rounds each solved row count with Python's round(), which
breaks exact .5 ties to the even number, and takes each table's
deviation from the rounded count. The model's round can break those
ties the other way, so TablePlan is removed. The source comment on the
foreign-key bounds describes what the loader does.
The ranks, category counts and leaders, network summary and regional
statistics are computed in the report over the points it prints, so a
point that lacks a printed attribute is left out of every figure, and
ranks have no gaps. A PageRank and degree tie goes to the smaller id.
point_rankings.py, strategic_categories.py and network_summary.py are
removed; the category rules are in supply_network.py with the graph
metrics they read.
Keep the report's results on inputs the bundled data does not exercise:

- The selected-upgrade count comes from the detail rows, so a plan that
  leaves a tier unused still reports its upgrades.
- The most severe advisory per MODEL is picked in pandas from the loaded
  rows: the advisory rows carry no id, so two notices with the same MODEL
  and type would merge into one entity in a rule, and equal severities
  keep the row pandas keeps. Drops the Advisory concept.
- Equipment without an at-risk status, including equipment with no
  status, gets the label 0 and stays in its training split.
- The advisory counts are 0 when there are no advisories.
- Towers above the failure-intensity threshold are counted over the
  tower scores (IntenseTowerCount), the population of the denominator.
- The predictive-only share prints nan% when no tower is critical.
- Region breakdowns skip towers without a region.
- The top subscribers are chosen from the complete rows, then cut to
  ten, ties listing the lower id first. Drops Subscriber.customer_rank.
- The selection rationale is joined in the report from the branch
  flags; the model keeps the rationale tally. Drops
  TowerUpgradeOption.rationale and its eight generated rules.

Also stops re-exporting customer_impact from the package (the stage
modules import it), and fixes stale comments and the README and runbook
module descriptions. No module is merged.
Keep the report's results on inputs the bundled data does not exercise:

- ScenarioCell.n_by_type and n_by_tier count every workload type and
  priority tier in a cell, and the report zero-fills the displayed
  columns, so a type outside the four floor types keeps its count and
  an empty scenario axis prints "No scenario cells returned."
- The top and bottom forecasts and the top gating workloads are chosen
  from the complete rows, then cut, ties listing the lower workload id
  first, so a workload without a name takes no slot. Drops
  WorkloadForecast.high_rank and low_rank and the GatingRank concept.
- The per-cell status comment says the label follows the cell's
  assignment count: INFEASIBLE marks an empty optimum, not a proof.

No module is merged.
Both loaders exclude an audit_cost source column, so the rule on the
amount is the only audit cost (a column of that name no longer gives a
transfer a second value). A transaction without an amount costs the
small audit, as the loader's np.where did. The top-20 alert table takes
its cutoff with head() after the display sort; the alert rank stays for
the naive budgeted queue.
ResolvedParty.n_records is the one count of a party's records: a party
with more than one is multi-record, and each of its records is a
duplicate (the same records as counting per entity key). The single-call
functions in match_graph.py, resolved_parties.py and
reinsurance_cessions.py are inlined; the documentation anchors follow.
A building coverage is underinsured when its limit is below 80% of the
location's replacement value, compared on the amounts as before. The
ratio rounds 1,024.80 / 1,281.00 to 0.7999999999999999, which flagged a
coverage exactly at 80% and could move an insured to Non-Standard.
Coverage.insurance_to_value stays for the report's ITV percentage.
The report's unread candidates are those without Candidate.is_read, and
Candidate.is_unread is removed. The embeddedness module states its link
to the hero pin once and numbers the stages as the README does.
The raw-count table sorts all factors by defects and id and takes the
top six with head(), so a factor missing a column no longer takes a
slot; Factor.raw_defect_rank is removed. The report reads each root
cause's signature on its own and builds the kind-specific evidence
through the factor's lot, machine or shift, as before; Factor.evidence
is removed. The signature share divides by the defective units that
have a defect type, the denominator the report used.
Each tower's assigned population and utilization are relationships on
TowerSite, replacing the TowerLoad concept. A relationship has no
uniqueness constraint, so it gets a store of its own instead of a column
in TowerSite's, which the solve reads. The report counts sites, zones
and coverage pairs with count() again; the three count relationships
are removed.
The metrics count (prediction, test row) pairs, the grain of the join
the report used: a person with two test rows is two observations, and
contradictory labels no longer give one prediction two held-out labels.
The report's sample joins TestTable for the label again, and
SmokerPrediction.actual_smoking is removed. The ROC-AUC reads the
positive count from ClassShare instead of a second sum.
The report reads each corridor summary and the winning routes, so nothing
reads the per-hop corridor steps.
The docs site requires each inline link label to appear verbatim in its
step explanation; the rewrap split "queries the model" across lines.
@github-actions

github-actions Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

The templates docs preview for this pull request has been deployed to Vercel!

✅ Preview: https://relationalai-docs-bhtt41v33-relationalai.vercel.app/build/templates
🔍 Inspect: https://vercel.com/relationalai/relationalai-docs/H1hBjK8pJbTsZYyQJzexR8zuoqP2

@chriscoey
chriscoey marked this pull request as ready for review November 25, 2026 23:54
@chriscoey
chriscoey requested a balanced review from Copilot November 25, 2026 23:54

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved defects miscount missed breaches and use undeclared columns during fresh imports, while unhandled zero-pair and edge-free inputs can break reports.

4 open issues
What changed in this PR

Building on #111’s deployed-model layout, this PR moves report calculations into shared model rules and splits reasoning modules by domain across 39 templates.

Changes:

  • Publish counts, totals, rankings, graph summaries, and solution metrics from deployed models.
  • Update reports and package exports to consume the new domain modules.
  • Align README, runbook, and walkthrough references with the reorganized code.
File Description
wildlife-conservation-network/​model/​partnership_network.py Clarifies the graph module’s docstring.
wildlife-conservation-network/​model/​network_summary.py Publishes network totals and averages.
wildlife-conservation-network/​model/​__init__.py Exports community and network summaries.
warehouse_allocation/​runbook.md Updates allocation module references.
warehouse_allocation/​README.md Documents the two-stage module split.
warehouse_allocation/​queries/​allocation_report.py Reads published component summaries.
warehouse_allocation/​model/​inventory_allocation.py Separates allocation from graph analysis.
warehouse_allocation/​model/​__init__.py Exports network analysis results.
underwriting_audit/​runbook.md Updates audit module references.
underwriting_audit/​model/​audit_verdicts.py Derives audit verdicts and tallies.
underwriting_audit/​model/​__init__.py Exports published verdicts.
traveling_salesman/​runbook.md Updates tour module references.
traveling_salesman/​README.md Documents the shortest-tour module.
traveling_salesman/​model/​shortest_tour.py Clarifies the module’s docstring.
traveling_salesman/​model/​__init__.py Imports the renamed tour module.
test_data_generation/​queries/​test_data_plan.py Sorts table results before generation.
test_data_generation/​model/​source.py Loads foreign-key bounds into concepts.
test_data_generation/​model/​schema.py Declares foreign-key metadata.
test_data_generation/​model/​row_count_plan.py Builds constraints from foreign-key facts.
test_data_generation/​model/​__init__.py Imports the row-count module.
telco_network_recovery/​runbook.md Clarifies advisory counts and module layout.
telco_network_recovery/​model/​schema.py Adds equipment status and clarifies labels.
telco_network_recovery/​model/​advisory_signals.py Publishes advisory coverage counts.
synthetic_order_lifecycle/​README.md Documents lifecycle and fill-total rules.
synthetic_order_lifecycle/​queries/​order_trace.py Reads published fill totals.
synthetic_order_lifecycle/​model/​source.py Derives disallowed symbol–venue pairs relationally.
synthetic_order_lifecycle/​model/​schema.py Declares allowed symbol–venue relationships.
synthetic_order_lifecycle/​model/​lifecycle_trace.py Publishes each order’s filled quantity.
synthetic_order_lifecycle/​model/​__init__.py Exports order fill results.
synthetic_eligibility_records/​README.md Updates member-record module references.
synthetic_eligibility_records/​model/​member_records.py Derives decision bounds from model facts.
synthetic_eligibility_records/​model/​__init__.py Imports the member-record module.
supply_chain_resilience/​runbook.md Updates flow-problem references.
supply_chain_resilience/​model/​source.py Preserves missing shipment delays.
supply_chain_resilience/​model/​__init__.py Exports domain modules and summaries.
supplier_reliability/​runbook.md Updates disruption module references.
supplier_reliability/​queries/​sourcing_report.py Reads published capacity rankings.
supplier_reliability/​model/​schema.py Updates module references in comments.
supplier_reliability/​model/​plan_marginals.py Publishes sensitivity results and rankings.
supplier_reliability/​model/​__init__.py Exports sourcing stages and rankings.
subscriber_retention/​model/​source.py Maps contract attributes relationally.
subscriber_retention/​model/​schema.py Explicitly declares plan attributes.
subscriber_retention/​model/​prediction_summary.py Publishes segment rankings and prediction error.
subscriber_retention/​model/​data_profile.py Publishes data counts and score ranges.
subscriber_retention/​model/​churn_predictor.py Separates prediction from call signals.
subscriber_retention/​model/​call_signals.py Houses call-graph features.
subscriber_retention/​model/​__init__.py Exports prediction and data summaries.
sprint_scheduling/​runbook.md Updates assignment module references.
sprint_scheduling/​model/​sprint_assignment.py Derives target sprints relationally.
sprint_scheduling/​model/​source.py Filters issues through model rules.
sprint_scheduling/​model/​__init__.py Documents and imports scheduling stages.
smoker_status_prediction/​model/​__init__.py Exports classification metrics.
retail_planning/​model/​source.py Removes the local week-count constant.
retail_planning/​model/​sales_forecast.py Houses the sales graph and predictor.
retail_planning/​model/​planning_horizon.py Publishes the planning-week count.
retail_planning/​model/​article_demand.py Houses demand aggregation and planning gaps.
retail_planning/​model/​__init__.py Imports separate forecasting and planning stages.
product_configurator/​runbook.md Updates enumeration module references.
product_configurator/​README.md Documents published build prices.
product_configurator/​queries/​feasible_builds.py Reads model-computed build totals.
product_configurator/​model/​source.py Updates a constraint-module comment.
product_configurator/​model/​build_enumeration.py Publishes each build’s total price.
product_configurator/​model/​__init__.py Exports build totals.
portfolio_balancing/​model/​regime_covariance.py Separates regime covariance rules.
portfolio_balancing/​model/​__init__.py Exports domain stages and cluster metrics.
pod_placement/​runbook.md Updates placement module references.
pod_placement/​queries/​placement_report.py Reads published node resource usage.
pod_placement/​model/​zone_spread.py Derives zone counts and replica caps.
pod_placement/​model/​schema.py Declares explicit spread overrides.
pod_placement/​model/​pod_assignment.py Imports spread-cap rules.
pod_placement/​model/​node_usage.py Publishes node resource totals.
pod_placement/​model/​__init__.py Exports node usage results.
planogram_optimization/​runbook.md Updates facing-allocation references.
planogram_optimization/​README.md Documents allocation and usage modules.
planogram_optimization/​queries/​facings_plan.py Reads shelf and category usage.
planogram_optimization/​model/​facing_allocation.py Clarifies the allocation docstring.
planogram_optimization/​model/​allocation_usage.py Publishes shelf and category totals.
planogram_optimization/​model/​__init__.py Exports allocation usage concepts.
memory_supply_allocation/​train.py Updates the forecast configuration error message.
memory_supply_allocation/​model/​source.py Explains why exact multiplication remains local.
memory_supply_allocation/​model/​dependency_chains.py Publishes chain labels and counts.
memory_supply_allocation/​model/​customer_dependencies.py Houses dependency-derived customer signals.
memory_supply_allocation/​model/​__init__.py Exports stage modules and summaries.
it-dependency-mapping/​model/​maximal_chains.py Identifies maximal and longest chains.
it-dependency-mapping/​model/​downstream_paths.py Publishes path summaries and leaf defaults.
it-dependency-mapping/​model/​__init__.py Exports path and chain summaries.
humanitarian-aid-supply-chain/​README.md Updates supply-network module references.
humanitarian-aid-supply-chain/​queries/​distribution_point_ranking.py Adds deterministic ranking tie-breaking.
humanitarian-aid-supply-chain/​model/​supply_network.py Clarifies the network docstring.
humanitarian-aid-supply-chain/​model/​__init__.py Imports the supply-network module.
hospital_staffing/​model/​shift_staffing.py Clarifies the staffing docstring.
hospital_staffing/​model/​schema.py Updates a staffing-module comment.
hospital_staffing/​model/​__init__.py Exports frontier analysis results.
fraud-detection/​README.md Updates configuration paths and source requirements.
fraud-detection/​model/​alert_scores.py Publishes alert rankings and expected loss.
fraud-detection/​model/​account_signals.py Houses account graph and activity features.
financial_index_replication/​runbook.md Documents selection and reporting modules.
financial_index_replication/​model/​tracking_quality.py Publishes replica returns and tracking metrics.
financial_index_replication/​model/​portfolio_selection.py Publishes the stock-universe count.
financial_index_replication/​model/​portfolio_exposure.py Publishes sector exposures and turnover.
financial_index_replication/​model/​__init__.py Exports portfolio reporting metrics.
factory_production/​README.md Documents production and sensitivity modules.
factory_production/​model/​production_plan.py Separates optimization from marginal reporting.
factory_production/​model/​plan_marginals.py Publishes marginals and capacity rankings.
factory_production/​model/​capacity_utilization.py Publishes used and idle factory hours.
factory_production/​model/​__init__.py Exports sensitivity and utilization results.
entity_resolution/​template-docs.yaml Updates walkthrough paths and anchors.
entity_resolution/​model/​source.py Explains local similarity scoring.
entity_resolution/​model/​review_queue.py Models review-confirmed parties and breaches.
entity_resolution/​model/​reinsurance_cessions.py Publishes cession totals beside the solve.
entity_resolution/​model/​match_graph.py Houses accepted-match clustering and graph counts.
entity_resolution/​model/​match_bands.py Publishes confidence bands and comparison reduction.
entity_resolution/​model/​__init__.py Exports resolution stages and summaries.
energy_grid_planning/​runbook.md Clarifies path requirements and corridor outputs.
energy_grid_planning/​model/​load_forecast.py Publishes load growth and breach periods.
energy_grid_planning/​model/​__init__.py Exports grid stages and summaries.
disease-outbreak-prevention/​model/​facility_network.py Publishes facility rankings and network statistics.
disease-outbreak-prevention/​model/​__init__.py Exports the network summary.
demand_planning_temporal/​runbook.md Updates production-plan references.
demand_planning_temporal/​queries/​demand_planning.py Reads published order counts.
demand_planning_temporal/​model/​weekly_demand.py Derives weekly demand with empty-week defaults.
demand_planning_temporal/​model/​schema.py Declares order keys and initial inventory.
demand_planning_temporal/​model/​production_plans.py Imports derived planning inputs.
demand_planning_temporal/​model/​horizon_scope.py Derives order weeks, horizons, and counts.
demand_planning_temporal/​model/​capacity_inputs.py Derives inventory and holding-cost inputs.
demand_planning_temporal/​model/​__init__.py Exports horizon counts and planning stages.
demand_forecasting/​runbook.md Updates split, forecast, and accuracy references.
demand_forecasting/​model/​temporal_split.py Derives temporal training and evaluation splits.
demand_forecasting/​model/​source.py Limits source loading to base facts.
demand_forecasting/​model/​schema.py Removes separate split-table concepts.
demand_forecasting/​model/​sales_summary.py Publishes sales counts and ranges.
demand_forecasting/​model/​demand_forecast.py Imports source and temporal split declarations.
demand_forecasting/​model/​__init__.py Exports forecasts, summaries, and split cutoffs.
defect_root_cause/​model/​source.py Maps factor kinds through model rules.
defect_root_cause/​model/​root_cause_evidence.py Publishes defect signatures and shares.
defect_root_cause/​model/​genealogy.py Houses genealogy reachability and incidence counts.
defect_root_cause/​model/​failure_timeline.py Publishes weekly failure rates and spike onset.
defect_root_cause/​model/​__init__.py Exports diagnosis stages and evidence summaries.
datacenter_compute_allocation/​model/​gating_scores.py Separates dependency-based gating scores.
cybersecurity-attack-paths/​model/​source.py Maps attack techniques through model predicates.
cybersecurity-attack-paths/​model/​entry_to_target_routes.py Publishes simple route steps and counts.
cybersecurity-attack-paths/​model/​__init__.py Exports route and kill-chain summaries.
commercial_underwriting/​runbook.md Describes published tier labels and totals.
commercial_underwriting/​model/​eligibility_flags.py Houses eligibility flags and coverage ratios.
commercial_underwriting/​model/​__init__.py Exports underwriting stages and tier premiums.
cicd_runner_allocation/​model/​__init__.py Imports the renamed allocation module.
cell_tower_coverage/​runbook.md Updates site-selection references.
cell_tower_coverage/​README.md Documents published coverage summaries.
cell_tower_coverage/​model/​site_selection.py Separates selection from coverage reporting.
cell_tower_coverage/​model/​__init__.py Exports coverage rates and assignments.
campaign_roi/​runbook.md Updates budget-plan references.
campaign_roi/​queries/​budget_reallocation.py Reads campaign and regional model totals.
campaign_roi/​model/​reasoning.py Removes the superseded reasoning module.
campaign_roi/​model/​__init__.py Exports budget-plan summaries.
book_slate_recommendation/​model/​source.py Removes local slot generation.
book_slate_recommendation/​model/​schema.py Updates a candidate-path module comment.
book_slate_recommendation/​model/​book_embeddedness.py Houses book-similarity triangle counts.
book_slate_recommendation/​model/​__init__.py Exports recommendation stages and slates.
bom-reachability/​README.md Documents graph and assembly modules.
bom-reachability/​model/​assembly_chains.py Separates assembly rules and publishes chain lengths.
bom-reachability/​model/​__init__.py Exports graph results and chain lengths.

Review effort: Balanced

Comment on lines +53 to +56
_confirmed, _resolved = Integer.ref(), Integer.ref()
model.where(num_confirmed_breaches(_confirmed), num_party_breaches(_resolved)).define(
num_surfaced_breaches(_confirmed - _resolved)
)
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
Comment on lines +51 to +52
model.where(CandidatePairCount(_candidates), num_all_pairs(_possible)).define(
comparison_reduction(1 - floats.float(_candidates) / floats.float(_possible))

# 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)

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants