-
Notifications
You must be signed in to change notification settings - Fork 393
/
intervalNetwork.py
3103 lines (2626 loc) · 119 KB
/
intervalNetwork.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
863
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
# Name: scale.intervalNetwork.py
# Purpose: A graph of intervals, for scales and harmonies.
#
# Authors: Christopher Ariza
# Michael Scott Asato Cuthbert
#
# Copyright: Copyright © 2010-2023 Michael Scott Asato Cuthbert
# License: BSD, see license.txt
# ------------------------------------------------------------------------------
'''
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.
'''
from __future__ import annotations
from collections import OrderedDict
from collections.abc import Sequence
import copy
import enum
import typing as t
from music21 import common
from music21 import environment
from music21 import exceptions21
from music21 import interval
from music21 import note
from music21 import pitch
from music21 import prebase
environLocal = environment.Environment('scale.intervalNetwork')
class Terminus(enum.Enum):
'''
One of the two Termini of a scale, either Terminus.LOW or
Terminus.HIGH
'''
LOW = 'terminusLow'
HIGH = 'terminusHigh'
def __repr__(self):
return 'Terminus.' self.name
def __str__(self):
return 'Terminus.' self.name
class Direction(enum.Enum):
'''
An enumerated Direction for a scale, either Direction.ASCENDING,
Direction.DESCENDING, or Direction.BI (bidirectional)
'''
BI = 'bi'
ASCENDING = 'ascending'
DESCENDING = 'descending'
def __repr__(self):
return 'Direction.' self.name
def __str__(self):
return 'Direction.' self.name
CacheKey = tuple[
int | Terminus, str, str | None, str | None, bool, bool | None]
def _gte(a, b):
'''
check if a > b or abs(a - b) < epsilon
'''
if a > b:
return True
elif abs(a - b) < 0.00001:
return True
return False
def _lte(a, b):
'''
check if a < b or abs(a - b) < epsilon
'''
if a < b:
return True
elif abs(a - b) < 0.00001:
return True
return False
class EdgeException(exceptions21.Music21Exception):
pass
class Edge(prebase.ProtoM21Object):
'''
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
'''
# noinspection PyShadowingBuiltins
# pylint: disable=redefined-builtin
def __init__(self,
intervalData: interval.Interval | str,
id=None, # id is okay: @ReservedAssignment
direction=Direction.BI):
if isinstance(intervalData, str):
i = interval.Interval(intervalData)
else:
i = intervalData
self.interval: interval.Interval = i
# direction will generally be set when connections added
self.direction: Direction = direction
self.weight = 1.0
# store id
self.id = id
# one or two pairs of Node ids that this Edge connects
# if there are two, it is a bidirectional, w/ first ascending
self._connections: list[tuple[int | Terminus, int | Terminus]] = []
def __eq__(self, other):
'''
>>> 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
'''
return (isinstance(other, self.__class__)
and self.__dict__ == other.__dict__)
def _reprInternal(self):
return f'{self.direction} {self.interval.name} {self._connections!r}'
def addDirectedConnection(
self,
node1: Node | int | Terminus,
node2: Node | int | Terminus,
direction=None
) -> None:
'''
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)]>
'''
# may be Node objects, or number, or Terminus
if isinstance(node1, (Terminus, int)):
n1Id = node1
else: # assume an Node
n1Id = node1.id
if isinstance(node2, (Terminus, int)):
n2Id = node2
else: # assume an Node
n2Id = node2.id
self._connections.append((n1Id, n2Id))
# must specify a direction
if direction not in (Direction.ASCENDING, Direction.DESCENDING):
raise EdgeException('must request a direction')
self.direction = direction
def addBiDirectedConnections(self, node1, node2):
'''
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)]>
'''
# must assume here that n1 to n2 is ascending; need to know
self.addDirectedConnection(node1, node2, Direction.ASCENDING)
self.addDirectedConnection(node2, node1, Direction.DESCENDING)
self.direction = Direction.BI # can be ascending, descending
def getConnections(
self,
direction: None | Direction = None
) -> list[tuple[int | Terminus, int | Terminus]]:
'''
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)]
'''
if direction is None:
direction = self.direction # assign native direction
# do not need to supply direction, because direction is defined
# in this Edge.
if self.direction == direction:
return self._connections
# if requesting bi from a mono directional edge is an error
if (direction == Direction.BI
and self.direction in (Direction.ASCENDING, Direction.DESCENDING)):
raise EdgeException('cannot request a bi direction from a mono direction')
# if bi and we get an ascending/descending request
if (direction in (Direction.ASCENDING, Direction.DESCENDING)
and self.direction == Direction.BI):
# assume that in a bi-representation, the first is ascending
# the second is descending
# NOTE: this may not mean that we are actually ascending, we may
# use the direction of the interval to determine
if direction == Direction.ASCENDING:
return [self._connections[0]]
elif direction == Direction.DESCENDING:
return [self._connections[1]]
# if no connections are possible, return empty list
return []
# keep separate property, since getConnections takes a direction argument.
@property
def connections(self) -> list[tuple[int | Terminus, int | Terminus]]:
return self.getConnections()
class Node(prebase.ProtoM21Object, common.SlottedObjectMixin):
'''
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
'''
__slots__ = ('id', 'degree', 'weight')
# noinspection PyShadowingBuiltins
# pylint: disable=redefined-builtin
def __init__(self, id: Terminus | int, degree: int, weight: float = 1.0):
# store id, either as string, such as terminusLow, or a number.
# ids are unique to any node in the network
self.id: Terminus | int = id
# the degree is used to define ordered node counts from the bottom
# the degree is analogous to scale degree or degree
# more than one node may have the same degree
self.degree: int = degree
# node weight might be used to indicate importance of scale positions
self.weight: float = weight
def __hash__(self):
hashTuple = (self.id, self.degree, self.weight)
return hash(hashTuple)
def __eq__(self, other):
'''
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
'''
return hash(self) == hash(other)
def _reprInternal(self):
return f'id={self.id!r}'
# ------------------------------------------------------------------------------
class IntervalNetworkException(exceptions21.Music21Exception):
pass
# presently edges are interval objects, can be marked as
# ascending, descending, or bidirectional
# edges are stored in dictionary by index values
# Nodes are undefined pitches; pitches are realized on demand.
# Nodes are stored as an unordered list of coordinate pairs.
# Pairs are edge indices: showing which edges connect to this node
# could model multiple connections within an object
# up: a M2 b m2 C M2 D
# down: a M2 b m3 D
# edges M2(1 -), m2(2 ), M2(3 )
# edges m3(4-)
# ------------------------------------------------------------------------------
class IntervalNetwork:
'''
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.
'''
def __init__(self,
edgeList: Sequence[interval.Interval | str] = (),
octaveDuplicating=False,
deterministic=True,
pitchSimplification='maxAccidental'):
# store each edge with an index that is incremented when added
# these values have no fixed meaning but are only for reference
self.edgeIdCount = 0
self.nodeIdCount = 0
# a dictionary of Edge object, where keys are edgeId values
# Edges store directed connections between Node ids
self.edges: OrderedDict[Terminus | int, Edge] = OrderedDict()
# nodes suggest Pitches, but Pitches are not stored
self.nodes: OrderedDict[Terminus | int, Node] = OrderedDict()
if edgeList: # auto initialize
self.fillBiDirectedEdges(edgeList)
# define if pitches duplicate each octave
self.octaveDuplicating = octaveDuplicating
self.deterministic = deterministic
# could be 'simplifyEnharmonic', 'mostCommon' or None
self.pitchSimplification = pitchSimplification
# store segments
self._ascendingCache: OrderedDict[
CacheKey,
tuple[list[pitch.Pitch], list[Terminus | int]]
] = OrderedDict()
self._descendingCache: OrderedDict[
CacheKey,
tuple[list[pitch.Pitch], list[Terminus | int]]
] = OrderedDict()
def clear(self):
'''
Remove and reset all Nodes and Edges.
'''
self.edgeIdCount = 0
self.nodeIdCount = 0
self.edges = OrderedDict()
self.nodes = OrderedDict()
self._ascendingCache = OrderedDict()
self._descendingCache = OrderedDict()
def __eq__(self, other):
'''
>>> 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
'''
# compare all nodes and edges; if the same, and all keys are the same,
# then matched
if not isinstance(other, self.__class__):
return False
for attr in ('edgeIdCount', 'nodeIdCount', 'edges', 'nodes',
'octaveDuplicating', 'deterministic', 'pitchSimplification'):
if getattr(self, attr) != getattr(other, attr):
return False
return True
def fillBiDirectedEdges(self, edgeList: Sequence[interval.Interval | str]):
# noinspection PyShadowingNames
'''
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']
'''
self.clear()
degreeCount = 1 # steps start from one
nLow = Node(id=Terminus.LOW, degree=degreeCount)
degreeCount = 1
self.nodes[nLow.id] = nLow
nPrevious = nLow
for i, eName in enumerate(edgeList):
# first, create the next node
if i < len(edgeList) - 1: # if not last
n = Node(id=self.nodeIdCount, degree=degreeCount)
self.nodeIdCount = 1
degreeCount = 1
nFollowing = n
else: # if last
# degree is same as start
nHigh = Node(id=Terminus.HIGH, degree=degreeCount)
nFollowing = nHigh
# add to node dictionary
self.nodes[nFollowing.id] = nFollowing
# then, create edge and connection
e = Edge(eName, id=self.edgeIdCount)
self.edges[e.id] = e # store
self.edgeIdCount = 1
e.addBiDirectedConnections(nPrevious, nFollowing)
# update previous with the node created after this edge
nPrevious = nFollowing
def fillDirectedEdges(self, ascendingEdgeList, descendingEdgeList):
'''
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.
'''
self.clear()
# if both are equal, then assigning steps is easy
if len(ascendingEdgeList) != len(descendingEdgeList):
# problem here is that we cannot automatically assign degree values
raise IntervalNetworkException('cannot manage unequal sized directed edges')
degreeCount = 1 # steps start from one
nLow = Node(id=Terminus.LOW, degree=degreeCount)
degreeCount = 1
self.nodes[nLow.id] = nLow
nPrevious = nLow
for i, eName in enumerate(ascendingEdgeList):
# first, create the next node
if i < len(ascendingEdgeList) - 1: # if not last
n = Node(id=self.nodeIdCount, degree=degreeCount)
self.nodeIdCount = 1
degreeCount = 1
nFollowing = n
else: # if last
nHigh = Node(id=Terminus.HIGH, degree=degreeCount) # degree is same as start
nFollowing = nHigh
# add to node dictionary
self.nodes[nFollowing.id] = nFollowing
# then, create edge and connection; eName is interval
e = Edge(eName, id=self.edgeIdCount)
self.edges[e.id] = e
self.edgeIdCount = 1
e.addDirectedConnection(nPrevious, nFollowing,
direction=Direction.ASCENDING)
# update previous with the node created after this edge
nPrevious = nFollowing
# repeat for descending, but reverse direction, and use
# same low and high nodes
degreeCount = 1 # steps start from one
nLow = self.nodes[Terminus.LOW] # get node; do not need to add
degreeCount = 1
nPrevious = nLow
for i, eName in enumerate(descendingEdgeList):
# first, create the next node
if i < len(descendingEdgeList) - 1: # if not last
n = Node(id=self.nodeIdCount, degree=degreeCount)
self.nodeIdCount = 1
degreeCount = 1
nFollowing = n
# add to node dictionary
self.nodes[nFollowing.id] = nFollowing
else: # if last
nHigh = self.nodes[Terminus.HIGH]
nFollowing = nHigh
# then, create edge and connection
e = Edge(eName, id=self.edgeIdCount)
self.edges[e.id] = e
self.edgeIdCount = 1
# order here is reversed from above
e.addDirectedConnection(nFollowing, nPrevious, direction=Direction.DESCENDING)
# update previous with the node created after this edge
nPrevious = nFollowing
def fillArbitrary(self, nodes, edges):
# noinspection PyShadowingNames
'''
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>]
'''
self.clear()
for nDict in nodes:
n = Node(id=nDict['id'], degree=nDict['degree'])
if 'weight' in nDict:
n.weight = nDict['weight']
self.nodes[n.id] = n
eId = 0
for eDict in edges:
e = Edge(eDict['interval'], id=eId)
for nId1, nId2, direction in eDict['connections']:
# do not need to access from nodes dictionary here
# but useful as a check that the node has been defined.
if direction == Direction.BI:
e.addBiDirectedConnections(self.nodes[nId1], self.nodes[nId2])
else:
e.addDirectedConnection(self.nodes[nId1],
self.nodes[nId2], direction=direction)
self.edges[e.id] = e
eId = 1
def fillMelodicMinor(self):
'''
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']
'''
nodes = ({'id': Terminus.LOW, 'degree': 1}, # a
{'id': 0, 'degree': 2}, # b
{'id': 1, 'degree': 3}, # c
{'id': 2, 'degree': 4}, # d
{'id': 3, 'degree': 5}, # e
{'id': 4, 'degree': 6}, # f# ascending
{'id': 5, 'degree': 6}, # f
{'id': 6, 'degree': 7}, # g# ascending
{'id': 7, 'degree': 7}, # g
{'id': Terminus.HIGH, 'degree': 8}, # a
)
edges = ({'interval': 'M2',
'connections': ([Terminus.LOW, 0, Direction.BI],) # a to b
},
{'interval': 'm2',
'connections': ([0, 1, Direction.BI],) # b to c
},
{'interval': 'M2',
'connections': ([1, 2, Direction.BI],) # c to d
},
{'interval': 'M2',
'connections': ([2, 3, Direction.BI],) # d to e
},
{'interval': 'M2',
'connections': ([3, 4, Direction.ASCENDING],) # e to f#
},
{'interval': 'M2',
'connections': ([4, 6, Direction.ASCENDING],) # f# to g#
},
{'interval': 'm2',
'connections': ([6, Terminus.HIGH, Direction.ASCENDING],) # g# to a
},
{'interval': 'M2',
'connections': ([Terminus.HIGH, 7, Direction.DESCENDING],) # a to g
},
{'interval': 'M2',
'connections': ([7, 5, Direction.DESCENDING],) # g to f
},
{'interval': 'm2',
'connections': ([5, 3, Direction.DESCENDING],) # f to e
},
)
self.fillArbitrary(nodes, edges)
self.octaveDuplicating = True
self.deterministic = True
# --------------------------------------------------------------------------
# for weighted selection of nodes
def weightedSelection(self, edges, nodes):
'''
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
'''
# use index values as values
iValues = list(range(len(edges)))
weights = [n.weight for n in nodes]
# environLocal.printDebug(['weights', weights])
i = common.weightedSelection(iValues, weights)
# return corresponding edge and node
return edges[i], nodes[i]
# --------------------------------------------------------------------------
@property
def degreeMin(self):
'''
Return the lowest degree value.
>>> edgeList = ['M2', 'M2', 'm2', 'M2', 'M2', 'M2', 'm2']
>>> net = scale.intervalNetwork.IntervalNetwork()
>>> net.fillBiDirectedEdges(edgeList)
>>> net.degreeMin
1
'''
x = None
for n in self.nodes.values():
if x is None:
x = n.degree
if n.degree < x:
x = n.degree
return x
@property
def degreeMax(self):
'''
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
'''
x = None
for n in self.nodes.values():
if x is None:
x = n.degree
if n.degree > x:
x = n.degree
return x
@property
def degreeMaxUnique(self):
'''
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
'''
x = None
for nId, n in self.nodes.items():
# reject terminus high, as this duplicates terminus low
if nId == Terminus.HIGH:
continue
if x is None:
x = n.degree
if n.degree > x:
x = n.degree
return x
@property
def terminusLowNodes(self) -> list[Node]:
'''
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.
'''
post = []
# for now, there is only one
post.append(self.nodes[Terminus.LOW])
return post
@property
def terminusHighNodes(self):
'''
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>]
'''
post = []
# for now, there is only one
post.append(self.nodes[Terminus.HIGH])
return post
# --------------------------------------------------------------------------
def getNodeDegreeDictionary(self, equateTermini: bool = True):
'''
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.
'''
post = OrderedDict()
for nId, n in self.nodes.items():
if equateTermini:
if nId == Terminus.HIGH:
# get the same degree as the low
post[nId] = self.nodes[Terminus.LOW].degree
else:
post[nId] = n.degree
else: # directly assign from attribute
post[nId] = n.degree
return post
def nodeIdToDegree(self, nId):
'''
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.
'''
nodeStep = self.getNodeDegreeDictionary()
return nodeStep[nId] # gets degree integer
def nodeIdToEdgeDirections(self, nId):
'''
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]
'''
collection = []
if isinstance(nId, Node):
nObj = nId
nId = nObj.id
else:
nObj = self.nodes[nId]
for eId in self.edges:
eObj = self.edges[eId]
# environLocal.printDebug(['nodeIdToEdgeDirections()', eObj])
for x, y in eObj.connections: # pairs of node ids
if x == nId: # this node is a source
collection.append(eObj.direction)
break # only get one direction for each edge
elif y == nId: # this node is a destination
collection.append(eObj.direction)
break
if not collection:
raise IntervalNetworkException('failed to match any edges', nObj)
return collection
def degreeModulus(self, degree: int) -> int:
'''
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)