Phase 2: Production Mathematical Formulations, Algorithms & Data Schemas for Commercial Freight Fleet Intelligence
Strong Tower Consulting, LLC
Technical designation: STC-FREIGHT-AI-P2-2026
Publication date: October 23, 2026
Authorial perspective: Principal Transportation Systems Architect & Applied AI Mathematician
Firm: Minnesota transportation systems architecture practice, founded in 2008 by Scott Elliott; more than 18 years of operating experience.
Engineering contract and conventions
The three modules specify reproducible calculation rules, typed events, mathematical optimization models, decision controls, engineering pseudocode, and JSON Schema Draft 2020-12 interfaces for commercial freight operations. Time is UTC in machine records and facility-local time in terminal schedules. Financial quantities use integer cents or decimal currency arithmetic; physical measurements retain explicit SI units. All fleet identifiers are scoped by tenant and authority. Each automated recommendation carries an input snapshot ID, rule/model version, data-quality classification, calculation trace, and decision provenance.
Engineering assurance requires staged historical replay, shadow operation, monitored production activation, and independently reproducible decision traces. All example values in this document are illustrative engineering parameters, not estimates of any particular fleet's operational outcomes. Regulatory conditions are resolved from the authoritative governing rules, shipment classification, and applicable loading situation.
Module 1 — Physical Diesel Fuel Consumption & J1939 CAN-Bus Anomaly Engine
1.1 Physical basis of highway tractor energy demand
Let gross combined weight (GCW) as a mass be \(m\) [kg], frontal area \(A\) [m²], aerodynamic drag coefficient \(C_d\), rolling-resistance coefficient \(C_{rr}\), vehicle road speed \(v\) [m/s], local air-relative speed \(v_a\) [m/s], grade angle \(\theta\) [rad], acceleration \(a=dv/dt\) [m/s²], air density \(\rho\) [kg/m³], and gravitational acceleration \(g\) [m/s²]. The direction of road travel defines positive propulsive force. The longitudinal resistance terms are:
\[
F_{\mathrm{roll}}=mgC_{rr}\cos\theta,\qquad
F_{\mathrm{grade}}=mg\sin\theta,
\]
\[
F_{\mathrm{aero}}=\tfrac12\rho C_d A v_a |v_a|,\qquad
F_{\mathrm{inertia}}=m_{\mathrm{eff}}a.
\]
Effective mass \(m_{\mathrm{eff}}\) incorporates rotating inertia under calibration. For headwind speed \(w\), \(v_a=v+w\); for a tailwind, \(w<0\). Include auxiliary loads, powertrain losses and terminal-duty power:
\[
P_{\mathrm{wheel}}=v\left(F_{\mathrm{roll}}+F_{\mathrm{grade}}+F_{\mathrm{aero}}+F_{\mathrm{inertia}}\right),
\]
\[
P_{\mathrm{engine,req}} = \frac{\max(0,P_{\mathrm{wheel}})}{\eta_{\mathrm{driveline}}}+P_{\mathrm{aux}}+P_{\mathrm{PTO}}.
\]
The positive-power clamp models demanded positive tractive power, while downhill engine braking, regenerative equipment (where installed), and engine idle must be handled in the operational regime rather than interpreted as negative diesel consumption. Let diesel lower heating value \(h_d\) [J/kg], diesel density \(\rho_d\) [kg/L], brake thermal efficiency \(\eta_b\in(0,1)\), and calibrated idle fuel rate \(q_{\mathrm{idle}}\) [L/h]. A nominal instantaneous fuel-consumption model is:
\[
\boxed{q_{\mathrm{phys}}(t)=\max\!\left(q_{\mathrm{idle}}(r_t),\frac{3600 P_{\mathrm{engine,req}}(t)}{\eta_b(n_t,\tau_t,T_t) h_d\rho_d}\right)}\quad [\mathrm{L/h}].
\]
Here \(r_t\) is a regime label (idle, loaded acceleration, cruise, grade climb, deceleration, PTO), \(n_t\) is engine speed, \(\tau_t\) torque and \(T_t\) thermal state. Treat \(\eta_b\) as an engine-map-dependent function rather than a universal constant. If no calibrated engine map is available, estimate \(\eta_b\) in an identified parameter model from validated fuel-rate and load observations, using physically plausible bounds. A useful parameterized residual model is:
\[
q_{183,t}=q_{\mathrm{phys},t}+b_{\mathrm{engine}}(r_t)+\epsilon_t,
\]
where \(q_{183,t}\) is SPN 183 decoded fuel rate, \(b_{\mathrm{engine}}\) is a learned engine/regime offset and \(\epsilon_t\) is heteroscedastic sensor error. For fleet-level trip planning:
\[
V_{\mathrm{pred}}=\int_0^T q_{\mathrm{phys}}(t)\,dt/3600,
\quad
\mathrm{MPG}_{\mathrm{pred}}=\frac{D_{\mathrm{miles}}}{V_{\mathrm{pred}}/3.785411784}.
\]
Numerical illustration. For a 32,000 kg tractor-trailer combination at 25 m/s, \(C_{rr}=0.006\), \(C_d=0.6\), \(A=10\) m², \(\rho=1.2\) kg/m³, 1% uphill grade (\(\theta=\arctan 0.01\)), and zero acceleration or wind: rolling force is approximately 1,883 N, aero drag 2,250 N and grade force 3,139 N. Road power is approximately 182 kW. With driveline efficiency 0.90, 4 kW auxiliaries, diesel heating value 42.7 MJ/kg, density 0.832 kg/L, and thermal efficiency 0.40, predicted rate is approximately 52.2 L/h (13.8 U.S. gal/h). Exact numerical outputs depend on calibrated inputs and engine operating point.
1.2 CAN transport and SPN normalization
A J1939 gateway receives 29-bit CAN identifiers, extracts PGNs, reconstructs transport-protocol messages when applicable, and maps source-address-specific signals to a tractor's authenticated electronic-control-unit (ECU) identity. Typical standard mappings for the requested signals are:
| SPN | Meaning | Typical PGN | Decoding / normalized units |
| 183 | Engine Fuel Rate | 65266 (0xFEF2) | unsigned 16-bit little-endian, 0.05 L/h per bit |
| 84 | Wheel-Based Vehicle Speed | 65265 (0xFEF1) | unsigned 16-bit little-endian, 1/256 km/h per bit |
| 96 | Fuel Level 1 | 65276 (0xFEFC) | unsigned 8-bit, 0.4% per bit |
| 92 | Engine Percent Load at Current Speed | 61443 (0xF003) | unsigned 8-bit, 1% per bit |
The ECU-specific profile defines field positions, explicit unavailable/error codes, tank geometry, fuel pickup/return architecture, sensor update cadence, and source-address assignment. Validate actual payload mappings against the vehicle's J1939/71 implementation; raw bytes marked unavailable or error are classified missing, never decoded into physical outliers. Signal 92 is not a direct fuel-consumption measurement. Signal 96 generally expresses level as a percentage, which requires a vehicle-specific tank calibration to convert to gallons. Auxiliary evidence should include ignition status, engine RPM, PTO flag, GPS, and IMU pitch/roll/acceleration, with provenance for every source.
The event stream must support out-of-order delivery and gaps. Ingestion writes append-only events using (tenant_id, vin, gateway_id, source_address, pgn, spn, event_time, sequence) for deduplication. Latest-value caches are convenience structures; authoritative anomaly replay reads the immutable stream.
1.3 Tank calibration and fuel mass balance
For a tank of capacity \(C_{\mathrm{gal}}\) and fractional level \(\ell_t\), simple volume is \(V_t=C_{\mathrm{gal}}\ell_t\). A production calibration uses a monotone fuel-volume map \(V_t=f_{\mathrm{tank}}(\ell_t,\phi_t,\psi_t,T_t)\), where \(\phi,\psi\) are pitch and roll. Dual tanks must be tracked separately if sensors are available, because unequalizing tank transfers can mimic withdrawal.
For a time interval \([t_0,t_1]\), conservation is:
\[
V_{t_1}=V_{t_0}+V_{\mathrm{refuel}}-V_{\mathrm{engine}}-V_{\mathrm{PTO}}-V_{\mathrm{other\ authorized}}-V_{\mathrm{unexpected}}+\epsilon_V,
\]
where engine consumption is \(V_{\mathrm{engine}}=\int_{t_0}^{t_1}q_{183}(t)dt/(3600\times3.785411784)\) if fuel rate is in liters/hour, with an appropriate retained telemetry integration rule. Define unexpected physical loss:
\[
R_{01}=V_{t_0}^{\mathrm{corrected}}-V_{t_1}^{\mathrm{corrected}}-V_{\mathrm{engine}}-V_{\mathrm{authorized\ draw}}+V_{\mathrm{known\ refuel}}.
\]
A candidate rapid-loss condition requires both an absolute residual and a rate:
\[
R_{01}>5\ \mathrm{US\ gallons},\qquad 0<t_1-t_0<180\ \mathrm{s},
\]
and stationary/off-or-idle operation, with valid sensor coverage and stable attitude. For confidence-aware classification, also require \(R_{01}-k\sigma_R>5\) gallons (e.g. \(k=2\)) if the purpose is a high-confidence confirmed fleet-security escalation. A less stringent investigation candidate condition can preserve sensitivity at the cost of additional review. The alert is a fuel-loss anomaly, not a final legal finding of theft.
1.4 Rejecting slosh, turns, and grade artifacts
Tank level readings are a convolution of static fuel geometry, free-surface dynamics and sensor response. Use the IMU to measure absolute pitch \(|\phi|\), roll \(|\psi|\), lateral acceleration \(|a_y|\), longitudinal acceleration \(|a_x|\), and yaw rate \(|\dot\psi|\). A bounded fleet-calibrated correction is:
\[
\widehat V_{\mathrm{level}} = f_{\mathrm{tank}}(\ell) - b_\phi\phi-b_\psi\psi-b_xa_x-b_ya_y.
\]
For a more general empirical surface, use monotone splines with tank-level-specific attitude effects. Derive coefficients using controlled parked measurements at known volumes and grade, then validate with recorded road trips.
Apply a Hampel filter to remove isolated sensor impulses:
\[
\mathrm{MAD}_t=1.4826\operatorname{median}_{i\in W_t}|V_i-\operatorname{median}(V_{W_t})|,
\]
and reject outliers if \(|V_t-\operatorname{median}(V_{W_t})|>k\mathrm{MAD}_t\). Preserve step changes by maintaining independent pre- and post-change plateaus, rather than smoothing over the entire drop. Define an attitude-stability gate:
\[
G_t=\mathbf1\{v_t<v_{\max},\ |a_y|<a_{y,\max},\ |\phi|<\phi_{\max},\ |\psi|<\psi_{\max},\ |\dot\psi|<\omega_{\max}\}.
\]
A valid pair of plateaus must have enough samples, be stable under these thresholds, exhibit sustained separation and show no subsequent rebound indicative of slosh. Compare a time interval's J1939 implied consumed volume with tank-implied decrease and corroborate GPS immobilization, key status and fueling records.
1.5 Implementable Python reference algorithm
The following is a dependency-light, deterministic anomaly detector for already normalized gateway events. It supports rolling 180-second windows, ignition/idle gating, fuel-rate integration, tank-specific affine attitude compensation, robust plateau medians, missing-data rejection, an uncertainty guard, and anti-duplicate alerting. Configure and certify tank correction and uncertainty parameters against actual equipment; external ingest normalizes and authenticates SPNs before invoking this detector.
from __future__ import annotations
from collections import defaultdict, deque
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from statistics import median
from math import isfinite
from typing import Deque, Dict, Optional
L_PER_US_GAL = 3.785411784
@dataclass(frozen=True)
class Telemetry:
vin: str
ts: datetime # UTC, timezone aware
spn183_lph: Optional[float] # rate, liters/hour
spn84_kph: Optional[float] # vehicle speed
spn96_pct: Optional[float] # level 0..100
spn92_pct: Optional[float] # load percent, ancillary
ignition_on: Optional[bool]
pitch_deg: Optional[float]
roll_deg: Optional[float]
lateral_mps2: Optional[float]
longitude: Optional[float] = None
latitude: Optional[float] = None
@dataclass(frozen=True)
class FuelConfig:
capacity_gal: float
pitch_gal_per_deg: float = 0.0
roll_gal_per_deg: float = 0.0
level_sigma_gal: float = 0.25
threshold_gal: float = 5.0
window_s: float = 180.0
max_stationary_kph: float = 2.0
max_idle_lph: float = 8.0
max_pitch_deg: float = 3.0
max_roll_deg: float = 3.0
max_lateral_mps2: float = 0.35
max_gap_s: float = 15.0
min_plateau_samples: int = 3
uncertainty_multiplier: float = 2.0
cooldown_s: float = 300.0
class FuelLossDetector:
def __init__(self, configs: Dict[str, FuelConfig]):
self.configs = configs
self.samples: Dict[str, Deque[Telemetry]] = defaultdict(deque)
self.last_alert: Dict[str, datetime] = {}
def _valid(self, e: Telemetry, c: FuelConfig) -> bool:
if e.ts.tzinfo is None:
return False
numeric = [e.spn96_pct, e.spn84_kph]
if any(v is None or not isfinite(v) for v in numeric):
return False
if not 0 <= e.spn96_pct <= 100:
return False
if e.spn84_kph > c.max_stationary_kph:
return False
if e.pitch_deg is None or e.roll_deg is None:
return False
if e.lateral_mps2 is None:
return False
if abs(e.pitch_deg) > c.max_pitch_deg:
return False
if abs(e.roll_deg) > c.max_roll_deg:
return False
if abs(e.lateral_mps2) > c.max_lateral_mps2:
return False
# Engine genuinely stopped, or authenticated low-rate idle.
if e.ignition_on is False:
return True
return (e.ignition_on is True
and e.spn183_lph is not None
and 0 <= e.spn183_lph <= c.max_idle_lph)
@staticmethod
def _volume(e: Telemetry, c: FuelConfig) -> float:
return (c.capacity_gal * e.spn96_pct / 100
- c.pitch_gal_per_deg * e.pitch_deg
- c.roll_gal_per_deg * e.roll_deg)
@staticmethod
def _consumed_gal(seq: list[Telemetry]) -> float:
result = 0.0
for a, b in zip(seq, seq[1:]):
dt_h = (b.ts - a.ts).total_seconds() / 3600.0
if dt_h <= 0:
continue
# Key-off measurement can carry stale ECU fuel-rate values.
ra = 0.0 if a.ignition_on is False else (a.spn183_lph or 0.0)
rb = 0.0 if b.ignition_on is False else (b.spn183_lph or 0.0)
result += 0.5 * (ra + rb) * dt_h / L_PER_US_GAL
return result
def ingest(self, e: Telemetry) -> Optional[dict]:
c = self.configs[e.vin]
q = self.samples[e.vin]
# Events must arrive in event-time order; an upstream reorder buffer
# handles late arrival and triggers replay for historical corrections.
if q and e.ts <= q[-1].ts:
return None
q.append(e)
while q and (e.ts - q[0].ts).total_seconds() >= c.window_s:
q.popleft()
if len(q) < c.min_plateau_samples * 2 + 2:
return None
seq = list(q)
if not all(self._valid(x, c) for x in seq):
return None
if any((b.ts - a.ts).total_seconds() > c.max_gap_s
for a, b in zip(seq, seq[1:])):
return None
if (seq[-1].ts - seq[0].ts).total_seconds() >= c.window_s:
return None
n = c.min_plateau_samples
early = [self._volume(x, c) for x in seq[:n]]
late = [self._volume(x, c) for x in seq[-n:]]
pre, post = median(early), median(late)
# Require stable local plateaus, not a single transient excursion.
tolerance = max(0.5, 3 * c.level_sigma_gal)
if max(abs(x - pre) for x in early) > tolerance:
return None
if max(abs(x - post) for x in late) > tolerance:
return None
residual = pre - post - self._consumed_gal(seq)
# Difference of two plateau estimates; conservative measurement bound.
sigma = (2 ** 0.5) * c.level_sigma_gal
lower = residual - c.uncertainty_multiplier * sigma
if residual <= c.threshold_gal or lower <= c.threshold_gal:
return None
last = self.last_alert.get(e.vin)
if last and (e.ts - last).total_seconds() < c.cooldown_s:
return None
self.last_alert[e.vin] = e.ts
return {
"event_type": "FUEL_LOSS_CANDIDATE",
"vin": e.vin,
"start_time": seq[0].ts.isoformat(),
"end_time": seq[-1].ts.isoformat(),
"duration_seconds": (seq[-1].ts-seq[0].ts).total_seconds(),
"observed_residual_gal": round(residual, 3),
"conservative_lower_gal": round(lower, 3),
"threshold_gal": c.threshold_gal,
"sample_count": len(seq),
"review_status": "INVESTIGATE"
}
Production integration notes. The reference engine is a conservative candidate-alert path. A deployed adapter should (i) convert raw PGN payloads into per-SPN values with source arbitration; (ii) resample asynchronous SPNs without using stale values beyond declared TTLs; (iii) use a tank-specific monotonic calibration curve in place of affine volume estimation where installed; (iv) explicitly model fuel equalization across multiple tanks; (v) add a persistence/rebound check after the first alert; (vi) implement stateful event-time windows with watermark/replay and alert retractions; (vii) reconcile legitimate tank draining, repairs and refueling tickets. A raw SPN 96 resolution step on a large tank can represent materially more than a fraction of a gallon, making uncertainty calibration indispensable.
1.6 Validation matrix and operational routing
| Scenario | Expected engine result |
| Parked, key off, sustained >5 gal unexplained reduction inside 180 s, stable readings | High-confidence fuel-loss candidate |
| Engine idling, J1939-measured 0.2 gal consumed, tank loss 5.8 gal | Candidate residual about 5.6 gal before uncertainty |
| Cornering/rapid lateral acceleration with recovery | Suppress transient, retain raw observations |
| Truck parked on grade beyond calibration range | Defer decision until stable grade observations |
| Authorized refueling, maintenance draining, tank transfer | Reconcile against authorization; classify appropriately |
| Level sender jump, rebound after 20 s | Sensor/slosh event and equipment-health diagnostic |
| Ignition-off fuel-rate message remains stale | Integrator uses zero engine burn while key off |
| Missing pitch/roll data or >15 s sensor gap | Evidence incomplete, no high-confidence detection |
Dashboard should display the time-aligned level trace, attitude trace, GPS/ignition evidence, modeled consumption, corrected-volume trend, sensor confidence, and linked investigation workflow. Audit immutability requires raw-frame retention hashes and calibration/model version histories.
1.7 JSON Schema — normalized telemetry and candidate anomaly
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://strongtoweronline.com/schemas/phase2/fuel-event.schema.json",
"title": "Freight Tractor Fuel Telemetry or Anomaly Event",
"oneOf": [
{"$ref": "#/$defs/telemetry"},
{"$ref": "#/$defs/anomaly"}
],
"$defs": {
"telemetry": {
"type": "object", "additionalProperties": false,
"required": ["event_type", "tenant_id", "vin", "ts_utc", "gateway_id", "spn", "calibration_version"],
"properties": {
"event_type": {"const": "J1939_FUEL_TELEMETRY"},
"tenant_id": {"type": "string", "minLength": 1},
"vin": {"type": "string", "pattern": "^[A-HJ-NPR-Z0-9]{17}$"},
"ts_utc": {"type": "string", "format": "date-time"},
"gateway_id": {"type": "string", "minLength": 1},
"source_address": {"type": "integer", "minimum": 0, "maximum": 253},
"sequence": {"type": "integer", "minimum": 0},
"calibration_version": {"type": "string", "minLength": 1},
"spn": {
"type": "object", "additionalProperties": false,
"properties": {
"183_lph": {"type": ["number", "null"], "minimum": 0},
"84_kph": {"type": ["number", "null"], "minimum": 0},
"96_pct": {"type": ["number", "null"], "minimum": 0, "maximum": 100},
"92_pct": {"type": ["number", "null"], "minimum": 0, "maximum": 125}
},
"required": ["183_lph", "84_kph", "96_pct", "92_pct"]
},
"ignition_on": {"type": ["boolean", "null"]},
"pitch_deg": {"type": ["number", "null"]},
"roll_deg": {"type": ["number", "null"]},
"lateral_mps2": {"type": ["number", "null"]}
}
},
"anomaly": {
"type": "object", "additionalProperties": false,
"required": ["event_type", "tenant_id", "vin", "start_time", "end_time", "observed_residual_gal", "threshold_gal", "review_status", "evidence_ids", "rule_version"],
"properties": {
"event_type": {"const": "FUEL_LOSS_CANDIDATE"},
"tenant_id": {"type": "string", "minLength": 1},
"vin": {"type": "string", "pattern": "^[A-HJ-NPR-Z0-9]{17}$"},
"start_time": {"type": "string", "format": "date-time"},
"end_time": {"type": "string", "format": "date-time"},
"observed_residual_gal": {"type": "number", "exclusiveMinimum": 5},
"conservative_lower_gal": {"type": "number"},
"threshold_gal": {"type": "number", "const": 5},
"review_status": {"enum": ["INVESTIGATE", "CONFIRMED_AUTHORIZED", "CONFIRMED_UNAUTHORIZED", "SENSOR_ARTIFACT", "CLOSED"]},
"evidence_ids": {"type": "array", "items": {"type": "string"}, "minItems": 1, "uniqueItems": true},
"rule_version": {"type": "string", "minLength": 1}
}
}
}
}
Strong Tower Consulting provides independent systems architecture, feasibility audits, and engineering roadmaps for motor carriers and freight brokers. Call 763-244-1373 to discuss operational data and evaluate practical implementation paths for your fleet.
Module 2 — LTL Cross-Dock Door Striping & Forklift Dispatch: Mixed-Integer Linear Program
2.1 Terminal topology and operating objects
An LTL cross-dock typically receives linehaul or pickup trailers at strip doors, scans and stages shipments, then loads outbound city-delivery, relay, or linehaul trailers at stack doors. The optimization goal is to position trailers where freight transfer flows incur the least safe forklift travel and labor, while meeting dispatch cutoffs and maintaining hazardous-material segregation. The terminal layout is an explicit aisle network \(G=(N,A)\), with directional forklift links, pedestrian crossing restrictions, exclusion zones, doorway dimensions, battery-charge facilities, and constrained aisle segments.
Sets:
- \(I\): inbound trailers to be stripped.
- \(O\): outbound routes/trailers to be stacked.
- \(D\): physical dock doors; \(D^I\) and \(D^O\) identify capability subsets (some doors support either role).
- \(T\): discrete dock occupancy slots (e.g. 15 minutes).
- \(F\): freight transfer tasks, each with origin inbound \(i(f)\), destination outbound \(o(f)\), handling-unit count \(n_f\), weight \(w_f\), and classification.
- \(K\): forklifts/operators with shift/skills/capacity profiles.
- \(A\): directed aisle arcs, each with slot throughput \(U_{at}\).
- \(H\): handling/segregation groups from verified hazard classifications.
Parameters:
\(d_{de}\): shortest legal forklift-path distance between strip door \(d\) and stack door \(e\), meters.
\(t_{fde}\): estimated handling minutes per move of task \(f\) on door pairing \((d,e)\).
\(\gamma_{afde}\in\{0,1\}\): whether the chosen directed path uses aisle \(a\).
\(\lambda_{ft}\): units of task \(f\) processed during slot \(t\).
\(\chi_{fg}\in\{0,1\}\): legally incompatible freight handling combination at an overlapping location/time, based on a versioned hazmat rules engine.
All handling-time predictions incorporate pallet count, breakbulk touches, direction, staging, floor conditions, and forklift type.
2.2 Binary and continuous variables
For each trailer \(r\in I\cup O\), door \(d\in D\), slot \(t\in T\):
\[
x_{rdt}\in\{0,1\}:\quad \text{trailer }r\text{ occupies door }d\text{ in slot }t.
\]
For placement start:
\[
s_{rdt}\in\{0,1\}:\quad r\text{ begins its uninterrupted door reservation at }(d,t).
\]
For transfer task \(f\), forklift \(k\), slot \(t\), door pair \((d,e)\):
\[
y_{fkdet}\in\{0,1\}:\quad \text{task }f\text{ is performed by }k\text{ on }(d,e)\text{ in }t.
\]
If \(f\) contains multiple pallet moves, create indexed subtasks \((f,j)\), or let \(u_{fkdet}\in\mathbb Z_{\ge0}\) represent the number of units moved. The latter enables a compact MILP:
\[
\sum_{k,d,e,t}u_{fkdet}=n_f\qquad\forall f.
\]
For congestion on aisle \(a\) at slot \(t\), define excess-over-target \(q_{at}\ge0\). For dispatch cutoff deviation, define tardiness \(\delta_o\ge0\).
2.3 Objective: travel, touch labor, congestion, and late departures
\[
\boxed{
\min \ \alpha \sum_{f,k,d,e,t} d_{de}u_{fkdet}
+\beta \sum_{f,k,d,e,t} t_{fkde}u_{fkdet}
+\gamma \sum_{a,t}q_{at}
+\zeta \sum_o\delta_o
+\xi \sum_{r,d,t}c^{\mathrm{reloc}}_{rdt}s_{rdt}
}
\]
Units: \(\alpha\) USD/meter, \(\beta\) USD/minute, \(\gamma\) USD/over-target aisle flow, \(\zeta\) USD/minute of missed outbound cutoff, and \(\xi\) USD per extra yard movement. Operationally, treat regulatory safety and physically blocked aisles as hard constraints, never as prices permitting violations.
2.4 Door assignment and no over-subscription
Each inbound and outbound trailer receives exactly one compatible start within its allowed interval (or one of multiple explicitly modeled door visit segments):
\[
\sum_{d,t}s_{rdt}=1\qquad\forall r.
\]
Let \(p_r\) be planned duration in slots. Link reservation starts to occupancy:
\[
x_{rd\tau}=\sum_{t:\ t\le\tau<t+p_r}s_{rdt}
\quad\forall r,d,\tau.
\]
One trailer per door and slot:
\[
\sum_r x_{rdt}\le1\qquad\forall d,t.
\]
If \(c_{rd}\in\{0,1\}\) states equipment and door compatibility:
\[
s_{rdt}\le c_{rd},\qquad
s_{rdt}=0\text{ outside the trailer's service window}.
\]
An inbound task may begin only after its trailer has docked and reached the unload-ready stage; outbound tasks must complete before customer-route or linehaul cutoffs. Let task completion slot be \(C_f\) and outbound route ready time \(R_o\):
\[
C_f\le R_{o(f)},\quad R_o\le\mathrm{cutoff}_o+\delta_o.
\]
When loading depends on receipt and freight sortation, add precedence \(\mathrm{start}_{f,\mathrm{load}}\ge\mathrm{finish}_{f,\mathrm{strip}}+\mathrm{sort\_lag}_f\). Encode task start-to-finish dependencies as a precedence DAG with tight big-\(M\) implications or CP-SAT intervals.
2.5 Linking forklift moves to docked trailers
For \(u_{fkdet}\) movements:
\[
u_{fkdet}\le n_f x_{i(f),dt},\qquad
u_{fkdet}\le n_f x_{o(f),et}.
\]
When outbound loading occurs after a different inbound stripping slot, use a staged inventory state instead of insisting on simultaneous inbound/outbound occupancy. Let \(B_{f,t}\) be the integer number of staged units at the end of slot \(t\):
\[
B_{f,t}=B_{f,t-1}+U^{\mathrm{strip}}_{f,t}-U^{\mathrm{stack}}_{f,t},\quad B_{f,t}\ge0,
\]
with initial inventory, counts, and outgoing departures reconciled. This more realistic two-leg cross-dock model uses inbound-to-stage and stage-to-outbound aisle paths, retaining physical staging location and its footprint.
For forklift \(k\), slot capacity is:
\[
\sum_{f,d,e} t_{fkde}u_{fkdet}\le \Delta_t a_{kt},
\]
where \(a_{kt}\in\{0,1\}\) indicates staffed/available forklift status. Forklift lift-capacity, fork geometry, hazmat operator qualifications, pedestrian corridor policies, and battery/fuel capacity are separate compatibility constraints.
2.6 Aisle choke points and geometry
Actual aisle throughput is based on directional travel, forklift geometry, opposing traffic, and loading intersection behavior. Define travel demand on aisle \(a\) during slot \(t\):
\[
N_{at}=\sum_{f,k,d,e}\gamma_{afde}u_{fkdet}.
\]
Hard safe capacity:
\[
N_{at}\le U_{at}.
\]
Soft target and congestion surcharge:
\[
q_{at}\ge N_{at}-U^{\mathrm{target}}_{at},\quad q_{at}\ge0.
\]
For junctions, model conflicts between opposite directions using exclusive route reservations. For a narrow aisle \(a\) and opposing paths \(a^+,a^-\), an optional binary direction variable \(z_{at}\) gives:
\[
N_{a^+,t}\le U_{at}z_{at},\quad
N_{a^-,t}\le U_{at}(1-z_{at}).
\]
Facility floor maps should be converted into surveyed graph coordinates; shortest legal forklift paths use Dijkstra or contraction hierarchy over aisle segments, with per-turn penalties and restricted intersections. The optimization consumes these pairwise path lengths rather than Euclidean line-of-sight distances.
2.7 Hazardous-material segregation formulation
49 CFR § 177.848 specifies segregation according to the hazards present and its table: X prohibits specified materials from being loaded, transported or stored together in the same transport vehicle or storage facility during transportation; O permits combinations only with required separation preventing commingling; \* invokes explosive compatibility rules. Subsidiary hazards, specific exceptions, and statutory notes are additional decisions. A simplistic hazard-class equality test is not a compliant segregation decision. See [49 CFR § 177.848](https://www.ecfr.gov/current/title-49/subtitle-B/chapter-I/subchapter-C/part-177/section-177.848).
For freight units \(f,g\), let \(\chi_{fg}=1\) when the validated rule engine establishes that a simultaneous shared storage/vehicle arrangement is prohibited. If location \(z\) identifies the same conveyance or a legally incompatible shared staging zone, and \(p_{fzt}\) means freight \(f\) resides there during slot \(t\):
\[
p_{fzt}+p_{gzt}\le1\qquad\forall(f,g):\chi_{fg}=1.
\]
For an O combination, let \(\operatorname{sep}(z,z')\) be the verified safe separation predicate for package leakage and handling arrangements, reflecting relevant class-specific prohibitions. For incompatible placement pairs:
\[
p_{fzt}+p_{gz't}\le1\quad \text{if }\operatorname{sep}(z,z')=0.
\]
For explosive compatibility groups, create the additional conditions prescribed by §177.848(f)-(i), evaluated against primary/subsidiary classification, proper shipping name, UN/NA number, packaging, and applicable authorizations. The optimization receives a prevalidated compatibility matrix from a version-controlled hazardous-materials rules service that produces a reason code and legal-rule citation for each prohibited pairing. Ensure staging safety also accounts for facility fire codes, handling method, pedestrian access and forklift work zones.
2.8 LTL MILP construction pseudocode
from ortools.linear_solver import pywraplp
def solve_terminal(trailers, doors, time_slots, moves, forklifts,
aisles, legal_pairs, max_seconds=60):
"""Pseudocode-quality model builder: optimize audited terminal input."""
solver = pywraplp.Solver.CreateSolver("SCIP")
assert solver is not None
x = {} # trailer-door-slot reservation
start = {} # trailer-door-start-slot
u = {} # integer pallet movements per forklift / pair / slot
for r in trailers:
feasible = []
for d in doors:
if not door_compatible(r, d):
continue
for t in time_slots:
if not fits_window(r, d, t, time_slots):
continue
start[r.id, d.id, t] = solver.BoolVar(
f"start:{r.id}:{d.id}:{t}")
feasible.append(start[r.id, d.id, t])
solver.Add(solver.Sum(feasible) == 1)
for d in doors:
for t in time_slots:
active = []
for r in trailers:
covered = [v for (rid, did, ts), v in start.items()
if rid == r.id and did == d.id
and ts <= t < ts + r.duration_slots]
if covered:
active.extend(covered)
solver.Add(solver.Sum(active) <= 1)
for task in moves:
candidates = []
for k, d, e, t in feasible_move_choices(task, forklifts,
doors, time_slots):
key = (task.id, k.id, d.id, e.id, t)
u[key] = solver.IntVar(0, task.unit_count, f"u:{key}")
candidates.append(u[key])
# In full 2-stage crossdock formulation use staging balance
# instead of direct simultaneous occupancy constraints.
solver.Add(u[key] <= task.unit_count * occupied(
solver, start, task.inbound_id, d.id, t, trailers))
solver.Add(u[key] <= task.unit_count * occupied(
solver, start, task.outbound_id, e.id, t, trailers))
solver.Add(solver.Sum(candidates) == task.unit_count)
for k in forklifts:
for t in time_slots:
solver.Add(solver.Sum(
processing_minutes(key) * v for key, v in u.items()
if key[1] == k.id and key[4] == t
) <= k.available_minutes(t))
for a in aisles:
for t in time_slots:
load = solver.Sum(path_uses_arc(key, a.id) * val
for key, val in u.items() if key[4] == t)
solver.Add(load <= a.safe_capacity(t))
add_legal_hazmat_segregation_constraints(
solver, start, u, legal_pairs, time_slots)
add_receipt_staging_and_departure_cutoffs(solver, start, u, moves)
travel_cost = solver.Sum(move_distance(key) * val
for key, val in u.items())
labor_cost = solver.Sum(processing_minutes(key) * val
for key, val in u.items())
congestion_cost = make_aisle_over_target_cost(solver, u, aisles)
lateness_cost = make_cutoff_delay_cost(solver, u, moves)
solver.Minimize(0.02 * travel_cost + 0.65 * labor_cost +
6.0 * congestion_cost + 25.0 * lateness_cost)
solver.SetTimeLimit(max_seconds * 1000)
status = solver.Solve()
return explain_and_verify_solution(solver, status, start, u)
occupied, feasible_move_choices, processing_minutes, path_uses_arc, add_legal_hazmat_segregation_constraints, add_receipt_staging_and_departure_cutoffs, and the remaining helper procedures are clearly identified solver-adapter interfaces; a build implements these against authoritative door calendars, task stages, staging-zone inventories, and the terminal graph. In production, use the staged-inventory version when freight is stripped before the outbound trailer docks. Set the solve gap tolerance, deterministic solver seed and wall-clock budget, and retain solver status, incumbent objective, best bound and input snapshot.
Practical decision cadence: full re-solve at major inbound arrival waves, on newly accepted linehaul manifests, and at outbound dispatch cutoff changes; limited local repairs on forklift breakdown or door blockage. Freeze tasks already being handled and enforce stable near-term assignments to avoid operational churn.
2.9 JSON Schema — terminal optimization request and response
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://strongtoweronline.com/schemas/phase2/crossdock-plan.schema.json",
"title": "Crossdock Door and Forklift Optimization Plan",
"type": "object", "additionalProperties": false,
"required": ["tenant_id", "terminal_id", "planning_start_utc", "slot_minutes", "doors", "trailers", "transfers", "forklifts", "aisles", "hazmat_ruleset_version"],
"properties": {
"tenant_id": {"type": "string", "minLength": 1},
"terminal_id": {"type": "string", "minLength": 1},
"planning_start_utc": {"type": "string", "format": "date-time"},
"slot_minutes": {"type": "integer", "minimum": 1, "maximum": 60},
"hazmat_ruleset_version": {"type": "string", "minLength": 1},
"doors": {"type": "array", "minItems": 1, "items": {
"type": "object", "additionalProperties": false,
"required": ["door_id", "role", "x_m", "y_m"],
"properties": {
"door_id": {"type": "string", "minLength": 1},
"role": {"enum": ["STRIP", "STACK", "BOTH"]},
"x_m": {"type": "number"}, "y_m": {"type": "number"}
}
}},
"trailers": {"type": "array", "items": {
"type": "object", "additionalProperties": false,
"required": ["trailer_id", "flow", "available_utc", "deadline_utc", "duration_slots"],
"properties": {
"trailer_id": {"type": "string", "minLength": 1},
"flow": {"enum": ["INBOUND", "OUTBOUND"]},
"available_utc": {"type": "string", "format": "date-time"},
"deadline_utc": {"type": "string", "format": "date-time"},
"duration_slots": {"type": "integer", "minimum": 1}
}
}},
"transfers": {"type": "array", "items": {
"type": "object", "additionalProperties": false,
"required": ["task_id", "inbound_trailer_id", "outbound_trailer_id", "units", "hazmat_class", "un_number", "staging_zone_id"],
"properties": {
"task_id": {"type": "string", "minLength": 1},
"inbound_trailer_id": {"type": "string", "minLength": 1},
"outbound_trailer_id": {"type": "string", "minLength": 1},
"units": {"type": "integer", "minimum": 1},
"hazmat_class": {"type": ["string", "null"]},
"subsidiary_hazards": {"type": "array", "items": {"type": "string"}},
"un_number": {"type": ["string", "null"]},
"staging_zone_id": {"type": "string", "minLength": 1}
}
}},
"forklifts": {"type": "array", "items": {
"type": "object", "additionalProperties": false,
"required": ["forklift_id", "lift_capacity_kg", "available_slot_indices"],
"properties": {
"forklift_id": {"type": "string", "minLength": 1},
"lift_capacity_kg": {"type": "number", "exclusiveMinimum": 0},
"available_slot_indices": {"type": "array", "items": {"type": "integer", "minimum": 0}, "uniqueItems": true}
}
}},
"aisles": {"type": "array", "items": {
"type": "object", "additionalProperties": false,
"required": ["arc_id", "from_node", "to_node", "distance_m", "capacity_moves_per_slot"],
"properties": {
"arc_id": {"type": "string", "minLength": 1},
"from_node": {"type": "string", "minLength": 1},
"to_node": {"type": "string", "minLength": 1},
"distance_m": {"type": "number", "minimum": 0},
"capacity_moves_per_slot": {"type": "integer", "minimum": 0}
}
}},
"solution": {"type": "object", "additionalProperties": false,
"required": ["status", "objective", "door_assignments", "forklift_tasks", "legal_rule_trace"],
"properties": {
"status": {"enum": ["OPTIMAL", "FEASIBLE", "INFEASIBLE", "TIME_LIMIT", "ERROR"]},
"objective": {"type": ["number", "null"]},
"best_bound": {"type": ["number", "null"]},
"door_assignments": {"type": "array", "items": {"type": "object", "required": ["trailer_id", "door_id", "start_slot"], "properties": {
"trailer_id": {"type": "string"}, "door_id": {"type": "string"}, "start_slot": {"type": "integer", "minimum": 0}
}}},
"forklift_tasks": {"type": "array", "items": {"type": "object", "required": ["task_id", "forklift_id", "slot_index", "units"], "properties": {
"task_id": {"type": "string"}, "forklift_id": {"type": "string"}, "slot_index": {"type": "integer", "minimum": 0}, "units": {"type": "integer", "minimum": 1}
}}},
"legal_rule_trace": {"type": "array", "items": {"type": "string"}}
}
}
}
}
2.10 Acceptance and measurement
Measure pallet-meters per transfer, verified forklift labor minutes per hundred handling units, trailer dwell minutes at doors, missed dispatch cutoffs, aisle congestion exceedances, restaging touches, route readiness, and operator override rates. Replay event logs with frozen floor geometry and independently check that every trailer occupancy reservation is nonoverlapping, every moved unit has a valid receipt/ship transition, all forklifts satisfy shift and capacity limits, and every required hazmat restriction is evidenced in the plan trace.
Strong Tower Consulting provides independent systems architecture, feasibility audits, and engineering roadmaps for motor carriers and freight brokers. Call 763-244-1373 to discuss operational data and evaluate practical implementation paths for your fleet.
Module 3 — Dynamic Brokerage Spot Margin Elasticity & Bid Regression
3.1 Commercial decision model
A freight brokerage must quote a shipper an all-in sell price \(S\), obtain a carrier buy price \(B\), and account for transaction-related costs \(A\): lumper exposure, anticipated detention, processing costs, route-specific fees, and approved contingencies. Gross profit dollars and gross margin on sales are:
\[
GP=S-(B+A),\qquad
m=\frac{S-(B+A)}{S}=1-\frac{B+A}{S}.
\]
Margin percentage and markup percentage are different quantities:
\[
\operatorname{markup}=\frac{S-(B+A)}{B+A}.
\]
The bid engine must guard actual gross margin on sell revenue, not substitute a cost markup. Gross margin floor \(m_{\min}\in[0,1)\) implies:
\[
\boxed{S\ge\frac{B+A}{1-m_{\min}}}.
\]
If carrier buy cost is a distribution \(B\sim F_B(\cdot\mid x)\), replace the point estimate with a risk-adjusted bound:
\[
S\ge\frac{Q_{1-\alpha}(B+A\mid x)}{1-m_{\min}}.
\]
Here \(Q_{1-\alpha}\) is a chosen high cost quantile (for example the 95th percentile). The quote may also be bounded by an approved credit exposure or revenue policy, and operational release requires a feasible carrier-cover probability.
3.2 Multivariate feature matrix
For quoted load \(i\), construct \(x_i\) at the time the quote decision is made—never with knowledge from after acceptance:
\[
\mathbf x_i=[1,\ \mathrm{OTRI}_{o,e,t},\ \Delta\mathrm{OTRI}_{7d},\ \log(1+\mathrm{capacity}_{o,e,t}),\ \mathrm{dwell}_{s,90d},\ \mathrm{diesel}_{p,t},\ \mathrm{daysToPickup},\ \epsilon^C_{lane},\ \mathrm{distance},\ \mathrm{deadhead},\ \mathrm{equipment},\ \mathrm{region},\ \mathrm{dayOfWeek},\ \mathrm{rateSpread},\ \mathrm{serviceRisk}]^T.
\]
Feature definition and source:
| Feature | Operational definition | Integrity rule |
| OTRI | Outbound tender rejection percentage for relevant origin/equipment/period | Capture observation/publication time and license lineage |
| \(\Delta\)OTRI | Recent absolute percentage-point change | Match origin market and same equipment definition |
| Equipment density | Available compatible tractors within repositioning radius and pickup horizon, divided by projected loads | Prefer verified carrier/equipment availability, deduplicate equipment IDs |
| Shipper dwell | Rolling historical origin/consignee wait-time distribution by facility, shift and carrier | Exclude uncompleted future visits, guard sparse samples |
| Diesel price peg | Applicable weekly EIA on-highway diesel regional price or contracted index | Freeze publication vintage and mapped PADD |
| Days to pickup | Exact business/time interval from quote UTC to facility-local appointment | Avoid date-only timezone errors |
| Capacity elasticity | Estimated responsiveness of carrier availability/quote acceptance to price | Estimate from unbiased tender/offer history |
| Carrier buy estimate | Conditional distribution by lane, equipment, lead time, market | Keep broker buy and shipper sell outcomes distinct |
| Operational risk | Detention propensity, weather/service exceptions, specialized equipment constraints | Logged as observable point-in-time features |
The Outbound Tender Rejection Index represents the percentage of tendered contract freight rejected by carriers in a market, according to SONAR's methodology. Market definition and entitlement must accompany the feature. The EIA publishes on-highway diesel price history for the United States and Petroleum Administration for Defense Districts (PADDs). See cited sources.
3.3 Shipper acceptance logistic regression
Define binary \(Y_i^S=1\) if a quoted shipper offer is accepted before its expiry, and zero otherwise after a complete observation window. For normalized and encoded feature vector \(x_i\) augmented by candidate all-in sell price \(S_i\) and market benchmark \(M_i\):
\[
P(Y_i^S=1\mid x_i,S_i)=\sigma\!\left(\beta_0+\beta^T x_i+\beta_S\log\frac{S_i}{M_i}+\beta_{S,L}\log\frac{S_i}{M_i}\cdot\mathrm{leadtime}_i\right),
\]
where \(\sigma(z)=(1+e^{-z})^{-1}\).
Estimate \(\beta\) using weighted penalized log likelihood:
\[
\min_\beta -\sum_i w_i\left[y_i\log p_i+(1-y_i)\log(1-p_i)\right]+\lambda_1\|\beta\|_1+\lambda_2\|\beta\|_2^2.
\]
The weights \(w_i\) may correct known sampling imbalance, but weight derivation must use only information available when training outcomes are finalized. An elasticity of acceptance to quoted price is:
\[
\epsilon_S(S)=\frac{\partial\log p(S)}{\partial\log S}=(1-p(S))\left(\beta_S+\beta_{S,L}\mathrm{leadtime}\right).
\]
A commercially interpretable model normally implies decreasing shipper acceptance with higher relative sell rates over comparable offers; calibrate and monitor local monotonicity and segment effects. Explicit price variation and historical offer policies are needed for causal interpretation of the response curve. If training data come from heavily filtered historical prices, use randomized approved-price bands, inverse propensity weights or doubly robust estimation under appropriate governance.
3.4 Carrier cover probability and capacity price elasticity
Separately model \(Y_i^C=1\) if an authorized carrier can be covered at or below buy cap \(B_{\max}\) before the appointment deadline:
\[
P(Y_i^C=1\mid x_i,B_{\max})=\sigma(\gamma_0+\gamma^T x_i+\gamma_B\log(B_{\max}/M_i^B)).
\]
Carrier capacity price elasticity is:
\[
\epsilon^C_i=\frac{\partial\log P(Y_i^C=1)}{\partial\log B_{\max}}=(1-p_i^C)\gamma_B.
\]
Carrier cover can also be modeled using conditional survival analysis for time to coverage, with remaining time before pickup as the relevant horizon. A two-stage decision combines shipper acceptance and carrier coverage in a joint service probability rather than multiplying probabilities under an unjustified independence assumption.
3.5 XGBoost model structure
For tabular heterogeneous freight data, gradient-boosted decision trees learn interactions among market dynamics, facility dwell, equipment scarcity, and quote sensitivity. Let \(\widehat f(x,S)\) be the additive log-odds model:
\[
\widehat f(x,S)=\sum_{k=1}^{K}\eta f_k(x,S),\qquad p=\sigma(\widehat f).
\]
The XGBoost training objective is:
\[
\mathcal L=\sum_i\ell(y_i,\widehat y_i)+\sum_k\Omega(f_k),
\quad \Omega(f)=\gamma T+\tfrac12\lambda\sum_{j=1}^T w_j^2.
\]
Build separate estimators for (i) shipper acceptance probability, (ii) carrier coverage probability or coverage survival, and (iii) carrier buy-cost distribution using quantile losses or a properly calibrated conditional distribution. With XGBoost, construct sell-price monotonic constraints in feature coordinates where the price-response direction is known and appropriate. Calibrate probabilities with out-of-time isotonic or Platt procedures on held-out data and compare calibration curves across origin market, equipment class, customer and lead-time segment.
3.6 Decision objective and rigorous floor
Let candidate price \(S\) and carrier buy cap \(B_{\max}\) be decision variables. Define sales-acceptance \(p_S(S,x)\), carrier-cover \(p_C(B_{\max},S,x)\), cost distribution \(F_B\), expected exception costs \(A\), and service failure penalty \(L\).
An economically coherent objective is:
\[
\max_{S,B_{\max}}\quad
\mathbb E\left[\mathbf1_{\mathrm{shipper\ accepts}}\mathbf1_{\mathrm{carrier\ covers}}(S-B-A)\right]
-\mathbb E[\mathrm{service\ risk\ cost}],
\]
subject to:
\[
S\ge\frac{B_{\max}+A_{\mathrm{reserved}}}{1-m_{\min}},
\quad p_C\ge p_{\min}^{\mathrm{cover}},
\quad S\in[\underline S,\overline S],
\]
and contracted/customer-specific rate approval bands. In post-acceptance execution, the release gate repeats the check using the actual contracted carrier cost and reserved accessorials:
\[
\mathrm{release}=1\iff S-(B_{\mathrm{actual}}+A_{\mathrm{reserved}})\ge m_{\min}S.
\]
The execution gate is authoritative even when the probabilistic model recommends a price. Margin exceptions follow an explicit approval state machine and are not automated as ordinary bids.
3.7 Worked brokerage quote example
Assume modeled carrier buy \(B=\$1{,}650\), reserved accessorial and transaction costs \(A=\$100\), and target gross margin \(m_{\min}=0.18\). Then:
\[
S_{\min}=\frac{1650+100}{1-0.18}=\$2{,}134.1463\ldots
\]
Round up to the permitted commercial precision, yielding a minimum all-in quote of $2,134.15. At a $2,100 quote, computed gross margin is \((2100-1750)/2100=16.67\%\), violating the 18% guardrail. At $2,250, it is \((2250-1750)/2250=22.22\%\). The optimizer must choose among permitted bids, considering likelihood of acceptance and carrier coverage, and verify the locked carrier cost before tender commitment.
3.8 Production-grade bid engine pseudocode
from decimal import Decimal, ROUND_CEILING
CENT = Decimal("0.01")
def ceil_cents(value: Decimal) -> Decimal:
return value.quantize(CENT, rounding=ROUND_CEILING)
def min_sell_for_margin(cost: Decimal, floor: Decimal) -> Decimal:
if cost < 0 or not (Decimal("0") <= floor < Decimal("1")):
raise ValueError("invalid approved pricing parameters")
return ceil_cents(cost / (Decimal("1") - floor))
def propose_spot_quote(load, point_in_time_features, models,
approved_policy, buy_distribution):
assert feature_vintage_valid(point_in_time_features, load.quote_time_utc)
floor = approved_policy.margin_floor(load.customer_id, load.equipment)
reserved = approved_policy.accessorial_reserve(load)
carrier_buy_cap = buy_distribution.quantile(
approved_policy.buy_cost_quantile)
minimum_sell = min_sell_for_margin(carrier_buy_cap + reserved, floor)
permitted = approved_policy.allowed_sell_candidates(load)
permitted = [Decimal(str(s)) for s in permitted
if Decimal(str(s)) >= minimum_sell]
choices = []
for sell in permitted:
cover = models.carrier_cover_probability(
point_in_time_features, carrier_buy_cap, load.pickup_utc)
if cover < approved_policy.minimum_cover_probability:
continue
accept = models.shipper_accept_probability(
point_in_time_features, sell)
expected_gp = models.expected_realized_gross_profit(
point_in_time_features, sell, carrier_buy_cap, reserved)
risk = models.expected_service_penalty(
point_in_time_features, sell, carrier_buy_cap)
score = accept * (cover * expected_gp - risk)
choices.append((score, sell, accept, cover))
if not choices:
return make_review_decision(load, "NO_POLICY_FEASIBLE_QUOTE")
_, sell, accept, cover = max(choices, key=lambda r: r[0])
decision = create_quote_proposal(
load=load, sell=sell, buy_cap=carrier_buy_cap,
approved_margin_floor=floor, acceptance_probability=accept,
cover_probability=cover, feature_snapshot=point_in_time_features)
return decision
def authorize_carrier_award(quote, actual_buy, reserved_cost, policy):
sell = Decimal(quote.sell_amount)
cost = Decimal(actual_buy) + Decimal(reserved_cost)
approved_floor = Decimal(quote.margin_floor)
# Final hard gate; database transaction / compare-and-swap enforces it.
if cost > sell * (Decimal("1") - approved_floor):
return "REQUIRES_MARGIN_APPROVAL"
if not policy.carrier_authorized(quote.carrier_id):
return "REQUIRES_CARRIER_CLEARANCE"
return "AUTHORIZED"
A transactional implementation locks quote state/version, verified carrier identity, credit status, rate confirmation, actual carrier cost, and approved reserves in one idempotent award operation. Concurrency controls prevent two brokers or automated agents from simultaneously committing contradictory buy rates. Persist rejected proposals and model-derived price responses for audit without exposing protected third-party market licensing beyond its permitted use.
3.9 Data leakage and model validation controls
Training splits follow time, then ideally held-out customers and lanes. Include a quote-time feature registry that reconstructs exactly which market data, EIA price vintage, dwell history, capacity snapshot, and current carrier offers were observable at the original quote timestamp. Canceled or expired offers require explicit labels or right-censoring rather than being indiscriminately treated as losses. Correct for selection bias from historical broker pricing policies. Monitor calibration (Brier score, reliability diagrams), log loss, AUC, accepted-bid gross margin, cover rate, negative contribution, margin-floor exceptions, and customer-specific retention. Evaluate uplift by a controlled shadow and champion/challenger process, enforcing the same hard margin guardrail for every challenger.
3.10 JSON Schema — spot quote proposal and financial guardrail
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://strongtoweronline.com/schemas/phase2/spot-bid.schema.json",
"title": "Brokerage Spot Quote Decision",
"type": "object", "additionalProperties": false,
"required": ["tenant_id", "quote_id", "load_id", "quote_time_utc", "currency", "equipment", "features", "model_versions", "buy_cost_quantile_usd", "reserved_cost_usd", "margin_floor", "proposed_sell_usd", "decision"],
"properties": {
"tenant_id": {"type": "string", "minLength": 1},
"quote_id": {"type": "string", "minLength": 1},
"load_id": {"type": "string", "minLength": 1},
"quote_time_utc": {"type": "string", "format": "date-time"},
"currency": {"const": "USD"},
"equipment": {"enum": ["DRY_VAN", "REEFER", "FLATBED", "BULK_TANKER", "CONTAINER_DRAYAGE", "OTHER_APPROVED"]},
"features": {
"type": "object", "additionalProperties": false,
"required": ["otri_pct", "equipment_density", "shipper_dwell_hours_p50", "diesel_padd_usd_per_gal", "days_to_pickup", "carrier_capacity_elasticity", "feature_asof_utc", "market_source"],
"properties": {
"otri_pct": {"type": "number", "minimum": 0, "maximum": 100},
"otri_change_7d_pp": {"type": "number"},
"equipment_density": {"type": "number", "minimum": 0},
"shipper_dwell_hours_p50": {"type": "number", "minimum": 0},
"diesel_padd_usd_per_gal": {"type": "number", "minimum": 0},
"diesel_padd_region": {"type": "string"},
"days_to_pickup": {"type": "number", "minimum": 0},
"carrier_capacity_elasticity": {"type": "number"},
"feature_asof_utc": {"type": "string", "format": "date-time"},
"market_source": {"type": "string", "minLength": 1}
}
},
"model_versions": {"type": "object", "additionalProperties": false,
"required": ["acceptance", "carrier_coverage", "buy_cost"],
"properties": {
"acceptance": {"type": "string"}, "carrier_coverage": {"type": "string"}, "buy_cost": {"type": "string"}
}
},
"buy_cost_quantile_usd": {"type": "number", "minimum": 0},
"reserved_cost_usd": {"type": "number", "minimum": 0},
"margin_floor": {"type": "number", "minimum": 0, "exclusiveMaximum": 1},
"proposed_sell_usd": {"type": "number", "exclusiveMinimum": 0},
"shipper_accept_probability": {"type": "number", "minimum": 0, "maximum": 1},
"carrier_cover_probability": {"type": "number", "minimum": 0, "maximum": 1},
"decision": {"enum": ["PROPOSED", "REQUIRES_REVIEW", "AUTHORIZED", "REJECTED", "EXPIRED"]},
"pricing_policy_version": {"type": "string"},
"approval_reference": {"type": ["string", "null"]}
}
}
Schema-level business validation: JSON Schema guarantees basic structural correctness. A domain validation layer separately enforces currency-decimal precision, feature_asof_utc <= quote_time_utc, pickup chronology, market-index vintage, and the cross-field margin inequality proposed_sell_usd * (1 - margin_floor) >= buy_cost_quantile_usd + reserved_cost_usd. Apply that cross-field rule using decimal arithmetic and repeat it with actual buy cost at the award event.
Strong Tower Consulting provides independent systems architecture, feasibility audits, and engineering roadmaps for motor carriers and freight brokers. Call 763-244-1373 to discuss operational data and evaluate practical implementation paths for your fleet.
Cross-module deployment blueprint, lineage, and verification
The three modules can share one freight event platform while independently scaling optimization, telemetry and pricing inference:
J1939 ECU gateway / terminal scan events / brokerage quoting activity
| | |
Authenticated ingest Terminal event log Quoting event log
| | |
Fuel signal normalizer Spatial graph service Point-in-time feature store
| | |
Fuel anomaly worker MILP solve coordinator Logistic / XGBoost inference
| | |
Fuel investigation Door/worker assignments Margin and award hard gate
| | |
Unified event and audit ledger
| | |
Fleet security Terminal operations Brokerage finance
Deployment and governance controls
• Tenant and company isolation: Every event and decision includes tenant identity, facility or operating authority where appropriate, and authorized access scope.
• Data provenance: Store raw messages and immutable document/event hashes, timestamp source and confidence, firmware/device revision, calibration version, model version, rule revision and user overrides.
• Durable event processing: Use an at-least-once event transport with idempotent consumers, event-time watermarks, replayable offsets and outbox transactions for commands affecting dispatch or financial obligations.
• Model registry: Maintain training cohort, target definition, label policy, time split, hyperparameters, validation results, bias checks by relevant freight segment, deployment timestamp and rollback lineage.
• Deterministic safety gates: Regulatory segregation, door capacity, actual carrier-award margin and data authorization checks execute independently of predictive models.
• Operations monitoring: Track telemetry gap rate, suspected fuel-loss investigation precision, MILP feasible-solve ratio and objective gap, forklift task execution, accepted-bid margin, carrier cover and model calibration drift.
• Human workflow: Investigation, terminal supervisor override and approved brokerage pricing exceptions carry structured reason codes, authorization identities and immutable before/after evidence.
• Release sequencing: Historical offline replay → supervised shadow mode → limited fleet/terminal/customer pilot → staged production rollout with automated regression and auditable rollback.
Sources and standards
• U.S. Department of Transportation, 49 CFR §177.848, Segregation of hazardous materials: https://www.ecfr.gov/current/title-49/subtitle-B/chapter-I/subchapter-C/part-177/section-177.848 . Regulatory compatibility decisions require evaluating the full provision and applicable shipment conditions.
• SAE International, SAE J1939 family of standards, in particular J1939/71 (vehicle application-layer parameter conventions): https://www.sae.org/standards/ . Vehicle manufacturer signal specifications are the implementation authority for each ECU.
• Garmin, J1939 Information, identifying SPN and PGN associations including SPN 92, 183 and 96: https://www8.garmin.com/manuals/webhelp/GUID-58383C42-BCE0-4965-BFF1-A648A7E884FC/EN-US/GUID-306ABD0D-9E94-498A-B4FA-50991FD78276.html .
• Au Group Electronics, SAE J1939 Simulator User Manual for supported signals SPN 84, 92, 96 and 183: https://www.auelectronics.com/downloads/usermanual_simj1939_2.pdf .
• SONAR Knowledge Center, Tender Rejection (OTRI): https://knowledge.freightwaves.com/resources/sonar-data/trucking/tender-rejection-tri/ .
• U.S. Energy Information Administration, Weekly Retail Gasoline and Diesel Prices: https://www.eia.gov/dnav/pet/pet_pri_gnd_a_epd2d_pte_dpgal_w.htm .
• Google OR-Tools documentation, MIP and CP-SAT optimization concepts: https://developers.google.com/optimization .
• XGBoost project documentation, tree boosting and monotonic constraints: https://xgboost.readthedocs.io/ .
• JSON Schema Draft 2020-12: https://json-schema.org/draft/2020-12/schema .
Engineering publication note
The algorithms distinguish measured observations, estimated physical conditions, optimized operating assignments, and approved financial decisions. Regulations are enforced through versioned deterministic rules, while probabilistic predictions are calibrated against fleet-specific historical outcomes. Numeric tuning parameters, tank geometry, facility pathing and brokerage-margin policies are controlled deployment configuration. The published formulas and schemas provide an inspectable basis for development, independent review, testing and implementation planning.
Strong Tower Consulting provides independent systems architecture, feasibility audits, and engineering roadmaps for motor carriers and freight brokers. Call 763-244-1373 to discuss operational data and evaluate practical implementation paths for your fleet.
Consult with Principal Systems Architect Scott Elliott
Engage Strong Tower Consulting for vendor-neutral transportation systems architecture, high-scale data engineering, and proprietary constraint solvers.
Call (763) 244-1373