Skip to content

Loading models from NPY files

Anders Reenberg Andersen edited this page Nov 13, 2026 · 6 revisions

MDPSolver can read the rewards and the transition probabilities from NumPy's .npy files. mdp() reads the files straight into MDPSolver's C++ core, a block of rows at a time, so the model is never held in Python, and the memory used is that of the model in the solver, also when the model is large. Writing the files needs only NumPy.

The format

The files hold the elementwise format, with one row per entry:

  • Rewards: One row per state and action, [state, action, reward].
  • Transition probabilities: One row per non-zero probability, [from_state, action, to_state, probability].

Each file holds one 2D NumPy array, as np.save writes it. The rows may come in any order, and the states may have different numbers of actions. The files are given to the same arguments as comma-separated files, rewardsFromFile and tranMatFromFile. A filename ending in .npy is read as an .npy file.

A small example

The model of the Quick start guide: Three states with two actions each.

import numpy as np
import mdpsolver

#Rewards, one row per state and action: [state,action,reward]
rewards = np.array([[0,0,5],
                    [0,1,-1],
                    [1,0,1],
                    [1,1,-2],
                    [2,0,50],
                    [2,1,0]])

#Transition probabilities, one row per non-zero probability:
#[from_state,action,to_state,probability]
transitions = np.array([[0,0,0,0.9],
                        [0,0,1,0.1],
                        [0,1,0,0.1],
                        [0,1,1,0.9],
                        [1,0,0,0.4],
                        [1,0,1,0.5],
                        [1,0,2,0.1],
                        [1,1,0,0.3],
                        [1,1,1,0.5],
                        [1,1,2,0.2],
                        [2,0,0,0.2],
                        [2,0,1,0.2],
                        [2,0,2,0.6],
                        [2,1,0,0.5],
                        [2,1,1,0.5]])

#Save the arrays as NPY files
np.save("rewards.npy", rewards)
np.save("transitions.npy", transitions)

#Load the files and solve the model
mdl = mdpsolver.model()
mdl.mdp(discount=0.8,
        rewardsFromFile="rewards.npy",
        tranMatFromFile="transitions.npy")
mdl.solve()
print(mdl.getPolicy())
#[1 1 0]

A large model, built piece by piece

A model can be written to the files a block of rows at a time, so that it is never held in memory as a whole while it is built. np.lib.format.open_memmap creates an .npy file with its final shape, and the rows are then filled in like those of an array. The example below builds a model with one million states, two actions in each state and ten next states for each state and action: 20 million transition probabilities, in a file of 640 MB.

import numpy as np
import mdpsolver

nStates = 1_000_000  #number of states
nActions = 2         #actions in each state
nNext = 10           #next states of each state and action
rng = np.random.default_rng(1)

#Create the NPY files with their final shapes. The arrays live in the files,
#so the model is never held in memory as a whole.
nPairs = nStates * nActions
rewards = np.lib.format.open_memmap("rewards.npy", mode="w+",
                                    dtype=np.float64, shape=(nPairs, 3))
transitions = np.lib.format.open_memmap("transitions.npy", mode="w+",
                                        dtype=np.float64, shape=(nPairs * nNext, 4))

#Fill in the rows, 10,000 states at a time
chunk = 10_000
for first in range(0, nStates, chunk):
    states = np.arange(first, min(first + chunk, nStates))

    #The state-action pairs of these states
    s = np.repeat(states, nActions)
    a = np.tile(np.arange(nActions), len(states))
    pairs = slice(first * nActions, first * nActions + len(s))

    #Rewards: [state,action,reward]
    rewards[pairs] = np.column_stack([s, a, rng.normal(size=len(s))])

    #Transition probabilities: [from_state,action,to_state,probability]
    #Each pair moves to one of the nNext states that follow it
    nextStates = (s[:, None] + np.arange(nNext)) % nStates
    probs = rng.random((len(s), nNext))
    probs /= probs.sum(axis=1, keepdims=True)
    rows = slice(pairs.start * nNext, pairs.stop * nNext)
    transitions[rows] = np.column_stack([np.repeat(s, nNext),
                                         np.repeat(a, nNext),
                                         nextStates.ravel(),
                                         probs.ravel()])

#Write everything to the files and close them
rewards.flush()
transitions.flush()
del rewards, transitions

#Load the files and solve the model
mdl = mdpsolver.model()
mdl.mdp(discount=0.9,
        rewardsFromFile="rewards.npy",
        tranMatFromFile="transitions.npy")
mdl.solve()
print(mdl.getPolicy()[:10])

Notes

  • The arrays may hold float64 numbers (NumPy's default for numbers with decimals), float32, int64 or int32. Transition probabilities in a float32 file are kept as float32 (see Classes and methods).
  • The rewards and the transition probabilities may come in different formats, e.g. the rewards as an array and the transition probabilities from an .npy file.
  • Other software can write .npy files too, e.g. R (RcppCNPy), Julia (NPZ.jl), MATLAB (npy-matlab) and C++ (cnpy).
  • mdp() stops with an error if a file is not an .npy file of a 2D array with enough columns (three for the rewards, four for the transition probabilities; further columns are ignored), or if a row holds a negative index or an index that is not a whole number. Archives of several arrays (.npz, from np.savez) are not read: save each array to an .npy file of its own.
  • File names that do not end in .npy are read as comma-separated files (see the Quick start guide).

Clone this wiki locally