"""
generate_random_node_spacings.py

This module uses the Dirichlet distribution to generate a set of "almost equal"
node spacings. It divides up the given length into N segments of roughly
equal, but not exactly equal, length. This more closely resembles a realistic
installation scenario.

Please see https://en.wikipedia.org/wiki/Dirichlet_distribution#String_cutting
for an example of how the Dirichlet distribution is used.

.. moduleauthor:: Scott Griffiths <stgriffi@ra.rockwell.com>
"""

import numpy as np


def generate_random_spacings(nodes, length=25, alpha=2):
    """
    Generates random spacing according to Dirichlet distribution.

    The Dirichlet alpha parameter sets how close spacings are to 1/N; higher
    alpha values are more evenly spaced, while lower alpha values are less
    evenly spaced (more random). This algorithm defaults to alpha = 2.

    The length parameter defines the total length of the cable (default = 25 m).
    The spacings generated by this function will always sum to the specified
    length.
    """
    if not length:
        length = 25
    dirichlet_spacings = length*np.random.dirichlet(alpha*np.ones(nodes-1))
    while np.min(dirichlet_spacings) < MIN_NODE_SPACING:
        dirichlet_spacings = length*np.random.dirichlet(alpha*np.ones(nodes-1))
        alpha += 1
    return dirichlet_spacings/Vp
