
    3j                   r   d Z ddlmZ ddlmZ ddlmZ ddlZddlZddl	Z
ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ  ej&                  d      Z G d dej*                        Z G d dej*                        Zeeez  eedz  edz  eedz  f   Zd Zd Z G d dej>                        Z  G d dejB                        Z" G d dejB                  ejF                        Z$ G d dej>                        Z% G d d      Z& G d de&      Z'e&e$e"gZ(e)d k(  rddlZ ejT                          yy)!a  
An IntervalNetwork defines a scale or harmonic unit as a (weighted)
digraph, or directed graph, where pitches are nodes and intervals are
edges. Nodes, however, are not stored; instead, an ordered list of edges
(Intervals) is provided as an archetype of adjacent nodes.

IntervalNetworks are unlike conventional graphs in that each graph must
define a low and high terminus. These points are used to create a cyclic
graph and are treated as point of cyclical overlap.

IntervalNetwork permits the definition of conventional octave repeating
scales or harmonies (abstract chords), non-octave repeating scales and
chords, and ordered interval sequences that might move in multiple
directions.

A scale or harmony may be composed of one or more IntervalNetwork objects.

Both nodes and edges can be weighted to suggest tonics, dominants,
finals, or other attributes of the network.

Changed in v8: nodeId and nodeName standardized.  TERMINUS and DIRECTION
are now Enums.
    )annotations)OrderedDict)SequenceN)common)environment)exceptions21)interval)note)pitch)prebasezscale.intervalNetworkc                  $    e Zd ZdZdZdZd Zd Zy)TerminuszU
    One of the two Termini of a scale, either Terminus.LOW or
    Terminus.HIGH
    terminusLowterminusHighc                     d| j                   z   S Nz	Terminus.nameselfs    J/DATA/.local/lib/python3.12/site-packages/music21/scale/intervalNetwork.py__repr__zTerminus.__repr__<       TYY&&    c                     d| j                   z   S r   r   r   s    r   __str__zTerminus.__str__?   r   r   N)__name__
__module____qualname____doc__LOWHIGHr   r    r   r   r   r   4   s     CD''r   r   c                  (    e Zd ZdZdZdZdZd Zd Zy)	Directionz
    An enumerated Direction for a scale, either Direction.ASCENDING,
    Direction.DESCENDING, or Direction.BI (bidirectional)
    bi	ascending
descendingc                     d| j                   z   S Nz
Direction.r   r   s    r   r   zDirection.__repr__K       dii''r   c                     d| j                   z   S r*   r   r   s    r   r   zDirection.__str__N   r+   r   N)	r   r   r   r    BI	ASCENDING
DESCENDINGr   r   r#   r   r   r%   r%   B   s"     
BIJ((r   r%   c                4    | |kD  ryt        | |z
        dk  ryy)z0
    check if a > b or abs(a - b) < epsilon
    Th㈵>Fabsabs     r   _gter7   V   $     	1u	QUg	r   c                4    | |k  ryt        | |z
        dk  ryy)z0
    check if a < b or abs(a - b) < epsilon
    Tr1   Fr2   r4   s     r   _lter:   a   r8   r   c                      e Zd Zy)EdgeExceptionNr   r   r   r#   r   r   r<   r<   l       r   r<   c                      e Zd ZdZdej
                  f	 d
dZd Zd Z	 d	 	 	 	 	 ddZ	d Z
	 d	 	 	 ddZedd	       Zy)Edgea6  
    Abstraction of an Interval as an Edge.

    Edges store an Interval object as well as a pathway direction specification.
    The pathway is the route through the network from terminus to terminus,
    and can either by ascending or descending.

    For directed Edges, the direction of the Interval may be used to
    suggest non-pitch ascending movements (even if the pathway direction is ascending).

    Weight values, as well as other attributes, can be stored.

    >>> i = interval.Interval('M3')
    >>> e = scale.intervalNetwork.Edge(i)
    >>> e.interval is i
    True
    >>> e.direction
    Direction.BI

    Return the stored Interval object

    >>> i = interval.Interval('M3')
    >>> e1 = scale.intervalNetwork.Edge(i, id=0)
    >>> n1 = scale.intervalNetwork.Node(id=0, degree=0)
    >>> n2 = scale.intervalNetwork.Node(id=1, degree=1)
    >>> e1.addDirectedConnection(n1, n2, scale.Direction.ASCENDING)
    >>> e1.interval
    <music21.interval.Interval M3>

    Return the direction of the Edge.

    >>> i = interval.Interval('M3')
    >>> e1 = scale.intervalNetwork.Edge(i, id=0)
    >>> n1 = scale.intervalNetwork.Node(id=0, degree=0)
    >>> n2 = scale.intervalNetwork.Node(id=1, degree=1)
    >>> e1.addDirectedConnection(n1, n2, scale.Direction.ASCENDING)
    >>> e1.direction
    Direction.ASCENDING
    Nc                    t        |t              rt        j                  |      }n|}|| _        || _        d| _        || _        g | _        y )N      ?)
isinstancestrr	   Interval	directionweightid_connections)r   intervalDatarH   rF   is        r   __init__zEdge.__init__   sK     lC(!!,/AA+,$- FHr   c                d    t        || j                        xr | j                  |j                  k(  S )aY  
        >>> i1 = interval.Interval('M3')
        >>> i2 = interval.Interval('M3')
        >>> i3 = interval.Interval('m3')
        >>> e1 = scale.intervalNetwork.Edge(i1)
        >>> e2 = scale.intervalNetwork.Edge(i2)
        >>> e3 = scale.intervalNetwork.Edge(i3)
        >>> e1 == e2
        True
        >>> e1 == e3
        False
        )rC   	__class____dict__r   others     r   __eq__zEdge.__eq__   s,     5$..1 4MMU^^3	5r   c                f    | j                    d| j                  j                   d| j                  S )N )rF   r	   r   rI   r   s    r   _reprInternalzEdge._reprInternal   s0    ..!4==#5#5"6a8I8I7LMMr   c                :   t        |t        t        f      r|}n|j                  }t        |t        t        f      r|}n|j                  }| j                  j                  ||f       |t        j                  t        j                  fvrt        d      || _
        y)a  
        Provide two Node objects that are connected by this Edge,
        in the direction from the first to the second.

        When calling directly, a direction, either
        ascending or descending, should be set here;
        this will override whatever the interval is.
        If None, this will not be set.

        >>> i = interval.Interval('M3')
        >>> e1 = scale.intervalNetwork.Edge(i, id=0)

        >>> n1 = scale.intervalNetwork.Node(id=0, degree=0)
        >>> n2 = scale.intervalNetwork.Node(id=1, degree=1)

        >>> e1.addDirectedConnection(n1, n2, scale.Direction.ASCENDING)
        >>> e1.connections
        [(0, 1)]
        >>> e1
        <music21.scale.intervalNetwork.Edge Direction.ASCENDING M3 [(0, 1)]>
        zmust request a directionN)rC   r   intrH   rI   appendr%   r.   r/   r<   rF   )r   node1node2rF   n1Idn2Ids         r   addDirectedConnectionzEdge.addDirectedConnection   s    8 eh_-D88Deh_-D88D  $. Y00)2F2FGG :;;"r   c                    | j                  ||t        j                         | j                  ||t        j                         t        j                  | _        y)a_  
        Provide two Edge objects that pass through
        this Node, in the direction from the first to the second.

        >>> i = interval.Interval('M3')
        >>> e1 = scale.intervalNetwork.Edge(i, id=0)
        >>> n1 = scale.intervalNetwork.Node(id=scale.Terminus.LOW, degree=0)
        >>> n2 = scale.intervalNetwork.Node(id=1, degree=1)

        >>> e1.addBiDirectedConnections(n1, n2)
        >>> e1.connections
        [(Terminus.LOW, 1), (1, Terminus.LOW)]
        >>> e1
        <music21.scale.intervalNetwork.Edge Direction.BI M3
            [(Terminus.LOW, 1), (1, Terminus.LOW)]>
        N)r]   r%   r.   r/   r-   rF   )r   rY   rZ   s      r   addBiDirectedConnectionszEdge.addBiDirectedConnections   s?    $ 	""5%1D1DE""5%1E1EF"r   c                   || j                   }| j                   |k(  r| j                  S |t        j                  k(  r7| j                   t        j                  t        j
                  fv rt        d      |t        j                  t        j
                  fv rc| j                   t        j                  k(  rF|t        j                  k(  r| j                  d   gS |t        j
                  k(  r| j                  d   gS g S )aP  
        Callable as a property (.connections) or as a method
        (.getConnections(direction)):

        Return a list of connections between Nodes, represented as pairs
        of Node ids. If a direction is specified, and if the Edge is
        directional, only the desired directed values will be returned.

        >>> i = interval.Interval('M3')
        >>> e1 = scale.intervalNetwork.Edge(i, id=0)
        >>> n1 = scale.intervalNetwork.Node(id=scale.Terminus.LOW, degree=1)
        >>> n2 = scale.intervalNetwork.Node(id=1, degree=2)

        >>> e1.addBiDirectedConnections(n1, n2)
        >>> e1.connections
        [(Terminus.LOW, 1), (1, Terminus.LOW)]
        >>> e1.getConnections(scale.Direction.ASCENDING)
        [(Terminus.LOW, 1)]
        >>> e1.getConnections(scale.Direction.DESCENDING)
        [(1, Terminus.LOW)]
        z3cannot request a bi direction from a mono directionr      )rF   rI   r%   r-   r.   r/   r<   )r   rF   s     r   getConnectionszEdge.getConnections  s    2 I >>Y&$$$ %NNy':':I<P<P&QQ UVV )--y/C/CDDNNill2
 I///))!,--i222))!,--	r   c                "    | j                         S N)rb   r   s    r   connectionszEdge.connections8  s    ""$$r   )rJ   zinterval.Interval | strrd   )rY   Node | int | TerminusrZ   rf   returnNone)rF   zNone | Directionrg   +list[tuple[int | Terminus, int | Terminus]])rg   ri   )r   r   r   r    r%   r-   rL   rR   rU   r]   r_   rb   propertyre   r#   r   r   r@   r@   p   s    &V $<<H4H&5 N 	+# +# !+#
 
+#Z&0 %)2!2 
12j % %r   r@   c                  0    e Zd ZdZdZdd	dZd Zd Zd Zy)
Nodea\  
    Abstraction of an unrealized Pitch Node.

    The Node `id` is used to store connections in Edges and has no real meaning.

    Terminal Nodes have special ids: Terminus.LOW, Terminus.HIGH

    The Node `degree` is translated to scale degrees in various applications,
    and is used to request a pitch from the network.

    The `weight` attribute is used to probabilistically select between
    multiple nodes when multiple nodes satisfy either a branching option in a pathway
    or a request for a degree.

    TODO: replace w/ NamedTuple; eliminate id, and have a terminus: low, high, None
    rH   degreerG   c                .    || _         || _        || _        y rd   rm   )r   rH   rn   rG   s       r   rL   zNode.__init__R  s     !# "#r   c                ^    | j                   | j                  | j                  f}t        |      S rd   )rH   rn   rG   hash)r   	hashTuples     r   __hash__zNode.__hash__]  s$    WWdkk4;;7	Ir   c                0    t        |       t        |      k(  S )aG  
        Nodes are equal if everything in the object.__slots__ is equal.

        >>> n1 = scale.intervalNetwork.Node(id=3, degree=1)
        >>> n2 = scale.intervalNetwork.Node(id=3, degree=1)
        >>> n3 = scale.intervalNetwork.Node(id=2, degree=1)
        >>> n1 == n2
        True
        >>> n1 == n3
        False
        >>> n2.weight = 2.0
        >>> n1 == n2
        False

        >>> n4 = scale.intervalNetwork.Node(id=scale.Terminus.LOW, degree=1)
        >>> n5 = scale.intervalNetwork.Node(id=scale.Terminus.LOW, degree=1)
        >>> n4 == n5
        True
        )rq   rP   s     r   rR   zNode.__eq__a  s    ( DzT%[((r   c                     d| j                   S )Nzid=rH   r   s    r   rU   zNode._reprInternalw  s    TWWK  r   N)rB   )rH   zTerminus | intrn   rW   rG   float)	r   r   r   r    	__slots__rL   rs   rR   rU   r#   r   r   rl   rl   =  s"      +I	$),!r   rl   c                      e Zd Zy)IntervalNetworkExceptionNr=   r#   r   r   rz   rz   |  r>   r   rz   c                  0   e Zd ZU dZ	 	 	 	 d;	 d<dZd Zd Zd<dZd Zd	 Z	d
 Z
d Zed        Zed        Zed        Zed=d       Zed        Zd>d?dZd Zd Zd@dZddd	 dAdZd Zd Zej4                  dd	 dBdZej8                  dddd	 	 	 	 	 	 	 	 	 dCdZdd	 	 	 	 	 	 	 	 	 	 	 	 	 dDd Z	 	 	 dEddd!	 	 	 	 	 	 	 	 	 dFd"Z	 	 	 dEddddd#	 	 	 	 	 	 	 dGd$Z dddej8                  ddf	 	 	 	 	 	 	 	 	 dHd%Z!dddej8                  ddf	 	 	 	 	 	 	 	 	 	 	 dId&Z"dddej8                  ddf	 	 	 	 	 	 	 	 	 dJd'Z#	 	 dK	 	 	 	 	 dLd(Z$	 	 dK	 	 	 	 	 dLd)Z%dd*ddej8                  df	 	 	 	 	 	 	 	 	 dMd+Z&d,ej8                  dd-	 	 	 	 	 	 	 	 	 dNd.Z'ej8                  df	 	 	 	 	 	 	 dOd/Z(d,ej8                  df	 	 	 	 	 dPd0Z)ej8                  ddddf	 	 	 	 	 dQd1Z*e+	 	 	 	 dRd2       Z,	 	 dS	 dTd4Z-d3ddej8                  df	 	 	 dUd5Z.d6Z/d7e0d8<   	 	 	 dVd9Z1	 	 	 	 	 	 dWd:Z2y)XIntervalNetworkat  
    A graph of undefined Pitch nodes connected by a defined,
    ordered list of :class:`~music21.interval.Interval` objects as edges.

    An `octaveDuplicating` boolean, if defined, can be used
    to optimize pitch realization routines.

    The `deterministic` boolean, if defined, can be used to declare that there
    is no probabilistic or multi-pathway segments of this network.

    The `pitchSimplification` method specifies how to simplify the pitches
    if they spiral out into double and triple sharps, etc.  The default is
    'maxAccidental' which specifies that each note can have at most one
    accidental; double-flats and sharps are not allowed.  The other choices
    are 'simplifyEnharmonic' (which also converts C-, F-, B#, and E# to
    B, E, C, and F respectively, see :meth:`~music21.pitch.Pitch.simplifyEnharmonic`),
    'mostCommon' (which adds to simplifyEnharmonic the requirement that the
    most common accidental forms be used, so A# becomes B-, G- becomes
    F#, etc. the only ambiguity allowed is that both G# and A- are acceptable),
    and None (or 'none') which does not do any simplification.
    FTc                    d| _         d| _        t               | _        t               | _        |r| j                  |       || _        || _        || _        t               | _	        t               | _
        y )Nr   )edgeIdCountnodeIdCountr   edgesnodesfillBiDirectedEdgesoctaveDuplicatingdeterministicpitchSimplification_ascendingCache_descendingCache)r   edgeListr   r   r   s        r   rL   zIntervalNetwork.__init__  sw      7Bm
 7Bm
$$X. "3* $7  M 	 M 	r   c                    d| _         d| _        t               | _        t               | _        t               | _        t               | _        y)z7
        Remove and reset all Nodes and Edges.
        r   N)r~   r   r   r   r   r   r   r   s    r   clearzIntervalNetwork.clear  s:      ]
 ]
*} +r   c                v    t        || j                        sydD ]  }t        | |      t        ||      k7  s y y)a  

        >>> edgeList1 = ['M2', 'M2', 'm2', 'M2', 'M2', 'M2', 'm2']
        >>> edgeList2 = ['M2', 'M2', 'm2', 'M2', 'A3', 'm2']

        >>> net1 = scale.intervalNetwork.IntervalNetwork()
        >>> net1.fillBiDirectedEdges(edgeList1)

        >>> net2 = scale.intervalNetwork.IntervalNetwork()
        >>> net2.fillBiDirectedEdges(edgeList1)

        >>> net3 = scale.intervalNetwork.IntervalNetwork()
        >>> net3.fillBiDirectedEdges(edgeList2)

        >>> net1 == net2
        True
        >>> net1 == net3
        False
        F)r~   r   r   r   r   r   r   T)rC   rN   getattr)r   rQ   attrs      r   rR   zIntervalNetwork.__eq__  sA    , %0RDtT"geT&::R r   c                l   | j                          d}t        t        j                  |      }|dz  }|| j                  |j
                  <   |}t        |      D ]  \  }}|t        |      dz
  k  r4t        | j                  |      }| xj                  dz  c_        |dz  }|}nt        t        j                  |      }	|	}|| j                  |j
                  <   t        || j                        }
|
| j                  |
j
                  <   | xj                  dz  c_        |
j                  ||       |} y)a  
        Given an ordered list of bi-directed edges given as :class:`~music21.interval.Interval`
        specifications, create and define appropriate Nodes. This
        assumes that all edges are bi-directed and all edges are in order.

        >>> edgeList = ['M2', 'M2', 'm2', 'M2', 'M2', 'M2', 'm2']
        >>> net = scale.intervalNetwork.IntervalNetwork()
        >>> net.nodes
        OrderedDict()
        >>> net.edges
        OrderedDict()

        >>> net.fillBiDirectedEdges(edgeList)
        >>> net.nodes
        OrderedDict([(Terminus.LOW, <music21.scale.intervalNetwork.Node id=Terminus.LOW>),
                     (0, <music21.scale.intervalNetwork.Node id=0>),
                     (1, <music21.scale.intervalNetwork.Node id=1>),
                     ...
                     (5, <music21.scale.intervalNetwork.Node id=5>),
                     (Terminus.HIGH, <music21.scale.intervalNetwork.Node id=Terminus.HIGH>)])
        >>> net.edges
        OrderedDict([(0, <music21.scale.intervalNetwork.Edge Direction.BI M2
                            [(Terminus.LOW, 0), (0, Terminus.LOW)]>),
                     (1, <music21.scale.intervalNetwork.Edge Direction.BI M2 [(0, 1), (1, 0)]>),
                     (2, <music21.scale.intervalNetwork.Edge Direction.BI m2 [(1, 2), (2, 1)]>),
                     ...
                     (5, <music21.scale.intervalNetwork.Edge Direction.BI M2 [(4, 5), (5, 4)]>),
                     (6, <music21.scale.intervalNetwork.Edge Direction.BI m2
                            [(5, Terminus.HIGH), (Terminus.HIGH, 5)]>)])

        >>> [str(p) for p in net.realizePitch('g4')]
        ['G4', 'A4', 'B4', 'C5', 'D5', 'E5', 'F#5', 'G5']
        >>> net.degreeMin, net.degreeMax
        (1, 8)

        Using another fill method creates a new network

        >>> net.fillBiDirectedEdges(['M3', 'M3', 'M3'])
        >>> [str(p) for p in net.realizePitch('g4')]
        ['G4', 'B4', 'D#5', 'G5']
        >>> net.degreeMin, net.degreeMax
        (1, 4)

        >>> net.fillBiDirectedEdges([interval.Interval('M3'),
        ...                          interval.Interval('M3'),
        ...                          interval.Interval('M3')])
        >>> [str(p) for p in net.realizePitch('c2')]
        ['C2', 'E2', 'G#2', 'B#2']
        ra   rH   rn   rv   N)r   rl   r   r!   r   rH   	enumeratelenr   r"   r@   r~   r   r_   )r   r   degreeCountnLow	nPreviousrK   eNamen
nFollowingnHighes              r   r   z#IntervalNetwork.fillBiDirectedEdges  s   f 	

x||K8q"

477	!(+HAu 3x=1$$D,,[A  A% q 
 kB"
 )3DJJz}}% Ut//0A DJJqtt!&&y*="I/ ,r   c                   | j                          t        |      t        |      k7  rt        d      d}t        t        j
                  |      }|dz  }|| j                  |j                  <   |}t        |      D ]  \  }}|t        |      dz
  k  r4t        | j                  |      }| xj                  dz  c_	        |dz  }|}	nt        t        j                  |      }
|
}	|	| j                  |	j                  <   t        || j                        }|| j                  |j                  <   | xj                  dz  c_        |j                  ||	t        j                          |	} d}| j                  t        j
                     }|dz  }|}t        |      D ]  \  }}|t        |      dz
  k  rMt        | j                  |      }| xj                  dz  c_	        |dz  }|}	|	| j                  |	j                  <   n| j                  t        j                     }
|
}	t        || j                        }|| j                  |j                  <   | xj                  dz  c_        |j                  |	|t        j"                         |	} y)a6  
        Given two lists of edges, one for ascending :class:`~music21.interval.Interval`
        objects and
        another for  descending, construct appropriate Nodes and Edges.

        Note that the descending :class:`~music21.interval.Interval` objects
        should be given in ascending form.
        z*cannot manage unequal sized directed edgesra   r   rv   rF   N)r   r   rz   rl   r   r!   r   rH   r   r   r"   r@   r~   r   r]   r%   r.   r/   )r   ascendingEdgeListdescendingEdgeListr   r   r   rK   r   r   r   r   r   s               r   fillDirectedEdgesz!IntervalNetwork.fillDirectedEdgesL  sM    	

  !S);%<<*+WXXx||K8q"

477	!"34HAu 3()A--D,,[A  A% q 
kB"
 )3DJJz}}% Ut//0A DJJqtt!##Iz.7.A.A $ C #I/ 56 zz(,,'q	!"45HAu 3)*Q..D,,[A  A% q 
,6

:==)

8==1"
 Ut//0A DJJqtt! ##J	YEYEY#Z"I- 6r   c                   | j                          |D ]<  }t        |d   |d         }d|v r
|d   |_        || j                  |j                  <   > d}|D ]  }t        |d   |      }|d   D ]t  \  }}	}
|
t        j                  k(  r-|j                  | j                  |   | j                  |	          G|j                  | j                  |   | j                  |	   |
	       v || j                  |j                  <   |d
z  } y)a9  
        Fill any arbitrary network given node and edge definitions.

        Nodes must be defined by a dictionary of id and degree values.
        There must be a terminusLow and terminusHigh id as string::

            nodes = ({'id': Terminus.LOW, 'degree': 1},
                     {'id': 0, 'degree': 2},
                     {'id': Terminus.HIGH, 'degree': 3},
                    )

        Edges must be defined by a dictionary of :class:`~music21.interval.Interval`
        strings and connections. Values for `id` will be automatically assigned.
        Each connection must define direction and pairs of valid node ids::

            edges = ({'interval': 'm2',
                      'connections': ([Terminus.LOW, 0, Direction.BI],)
                      },
                     {'interval': 'M3',
                      'connections': ([0, Terminus.HIGH, Direction.BI],)
                      },
                    )

        >>> nodes = ({'id': scale.Terminus.LOW, 'degree': 1},
        ...          {'id': 0, 'degree': 2},
        ...          {'id': scale.Terminus.HIGH, 'degree': 3})
        >>> edges = ({'interval': 'm2',
        ...           'connections': ([scale.Terminus.LOW, 0, scale.Direction.BI],)},
        ...          {'interval': 'M3',
        ...           'connections': ([0, scale.Terminus.HIGH, scale.Direction.BI],)},)

        >>> net = scale.intervalNetwork.IntervalNetwork()
        >>> net.fillArbitrary(nodes, edges)
        >>> net.realizePitch('c4', 1)
        [<music21.pitch.Pitch C4>, <music21.pitch.Pitch D-4>, <music21.pitch.Pitch F4>]
        rH   rn   r   rG   r   r	   rv   re   r   ra   N)r   rl   rG   r   rH   r@   r%   r-   r_   r]   r   )r   r   r   nDictr   eIdeDictr   nId1nId2rF   s              r   fillArbitraryzIntervalNetwork.fillArbitrary  s   L 	

EdE(O<A5  ? DJJqtt	  EU:&3/A).})=%dI 	,..tzz$/?DAQR++DJJt,<,0JJt,<	 , S *>  !DJJqtt1HC r   c                   t         j                  dddddddddddddddddddddd	dd	d	dt         j                  d
df
}dt         j                  dt        j                  gfddddt        j                  gfddddt        j                  gfddddt        j                  gfddddt        j
                  gfddddt        j
                  gfdddt         j                  t        j
                  gfddt         j                  d	t        j                  gfddd	dt        j                  gfddddt        j                  gfdf
}| j                  ||       d| _        d| _	        y)a!  
        A convenience routine for testing a complex, bi-directional scale.

        >>> net = scale.intervalNetwork.IntervalNetwork()
        >>> net.fillMelodicMinor()
        >>> [str(p) for p in net.realizePitch('c4')]
        ['C4', 'D4', 'E-4', 'F4', 'G4', 'A4', 'B4', 'C5']
        ra   r   r                        M2)r	   re   m2TN)
r   r!   r"   r%   r-   r.   r/   r   r   r   )r   r   r   s      r   fillMelodicMinorz IntervalNetwork.fillMelodicMinor  s    !2Q'Q'Q'Q'Q'Q'Q'Q' 3 ##+<<ILL"A!C ##$a"6!8 ##$a"6!8 ##$a"6!8 ##$a)<)<"=!? ##$a)<)<"=!? ##$hmmY5H5H"I!K ##+==!Y5I5I"J!L ##$a)=)=">!@ ##$a)=)=">!@7@ 	5%(!%!r   c                    t        t        t        |                  }|D cg c]  }|j                   }}t	        j
                  ||      }||   ||   fS c c}w )a  
        Perform weighted random selection on a parallel list of
        edges and corresponding nodes.

        >>> n1 = scale.intervalNetwork.Node(id=1, degree=1, weight=1000000)
        >>> n2 = scale.intervalNetwork.Node(id=2, degree=1, weight=1)
        >>> e1 = scale.intervalNetwork.Edge(interval.Interval('m3'), id=1)
        >>> e2 = scale.intervalNetwork.Edge(interval.Interval('m3'), id=2)
        >>> net = scale.intervalNetwork.IntervalNetwork()
        >>> e, n = net.weightedSelection([e1, e2], [n1, n2])

        Note: this may fail as there is a slight chance to get 2

        >>> e.id
        1
        >>> n.id
        1
        )listranger   rG   r   weightedSelection)r   r   r   iValuesr   weightsrK   s          r   r   z!IntervalNetwork.weightedSelection  sY    ( uSZ()%*+U188U+$$Wg6Qxq!!	 ,s   Ac                    d}| j                   j                         D ]'  }||j                  }t        ||j                        }) |S )a   
        Return the lowest degree value.

        >>> edgeList = ['M2', 'M2', 'm2', 'M2', 'M2', 'M2', 'm2']
        >>> net = scale.intervalNetwork.IntervalNetwork()
        >>> net.fillBiDirectedEdges(edgeList)
        >>> net.degreeMin
        1
        N)r   valuesrn   minr   xr   s      r   	degreeMinzIntervalNetwork.degreeMin-  E     ""$AyHH188$	 %
 r   c                    d}| j                   j                         D ]'  }||j                  }t        ||j                        }) |S )a.  
        Return the largest degree value.

        >>> edgeList = ['M2', 'M2', 'm2', 'M2', 'M2', 'M2', 'm2']
        >>> net = scale.intervalNetwork.IntervalNetwork()
        >>> net.fillBiDirectedEdges(edgeList)
        >>> net.degreeMax    # returns eight, as this is the last node
        8
        N)r   r   rn   maxr   s      r   	degreeMaxzIntervalNetwork.degreeMax@  r   r   c                    d}| j                   j                         D ]>  \  }}|t        j                  k(  r||j                  })t        ||j                        }@ |S )aQ  
        Return the largest degree value that represents a pitch level
        that is not a terminus of the scale.

        >>> edgeList = ['M2', 'M2', 'm2', 'M2', 'M2', 'M2', 'm2']
        >>> net = scale.intervalNetwork.IntervalNetwork()
        >>> net.fillBiDirectedEdges(edgeList)
        >>> net.degreeMaxUnique
        7
        N)r   itemsr   r"   rn   r   )r   r   nIdr   s       r   degreeMaxUniquezIntervalNetwork.degreeMaxUniqueS  sX     jj&&(FChmm#yHH188$ ) r   c                b    g }|j                  | j                  t        j                            |S )a  
        Return a list of first Nodes, or Nodes that contain Terminus.LOW.

        >>> edgeList = ['M2', 'M2', 'm2', 'M2', 'M2', 'M2', 'm2']
        >>> net = scale.intervalNetwork.IntervalNetwork()
        >>> net.fillBiDirectedEdges(edgeList)
        >>> net.terminusLowNodes
        [<music21.scale.intervalNetwork.Node id=Terminus.LOW>]

        Note that this list currently always has one element.
        )rX   r   r   r!   r   posts     r   terminusLowNodesz IntervalNetwork.terminusLowNodesj  s'     DJJx||,-r   c                b    g }|j                  | j                  t        j                            |S )a`  
        Return a list of last Nodes, or Nodes that contain Terminus.HIGH.

        >>> edgeList = ['M2', 'M2', 'm2', 'M2', 'M2', 'M2', 'm2']
        >>> net = scale.intervalNetwork.IntervalNetwork()
        >>> net.fillBiDirectedEdges(edgeList)
        >>> net.terminusHighNodes
        [<music21.scale.intervalNetwork.Node id=Terminus.HIGH>]
        )rX   r   r   r"   r   s     r   terminusHighNodesz!IntervalNetwork.terminusHighNodes|  s'     DJJx}}-.r   c                   t               }| j                  j                         D ]d  \  }}|rN|t        j                  k(  r+| j                  t        j
                     j                  ||<   F|j                  ||<   V|j                  ||<   f |S )a^  
        Return a dictionary of node-id, node-degree pairs.
        The same degree may be given for each node

        There may not be an unambiguous way to determine the degree.
        Or, a degree may have different meanings when ascending or descending.

        If `equateTermini` is True, the terminals will be given the same degree.
        )r   r   r   r   r"   r!   rn   )r   equateTerminir   r   r   s        r   getNodeDegreeDictionaryz'IntervalNetwork.getNodeDegreeDictionary  sr     0;}jj&&(FC(--' $

8<< 8 ? ?DI !DIHHS	 ) r   c                ,    | j                         }||   S )z
        Given a strict node id (the .id attribute of the Node), return the degree.

        There may not be an unambiguous way to determine the degree.
        Or, a degree may have different meanings when ascending or descending.
        )r   )r   r   nodeSteps      r   nodeIdToDegreezIntervalNetwork.nodeIdToDegree  s     //1}r   c                r   g }t        |t              r|}|j                  }n| j                  |   }| j                  D ]i  }| j                  |   }|j
                  D ]I  \  }}||k(  r|j                  |j                          F||k(  s.|j                  |j                          i k |st        d|      |S )a-  
        Given a Node id, find all edges associated
        with this node and report on their directions

        >>> net = scale.intervalNetwork.IntervalNetwork()
        >>> net.fillMelodicMinor()
        >>> net.nodeIdToEdgeDirections(scale.Terminus.LOW)
        [Direction.BI]
        >>> net.nodeIdToEdgeDirections(0)
        [Direction.BI, Direction.BI]
        >>> net.nodeIdToEdgeDirections(6)
        [Direction.ASCENDING, Direction.ASCENDING]
        >>> net.nodeIdToEdgeDirections(5)
        [Direction.DESCENDING, Direction.DESCENDING]

        This node has bi-directional (from below),
        ascending (to above), and descending (from above)
        edge connections connections

        >>> net.nodeIdToEdgeDirections(3)
        [Direction.BI, Direction.ASCENDING, Direction.DESCENDING]
        zfailed to match any edges)	rC   rl   rH   r   r   re   rX   rF   rz   )r   r   
collectionnObjr   eObjr   ys           r   nodeIdToEdgeDirectionsz&IntervalNetwork.nodeIdToEdgeDirections  s    . 
c4 D''C::c?D::C::c?D((18%%dnn5#X%%dnn5 )  *+FMMr   c                l    |t        d      | j                  }| j                  }||z
  }|dz
  |z  |z   S )a  
        Return the degree modulus degreeMax - degreeMin.

        >>> edgeList = ['M2', 'M2', 'm2', 'M2', 'M2', 'M2', 'm2']
        >>> net = scale.intervalNetwork.IntervalNetwork()
        >>> net.fillBiDirectedEdges(edgeList)
        >>> net.degreeModulus(3)
        3
        >>> net.degreeModulus(8)
        1
        >>> net.degreeModulus(9)
        2
        >>> net.degreeModulus(0)
        7
        z%Degree of None given to degreeModulusra   )rz   r   r   )r   rn   sMinsMax	spanCounts        r   degreeModuluszIntervalNetwork.degreeModulus  sH      >*+RSS~~~~ 4K	 !y(D00r   )r   permitDegreeModulic                  t        |t              rg }| j                  |      }|j                         D ])  \  }}||k(  s|j	                  | j
                  |          + |sM|rK|j                         D ]8  \  }}| j                  |      |k(  s|j	                  | j
                  |          : |S t        |t              r?|t        j                  k(  r| j                  S |t        j                  k(  r| j                  S yt        |t              r*| j
                  D ]  }| j
                  |   }||u s|gc S  yt        |t              rt        d|d      t        d|       )a  
        The `nodeId` parameter may be a :class:`~music21.scale.intervalNetwork.Node` object,
        a node degree (as a number), a terminus string, or a None (indicating Terminus.LOW).

        Return a list of Node objects that match this identification.

        If `equateTermini` is True, and the name given is a degree number,
        then the first terminal will return both the first and last.

        >>> edgeList = ['M2', 'M2', 'm2', 'M2', 'M2', 'M2', 'm2']
        >>> net = scale.intervalNetwork.IntervalNetwork()
        >>> net.fillBiDirectedEdges(edgeList)
        >>> net.nodeNameToNodes(1)[0]
        <music21.scale.intervalNetwork.Node id=Terminus.LOW>
        >>> net.nodeNameToNodes(scale.Terminus.HIGH)
        [<music21.scale.intervalNetwork.Node id=Terminus.HIGH>]
        >>> net.nodeNameToNodes(scale.Terminus.LOW)
        [<music21.scale.intervalNetwork.Node id=Terminus.LOW>]

        Test using a nodeStep, or an integer nodeName

        >>> net.nodeNameToNodes(1)
        [<music21.scale.intervalNetwork.Node id=Terminus.LOW>,
         <music21.scale.intervalNetwork.Node id=Terminus.HIGH>]
        >>> net.nodeNameToNodes(1, equateTermini=False)
        [<music21.scale.intervalNetwork.Node id=Terminus.LOW>]
        >>> net.nodeNameToNodes(2)
        [<music21.scale.intervalNetwork.Node id=0>]

        With degree moduli, degree zero is the top-most non-terminal
        (since terminals are redundant)

        >>> net.nodeNameToNodes(0)
        [<music21.scale.intervalNetwork.Node id=5>]
        >>> net.nodeNameToNodes(-1)
        [<music21.scale.intervalNetwork.Node id=4>]
        >>> net.nodeNameToNodes(8)
        [<music21.scale.intervalNetwork.Node id=Terminus.LOW>,
         <music21.scale.intervalNetwork.Node id=Terminus.HIGH>]
        )r   zStrings like z are no longer valid nodeIds.zcannot filter by: N)rC   rW   r   r   rX   r   r   r   r!   r   r"   r   rl   rD   rz   )	r   nodeIdr   r   r   r   r   nStepr   s	            r   nodeNameToNodeszIntervalNetwork.nodeNameToNodes  sM   \ fc"D33+ 4 -H&nn.
UU?KK

30 / ."*.."2JC))&1U:DJJsO4 #3 K)%,,,8==(--- )%zzJJsO;3J " $*]6*Da+bcc*-?x+HIIr   c                b   g }g }|j                   }|t        j                  k(  r$|t        j                  k(  rt        j
                  }n6|t        j
                  k(  r#|t        j                  k(  rt        j                  }| j                  D ]W  }| j                  |   }|j                  |      }|s&|D ]-  \  }	}
|	|k(  s|j                  |       |j                  |
       / Y |s&t        j                  d|d|d|g       t        d      |D cg c]  }| j                  |    }}||fS c c}w )a  
        Given a Node, get two lists, one of next Edges, and one of next Nodes,
        searching all Edges to find all matches.

        There may be more than one possibility. If so, the caller must look
        at the Edges and determine which to use

        >>> edgeList = ['M2', 'M2', 'm2', 'M2', 'M2', 'M2', 'm2']
        >>> net = scale.intervalNetwork.IntervalNetwork()
        >>> net.fillBiDirectedEdges(edgeList)
        >>> net.nodeNameToNodes(1)[0]
        <music21.scale.intervalNetwork.Node id=Terminus.LOW>
        	nodeStartrF   postEdgezcould not find any edges)rH   r   r!   r%   r/   r"   r.   r   rb   rX   environLocal
printDebugrz   r   )r   r   rF   r   
postNodeIdsrcIdkr   pairssrcdstr   postNodes                r   getNextzIntervalNetwork.getNextG  s     
 HLL Y)2F2F%FMMEhmm#	Y5H5H(HLLEA

1A$$Y/E!S %<OOA&%%c* "  ##[)[)%/%; < ++EFF 0::zDJJsOz:!! ;s   D,c                  |s|S |j                   |vr|S ||j                      d   }d}||k(  rd}no|t        j                  k(  r%|t        j                  t        j                  fv rd}n7|t        j                  t        j                  fv r|t        j                  k(  rd}|r$| j                  ||j                      d   |      }|S |S )z
        Return an altered pitch for given node, if an alteration is specified
        in the alteredDegrees dictionary
        rF   FTr	   )rn   r%   r-   r.   r/   $transposePitchAndApplySimplification)r   alteredDegreesr   prF   directionSpecmatchpPosts           r   processAlteredNodesz#IntervalNetwork.processAlteredNodesz  s     H88>)H&qxx0=  %E 9<<'I$7$79M9M#NNEI//1E1EFF9<</E==qxx(4a9ELr   NrF   r   c                   |s|S |j                   |v r2| j                  ||j                      d   j                         |      }|S |S )zg
        Given a node and alteredDegrees get the unaltered pitch, or return the current object
        r	   )rn   r   reverse)r   pitchObjnodeObjrF   r   r   s         r   getUnalteredPitchz!IntervalNetwork.getUnalteredPitch  sQ     O >>^+99w~~.z:BBDhPAHr   ra   )rF   stepSizer   getNeighborc          	        |t        d      t        |t              rt        j                  |      }nt        j                  |      }d}	| j                  |||||      }
d}|
d|dt        j                  t        j                  t        j                  fv r2d}| j                  ||||      \  }}|t        j                  k(  r|}
n|}
| j                  ||| j                  |
   j                  |ddd      }|j                   |_        d}| j#                  |
      }|r||v r||   d	   j$                  }|r|t        j                  k(  s|sj|t        j                  k(  rW|j                   |j'                  |      |kD  r|xj                   d
z  c_        |j                   l|j'                  |      |kD  r6nV|j                   J|j'                  |      |k  r6|xj                   d
z  c_        |j                   |j'                  |      |k  r6| j                  |
   }t)        |      D ]  }| j+                  ||      \  }}t-        |      d
kD  r"| j/                  ||      \  }}|j0                  }n|d   j0                  }|d   }|t        j                  k(  r| j3                  ||      }n | j3                  |j5                         |      }| j7                  ||||      }	 |	S )aQ  
        Given a pitchReference, nodeName, and a pitch origin, return the next pitch.

        The `nodeName` parameter may be a :class:`~music21.scale.intervalNetwork.Node` object,
        a node degree, a Terminus Enum, or a None (indicating Terminus.LOW).

        >>> edgeList = ['M2', 'M2', 'm2', 'M2', 'M2', 'M2', 'm2']
        >>> net = scale.intervalNetwork.IntervalNetwork()
        >>> net.fillBiDirectedEdges(edgeList)
        >>> net.nextPitch('g', 1, 'f#5', direction=scale.Direction.ASCENDING)
        <music21.pitch.Pitch G5>
        >>> net.nextPitch('g', 1, 'f#5', direction=scale.Direction.DESCENDING)
        <music21.pitch.Pitch E5>

        The `stepSize` parameter can be configured to permit different sized steps
        in the specified direction.

        >>> net.nextPitch('g', 1, 'f#5',
        ...               direction=scale.Direction.ASCENDING,
        ...               stepSize=2)
        <music21.pitch.Pitch A5>

        Altered degrees can be given to temporarily change the pitches returned
        without affecting the network as a whole.

        >>> alteredDegrees = {2: {'direction': scale.Direction.BI,
        ...                       'interval': interval.Interval('-a1')}}
        >>> net.nextPitch('g', 1, 'g2',
        ...               direction=scale.Direction.ASCENDING,
        ...               alteredDegrees=alteredDegrees)
        <music21.pitch.Pitch A-2>
        >>> net.nextPitch('g', 1, 'a-2',
        ...               direction=scale.Direction.ASCENDING,
        ...               alteredDegrees=alteredDegrees)
        <music21.pitch.Pitch B2>
        Nz/No pitch origin for calling next on this pitch!)r   pitchTargetrF   r   FT)pitchReferencenodeNamer   rF   )r   r  nodeDegreeTargetrF   minPitchmaxPitchr   r   r	   ra   r   r   r   rF   )	TypeErrorrC   rD   r   PitchcopydeepcopygetRelativeNodeIdr%   r.   r/   r-   getNeighborNodeIdsgetPitchFromNodeDegreer   rn   octaver   	semitones	transposer   r   r   r   r	   r   r   r   )r   r   r  pitchOriginrF   r   r   r   pitchOriginObjpCollectr   usedNeighborlowIdhighIdr   alterSemitonesrn   r   rK   r   r   r   intervalObjs                          r   	nextPitchzIntervalNetwork.nextPitch  s   ` MNNk3'"[[5N!]];7N ''/74B2;7E	 ( G ND)*=*=y?S?SU^UaUa#bbL 33>=E@N>G 4 IME6 i222 '')!ZZ/66 ( 
  "(( $$V,f6+F3J?IINkY-A-AA$i6I6I)I((&1;;~+F+WA ((&1;;~+F+W ((&1;;~+F+WA ((&1;;~+F+W JJv xA!%a!;Hh8}q --hA1jj&qk22QK I///==k1M==k>Q>Q>SUVW//~3434;D 0 FH' !0 r   )r   c               ~    ||j                   }nd}||j                   }nd}|j                  |j                   ||||fS )zF
        Return key for caching based on critical components.
        N)nameWithOctaverH   )	r   r   r   r  r  includeFirstr   minKeymaxKeys	            r   _getCacheKeyzIntervalNetwork._getCacheKeyX  sV     ,,FF,,FF

-- 	r   )r   fillMinMaxIfNonec               $   t        |t              rt        j                  |      }nt	        j
                  |      }t        |t              r|}n&|| j                  d   }n| j                  |      d   }|j                  |j                  |_	        t        |t              rt        j                  |      }t        |t              rt        j                  |      }|r||| j                  |||      \  }}| j                  ||t        j                  |      }| j                  r3| j!                  ||||d      }|| j"                  v r| j"                  |   S d}| j$                  r||j'                  |dd       |}	|}
|
}g }g }d}d	}||k  r|d
z  }d}|Et)        |j*                  |j*                        r%|#t-        |j*                  |j*                        rd}nT|%t)        |j*                  |j*                        r|d}n-|%t-        |j*                  |j*                        r|d}n||d}|r,|j/                  |       |j/                  |	j0                         |!t)        |
j*                  |j*                        rn|	j0                  t2        j4                  k(  r|n| j                  d   }	| j7                  |	t        j                        }|n|\  }}t9        |      d
kD  r"| j;                  ||      \  }}	|j<                  }n|d   j<                  }|d   }	| j?                  ||
      }
|
}| jA                  ||	|
t        j                        }||k  r||k\  rtC        d      | j                  r|||f| j"                  |<   ||fS )aj  
        Given a reference pitch, realize upwards to a maximum pitch.

        >>> edgeList = ['M2', 'M2', 'm2', 'M2', 'M2', 'M2', 'm2']

        >>> net = scale.intervalNetwork.IntervalNetwork()
        >>> net.fillBiDirectedEdges(edgeList)
        >>> (pitches, nodeKeys) = net.realizeAscending('c2', 1, 'c5', 'c6')
        >>> [str(p) for p in pitches]
        ['C5', 'D5', 'E5', 'F5', 'G5', 'A5', 'B5', 'C6']
        >>> nodeKeys
        [Terminus.HIGH, 0, 1, 2, 3, 4, 5, Terminus.HIGH]

        >>> net = scale.intervalNetwork.IntervalNetwork(octaveDuplicating=True)
        >>> net.fillBiDirectedEdges(edgeList)
        >>> (pitches, nodeKeys) = net.realizeAscending('c2', 1, 'c5', 'c6')
        >>> [str(p) for p in pitches]
        ['C5', 'D5', 'E5', 'F5', 'G5', 'A5', 'B5', 'C6']
        >>> nodeKeys
        [Terminus.LOW, 0, 1, 2, 3, 4, 5, Terminus.HIGH]
        Nr   r   r   F)r  TminimizeinPlaced   ra   r  zrCannot realize these pitches; is your scale well-formed? (especially check if you're giving notes without octaves))"rC   rD   r   r  r  r	  rl   r   r   r  implicitOctaverealizeMinMaxr   r%   r.   r   r  r   r   transposeBelowTargetr7   psr:   rX   rH   r   r"   r   r   r   r	   r   r   rz   )r   r   r   r  r  r   r  r   ckr   r   r  r   r   attemptsmaxAttemptsappendPitch
nextBundler   r   r   r  s                         r   realizeAscendingz IntervalNetwork.realizeAscendingv  s   @ nc*"[[8N!]]>:N fd#G^++A.G**6215G   ($2$A$AN!h${{8,Hh${{8,H 0X5E!%!3!3N4;CQ "4 "SHh //07:C:M:M?M 0 O ""7#1#+#+05	 # 7B
 T)))++B//B !!h&://4QU/V 
 $MHK$X[[(++6 ,X[[(++6"&8;;4&"&8;;4&"!h&6"H%!!!$$'#QTT8;;(? ttx}}$#))!,a)<)<=J !!+Hh8}q  --hA1jj&qk22QK99+qIAH//~3434;D;N;N 0 PHm $v {"*[\ \
 ".'+Z'7D  $ Zr   )r   r  r  r   c                  d}	t        |t              rt        j                  |      }
nt	        j
                  |      }
|
j                  d|
_        t        |t              r|}n&|| j                  d   }n| j                  |      d   }t        |t              rt        j                  |      }n|}t        |t              rt        j                  |      }n|}|r||| j                  |
||      \  }}| j                  |
|t        j                  |      }
| j                  r4| j                  ||
||||      }	|	| j                   v r| j                   |	   S | j"                  r||
j%                  |dd       |}|
}|}g }g }d}	 d	}|Et'        |j(                  |j(                        r%|#t+        |j(                  |j(                        rd}nT|%t'        |j(                  |j(                        r|d}n-|%t+        |j(                  |j(                        r|d}n||d}|r|r|r0|r.|r,|j-                  |       |j-                  |j.                         d	}||j(                  |j(                  k  rn |j.                  t0        j2                  k(  r|n| j4                  d   }|j.                  t0        j2                  k(  r|n| j7                  |t        j                        }|n|\  }}t9        |      d
kD  r"| j;                  ||      \  }}|j<                  }n|d   j<                  }|d   }| j?                  |jA                         |      }| jC                  |||t        j                        }|r |jA                          |jA                          | j                  r|	||f| j                   |	<   ||fS )a  
        Given a reference pitch, realize downward to a minimum.

        If no minimum is given, the terminus is used.

        If `includeFirst` is False, the starting (highest) pitch will not be included.

        If `fillMinMaxIfNone` is True, a min and max will be artificially
        derived from an ascending scale and used as min and max values.

        >>> edgeList = ['M2', 'M2', 'm2', 'M2', 'M2', 'M2', 'm2']
        >>> net = scale.intervalNetwork.IntervalNetwork()
        >>> net.fillBiDirectedEdges(edgeList)
        >>> net.realizeDescending('c2', 1, 'c3')  # minimum is above ref
        ([], [])
        >>> (pitches, nodeKeys) = net.realizeDescending('c3', 1, 'c2')
        >>> [str(p) for p in pitches]
        ['C2', 'D2', 'E2', 'F2', 'G2', 'A2', 'B2']
        >>> nodeKeys
        [Terminus.LOW, 0, 1, 2, 3, 4, 5]
        >>> (pitches, nodeKeys) = net.realizeDescending('c3', 1, 'c2', includeFirst=True)
        >>> [str(p) for p in pitches]
        ['C2', 'D2', 'E2', 'F2', 'G2', 'A2', 'B2', 'C3']
        >>> nodeKeys
        [Terminus.LOW, 0, 1, 2, 3, 4, 5, Terminus.LOW]

        >>> (pitches, nodeKeys) = net.realizeDescending('a6', scale.Terminus.HIGH)
        >>> [str(p) for p in pitches]
        ['A5', 'B5', 'C#6', 'D6', 'E6', 'F#6', 'G#6']
        >>> nodeKeys
        [Terminus.LOW, 0, 1, 2, 3, 4, 5]

        >>> (pitches, nodeKeys) = net.realizeDescending('a6', scale.Terminus.HIGH,
        ...                                             includeFirst=True)
        >>> [str(p) for p in pitches]
        ['A5', 'B5', 'C#6', 'D6', 'E6', 'F#6', 'G#6', 'A6']
        >>> nodeKeys
        [Terminus.LOW, 0, 1, 2, 3, 4, 5, Terminus.HIGH]

        >>> net = scale.intervalNetwork.IntervalNetwork(octaveDuplicating=True)
        >>> net.fillBiDirectedEdges(edgeList)
        >>> (pitches, nodeKeys) = net.realizeDescending('c2', 1, 'c0', 'c1')
        >>> [str(p) for p in pitches]
        ['C0', 'D0', 'E0', 'F0', 'G0', 'A0', 'B0']
        >>> nodeKeys
        [Terminus.LOW, 0, 1, 2, 3, 4, 5]
        Nr   r   r!  r   )r  r  r  r   Tr"  Fra   r  )"rC   rD   r   r  r  r	  r  rl   r   r   r'  r   r%   r/   r   r  r   r   transposeAboveTargetr7   r)  r:   rX   rH   r   r!   r   r   r   r   r	   r   r   r   )r   r   r   r  r  r   r  r  r   r*  pitchRefr   minPitchObjmaxPitchObjr   r   r  pre	preNodeIdisFirstr-  r.  r   r   r   r  s                             r   realizeDescendingz!IntervalNetwork.realizeDescending  s   x nc*{{>2H}}^4H ??"HO fd#G^ ++A.G**6215G h$++h/K"K h$++h/K"K 38K'+'9'9(:AIW (: (Y$K ))(*14=4H4H9G * I ""7#+,7,70<+2 # %B T***,,R00 !!k&=))+d)S	K'QTT;>>2#/QTT;>>2")1440!)")1440!)"$)<"
 G\

8$  &G&144;>>+Attx||#&**1-ttx||#&a)=)=>J !!+Hh8}q  --hA1jj&qk22QK99+:M:M:OQRSA//~2323:C:N:N 0 PHo x KKM ".(+YD!!"%I~r   c           	        |t        d      t        |t              rt        j                  |      }nt        j                  |      }|j                  |j                  |_        t        |t              rt        j                  |      }	n|}	t        |t              rt        j                  |      }
n|}
d}| j                  rd}|rX|t        j                  k(  r=| j                  r|	|j                  |	d       | j                  |||	|
|d      \  }}nE|t        j                  k(  r>| j                  r|
|j                  |
d       | j!                  |||	|
|dd      \  }}n|t        j"                  k(  rt        j                  |      }t        j                  |      }| j                  r|	|j                  |	d       | j                  |||	|
|      \  }}| j                  r|
|j                  |
d       | j!                  |||	|
|d      \  }}g }g }d	}d	}d
}|d	kD  r|dz  }|t%        |      k  r4||   |vr-|j'                  ||          |j'                  ||   ||   f       |dz  }|t%        |      k  r4||   |vr-|j'                  ||          |j'                  ||   ||   f       |dz  }|t%        |      k\  r|t%        |      k\  rn|d	kD  rg }g }|D ]'  \  }}|j'                  |       |j'                  |       ) nKt        d|      | j                  |||	|
|      \  }}| j!                  |||	|
|d      \  }}||z   ||z   }}|r(t)        t+        |            }t)        t+        |            }||fS )a  
        Realize the nodes of this network based on a pitch assigned to a
        valid `nodeId`, where `nodeId` can be specified by integer
        (starting from 1) or key (a tuple of origin, destination keys).

        Without a min or max pitch, the given pitch reference is assigned
        to the designated node, and then both ascends to the terminus and
        descends to the terminus.

        The `alteredDegrees` dictionary permits creating mappings between
        node degree and direction and :class:`~music21.interval.Interval`
        based transpositions.

        Returns two lists, a list of pitches, and a list of Node keys.

        >>> edgeList = ['M2', 'M2', 'm2', 'M2', 'M2', 'M2', 'm2']
        >>> net = scale.intervalNetwork.IntervalNetwork()
        >>> net.fillBiDirectedEdges(edgeList)
        >>> (pitches, nodeKeys) = net.realize('c2', 1, 'c2', 'c3')
        >>> [str(p) for p in pitches]
        ['C2', 'D2', 'E2', 'F2', 'G2', 'A2', 'B2', 'C3']
        >>> nodeKeys
        [Terminus.LOW, 0, 1, 2, 3, 4, 5, Terminus.HIGH]

        >>> alteredDegrees = {7: {'direction': scale.Direction.BI,
        ...                       'interval': interval.Interval('-a1')}}
        >>> (pitches, nodeKeys) = net.realize('c2', 1, 'c2', 'c4', alteredDegrees=alteredDegrees)
        >>> [str(p) for p in pitches]
        ['C2', 'D2', 'E2', 'F2', 'G2', 'A2', 'B-2', 'C3',
         'D3', 'E3', 'F3', 'G3', 'A3', 'B-3', 'C4']
        >>> nodeKeys
        [Terminus.LOW, 0, 1, 2, 3, 4, 5, Terminus.HIGH, 0, 1, 2, 3, 4, 5, Terminus.HIGH]
        zpitchReference cannot be NoneFTr$  )r   r   r  r  r   r  r   r   r  r  r   r  r  )r   r   r  r  r   )r   r   r  r  r   r  r   i'  ra   z&cannot match direction specification: )rz   rC   rD   r   r  r  r	  r  r&  r   r%   r.   r(  r/  r/   r1  r8  r-   r   rX   r   reversed)r   r   r   r  r  rF   r   r   r2  r3  r4  directedRealizationmergedPitchesmergedNodespitchReferenceApitchReferenceBr   r   r5  r6  mergedfoundPitchesrK   jpreventPermanentRecursionr   r   s                              r   realizezIntervalNetwork.realize  s   Z !*+JKKnc*{{>2H}}^4H ??"&55HO h$++h/K"K h$++h/K"K#!!"& I///))k.E11+t1L-1-B-B#+!((#1%) .C .+*{ i222))k.E11+t1L .2-C-C#+!((#1!%%) .D .+*{ ill*"&--"9"&--"9))k.E#88d8S $(#8#8@FBMBMHV	 $9 $X j ))k.E#88d8S "&!7!7?EALALGUEI "8 "KY !,0)/!3-2-3t9}a)D$++DG4tAw
1&>?FA3s8|Al(B$++CF3s1vy|&<=FA CI~!s3x- 0!3 !# "DAq!((+&&q) # /<YMJL L  $44H<B>I>IDR	  5  TD*
 "338;A=H=HCQAF 4 HNC *-tY5K;M !-!89Mx45Kk))r   c           	     <    | j                  |||||||      }|d   S )a  
        Realize the native nodes of this network based on a pitch
        assigned to a valid `nodeId`, where `nodeId` can be specified by integer
        (starting from 1) or key (a tuple of origin, destination keys).

        The nodeId, when a simple, linear network, can be used as a scale degree
        value starting from one.

        >>> edgeList = ['M2', 'M2', 'm2', 'M2', 'M2', 'M2', 'm2']
        >>> net = scale.intervalNetwork.IntervalNetwork()
        >>> net.fillBiDirectedEdges(edgeList)
        >>> [str(p) for p in net.realizePitch(pitch.Pitch('G3'))]
        ['G3', 'A3', 'B3', 'C4', 'D4', 'E4', 'F#4', 'G4']

        G3 is the fifth (scale) degree

        >>> [str(p) for p in net.realizePitch(pitch.Pitch('G3'), 5)]
        ['C3', 'D3', 'E3', 'F3', 'G3', 'A3', 'B3', 'C4']

        G3 is the seventh (scale) degree

        >>> [str(p) for p in net.realizePitch(pitch.Pitch('G3'), 7) ]
        ['A-2', 'B-2', 'C3', 'D-3', 'E-3', 'F3', 'G3', 'A-3']

        >>> [str(p) for p in net.realizePitch(pitch.Pitch('f#3'), 1, 'f2', 'f3') ]
        ['E#2', 'F#2', 'G#2', 'A#2', 'B2', 'C#3', 'D#3', 'E#3']

        >>> [str(p) for p in net.realizePitch(pitch.Pitch('a#2'), 7, 'c6', 'c7')]
        ['C#6', 'D#6', 'E6', 'F#6', 'G#6', 'A#6', 'B6']

        Circle of fifths

        >>> edgeList = ['P5'] * 6 + ['d6'] + ['P5'] * 5
        >>> net5ths = scale.intervalNetwork.IntervalNetwork()
        >>> net5ths.fillBiDirectedEdges(edgeList)
        >>> [str(p) for p in net5ths.realizePitch(pitch.Pitch('C1'))]
        ['C1', 'G1', 'D2', 'A2', 'E3', 'B3', 'F#4', 'D-5', 'A-5', 'E-6', 'B-6', 'F7', 'C8']
        >>> [str(p) for p in net5ths.realizePitch(pitch.Pitch('C2'))]
        ['C2', 'G2', 'D3', 'A3', 'E4', 'B4', 'F#5', 'D-6', 'A-6', 'E-7', 'B-7', 'F8', 'C9']

        r   r   r  r  rF   r   r   r   )rF  )	r   r   r   r  r  rF   r   r   
componentss	            r   realizePitchzIntervalNetwork.realizePitch  s9    f \\)) " 
 !}r   c           	         d}| j                  |||||||      d   }g }	t        |      D ]D  \  }
}|
t        |      dz
  k  s||
dz      }|	j                  t	        j
                  ||             F |	S )a4  
        Realize the sequence of intervals between the specified pitches, or the termini.

        >>> edgeList = ['M2', 'M2', 'm2', 'M2', 'M2', 'M2', 'm2']
        >>> net = scale.intervalNetwork.IntervalNetwork()
        >>> net.fillBiDirectedEdges(edgeList)
        >>> net.realizeIntervals()
        [<music21.interval.Interval M2>, <music21.interval.Interval M2>,
         <music21.interval.Interval m2>, <music21.interval.Interval M2>,
         <music21.interval.Interval M2>, <music21.interval.Interval M2>,
         <music21.interval.Interval m2>]
        c4rH  r   ra   )rF  r   r   rX   r	   rE   )r   r   r  r  rF   r   r   r   pListiListrK   p1p2s                r   realizeIntervalsz IntervalNetwork.realizeIntervals  s    2 N$*&.&.'0,:%,  . /01 u%EAr3u:>!1q5\X..r267 & r   c                    | j                  |||d      d   }| j                  |||dd      d   }||z   }|d   |d   fS )a  
        Realize the pitches of the 'natural' terminus of a network. This (presently)
        must be done by ascending, and assumes only one valid terminus for both extremes.

        This suggests that in practice termini should not be affected by directionality.

        >>> edgeList = ['M2', 'M2', 'm2', 'M2', 'M2', 'M2', 'm2']
        >>> net = scale.intervalNetwork.IntervalNetwork()
        >>> net.fillBiDirectedEdges(edgeList)
        >>> net.realizeTermini(pitch.Pitch('G3'))
        (<music21.pitch.Pitch G3>, <music21.pitch.Pitch G4>)
        >>> net.realizeTermini(pitch.Pitch('a6'))
        (<music21.pitch.Pitch A6>, <music21.pitch.Pitch A7>)
        F)r   r   r   r  r   )r   r   r   r  r  )r/  r8  )r   r   r   r   r   r5  r>  s          r   realizeTerminizIntervalNetwork.realizeTermini  s    0 $$))"	 % $ %&	'
 $$))" % $
 %&' d
 Qr!222r   c           	     v   | j                  |||      \  }}|j                  d      }|j                  d      }| j                  |||||d      \  }}| j                  |||||dd      \  }}	g }
d}t	        |      D ]  \  }}||   }|dk(  r#|t
        j                  t
        j                  fv r3|t
        j                  t
        j                  fv r|du r|
j                  ||f        n@|t
        j                  t
        j                  fv r|du rd}|s|
j                  ||f        g }d}t	        |	      D ]  \  }}||   }|dk(  r#|t
        j                  t
        j                  fv r3|t
        j                  t
        j                  fv r|du r|j                  ||f        n@|t
        j                  t
        j                  fv r|du rd}|s|j                  ||f        |d	   }|d   }|
|z   D ]<  \  }}|j                  |j                  k  r|}|j                  |j                  kD  s;|}> ||fS )
a1  
        Realize the min and max pitches of the scale, or the min and max values
        found between two termini.

        This suggests that min and max might be beyond the terminus.

        >>> edgeList = ['M2', 'M2', 'm2', 'M2', 'M2', 'M2', 'm2']
        >>> net = scale.intervalNetwork.IntervalNetwork()
        >>> net.fillBiDirectedEdges(edgeList)

        >>> net.realizeMinMax(pitch.Pitch('C4'))
        (<music21.pitch.Pitch C4>, <music21.pitch.Pitch C6>)
        >>> net.realizeMinMax(pitch.Pitch('B-5'))
        (<music21.pitch.Pitch B-5>, <music21.pitch.Pitch B-7>)

        Note that it might not always be two octaves apart

        #  s = scale.AbstractDiatonicScale('major')
        #  s._net.realizeMinMax(pitch.Pitch('D2'))
        #  (<music21.pitch.Pitch D2>, <music21.pitch.Pitch D3>)
        )r   r   r      F)r   r   r   r  r  r  Tr;  r   rS  )
rT  r  r/  r8  r   r   r!   r"   rX   r)  )r   r   r   r   lowhighr   r   r5  r6  	postPairscollectrK   r   r   prePairsr  r  _nIds                      r   r'  zIntervalNetwork.realizeMinMax<  sR   8 ''~/57E ( G	T
 mmC ~~b!00))" 1 $j //))" 0 $Y =?	
+FAsQAAv#(,,!>>x}}55'T/  !S*x}}55'U:J  !S* , <>	*FAsAAAv#(,,!>>x}}55'T/C)x}}55'U:JC) +" 87 8+GAttthkk!tthkk!	 , !!r   )ra   c                ,   | j                  ||||||      \  }}	|D 
cg c]  }
| j                  |
       }}
g }t        |      D ]F  \  }}| j                  |	|      }| j                  |j                        |v s6|j                  |       H |S c c}
w )ae  
        Realize the native nodes of this network based on
        a pitch assigned to a valid `nodeId`, where `nodeId` can
        be specified by integer (starting from 1) or key
        (a tuple of origin, destination keys).

        The `nodeDegreeTargets` specifies the degrees to be
        included within the specified range.

        Example: build a network of the Major scale:

        >>> edgeList = ['M2', 'M2', 'm2', 'M2', 'M2', 'M2', 'm2']
        >>> net = scale.intervalNetwork.IntervalNetwork()
        >>> net.fillBiDirectedEdges(edgeList)

        Now for every "scale" where G is the 3rd degree, give me the
        tonic if that note is between C2 and C3.
        (There's only one such note: E-2).

        >>> net.realizePitchByDegree('G', 3, [1], 'c2', 'c3')
        [<music21.pitch.Pitch E-2>]

        But between c2 and f3 there are two, E-2 and E-3 (it doesn't matter that the G
        which is scale degree 3 for E-3 is above F3):

        >>> net.realizePitchByDegree('G', 3, [1], 'c2', 'f3')
        [<music21.pitch.Pitch E-2>, <music21.pitch.Pitch E-3>]

        Give us nodes 1, 2, and 5 for scales where G is node 5 (e.g., C major's dominant)
        where any pitch is between C2 and F4

        >>> pitchList = net.realizePitchByDegree('G', 5, [1, 2, 5], 'c2', 'f4')
        >>> print(' '.join([str(p) for p in pitchList]))
        C2 D2 G2 C3 D3 G3 C4 D4

        There are no networks based on the major scale's edge-list where
        with node 1 (i.e. "tonic") between C2 and F2 where
        G is scale degree 7

        >>> net.realizePitchByDegree('G', 7, [1], 'c2', 'f2')
        []
        r   r   r  r  rF   r   )rF  r   r   r   rn   rX   )r   r   r   nodeDegreeTargetsr  r  rF   r   realizedPitchrealizedNodesnodeDegreeTargetsModulusr   rK   r   r   s                   r   realizePitchByDegreez$IntervalNetwork.realizePitchByDegree  s    j '+ll)) '3 '+#| DU#UCTaD$6$6q$9CT #U m,DAq

<?+A!!!((+/GGA -  $Vs   Br)  )comparisonAttributerF   r   c                  || j                   d   }n| j                  |      d   }t        |t              rt	        j
                  |      }n)t        |t        j                        r|j                  }n|}|j                  }	|	|j                  |_        |j                  dd      }
|j                  dd      }| j                  |||
|||      \  }}g }t        ||      D ]5  \  }}t        ||      t        ||      k(  s ||vs%|j                  |       7 |	d|_        |syt        |      dk(  r|d   S t!        j"                  ||D cg c]  }| j$                  |   j&                   c}      S c c}w )	ag  
        Given a reference pitch assigned to node id, determine the
        relative node id of pitchTarget, even if displaced over multiple octaves

        The `nodeId` parameter may be
        a :class:`~music21.scale.intervalNetwork.Node` object, a node degree,
        a terminus string, or a None (indicating Terminus.LOW).

        Returns None if no match.

        If `getNeighbor` is True, or direction, the nearest node will be returned.

        If more than one node defines the same pitch, Node weights are used
        to select a single node.

        >>> edgeList = ['M2', 'M2', 'm2', 'M2', 'M2', 'M2', 'm2']
        >>> net = scale.intervalNetwork.IntervalNetwork(edgeList)
        >>> net.getRelativeNodeId('a', 1, 'a4')
        Terminus.LOW
        >>> net.getRelativeNodeId('a', 1, 'b4')
        0
        >>> net.getRelativeNodeId('a', 1, 'c#4')
        1
        >>> net.getRelativeNodeId('a', 1, 'c4', comparisonAttribute='step')
        1
        >>> net.getRelativeNodeId('a', 1, 'c', comparisonAttribute='step')
        1
        >>> net.getRelativeNodeId('a', 1, 'b-4') is None
        True
        Nr   rV  Fr:  rW  r  r  rF   r   ra   )r   r   rC   rD   r   r  r
   Noter  r&  r  rF  zipr   rX   r   r   r   r   rG   )r   r   r   r   rf  rF   r   r   pitchTargetObj
saveOctaver  r  realizedPitchesrealizedNodesr   ra  rb  r   s                     r   r
  z!IntervalNetwork.getRelativeNodeId  s   V >++A.G**6215G
 k3'"[[5NTYY/(..N(N#**
$2$A$AN! "++C+?!++B+>)-n6=?G?G@IES *6 *U& +.+N'M<
 (;<}.ABCt+KK- ,O $(N!Y!^7N ++DKO,P4aTZZ]-A-A4,PR R,Ps    E5
c                   || j                   d   }n| j                  |      d   }t        |t              rt	        j
                  |      }n|}|j                  }||j                  |_        |j                  dd      }	|j                  dd      }
| j                  |||	|
||      \  }}d}d}t        ||      D ](  \  }}|j                  |j                  k  r|}||fc S |}* |||_        y)a  
        Given a reference pitch assigned to a node id, determine the node ids
        that neighbor this pitch.

        Returns None if an exact match.

        >>> edgeList = ['M2', 'M2', 'm2', 'M2', 'M2', 'M2', 'm2']
        >>> net = scale.intervalNetwork.IntervalNetwork(edgeList)
        >>> net.getNeighborNodeIds('c4', 1, 'b-')
        (4, 5)
        >>> net.getNeighborNodeIds('c4', 1, 'b')
        (5, Terminus.HIGH)
        Nr   rV  Fr:  rW  rh  )r   r   rC   rD   r   r  r  r&  r  rF  rj  r)  )r   r   r  r   rF   r   r   rk  savedOctaver  r  rm  rn  lowNeighborhighNeighborra  rb  s                    r   r  z"IntervalNetwork.getNeighborNodeIdsO	  s    , **1-F))(3A6Fk3'"[[5N(N$++$2$A$AN! "++C+?!++B+>)-n6<?G?G@IES *6 *U& +.+N'M<  =#3#33+"L00&K ,O $/N!r   c                X    | j                  ||||||      }|y| j                  |      S )a  
        Given a reference pitch assigned to node id,
        determine the relative node degree of pitchTarget,
        even if displaced over multiple octaves

        Comparison Attribute determines what will be used to determine
        equality.  Use `ps` (default) for post-tonal uses.  `name` for
        tonal, and `step` for diatonic.

        >>> edgeList = ['M2', 'M2', 'm2', 'M2', 'M2', 'M2', 'm2']
        >>> net = scale.intervalNetwork.IntervalNetwork(edgeList)
        >>> [str(p) for p in net.realizePitch(pitch.Pitch('e-2')) ]
        ['E-2', 'F2', 'G2', 'A-2', 'B-2', 'C3', 'D3', 'E-3']

        >>> net.getRelativeNodeDegree('e-2', 1, 'd3')  # if e- is tonic, what is d3
        7

        For an octave repeating network, the neither pitch's octave matters:

        >>> net.getRelativeNodeDegree('e-', 1, 'd5')  # if e- is tonic, what is d3
        7
        >>> net.getRelativeNodeDegree('e-2', 1, 'd')  # if e- is tonic, what is d3
        7

        >>> net.getRelativeNodeDegree('e3', 1, 'd5') is None
        True
        >>> net.getRelativeNodeDegree('e3', 1, 'd5', comparisonAttribute='step')
        7
        >>> net.getRelativeNodeDegree('e3', 1, 'd', comparisonAttribute='step')
        7

        >>> net.getRelativeNodeDegree('e-3', 1, 'b-3')
        5

        >>> net.getRelativeNodeDegree('e-3', 1, 'e-5')
        1
        >>> net.getRelativeNodeDegree('e-2', 1, 'f3')
        2
        >>> net.getRelativeNodeDegree('e-3', 1, 'b6') is None
        True

        >>> net.getRelativeNodeDegree('e-3', 1, 'e-2')
        1
        >>> net.getRelativeNodeDegree('e-3', 1, 'd3')
        7
        >>> net.getRelativeNodeDegree('e-3', 1, 'e-3')
        1
        >>> net.getRelativeNodeDegree('e-3', 1, 'b-1')
        5

        >>> edgeList = ['p4', 'p4', 'p4']  # a non octave-repeating scale
        >>> net = scale.intervalNetwork.IntervalNetwork(edgeList)
        >>> [str(p) for p in net.realizePitch('f2')]
        ['F2', 'B-2', 'E-3', 'A-3']
        >>> [str(p) for p in net.realizePitch('f2', 1, 'f2', 'f6')]
        ['F2', 'B-2', 'E-3', 'A-3', 'D-4', 'G-4', 'C-5', 'F-5', 'A5', 'D6']

        >>> net.getRelativeNodeDegree('f2', 1, 'a-3')  # could be 4 or 1
        1
        >>> net.getRelativeNodeDegree('f2', 1, 'd-4')  # 2 is correct
        2
        >>> net.getRelativeNodeDegree('f2', 1, 'g-4')  # 3 is correct
        3
        >>> net.getRelativeNodeDegree('f2', 1, 'c-5')  # could be 4 or 1
        1
        >>> net.getRelativeNodeDegree('f2', 1, 'e--6')  # could be 4 or 1
        1

        >>> [str(p) for p in net.realizePitch('f6', 1, 'f2', 'f6')]
        ['G#2', 'C#3', 'F#3', 'B3', 'E4', 'A4', 'D5', 'G5', 'C6', 'F6']

        >>> net.getRelativeNodeDegree('f6', 1, 'd5')
        1
        >>> net.getRelativeNodeDegree('f6', 1, 'g5')
        2
        >>> net.getRelativeNodeDegree('f6', 1, 'a4')
        3
        >>> net.getRelativeNodeDegree('f6', 1, 'e4')
        2
        >>> net.getRelativeNodeDegree('f6', 1, 'b3')
        1

        )r   r   r   rf  r   rF   N)r
  r   )r   r   r   r   rf  rF   r   r   s           r   getRelativeNodeDegreez%IntervalNetwork.getRelativeNodeDegree	  sG    x $$)# 3) % ! ;&&s++r   c	           	        | j                  |      }	d}
| j                  |d|      }t        |      dk(  r|d   }
na|D cg c]  }|j                   c}t        j                  t        j
                  gk(  r|d   }
n |D ]  }| j                  |      }||v s|}
 n |
|d   }
t        d      D ]  }| j                  ||	d   ||||      \  }}t        |      D ]x  \  }}||
j                  k(  r	||   c c S |s!|t        j
                  t        j                  fv sD|
j                  t        j
                  t        j                  fv sq||   c c S   yc c}w )aS  
        Given a reference pitch assigned to node id,
        determine the pitch for the target node degree.

        >>> edgeList = ['M2', 'M2', 'm2', 'M2', 'M2', 'M2', 'm2']
        >>> net = scale.intervalNetwork.IntervalNetwork(edgeList)
        >>> [str(p) for p in net.realizePitch(pitch.Pitch('e-2')) ]
        ['E-2', 'F2', 'G2', 'A-2', 'B-2', 'C3', 'D3', 'E-3']
        >>> net.getPitchFromNodeDegree('e4', 1, 1)
        <music21.pitch.Pitch E4>
        >>> net.getPitchFromNodeDegree('e4', 1, 7)  # seventh scale degree
        <music21.pitch.Pitch D#5>
        >>> net.getPitchFromNodeDegree('e4', 1, 8)
        <music21.pitch.Pitch E4>
        >>> net.getPitchFromNodeDegree('e4', 1, 9)
        <music21.pitch.Pitch F#4>
        >>> net.getPitchFromNodeDegree('e4', 1, 3, minPitch='c2', maxPitch='c3')
        <music21.pitch.Pitch G#2>

        This will always get the lowest pitch:

        >>> net.getPitchFromNodeDegree('e4', 1, 3, minPitch='c2', maxPitch='c10')
        <music21.pitch.Pitch G#2>

        >>> net.fillMelodicMinor()
        >>> net.getPitchFromNodeDegree('c', 1, 5)
        <music21.pitch.Pitch G4>
        >>> net.getPitchFromNodeDegree('c', 1, 6, scale.Direction.ASCENDING)
        <music21.pitch.Pitch A4>
        >>> net.getPitchFromNodeDegree('c', 1, 6, scale.Direction.DESCENDING)
        <music21.pitch.Pitch A-4>
        NT)r   r   ra   r   
   r_  )
r   r   rH   r   r!   r"   r   r   rF  r   )r   r   r  r  rF   r  r  r   r   nodeListForNamesnodeTargetIdnodeTargetIdListr   r   dirListunused_counterra  rb  rK   s                      r   r  z&IntervalNetwork.getPitchFromNodeDegree	  s{   Z  //9 //0@CG>K 0 M  A%+A.L,-,qadd,-(,,1NN+A.L'55c:
 '#&L (  ,A.L $BiN*.,,-'*!!#- +7 +/'M< $L13 ,//)(++ ! ==*oo(--1NN,Q// 2 (; .s    Ec                   t        | t        t        f      s,t        | t              rt	        j
                  |       }n| }|g}nOg }| D ]H  }t        |t              r%|j                  t	        j
                  |             8|j                  |       J |st        d      t        |      D cg c]  \  }}|j                  |f }}}|j                          ||d   d      }||d   d      }|||fS c c}}w )a~  
        Given a list or one pitch, check if all are pitch objects; convert if necessary.
        Return a 3-tuple: a list of all pitches, the min value and the max value.

        >>> Net = scale.intervalNetwork.IntervalNetwork
        >>> Net.filterPitchList(['c#4', 'f5', 'd3'])
        ([<music21.pitch.Pitch C#4>, <music21.pitch.Pitch F5>, <music21.pitch.Pitch D3>],
         <music21.pitch.Pitch D3>,
         <music21.pitch.Pitch F5>)

        A single string or pitch can be given.

        >>> Net.filterPitchList('c#')
        ([<music21.pitch.Pitch C#>],
         <music21.pitch.Pitch C#>,
         <music21.pitch.Pitch C#>)

        Empty lists raise value errors:

        >>> Net.filterPitchList([])
        Traceback (most recent call last):
        ValueError: There must be at least one pitch given.

        * Changed in v8: staticmethod.  Raise value error on empty.
        z'There must be at least one pitch given.r   ra   rS  )rC   r   tuplerD   r   r  rX   
ValueErrorr   r)  sort)	r   r   	pitchListr   rK   r   sortListr  r  s	            r   filterPitchListzIntervalNetwork.filterPitchListq
  s    < +e}5+s+ ;;{3&!
I I a%$$U[[^4$$Q'	 ! FGG 3<I2FG2FhaUXXqM2FGXa[^,Xb\!_-(H,, Hs   -C3
pitchClassc                d   || j                   d   }n| j                  |      d   }| j                  |      \  }}}| j                  |||||      }g }	g }
|D ]S  }d}|D ]6  }d}t	        ||      t	        ||      k(  rd}|s#|	j                  |       d} n |rC|
j                  |       U |	|
fS )a  
        Given one or more pitches in `pitchTarget`, return a
        tuple of a list of matched pitches, and a list of unmatched pitches.

        >>> edgeList = ['M2', 'M2', 'm2', 'M2', 'M2', 'M2', 'm2']
        >>> net = scale.intervalNetwork.IntervalNetwork(edgeList)
        >>> [str(p) for p in net.realizePitch('e-2')]
        ['E-2', 'F2', 'G2', 'A-2', 'B-2', 'C3', 'D3', 'E-3']

        >>> net.match('e-2', 1, 'c3')  # if e- is tonic, is 'c3' in the scale?
        ([<music21.pitch.Pitch C3>], [])

        >>> net.match('e-2', 1, 'd3')
        ([<music21.pitch.Pitch D3>], [])

        >>> net.match('e-2', 1, 'd#3')
        ([<music21.pitch.Pitch D#3>], [])

        >>> net.match('e-2', 1, 'e3')
        ([], [<music21.pitch.Pitch E3>])

        >>> pitchTarget = [pitch.Pitch('b-2'), pitch.Pitch('b2'), pitch.Pitch('c3')]
        >>> net.match('e-2', 1, pitchTarget)
        ([<music21.pitch.Pitch B-2>, <music21.pitch.Pitch C3>], [<music21.pitch.Pitch B2>])

        >>> pitchTarget = ['b-2', 'b2', 'c3', 'e-3', 'e#3', 'f2', 'e--2']
        >>> (matched, unmatched) = net.match('e-2', 1, pitchTarget)
        >>> [str(p) for p in matched]
        ['B-2', 'C3', 'E-3', 'E#3', 'F2', 'E--2']
        >>> unmatched
        [<music21.pitch.Pitch B2>]

        r   r!  FT)r   r   r  rJ  r   rX   )r   r   r   r   rf  r   r  r  nodesRealizedmatchednoMatchtargetfoundr   r   s                  r   r   zIntervalNetwork.match
  s    T >**1-F))&1!4F*.*>*>{*K'Xx )).*0*2*29G	 * I  "FE"112gfFY6ZZ ENN6* E # v& " r   c	                .   || j                   d   }n| j                  |      d   }| j                  |||||      }	| j                  |      \  }}}g }
|	D ]<  }d}|D ]  }t	        ||      t	        ||      k(  sd} n |r,|
j                  |       > |
S )a  
        Find all pitches in the realized scale that are not in the
        pitch target network based on the comparison attribute.

        >>> edgeList = ['M2', 'M2', 'm2', 'M2', 'M2', 'M2', 'm2']
        >>> net = scale.intervalNetwork.IntervalNetwork(edgeList)
        >>> [str(p) for p in net.realizePitch('G3')]
        ['G3', 'A3', 'B3', 'C4', 'D4', 'E4', 'F#4', 'G4']
        >>> net.findMissing('g', 1, ['g', 'a', 'b', 'd', 'f#'])
        [<music21.pitch.Pitch C5>, <music21.pitch.Pitch E5>]
        r   )r  r  r   FT)r   r   rJ  r  r   rX   )r   r   r   r   rf  r  r  rF   r   r  r   r  r   r   s                 r   findMissingzIntervalNetwork.findMissing
  s    , >**1-F))&1!4F )).*03;3;9G	 * I +/*>*>{*K'Xx #FE 112gfFY6ZZ E	 ! F# $ r   )CzC#zD-DzD#zE-EFzF#GzG#AzB-BzC-ztuple[str, ...]_SCALE_STARTSc                (   | j                   d   }g }| j                  D ]J  }| j                  |||||      \  }}	|j                  t	        |      t        j                  |      f       L |j                          |j                          ||d| S |S )aB  
        Given a collection of pitches, test all transpositions of a realized
        version of this network, and return the number of matches in each for
        each pitch assigned to the first node.

        >>> edgeList = ['M2', 'M2', 'm2', 'M2', 'M2', 'M2', 'm2']
        >>> net = scale.intervalNetwork.IntervalNetwork(edgeList)

        a network built on G or D as

        >>> net.find(['g', 'a', 'b', 'd', 'f#'])
        [(5, <music21.pitch.Pitch G>), (5, <music21.pitch.Pitch D>),
         (4, <music21.pitch.Pitch A>), (4, <music21.pitch.Pitch C>)]

        >>> net.find(['g', 'a', 'b', 'c', 'd', 'e', 'f#'])
        [(7, <music21.pitch.Pitch G>), (6, <music21.pitch.Pitch D>),
         (6, <music21.pitch.Pitch C>), (5, <music21.pitch.Pitch A>)]

        If resultsReturned is None then return every such scale.
        r   )rf  r   N)	r   r  r   rX   r   r   r  r  r   )
r   r   resultsReturnedrf  r   r   r  r   r  unused_noMatchs
             r   findzIntervalNetwork.find3  s    2 &&q)
 ##A '+jj$7- '1 '/#G^ OOS\5;;q>:; $ 	&,_--Or   c                   | j                   }|dv r4t        |d      r|j                  st        |t        j
                        rd}|dk(  r|j                  |d      }|S |j                  |      }|j                  rO|dk(  r|j                  d	       |S |dk(  r|j                  dd
       |S |dv r	 |S t        d| ddz   dz         |S )a  
        transposes the pitch according to the given interval object and
        uses the simplification of the `pitchSimplification` property
        to simplify it afterwards.

        >>> b = scale.intervalNetwork.IntervalNetwork()
        >>> b.pitchSimplification  # default
        'maxAccidental'
        >>> i = interval.Interval('m2')
        >>> p = pitch.Pitch('C4')
        >>> allPitches = []
        >>> for j in range(15):
        ...    p = b.transposePitchAndApplySimplification(i, p)
        ...    allPitches.append(p.nameWithOctave)
        >>> allPitches
        ['D-4', 'D4', 'E-4', 'F-4', 'F4', 'G-4', 'G4', 'A-4', 'A4',
         'B-4', 'C-5', 'C5', 'D-5', 'D5', 'E-5']

        >>> b.pitchSimplification = 'mostCommon'
        >>> p = pitch.Pitch('C4')
        >>> allPitches = []
        >>> for j in range(15):
        ...    p = b.transposePitchAndApplySimplification(i, p)
        ...    allPitches.append(p.nameWithOctave)
        >>> allPitches
        ['C#4', 'D4', 'E-4', 'E4', 'F4', 'F#4', 'G4', 'A-4', 'A4', 'B-4',
         'B4', 'C5', 'C#5', 'D5', 'E-5']

        PitchSimplification can also be specified in the creation of the IntervalNetwork object

        >>> b = scale.intervalNetwork.IntervalNetwork(pitchSimplification=None)
        >>> p = pitch.Pitch('C4')
        >>> allPitches = []
        >>> for j in range(5):
        ...    p = b.transposePitchAndApplySimplification(i, p)
        ...    allPitches.append(p.nameWithOctave)
        >>> allPitches
        ['D-4', 'E--4', 'F--4', 'G---4', 'A----4']

        Note that beyond quadruple flats or sharps, pitchSimplification is automatic:

        >>> p
        <music21.pitch.Pitch A----4>
        >>> b.transposePitchAndApplySimplification(i, p)
        <music21.pitch.Pitch F#4>
        )NnoneimplicitDiatonic
mostCommonmaxAccidentalra   )r  simplifyEnharmonicTr:  )r$  r  z!unknown pitchSimplification type ,zG allowable values are "maxAccidental" (default), "simplifyEnharmonic", z!"mostCommon", or None (or "none"))
r   hasattrr  rC   r	   ChromaticIntervaltransposePitch
accidentalr  rz   )r   r  r   r   r   s        r   r   z4IntervalNetwork.transposePitchAndApplySimplificationd  s   f #66>1+'9:{?[?[X-G-GH"./1..xq.IE   ..x8E&*>>,,T,:  )L8,,Td,K  )N: 	 3;<O;PPQRcd=>? ? r   )r#   FTr  )r   z!Sequence[interval.Interval | str])rg   z
list[Node])T)r   bool)rn   rW   rg   rW   )r   Node | int | Terminus | None)rg   pitch.Pitch)
r   pitch.Pitch | strr  r  r  r  rF   r%   r   zbool | Direction)r   rl   r   r  r  pitch.Pitch | Noner  r  r  r  r   zbool | Nonerg   CacheKey)NNN)
r   r  r   r  r  pitch.Pitch | str | Noner  r  rg   z.tuple[list[pitch.Pitch], list[Terminus | int]])r   r  r   r  r  r  r  r  )
r   str | pitch.Pitchr   r  r  r  r  r  rF   r%   )r   r  r   r  r  r  r  r  rF   r%   rg   zlist[pitch.Pitch])
r   r  r  r  r  r  rF   r%   rg   zlist[interval.Interval])NN)r   r  r   r  rg   ztuple[pitch.Pitch, pitch.Pitch])
r   r  r   r  r  r  r  r  rF   r%   )
r   r  r   r  r   zpitch.Pitch | note.Note | strrf  rD   rF   r%   )r   r  r  r  r   r  rF   r%   )r   r  r   r  rF   r%   )r   r  r  r  rF   r%   )r   z7t.Union[list[str], list[pitch.Pitch], str, pitch.Pitch]rg   z2tuple[list[pitch.Pitch], pitch.Pitch, pitch.Pitch])r  N)r   r  )r   r  rF   r%   )r   r  N)r  zinterval.Intervalr   r  rg   r  )3r   r   r   r    rL   r   rR   r   r   r   r   r   rj   r   r   r   r   r   r   r   r   r   r   r   r   r%   r-   r   r.   r  r  r/  r8  rF  rJ  rQ  rT  r'  re  r
  r  rt  r  staticmethodr  r   r  r  __annotations__r  r   r#   r   r   r|   r|     s   . >@#(#%4	#:#J	.<S#jK#Z:x8"x"8  $  $  ,  "  ".+Z1F '++/	IJ 6IJV1"f)` ,, 
:  )22&*X'X )X %	X X $XH " $ #	
 #   
B *.)-)-c  c 'c  'c  '	c 
 'c  
6c P *.)-)-F F'F 'F '	F
 'FT 261515'0':':#E* /E*.E* /E* /	E*
 %E*T *.)-)-(22;'; '; '	;
 '; ; 
;~ *.)-)-(22(&( '( '	(
 ( 
!(Z *.	)3')3 ')3
 
))3\ *.	a"'a" 'a"
 
)a"L *.)-)-(22I'I 'I
 'I 'I Ib $((22cR'cR 'cR /	cR !cR cRT  )22;'; ); %	;
 ;D !(22g,'g, %	g, g,\  )22w0'w0 )w0
 w0x 6-L6-	;6- 6-x #/!J -J ` )5!!+4+>+>#'1$31  )1h&M?  !- 	/bJ&J J 
	Jr   r|   c                      e Zd ZdZy)BoundIntervalNetworkz_
    This class is kept only because of the ICMC Paper.  Just use IntervalNetwork instead.
    N)r   r   r   r    r#   r   r   r  r    s     	r   r  __main__)+r    
__future__r   collectionsr   collections.abcr   r  enumtypingtmusic21r   r   r   r	   r
   r   r   Environmentr   Enumr   r%   r}  rW   rD   r  r  r7   r:   Music21Exceptionr<   ProtoM21Objectr@   SlottedObjectMixinrl   rz   r|   r  
_DOC_ORDERr   mainTestr#   r   r   <module>r     s6  . # # $           &{&&'>?'tyy '(		 (  L#s4xT4d:<	L11 	J%7!! J%Z;!7!!6#<#< ;!~	|<< 	,\( \(~P	? 	 tT*
zG r   