Skip to content

Airplane ticket selling MDP formulation

A deliberately simple example: a company sells tickets to a flight. The flight can carry at most 10 passengers, and there are three types of customers:

  • Type 1 customers pay r1 = 3000 euros for a seat
  • Type 2 customers pay r2 = 2000 euros for a seat
  • Type 3 customers pay r3 = 1000 euros for a seat

Seats are sold for 25 days, and the flight leaves on day 26, even if not all seats are sold yet. The goal of the company is to maximize the total payments received, subject to the constraint that each seat can be sold at most once. On each day, exactly one customer arrives. With 40% probability a Type 1 customer tries to buy a seat, with 30% probability a Type 2 customer tries to buy a seat, with 30% probability a Type 3 customer tries to buy a seat. The company decides on each day whether to accept or reject the customer that arrived. Accepted customers pay their associated price and have a seat assigned. Rejected customers pay nothing and don't get a seat assigned. The company cannot revisit decisions once they are made.

The components of the MDP

  1. States (S): The state has only 4 variables: (i) the remaining days until the flight leaves, (ii) the number of remaining seats that can still be offered to customers, (iii) the type of the customer that just arrived (0, 1 or 2) and (iv) the price that this customer is willing to pay (3000, 2000 or 1000).

    We consider 3 types of states to which we can transition: (i) a state after an event (new customer arrival) happened, right before the decision to accept or reject that customer (AWAIT_ACTION), (ii) a state right after a customer is accepted or rejected, before the next customer arrives (AWAIT_EVENT), and (iii) the final state, when no more seats can be sold (FINAL).

  2. Actions (A): The action is simple: sell the seat to the customer or reject the customer.

  3. Randomness / events: On each day, exactly one customer arrives, the type of which is random. In the code the type distribution is a DiscreteDist over the type indices, and the event draws from its precomputed AliasSampler — the idiomatic way to sample a fixed discrete distribution in DynaPlex.

  4. Transitions:

    • When we are in the AWAIT_EVENT state and a new customer arrives, the state transitions to AWAIT_ACTION.
    • When we are in the AWAIT_ACTION state and a customer is accepted or rejected, the state transitions to AWAIT_EVENT.
    • No more changes after the state becomes FINAL.
  5. Costs (C): The rewards of selling a seat against the different prices.

Note

DynaPlex is costs based, so for this MDP we will denote negative costs, which are equivalent to positive rewards.

Policy

A closely related concept to MDPs are policies. A policy is a function that maps a state to an action.

Policy (π): Apart from the RL algorithms available through DynaPlex, you can supply your own policy, which you could use as a benchmark.

For this MDP we will implement a simple rule-based benchmark:

  1. When there are more than 5 seats left, we sell to all customers.
  2. When there are 1 to 5 seats and 9 or fewer days remaining, we sell to Type 1 and Type 2 customers.
  3. When there are between 1 and 5 seats and 10 or more days remaining, we sell only to Type 1 customers.
  4. When there are no seats remaining, we cannot sell to anybody.

Python code

You can download a complete Python implementation of this MDP example: airplane_mdp_example.py.

The file contains, in order: the State and MDP classes with the transition functions, a rule-based benchmark policy, a featurizer (the class that defines the state representation used as neural-network input — declared separately from the MDP itself), and driver code that first walks through a single episode step by step (useful for validating a model), then evaluates the policy over many episodes with the PolicyComparer, and optionally trains a PPO agent and compares it against the rule-based policy on common random numbers.

Const MDPs and policies

The MDP and the rule-based policy are declared with @const_dataclass: their fields (prices, the customer-type sampler, thresholds) never change once constructed. This is what allows the compiled engine to share one MDP and policy across its worker worlds. PolicyComparer defaults to backend="auto", which silently falls back to plain Python when a model does not compile; pass backend="engine" while developing to be told exactly what the compiler objects to.

Catch interface mistakes statically with pyright

The driver code calls assert_mdp(mdp) and assert_policy_for_mdp(mdp, policy). These do nothing at runtime, but they let a type checker verify that your classes have the members and method signatures DynaPlex expects. Running pyright airplane_mdp_example.py thus detects many modelling mistakes (a missing category field, a wrongly typed transition function) statically — before anything is run or compiled. More generally, pyright flags most code that is not valid DynaML; see the language reference.

Beyond the cost: keeping your own statistics

Every transition function receives a context — the trajectory's random stream, cumulative_cost and time_elapsed. PolicyComparer reports the cost, but a study usually wants more: how many customers of each type were accepted, how revenue is spread over the selling days, whether the flight sold out. You get that by declaring your own context class with a field per statistic, updating it inside the transition functions where the information is already at hand, and reading the per-trajectory arrays back from assessment.stats. The advanced guide Custom trajectory statistics extends this very model that way.

Solve it exactly

The state space of this model is small — 660 decision states on the instance below — so the exact solver computes the rule-based policy's expected revenue without simulation noise and finds the optimal policy, which then runs in the PolicyComparer like any other:

solver = dp.ExactSolver(mdp)
print(solver.evaluate(policy))          # expected total cost -25074.7 (revenue 25 075)
opt = solver.solve(warm_start=policy)   # expected total cost -28769.2 (revenue 28 769)
exact_policy = opt.get_policy()

Below is the full code for reference:

airplane_mdp_example.py
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
"""
This demonstrates the definition of an MDP and a policy in DynaPlex:
1. Defining an MDP in DynaML
2. Defining a policy in DynaML
3. Validating the MDP and policy
4. Training a policy with PPO
"""

from __future__ import annotations

from dataclasses import dataclass
from typing import Final

import numpy as np
from numpy.typing import NDArray

import dynaplex as dp
from dynaplex.modelling import (
    Featurizer,
    AliasSampler,
    DiscreteDist,
    GlobalStateWriter,
    HorizonType,
    StateCategory,
    TrajectoryContext,
    Validity,
    assert_mdp,
    assert_policy_for_mdp,
    const_dataclass,
    featurizer,
    new_context,
)
from dynaplex.validation import mdp, policy


# ============================================================================
# MDP Definition
# ============================================================================

@dataclass(slots=True)
class State:
    """
    State representation for the airplane MDP.
    """
    remaining_days: int
    remaining_seats: int
    customer_type: int
    price_offered_per_seat: int
    # this member must always be defined on any dynaplex MDP state:
    category: StateCategory = StateCategory.AWAIT_EVENT


@mdp
@const_dataclass(init=False, slots=True)
class AirplaneMDP:
    """
    Airplane ticket selling MDP.

    Actions:
        0: Reject customer
        1: Accept customer (sell seat)
    """    
    # MDP configuration (instance attributes, no defaults). The MDP is a
    # const_dataclass: its fields are fixed for the lifetime of the MDP.
    initial_days: int
    initial_seats: int
    prices_per_customer_type: NDArray[np.int64]   # 1-D by default; use Array2D etc. for more dimensions
    average_price: float
    customer_type_dist: DiscreteDist       # distribution over customer types
    customer_type_sampler: AliasSampler    # O(1) draws from customer_type_dist
    num_actions: int
    horizon_type: HorizonType

    def __init__(
        self,
        initial_days: int,
        initial_seats: int,
        prices_per_customer_type: list[int],
        customer_type_probs: list[float],
    ):
        """
        Initialize the Airplane MDP with validation.

        Args:
            initial_days: Number of days in selling period (must be > 0)
            initial_seats: Flight capacity (must be > 0)
            prices_per_customer_type: List of prices for each customer type (all must be > 0)
            customer_type_probs: Probability distribution over customer types (must sum to 1.0)

        Raises:
            ValueError: If any validation checks fail
        """
        # NOTE:  __init__ on the MDP class itself is never called by the dynaplex compiler, so we can use any valid cpython code here
        #  but the class must be a dataclass, and other functions need to be valid  DynaML code.  

        # Validating parameters
        assert initial_days > 0 and initial_seats > 0
        assert prices_per_customer_type and all(price > 0 for price in prices_per_customer_type)
        assert customer_type_probs and len(customer_type_probs) == len(prices_per_customer_type)
        assert all(prob >= 0 for prob in customer_type_probs) and np.isclose(sum(customer_type_probs), 1.0, atol=1e-6)

        # Set attributes
        #NOTE: ensure all attributes are set that are part of the annotation!
        self.initial_days = initial_days
        self.initial_seats = initial_seats
        self.prices_per_customer_type = np.array(prices_per_customer_type)
        self.average_price = sum(prices_per_customer_type) / len(prices_per_customer_type)
        # A DiscreteDist over the type indices 0, 1, 2, ... and a precomputed
        # alias sampler for it: drawing a customer type is then O(1), and the
        # same sampler code runs in CPython and in the compiled engine.
        self.customer_type_dist = DiscreteDist.custom(customer_type_probs)
        self.customer_type_sampler = self.customer_type_dist.alias_sampler()

        # number of actions in the MDP that are potentially valid. 
        self.num_actions = 2  # 0: Reject, 1: Accept
        self.horizon_type = HorizonType.FINITE

        # Discover the number of features; should be called last in __init__. 

    def get_initial_state(self, context: TrajectoryContext) -> State:
        """
        Generates and returns an initial state of the MDP.

        Args:
            context.rng: NumPy random generator to support random initial state.
        """
        # NOTE: function get_initial_state and any functions that it calls must be valid DynaML code.
        return State(
            remaining_days=self.initial_days,
            remaining_seats=self.initial_seats,
            customer_type=0,
            price_offered_per_seat=0,
            category=StateCategory.AWAIT_EVENT,
        )

    def modify_state_with_event(self, state: State, context: TrajectoryContext) -> None:
        """
        Generate a (customer arrival) event and modify state in place.

        Args:
            state: Current state (modified in place)
            context: Trajectory context containing rng and cumulative_cost
        """
        # NOTE: function modify_state_with_event and any functions that it calls must be valid DynaML code.

        # Draw the type of the arriving customer from the alias sampler using the
        # trajectory's event stream, then look up the price that type pays.
        state.customer_type = self.customer_type_sampler.sample(context.rng)
        state.price_offered_per_seat = int(self.prices_per_customer_type[state.customer_type])

        # Next, the agent must decide whether to accept or reject the customer.
        state.category = StateCategory.AWAIT_ACTION        
        # time elapsed increases by 1 (do this in every modify_state_with_event unless you know what you are doing):
        context.time_elapsed += 1

    def modify_state_with_action(self, state: State, context: TrajectoryContext, action: int) -> None:
        """
        Apply an action to the state (modify in place).

        Args:
            state: Current state (modified in place)
            context: Trajectory context containing cumulative_cost (updated in place)
            action: Action to apply to the state
        """
        # NOTE: this function (and any functions that it calls) must be valid DynaML code.

        # NOTE: do _not_ attempt to generate random numbers here. Any random transitions must happen 
        # in modify_state_with_event, using the rng parameter passed in there. 

        assert state.remaining_days > 0, "No selling days left"
        state.remaining_days -= 1


        if action == 0:
            # Reject customer
            # No cost, so cumulative_cost remains unchanged
            state.price_offered_per_seat = 0

        elif action == 1:
            assert state.remaining_seats > 0, "Cannot accept customer: no seats available"
            # Accept customer ; sell the seat:
            state.remaining_seats -= 1            
            # Use a cost-based formulation (cost = -reward),    
            # hence we should update cumulative cost as follows:
            context.cumulative_cost -= state.price_offered_per_seat
            # Reset the price offered per seat to 0, awaiting the next event. 
            state.price_offered_per_seat = 0

        else:
            assert False, f"Invalid action: Must be 0 (reject) or 1 (accept)"

         # After processing action, we await the next event - customer arrival. 
        if state.remaining_days == 0:
            state.category = StateCategory.FINAL
        else:
            state.category = StateCategory.AWAIT_EVENT


    def write_action_validity(self, state: State, valid: Validity) -> None:
        """
        Write action validity: valid[i] = True  if action i is allowed in the current state
                               valid[i] = False otherwise. 

        Args:
            state: Current state
            valid: Boolean array of length num_actions to write the validity mask to
        """
        # NOTE: function write_action_validity must be valid DynaML code.
        valid.set(0, True)                       # Reject is always allowed. 
        valid.set(1, state.remaining_seats > 0)  # Can accept only if seats available

        # at least one action must be valid. When in doubt, consider adding:
        # assert np.any(valid), "No valid actions"


# ============================================================================
# Policy Definition
# ============================================================================

@policy
@const_dataclass(slots=True)
class SimplePolicy:
    """
    Simple rule-based policy for the airplane MDP. This policy adheres to the DynaPlex DSL.

    This policy uses threshold-based rules to decide when to accept or reject customers.
    Like the MDP it is a const_dataclass: its parameters never change while it is
    evaluated, which lets the compiled engine share it across worker worlds.
    """
    mdp: AirplaneMDP
    seat_threshold: int = 5
    days_threshold: int = 9
    min_price_low_days: int = 2000
    min_price_high_days: int = 3000

    def get_action(self, state: State) -> int:
        """
        Determine which action to take given the current state. Simple heuristic policy.


        # NOTE: this function must be valid DynaML code.
        Args:
            state: Current state

        Returns:
            Action (0=reject, 1=accept)
        """
        if state.remaining_seats == 0:
            return 0

        # Rule 1: More than seat_threshold seats left
        elif state.remaining_seats > self.seat_threshold:
            return 1

        # Rule 2: 1-seat_threshold seats and <= days_threshold remaining
        elif state.remaining_days <= self.days_threshold and state.price_offered_per_seat >= self.min_price_low_days:
            return 1

        # Rule 3: 1-seat_threshold seats and > days_threshold remaining
        elif state.remaining_days > self.days_threshold and state.price_offered_per_seat >= self.min_price_high_days:
            return 1
        else:
            return 0


# ============================================================================
# Featurizer — state representation OUTSIDE the MDP
# ============================================================================

@featurizer
@dataclass(slots=True)
class AirplaneFeaturizer(Featurizer):
    """Featurizer: writer fields declare the representation, write_features fills one
    batch row through them. @featurizer derives the FeatureHolder class (attached as
    AirplaneFeaturizer.Holder) and synthesizes the bind/reset/finish field-walks —
    hand-writing them remains possible."""
    mdp: Final[AirplaneMDP]
    v: Final[GlobalStateWriter]

    def write_features(self, state: State) -> None:
        # NOTE: must be valid DynaML code.
        self.v.append(state.remaining_days / self.mdp.initial_days)
        self.v.append(state.remaining_seats / self.mdp.initial_seats)
        self.v.append(state.price_offered_per_seat / self.mdp.average_price)

    # The observation spec (gym's observation_space analog) is auto-generated:
    # @featurizer synthesizes a spec() method that sizes each writer field by
    # counting the writes on a probe state. Declaring spec() by hand is possible
    # when you want the observation space stated explicitly.


# ============================================================================
# Validation: Manual Simulation
# ============================================================================

def simulate_episode(mdp: AirplaneMDP, policy: SimplePolicy, *, seed: int = 42) -> None:
    """
    Simulate a single episode to validate MDP implementation.

    Useful for debugging and validating your MDP before training.
    """     
    context = new_context(mdp, seed)   # the trajectory's streams + bookkeeping, seeded
    state = mdp.get_initial_state(context)

    step = 0
    print("=" * 80)
    print("DETAILED SIMULATION (Single Episode for MDP & policy validation)")
    print(f"Initial state: {state}")
    print("-" * 80)

    while state.category != StateCategory.FINAL:
        if state.category == StateCategory.AWAIT_EVENT:
            mdp.modify_state_with_event(state, context)
            print(f"  State after event: {state}")

        elif state.category == StateCategory.AWAIT_ACTION:
            # Apply policy and set action on context
            action = policy.get_action(state)
            mdp.modify_state_with_action(state, context, action)
            print(f"Step {step}: ACTION {action} -> State after action: {state}")
            step += 1

        else:
            raise RuntimeError(f"Unexpected state category: {state.category}")

    print("-" * 80)
    print(f"Episode finished: {step} steps, total revenue: €{-context.cumulative_cost:.0f}")



def main() -> None:
    """Run airplane MDP simulation example."""
    # Create MDP with standard configuration
    mdp = AirplaneMDP(
        initial_days=25,
        initial_seats=10,
        prices_per_customer_type=[3000, 2000, 1000],
        customer_type_probs=[0.4, 0.3, 0.3],
    )

    # Create policy with default parameters
    policy = SimplePolicy(mdp=mdp)  


    # No-ops at runtime; they make pyright statically verify that the MDP and
    # policy satisfy the interfaces DynaPlex expects.
    assert_mdp(mdp)
    assert_policy_for_mdp(mdp, policy)
    # Run single simulation with detailed output
    simulate_episode(mdp, policy, seed=42)



    num_simulations = 10000
    print("\n" + "=" * 80)
    print(f"PERFORMANCE EVALUATION ({num_simulations} Episodes)")
    print("=" * 80)

    # PolicyComparer runs the episodes on the compiled engine (falling back to
    # plain Python automatically if a policy cannot be compiled).
    comparer = dp.PolicyComparer(mdp, number_of_trajectories=num_simulations, seed=0)
    assessment = comparer.assess(policy)

    # Costs are negative revenues, so profit = -cost.
    print(f"Number of simulations: {num_simulations}")
    print(f"Average profit: €{-assessment.mean:.2f}")
    print(f"Standard error of the mean: €{assessment.error:.2f}")
    print(f"Min profit: €{-np.max(assessment.returns):.2f}")
    print(f"Max profit: €{-np.min(assessment.returns):.2f}")
    print("=" * 80)


# ============================================================================
# PPO Training Example
# ============================================================================

def train_ppo_airplane() -> None:
    """Train a PPO policy for the airplane MDP."""
    # dp.PPO and dp.MLP load torch on first use: this file stays importable without it.

    # Create MDP
    initial_days = 25
    mdp = AirplaneMDP(
        initial_days=initial_days,
        initial_seats=10,
        prices_per_customer_type=[3000, 2000, 1000],
        customer_type_probs=[0.4, 0.3, 0.3],
    )

    # Create baseline policy for comparison
    policy = SimplePolicy(mdp=mdp)

    # Configure PPO trainer
    config = dp.PPOConfig(
        seed=42,
        device="cpu",
        num_envs=100,
        total_timesteps=100000,
        num_steps=2 * initial_days,
        minibatch_size=64,
        lr=2.5e-4,
    )

    # Train policy. Artifacts land in dynaplex_runs/; if the workdir was
    # already trained, train() loads and returns the stored agent instead
    # of retraining.
    ppo = dp.PPO(
        mdp,
        features=AirplaneFeaturizer,
        config=config,
        network=dp.MLP(hidden=(128, 128)),
    )
    print("Training policy...")
    trained_policy = ppo.train()
    print("Training completed!")

    # Compare with baseline
    print("=" * 80)
    print("POLICY COMPARISON (Note: PPO does not easily beat the simple policy in this example)")
    print("=" * 80)
    # Both policies see the same random streams (common random numbers), so the
    # delta columns are paired differences with tight standard errors.
    comparer = dp.PolicyComparer(mdp, number_of_trajectories=1000, seed=0)
    results = comparer.compare({"simple rule": policy, "trained (PPO)": trained_policy})
    print(results)
    print("=" * 80)



if __name__ == "__main__":
    main()
    # once a model is validated, you could consider training a policy:
    train_ppo_airplane()