MarkovCorrelation.java

  1. package org.opentrafficsim.road.gtu.generator;

  2. import java.util.ArrayList;
  3. import java.util.LinkedHashMap;
  4. import java.util.LinkedHashSet;
  5. import java.util.List;
  6. import java.util.Locale;
  7. import java.util.Map;
  8. import java.util.Set;

  9. import org.djutils.exceptions.Throw;

  10. import nl.tudelft.simulation.jstats.streams.StreamInterface;

  11. /**
  12.  * Markov Chain functionality using state auto-correlations. Rather than specifying a Transition Matrix, this matrix is
  13.  * calculated from a steady-state and from given auto-correlations. Auto-correlation increases the probability that state S
  14.  * returns after state S. Correlation between states can be captured with grouping several states under a super state. This
  15.  * creates a Transition Matrix within a cell of a Transition Matrix. To the super matrix, this is simply a single
  16.  * state-supplying element, applicable to all previous states that are concerned within the element.<br>
  17.  * <br>
  18.  * This class is oblivious to intensity data of the states, in the sense that it must be provided to draw the next state. This
  19.  * class actually only remembers state auto-correlations. Together with input intensities, a part of the Transition Matrix is
  20.  * calculated on the fly. This flexibility over a fixed Transition Matrix allows 1) dynamic intensities, and 2) a single object
  21.  * of this class to be used for multiple processes in which intensities differ, but correlations are equal. This class is
  22.  * therefore also fairly flexible in terms of which states are concerned. Only states with correlation need to be added. For any
  23.  * state included in the input, for which no correlation is defined, a correlation of 0 is assumed. Reversely, states that are
  24.  * included in the class, but that are not part of the input states, are ignored.
  25.  * <p>
  26.  * Copyright (c) 2013-2024 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
  27.  * BSD-style license. See <a href="https://opentrafficsim.org/docs/license.html">OpenTrafficSim License</a>.
  28.  * </p>
  29.  * @author <a href="https://github.com/averbraeck">Alexander Verbraeck</a>
  30.  * @author <a href="https://github.com/peter-knoppers">Peter Knoppers</a>
  31.  * @author <a href="https://github.com/wjschakel">Wouter Schakel</a>
  32.  * @param <S> state type
  33.  * @param <I> intensity type
  34.  */
  35. public class MarkovCorrelation<S, I extends Number>
  36. {

  37.     /** Leaf node for each state present in the Markov Chain, including in all sub-groups. */
  38.     private Map<S, FixedState<S, I>> leaves = new LinkedHashMap<>();

  39.     /** Transition Matrix for each super state, i.e. the matrix within which states are put that have the given super state. */
  40.     private Map<S, TransitionMatrix<S, I>> superMatrices = new LinkedHashMap<>();

  41.     /** Matrix in which each state is located. */
  42.     private Map<S, TransitionMatrix<S, I>> containingMatrices = new LinkedHashMap<>();

  43.     /** Root matrix. */
  44.     private TransitionMatrix<S, I> root = new TransitionMatrix<>(null, 0.0); // input not important, it's for sub-groups

  45.     /**
  46.      * Adds a state to the root group of the Markov Chain. The correlation increases the chance that the state will occur after
  47.      * itself. We have: <br>
  48.      *
  49.      * <pre>
  50.      * p_ii = ss_i + (1 - ss_i) * c_i {eq. 1}
  51.      * </pre>
  52.      *
  53.      * where,
  54.      *
  55.      * <pre>
  56.      *   p_ii: the probability state i returns after state i
  57.      *   ss_i: the steady-state (overall mean) probability of state i
  58.      *   c_i:  correlation of state i
  59.      * </pre>
  60.      *
  61.      * Effective correlations of states depend on correlations of other states as well, so the given correlation is not
  62.      * guaranteed to result. One can easily see this from a system with 2 states: A and B. Suppose B has correlation. In order
  63.      * to maintain the same overall steady-state (occurrence proportion of A and B), it follows that state A also must be seen
  64.      * more frequently to follow itself.
  65.      *
  66.      * <pre>
  67.      * not correlated:  A B B A A A B A A A B A A B B
  68.      * very correlated: A A A A A A A A A B B B B B B (all B's grouped together, hence all A's grouped together and correlated)
  69.      * </pre>
  70.      *
  71.      * The effective correlation <i>c_i</i> of any state <i>i</i> can be calculated by reversing equation {@code eq. 1} using
  72.      * for <i>p_ii</i> the effective value after all correlations are applied. The procedure to derive the various probabilities
  73.      * from state <i>i</i> to state <i>j</i> (<i>p_ij</i>) is explained below. The procedure is based on the transition matrix
  74.      * <i>T</i>, in which each value gives the probability that the state changes from <i>i</i> (the row) to state <i>j</i> (the
  75.      * column). Consequently, the values in each row must sum to 1, as each state will be followed by another state.<br>
  76.      * <br>
  77.      * It is important that the transition matrix <i>T</i> results in a steady-state as provided. In particular we have for
  78.      * steady state <i>S</i> that <b><i>S</i>*<i>T</i> &#61; <i>S</i></b> should hold. Suppose we have <i>S</i> &#61; [0.7, 0.2,
  79.      * 0.1] for states A, B and C. Without any correlation this would give the base transition matrix:
  80.      *
  81.      * <pre>
  82.      *     | p_11  p_12  p_13 |   | 0.70  0.20  0.10 |
  83.      * T = | p_21  p_22  p_23 | = | 0.70  0.20  0.10 |
  84.      *     | p_31  p_32  p_33 |   | 0.70  0.20  0.10 |
  85.      * </pre>
  86.      *
  87.      * Our steady-state results as for whatever the previous state was, the steady-state probabilities are applied. Now suppose
  88.      * that state C has a correlation of 0.4. This would give that <i>p_33</i> :&#61; <i>p_33</i> + (1 - <i>p_33</i>) * <i>c</i>
  89.      * &#61; 0.46. With this increased value, the probabilities of row 3 no longer add up to 1. Hence, <i>p_31</i> and
  90.      * <i>p_32</i> should be reduced. However, we require that the same steady-state <i>S</i> is maintained. This will remain
  91.      * the case for as long as <i>T</i> remains a <i>reversible</i> Markov Chain. This means that each state has as much input
  92.      * probability, as it has output probability. A matrix where, except for the values on the diagonal, all column values are
  93.      * equal, is reversible. So the base <i>T</i> without correlation is reversible, and we only need to maintain reversibility.
  94.      * A method to maintain reversibility is to <i>scale symmetric pairs</i>. Hence, if we reduce <i>p_32</i>, we should reduce
  95.      * <i>p_23</i> by the same <i>factor</i>. Forcing row 3 to sum to 1, and scaling <i>p_31</i>, <i>p_13</i>, <i>p_32</i> and
  96.      * <i>p_23</i> by the same factor 0.6 we obtain the third matrix below.
  97.      *
  98.      * <pre>
  99.      *      | 0.70  0.20  0.10 |    | 0.70  0.20  0.10 |    | 0.70  0.20  0.06 |    | 0.74  0.20  0.06 |
  100.      * T =&gt; | 0.70  0.20  0.10 | =&gt; | 0.70  0.20  0.10 | =&gt; | 0.70  0.20  0.06 | =&gt; | 0.70  0.24  0.06 |
  101.      *      | 0.70  0.20  0.10 |    | 0.70  0.20  0.46 |    | 0.42  0.12  0.46 |    | 0.42  0.12  0.46 |
  102.      * </pre>
  103.      *
  104.      * As we reduce <i>p_13</i> and <i>p_23</i>, we also reduce the probability sums of rows 1 and 2. These reductions can be
  105.      * compensated by increasing the values on the diagonals, as is done in the fourth matrix. Note that changing the diagonal
  106.      * values does not affect reversibility. For example, 0.7*0.74 + 0.2*0.70 + 0.1*0.42 &#61; 0.7 for the first column.<br>
  107.      * <br>
  108.      * Changing the diagonal values <i>p_11</i> and <i>p_22</i> as the result of correlation for state C, shows that correlation
  109.      * of one state automatically introduces correlation at other states, as should also intuitively occur from the A-B example.
  110.      * The procedure can be started with the base <i>T</i> from steady-state <i>S</i> and can be repeated for each state
  111.      * <i>i</i> with correlation:
  112.      * <ol>
  113.      * <li>Increase <i>p_ii</i> to <i>p_ii</i> + (1-<i>p_ii</i>) * <i>c_i</i>.</li>
  114.      * <li>Reduce <i>p_ij</i> for all <i>j</i> unequal to <i>i</i> such that row <i>i</i> sums to 1, use one factor <i>f</i> for
  115.      * all.</li>
  116.      * <li>Reduce <i>p_ji</i> for all <i>j</i> unequal to <i>i</i> to maintain reversibility. Use factor <i>f</i> again.</li>
  117.      * <li>Set all <i>p_jj</i> for all <i>j</i> unequal to <i>i</i> such that row <i>j</i> sums to 1.</li>
  118.      * </ol>
  119.      * Knowing that each value <i>p_ij</i> gets reduced for correlation of state <i>i</i> and <i>j</i>, and realizing that the
  120.      * reduction factors <i>f</i> equal (1 - <i>c_i</i>) and (1 - <i>c_j</i>) respectively, the effective correlation can be
  121.      * calculated by adding all reductions in a row to the diagonal value <i>p_ii</i> and using {@code eq. 1}.<br>
  122.      * <br>
  123.      * See also "Construction of Transition Matrices of Reversible Markov Chains" by Qian Jiang.
  124.      * @param state state
  125.      * @param correlation correlation
  126.      * @throws IllegalArgumentException if correlation is not within the range (-1 ... 1), or the state is already defined
  127.      * @throws NullPointerException if state is null
  128.      */
  129.     public synchronized void addState(final S state, final double correlation)
  130.     {
  131.         Throw.whenNull(state, "State may not be null.");
  132.         Throw.when(this.leaves.containsKey(state), IllegalArgumentException.class, "State %s already defined.", state);
  133.         Throw.when(correlation <= -1.0 || correlation >= 1.0, IllegalArgumentException.class,
  134.                 "Correlation at root level need to be in the range (-1 ... 1).");
  135.         FixedState<S, I> node = new FixedState<>(state, correlation);
  136.         this.root.addNode(state, node);
  137.         this.containingMatrices.put(state, this.root);
  138.         this.leaves.put(state, node);
  139.     }

  140.     /**
  141.      * Adds a state to the group of the Markov Chain indicated by a super state. If the super state is not yet placed in a
  142.      * sub-group, the sub-group is created. Grouping is useful to let a set of states correlate to any other of the states in
  143.      * the set. For example, after state A, both states A and B can occur with some correlation, while state C is not correlated
  144.      * to states A and B. The same correlation is applied when the previous state was B, as it is also part of the same group.
  145.      * <br>
  146.      * <br>
  147.      * To explain sub-groups, suppose we have the following 3-state matrix in which the super state <i>s_2</i> is located (this
  148.      * can be the root matrix, or any sub-matrix). In this matrix, state <i>s_2</i> is replaced by a matrix <i>S_2</i>.
  149.      *
  150.      * <pre>
  151.      *       s_1   s_2   s_3             s_1   S_2   s_3
  152.      * s_1 | p_11  p_12  p_13 |    s_1 | p_11  p_12  p_13 |
  153.      * s_2 | p_21  p_22  p_23 | =&gt; S_2 | p_21  p_22  p_23 |
  154.      * s_3 | p_31  p_32  p_33 |    s_3 | p_31  p_32  p_33 |
  155.      * </pre>
  156.      *
  157.      * From the level of this matrix, nothing changes. Whenever the prior state was any of those inside <i>S_2</i>, row 2 is
  158.      * applied to determine the next state. If the next state is matrix <i>S_2</i>, the state is further specified by
  159.      * <i>S_2</i>. Matrix <i>S_2</i> itself will be:
  160.      *
  161.      * <pre>
  162.      *       s_2   s_4
  163.      * s_2 | p_22' p_24 |
  164.      * s_4 | p_42  p_44 |
  165.      * </pre>
  166.      *
  167.      * It will thus result in either state <i>s_2</i> or state <i>s_4</i>. More states can now be added to <i>S_2</i>, using the
  168.      * same super state <i>s_2</i>. In case the prior state was either <i>s_1</i> or <i>s_3</i>, i.e. no state included in the
  169.      * sub-group, the matrix of the sub-group defaults to fractions based on the steady-state only. Correlations are then also
  170.      * ignored.<br>
  171.      * <br>
  172.      * Correlation of <i>s_2</i> is applied to the whole group, and all other states of the group can be seen as sub-types of
  173.      * the group's super state. Correlations as considered inside the group (<i>c'_2</i> and <i>c'_4</i>) are mapped from the
  174.      * range <i>c_2</i> to 1. So, <i>c'_2</i> = 0, meaning that within the group there is no further correlation for the super
  175.      * state. Sub states, who are required to have an equal or larger correlation than the super state of the group, map
  176.      * linearly between <i>c_2</i> and 1.<br>
  177.      * <br>
  178.      * If the super state is only a virtual layer that should not in itself be a valid state of the system, it can simply be
  179.      * excluded from obtaining a new state using {@code getState()}.<br>
  180.      * <br>
  181.      * @param superState state of group
  182.      * @param state state to add
  183.      * @param correlation correlation
  184.      * @throws IllegalArgumentException if correlation is not within the range (0 ... 1), the state is already defined, or
  185.      *             superState is not yet a state
  186.      * @throws NullPointerException if an input is null
  187.      */
  188.     public synchronized void addState(final S superState, final S state, final double correlation)
  189.     {
  190.         Throw.whenNull(superState, "Super-state may not be null.");
  191.         Throw.whenNull(state, "State may not be null.");
  192.         Throw.when(this.leaves.containsKey(state), IllegalArgumentException.class, "State %s already defined.", state);
  193.         Throw.when(correlation < 0.0 || correlation >= 1.0, IllegalArgumentException.class,
  194.                 "Correlation at root level need to be in the range (-1 ... 1).");
  195.         if (!this.superMatrices.containsKey(superState))
  196.         {
  197.             // branch the super state in to a matrix
  198.             FixedState<S, I> superOriginal = this.leaves.get(superState);
  199.             // remove original from it's matrix
  200.             TransitionMatrix<S, I> superMatrix = this.containingMatrices.get(superState);
  201.             Throw.when(superMatrix == null, IllegalArgumentException.class, "No state has been defined for super-state %s.",
  202.                     superState);
  203.             superMatrix.removeNode(superState);
  204.             // replace with matrix
  205.             TransitionMatrix<S, I> matrix = new TransitionMatrix<>(superState, superOriginal.getCorrelation());
  206.             superMatrix.addNode(superState, matrix);
  207.             this.superMatrices.put(superState, matrix);
  208.             // add original node to that matrix
  209.             superOriginal.clearCorrelation();
  210.             matrix.addNode(superState, superOriginal);
  211.             this.containingMatrices.put(superState, matrix);
  212.         }
  213.         // add node
  214.         TransitionMatrix<S, I> superMatrix = this.superMatrices.get(superState);
  215.         Throw.when(correlation < superMatrix.getCorrelation(), IllegalArgumentException.class,
  216.                 "Sub states in a group can not have a lower correlation than the super state of the group.");
  217.         FixedState<S, I> node =
  218.                 new FixedState<>(state, (correlation - superMatrix.getCorrelation()) / (1.0 - superMatrix.getCorrelation()));
  219.         superMatrix.addNode(state, node);
  220.         this.containingMatrices.put(state, superMatrix);
  221.         this.leaves.put(state, node);
  222.         // register state as part of matrix node
  223.         this.root.registerInGroup(superState, state);
  224.         for (TransitionMatrix<S, I> matrix : this.superMatrices.values())
  225.         {
  226.             if (matrix.getState() != superState)
  227.             {
  228.                 matrix.registerInGroup(superState, state);
  229.             }
  230.         }
  231.     }

  232.     /**
  233.      * Draws a next state from this Markov Chain process, with predefined state correlations, but dynamic intensities. Any
  234.      * states that are present in the underlying Transition Matrix, but not present in the given states, are ignored. States
  235.      * that are not present in the underlying Transition Matrix, are added to it with a correlation of 0.
  236.      * @param previousState previous state
  237.      * @param states set of states to consider
  238.      * @param steadyState current steady-state intensities of the states
  239.      * @param stream to draw random numbers
  240.      * @return next state
  241.      * @throws IllegalArgumentException if number of states is not the same as the stead-state length
  242.      * @throws NullPointerException if states, steadyState or stream is null
  243.      */
  244.     public synchronized S drawState(final S previousState, final S[] states, final I[] steadyState,
  245.             final StreamInterface stream)
  246.     {
  247.         Throw.whenNull(states, "States may not be null.");
  248.         Throw.whenNull(steadyState, "Steady-state may not be null.");
  249.         Throw.whenNull(stream, "Stream for random numbers may not be null.");
  250.         Throw.when(states.length != steadyState.length, IllegalArgumentException.class,
  251.                 "Number of states should match the length of the steady state.");
  252.         for (FixedState<S, I> node : this.leaves.values())
  253.         {
  254.             node.clearIntensity();
  255.         }
  256.         int n = states.length;
  257.         for (int i = 0; i < n; i++)
  258.         {
  259.             S state = states[i];
  260.             FixedState<S, I> leaf = this.leaves.get(state);
  261.             if (leaf == null)
  262.             {
  263.                 addState(state, 0.0);
  264.                 leaf = this.leaves.get(state);
  265.             }
  266.             leaf.setIntensity(steadyState[i]);
  267.         }
  268.         return this.root.drawState(previousState, stream);
  269.     }

  270.     @Override
  271.     public String toString()
  272.     {
  273.         return "MarkovCorrelation [ " + this.root + " ]";
  274.     }

  275.     /**
  276.      * Base class for elements inside a Markov {@code TransitionMatrix}.
  277.      * <p>
  278.      * Copyright (c) 2013-2024 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved.
  279.      * <br>
  280.      * BSD-style license. See <a href="https://opentrafficsim.org/docs/license.html">OpenTrafficSim License</a>.
  281.      * </p>
  282.      * @author <a href="https://github.com/averbraeck">Alexander Verbraeck</a>
  283.      * @author <a href="https://github.com/peter-knoppers">Peter Knoppers</a>
  284.      * @author <a href="https://github.com/wjschakel">Wouter Schakel</a>
  285.      * @param <S> state type
  286.      * @param <I> intensity type
  287.      */
  288.     private abstract static class MarkovNode<S, I extends Number>
  289.     {

  290.         /** State. */
  291.         private final S state;

  292.         /** Correlation. */
  293.         private double correlation;

  294.         /**
  295.          * Constructor.
  296.          * @param state state
  297.          * @param correlation correlation
  298.          */
  299.         MarkovNode(final S state, final double correlation)
  300.         {
  301.             this.state = state;
  302.             this.correlation = correlation;
  303.         }

  304.         /**
  305.          * Returns the encapsulated state, which is either a fixed state, or the super-state of a group.
  306.          * @return encapsulated state, which is either a fixed state, or the super-state of a group
  307.          */
  308.         final S getState()
  309.         {
  310.             return this.state;
  311.         }

  312.         /**
  313.          * Returns the correlation.
  314.          * @return correlation
  315.          */
  316.         final double getCorrelation()
  317.         {
  318.             return this.correlation;
  319.         }

  320.         /**
  321.          * Clears the correlation.
  322.          */
  323.         protected final void clearCorrelation()
  324.         {
  325.             this.correlation = 0.0;
  326.         }

  327.         /**
  328.          * Returns the current intensity, used for the Markov Chain process.
  329.          * @return current intensity, used for the Markov Chain process, 0.0 if no intensity was provided
  330.          */
  331.         abstract double getIntensity();

  332.         /**
  333.          * Returns a state from this node, which is either a fixed state, or a randomly drawn state from a sub-group.
  334.          * @param previousState previous state
  335.          * @param stream to draw random numbers
  336.          * @return state from this node, which is either a fixed state, or a randomly drawn state from a sub-group
  337.          */
  338.         abstract S drawState(S previousState, StreamInterface stream);

  339.     }

  340.     /**
  341.      * Transition matrix with functionality to return a next state, and to entail a set of fixed states mixed with matrices for
  342.      * sub-groups.
  343.      * <p>
  344.      * Copyright (c) 2013-2024 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved.
  345.      * <br>
  346.      * BSD-style license. See <a href="https://opentrafficsim.org/docs/license.html">OpenTrafficSim License</a>.
  347.      * </p>
  348.      * @author <a href="https://github.com/averbraeck">Alexander Verbraeck</a>
  349.      * @author <a href="https://github.com/peter-knoppers">Peter Knoppers</a>
  350.      * @author <a href="https://github.com/wjschakel">Wouter Schakel</a>
  351.      * @param <S> state type
  352.      * @param <I> intensity type
  353.      */
  354.     private static final class TransitionMatrix<S, I extends Number> extends MarkovNode<S, I>
  355.     {

  356.         /** List of state-defining states, where sub-groups are defined by a set of state. */
  357.         private List<Set<S>> states = new ArrayList<>();

  358.         /** List of nodes (fixed state or sub-group matrix). */
  359.         private List<MarkovNode<S, I>> nodes = new ArrayList<>();

  360.         /**
  361.          * Constructor.
  362.          * @param state super state representing the sub-group, or {@code null} for the root matrix.
  363.          * @param correlation correlation for the sub-group, or any value for the root matrix.
  364.          */
  365.         TransitionMatrix(final S state, final double correlation)
  366.         {
  367.             super(state, correlation);
  368.         }

  369.         /**
  370.          * Adds a node to the matrix.
  371.          * @param state state of the node
  372.          * @param node node
  373.          */
  374.         void addNode(final S state, final MarkovNode<S, I> node)
  375.         {
  376.             Set<S> set = new LinkedHashSet<>();
  377.             set.add(state);
  378.             this.states.add(set);
  379.             this.nodes.add(node);
  380.         }

  381.         /**
  382.          * Registers the state to belong to the group of super-state. This is used such that the matrix knows which previous
  383.          * states to map to the group.
  384.          * @param superState super-state of the group
  385.          * @param state state inside the group
  386.          */
  387.         void registerInGroup(final S superState, final S state)
  388.         {
  389.             for (Set<S> set : this.states)
  390.             {
  391.                 if (set.contains(superState))
  392.                 {
  393.                     set.add(state);
  394.                     return;
  395.                 }
  396.             }
  397.         }

  398.         /**
  399.          * Removes the node from the matrix, including group registration. This is used to replace a state with a group.
  400.          * @param state state to remove
  401.          */
  402.         void removeNode(final S state)
  403.         {
  404.             int i = -1;
  405.             for (int j = 0; j < this.states.size(); j++)
  406.             {
  407.                 if (this.states.get(j).contains(state))
  408.                 {
  409.                     i = j;
  410.                     break;
  411.                 }
  412.             }
  413.             if (i > -1)
  414.             {
  415.                 this.states.remove(i);
  416.                 this.nodes.remove(i);
  417.             }
  418.         }

  419.         /**
  420.          * Returns a state from this matrix. This is done by calculating the row of the Markov Transition Chain for the given
  421.          * previous state, and using those probabilities to draw an output state.
  422.          * @param previousState previous state
  423.          * @param stream to draw random numbers
  424.          * @return state from this matrix
  425.          * @see MarkovCorrelation#addState(Object, double) algorithm for calculating the Transition Matrix
  426.          */
  427.         @Override
  428.         S drawState(final S previousState, final StreamInterface stream)
  429.         {
  430.             // figure out whether this matrix contains the previous state, and if so the correlation factor and row number i
  431.             boolean contains = false;
  432.             int n = this.states.size();
  433.             double intensitySum = 0.0;
  434.             int i = 0;
  435.             double iFactor = 1.0;
  436.             for (int j = 0; j < n; j++)
  437.             {
  438.                 intensitySum += this.nodes.get(j).getIntensity();
  439.                 if (this.states.get(j).contains(previousState))
  440.                 {
  441.                     i = j;
  442.                     contains = true;
  443.                     iFactor = 1.0 - this.nodes.get(i).getCorrelation();
  444.                 }
  445.             }
  446.             // gather probabilities and apply correlation factors
  447.             double[] p = new double[n];
  448.             double pSum = 0.0;
  449.             for (int j = 0; j < n; j++)
  450.             {
  451.                 if (i != j || !contains)
  452.                 {
  453.                     MarkovNode<S, I> node = this.nodes.get(j);
  454.                     double jFactor = 1.0;
  455.                     if (contains)
  456.                     {
  457.                         jFactor = 1.0 - node.getCorrelation();
  458.                     }
  459.                     p[j] = jFactor * iFactor * node.getIntensity() / intensitySum;
  460.                     pSum += p[j];
  461.                 }
  462.             }
  463.             // correct to get row sum = 1.0 by changing the diagonal value
  464.             if (contains)
  465.             {
  466.                 p[i] = 1.0 - pSum;
  467.             }
  468.             // make probabilities cumulative
  469.             for (int j = 1; j < n; j++)
  470.             {
  471.                 p[j] = p[j - 1] + p[j];
  472.             }
  473.             // draw
  474.             double r = stream.nextDouble();
  475.             for (int j = 0; j < n; j++)
  476.             {
  477.                 if (r < p[j])
  478.                 {
  479.                     return this.nodes.get(j).drawState(previousState, stream);
  480.                 }
  481.             }
  482.             throw new RuntimeException("Unexpected error while drawing state from matrix.");
  483.         }

  484.         /**
  485.          * Returns the current intensity, used for the Markov Chain process, as the sum of matrix elements.
  486.          * @return current intensity, used for the Markov Chain process, 0.0 if no intensity was provided
  487.          */
  488.         @Override
  489.         double getIntensity()
  490.         {
  491.             double intensity = 0;
  492.             for (MarkovNode<S, I> node : this.nodes)
  493.             {
  494.                 intensity += node.getIntensity();
  495.             }
  496.             return intensity;
  497.         }

  498.         @Override
  499.         public String toString()
  500.         {
  501.             String superType = this.getState() == null ? "" : "(" + this.getState() + ")";
  502.             String statesStr = "";
  503.             String sep = "";
  504.             for (MarkovNode<S, I> node : this.nodes)
  505.             {
  506.                 statesStr += sep + node;
  507.                 sep = ", ";
  508.             }
  509.             return "T" + superType + "[ " + statesStr + " ]";
  510.         }
  511.     }

  512.     /**
  513.      * Container for a fixed state. Each state is reflected in a single object of this class. They are grouped in matrices,
  514.      * possibly all in the root. Subsets of all states may be grouped in a matrix, but no state is present in more than one
  515.      * matrix.
  516.      * <p>
  517.      * Copyright (c) 2013-2024 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved.
  518.      * <br>
  519.      * BSD-style license. See <a href="https://opentrafficsim.org/docs/license.html">OpenTrafficSim License</a>.
  520.      * </p>
  521.      * @author <a href="https://github.com/averbraeck">Alexander Verbraeck</a>
  522.      * @author <a href="https://github.com/peter-knoppers">Peter Knoppers</a>
  523.      * @author <a href="https://github.com/wjschakel">Wouter Schakel</a>
  524.      * @param <S> state type
  525.      * @param <I> intensity type
  526.      */
  527.     private static final class FixedState<S, I extends Number> extends MarkovNode<S, I>
  528.     {

  529.         /** Intensity. */
  530.         private I intensity;

  531.         /**
  532.          * Constructor.
  533.          * @param state state
  534.          * @param correlation correlation
  535.          */
  536.         FixedState(final S state, final double correlation)
  537.         {
  538.             super(state, correlation);
  539.         }

  540.         /**
  541.          * Returns the state.
  542.          * @param previousState previous state
  543.          * @param stream to draw random numbers
  544.          * @return the state
  545.          */
  546.         S drawState(final S previousState, final StreamInterface stream)
  547.         {
  548.             return getState();
  549.         }

  550.         /**
  551.          * Sets the current intensity.
  552.          * @param intensity intensity
  553.          */
  554.         void setIntensity(final I intensity)
  555.         {
  556.             this.intensity = intensity;
  557.         }

  558.         /**
  559.          * Clears the intensity.
  560.          */
  561.         void clearIntensity()
  562.         {
  563.             this.intensity = null;
  564.         }

  565.         @Override
  566.         double getIntensity()
  567.         {
  568.             return this.intensity == null ? 0.0 : this.intensity.doubleValue();
  569.         }

  570.         @Override
  571.         public String toString()
  572.         {
  573.             return String.format(Locale.US, "%s(%.2f)", getState(), getCorrelation());
  574.         }
  575.     }

  576. }