← Abderrahmane Moujar All projects

Reinforcement learning · Supply chain · 2025 – present

Learning to run a slurry pipeline

An agent that decides, hour by hour, whether to pump phosphate slurry, flush with water or stop, on a pipeline where every decision takes 26 hours to reach the plant. Instead of handing a solver a large constraint model, most of the constraints are written into a simulator, an action space and a reward.

Background: my AnyLogic 3D simulation of the network (head-station tanks, pipeline, terminal tank groups)

187km
main pipeline, mine to coast
26h
from pump to terminal tank
4→12
mine feeders to downstream clients
3
actions per hour: product · water · stop
48h
rolling scheduling horizon

The system

From the mine to the plant, through one pipe

In Morocco's phosphate supply chain, ore from the Khouribga mining basin is washed, mixed with water into a pulp, and pumped as slurry to the Jorf Lasfar industrial platform on the Atlantic coast. There it feeds phosphoric-acid units and drying plants. The pipeline replaces a long chain of trains, but scheduling it is a difficult problem in its own right.

Mines

Four feeders produce ore at rates that vary from hour to hour.

Washing & head station

Pulp is stored in local and export tank groups before injection.

Slurry pipeline

Product, water and stops travel as batches. This is where the agent decides.

Terminal & plants

Three tank groups serve 12 acid, fertiliser and drying clients.

Jorf Lasfar terminal station · plants · port main line · 187 km · 26 h transit Khouribga head station feeder lines · 48 km Atlantic coast
Aerial view of slurry storage tanks at the Jorf Lasfar industrial platform
Terminal-side storage at Jorf Lasfar. Photo: OCP Group.
The arrival end of the phosphate slurry pipeline at the terminal station
“Conduite arrivée de la pulpe de phosphate”, the pipeline's arrival point. Photo: OCP Group.

The problem

Every decision is committed a day in advance

A batch pumped at 08:00 arrives at the terminal tanks at 10:00 the next day. In the meantime the operator has to:

  • keep 12 clients supplied, each with its own demand profile and grade
  • separate different product grades with a water batch, which uses water and pipeline capacity
  • avoid stopping the line (a stopped slurry line is costly to restart)
  • stop the head-station and terminal tanks from overflowing or running dry
  • switch a tank to another grade only once it is empty

The usual approach is a mixed-integer linear program: one binary variable per tank, product and hour for every switch, stoppage, water batch and dispatch decision, all linked by big-M constraints. This gives exact answers for a fixed forecast. It is slow to re-solve when the forecast changes, and it gets much harder with each new grade.

The idea

Don't solve the constraints. Put each one where an agent can use it.

An RL agent doesn't need every rule written as an inequality. Each MILP constraint goes to one of four places, and only the last of them leaves the agent anything to learn.

01

Simulator dynamics

The next state is computed, so the agent cannot violate these rules.

  • inventory balance
  • 26-h transit as a FIFO buffer
  • flow-rate caps
  • tank capacity
02

Action space

A single discrete choice per hour means only one thing can happen at a time.

  • one product per period
  • water ≠ stop
  • removes the switch, stop and activator binaries
03

Action masking

Illegal moves are removed before the agent chooses.

  • stop budget per horizon
  • water between two grades
  • empty tank before switching
04

Reward

Soft goals become costs the agent learns to trade off.

  • unmet demand (dominant)
  • water and stop hours
  • tank levels in a healthy band
  • wrong-grade deliveries

MILP, per schedule

  • dozens of linked binaries for every hour
  • re-solved from scratch when the forecast changes
  • hard constraints can make an instance infeasible
→

Agent, per hour

  • one of 3 actions (or 1 of 1 152 with full routing)
  • one network forward pass, in milliseconds
  • trade-offs are explicit, tunable reward weights

By the numbers

From 194 constraint families to one choice per hour

The reference is the integrated HS + pipeline + TS MILP from the project's modelling deliverable. Its objective is followed by constraints numbered (2) to (194). The agent is trained on the Gymnasium environment in this repository. Both columns cover one 24-hour plan.

Integrated MILP · 24-h plan

Constraint families194
Constraint rows (lower bound, ×24 periods)≈ 4 600+
Binary variable families25
Binary variables per hour41
Binary variables per plan≈ 980
Continuous variables per plan≈ 4 700
Combinations of binaries per hour241≈ 2·10¹²

RL agent · same 24-h plan

Constraints in the learning problem0explicit
Rules enforced by the simulator138
Binary variables0
Decisions per hour1of 3
Decisions per plan24
Full routing action space9heads · 1 152 combos
Inference cost per decision1forward pass

Where the 193 numbered constraints go

Simulator dynamics · 72 % Action masks · 16 % Action space · 9 % Reward · 4 % (plus the objective)
Goes toMILP constraints (numbering of the integrated model)#
Simulator dynamicsfeeder rates (2–8), transfers (11–18), inventory balance (19–23), capacity (24–28), switch indicators (29–33, 55), backlog (34), demand triggers and consumption windows (36–37, 159–162), discharge/injection rates and conservation (38–42, 48, 51, 54, 60–61, 64, 94), mix-batch interface (71–93), shared feeders, repulping and pulp return (113–120, 127–151), contamination detection (163–192), client inventory (193–194)138
Action masksnew product only into an empty tank (43–47), water separator (56), single stoppage (66–70), storage priority (97–99), transfer activation (100–110), minimum batch length (111–112), 24 h between stops (121), stops framed by water (122–123)30
Action spaceone product per feeder or tank (9–10), one product discharged or injected per hour (49–50, 52–53), water batch and stop exclusivity (63, 65, 95–96), one terminal group per hour (152–158)17
Rewardobjective (1), demand met by tmax (35), wrong-grade volume (57–59), water bounds (62), smooth distribution (124–126)8

How the counts are derived: constraint numbers come from the integrated model. Variable counts assume 2 product grades, 24 hourly periods, 12 client feeders, 4 washery feeders and 4 clients sharing feeders, so they are estimates of model size rather than solver-reported figures. Assigning each constraint to a bucket is my own design choice. The current environment implements a simplified subset of these dynamics (one grade, 5 tank groups). Mix batches, pulp return and contamination are on the roadmap. The DQN reads an 18-feature state into a 256-128-64 network (46 211 weights); the full Gymnasium observation has 455 features.

Formulation

The pipeline as a Markov decision process

State

  • 5 normalised tank levels
  • pipeline contents: 26 slots × {empty, product, water}
  • 12 client backlogs
  • 24-h demand and mine-inflow forecasts
  • sin/cos time of day

Action

Pipeline mode {product, water, stop}, plus head-station source, terminal destination, feeder routing and terminal transfers, defined as a Gymnasium MultiDiscrete space.

Reward

− 1000 · unmet / 100
− 5   if water
− 5   if stop
+ 0.5 per tank in 20–80 %
− 2   per tank < 10 %
− 1   per tank > 95 %

Simulation

An AnyLogic model of the network

I built a fluid-library model of the network in AnyLogic: sources, head-station tanks, a selector that sends water or product into the pipeline, and split terminal tank groups. Batches are colour-coded by grade. It serves as a test bench: schedules produced in Python are replayed in it to check that they hold up in a more detailed model, and the next step is to train the agent on it directly.

3D view: product (red/orange) and water (blue) batches filling the head-station and terminal tank groups.

Open the model on AnyLogic Cloud →

Agents

Three learners and one exact baseline

Baseline

MILP

Pyomo + GLPK. Optimal for one fixed forecast, and the reference every agent is measured against.

Sanity check

Tabular Q-learning

Discretised state, 10 bins per feature. Quick to train on short horizons.

Online

DQN

Written from scratch in NumPy: a 256-128-64 network, a 20k replay buffer, a target network and ε-greedy exploration.

Offline

Conservative Q-Learning

PyTorch. Learns from logged transitions and penalises Q-values for actions not in the data, because nobody lets an agent explore on a real pipeline.

Where it stands

Work in progress, reported honestly

CQL training: Q-loss falls then rises after about 10,000 steps; policy and CQL losses increase steadily
CQL training losses. The Q-loss improves until about 10k steps and then diverges, which is the next thing to fix.

Done

  • Gymnasium environment with the 26-hour transit buffer
  • MILP baseline solved to optimality on a 48-h horizon
  • DQN, CQL and tabular agents, with 26-h schedule export
  • AnyLogic simulation in 2D, 3D and logic views

Next

  • Implement action masking (bucket 03), which is currently reward-only
  • Stabilise CQL: reward scaling, Huber loss, soft target updates
  • Two-grade actions with a wrong-grade penalty
  • Connect AnyLogic as the training environment
  • Benchmark against the MILP: backlog, water, stops, violations, decision time

In one line

The physics goes in the simulator, the logic in the action space, the trade-offs in the reward. The agent only has to act.