Distribution Module¶
Distribution
¶
Distribution(
name: str,
data: List[Any],
distribution_type: str,
dimensions: List[int],
x_categories: List[Union[int, float, str]],
x_label: str,
y_categories: Optional[List[Union[int, float, str]]],
y_label: str,
)
Represents a probability distribution or histogram and its metadata.
See histogram.py for Histogram1D and Histogram2D, which facilitate the computation of distributions from data.
Author: Roger B. Dannenberg
Parameters:
-
name(str) –The name of the distribution used for plot titles.
-
data(List[Any]) –The data points for the distribution.
-
distribution_type(str) –The type of distribution. Currently used values are described below. "weights" can mean either probabilities or raw counts.
- "pitch_class" - weights for 12 pitch classes, possibly weighted by duration.
- "interval" - weights for pitch intervals, possibly weighted by duration.
- "pitch_class_interval" - weights for pitch class intervals, possibly weighted by duration. (mod 12, not currently used; should there also be a pitch_class_size based on absolute interval size mod 12? And if so, should there be an interval_class computed from interval mod 12? And interval_size_class based on absolute interval size mod 12? Note that "interval" ignores intervals larger than one octave.)
- "duration" - weights for durations
- "interval_size" - weights for interval sizes, possibly weighted by duration.
- "interval_direction" - proportion of upward intervals for each interval size, possibly weighted by duration.
- "pitch_class_transition" - weights for pitch class transitions, possibly weighted by duration (2-dimensional distribution).
- "interval_transition" - weights for interval transitions, possibly weighted by duration (2-dimensional distribution).
- "duration_transition" - weights for duration transitions, possibly weighted by duration (2-dimensional distribution).
- "key_correlation" - weights for key correlations, generally correlation with 12 major key profiles followed by correlations with 12 minor key profiles.
- "symmetric_key_profile" - weights for symmetric key profiles. Key profiles themselves are distributions. Symmetric keys use the same 12 weights for all keys (e.g.,, Krumhansl-Kessler), simply rotated for each key.
- "asymmetric_key_profile" - weights for asymmetric key profiles, where each key has its own set of 12 weights (e.g.,, Bellman-Budge).
- "root_support_weights" - root support weights (see
amads.harmony.root_finding.parncutt) - "pitch" - weights over raw (MIDI) pitch numbers,
e.g.,, for vocal/instrumental range, as opposed to pitch class (as above).
See
Distribution.from_pitchesfor a constructor that builds one of these directly from a list of pitches.
This list is open-ended (see
Distribution.KNOWN_TYPES) and is currently just informational: the value is not used to control plotting, except thatdistribution_type="pitch"changes the default 1-D plot style from "bar" to "line" (seeplot). -
dimensions(List[int]) –The dimensions of the distribution, e.g., [12] for a pitch class distribution or [25, 25] for an interval_transition (intervals are from -12 to +12 and include 0 for unison, intervals larger than one octave are ignored).
-
x_categories(List[Union[int, float, str]]) –The categories for the x-axis.
-
x_label(str) –The label for the x-axis.
-
y_categories(Optional[List[Union[int, float, str]]]) –The categories for the y-axis, if any, otherwise None.
-
y_label(str) –The label for the y-axis.
Attributes:
-
same as Parameters (above)–
Raises:
-
ValueError–If
dimensionsis not 1-D or 2-D, or ifdata,x_categories, ory_categoriesare inconsistent withdimensions(see_validate).
Source code in amads/core/distribution.py
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 | |
Functions¶
normalize
¶
normalize(method: str = 'Sum')
Convert weights or counts to a probability distribution.
Parameters:
-
method(str, default:'Sum') –Normalization method, forwarded to
amads.algorithms.norm.normalize. Any value accepted there is valid here, e.g., "Sum"/"l1" (values sum to 1, the default and previous hard-coded behavior), "Euclidean"/"l2" (vector length 1), or "max"/"infinity" (largest value becomes 1).
Returns:
-
Distribution–self, for chaining.
Notes
For a 2-D distribution, data is flattened before normalizing and reshaped back afterward,
so e.g., the default "Sum" normalizes over the entire matrix
(all cells sum to 1), not per row or column.
If you want each row to be its own conditional distribution summing to 1
(e.g., for a transition matrix),
normalize each row individually before constructing the Distribution,
or call normalize on single-row slices.
Source code in amads/core/distribution.py
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 | |
from_pitches
classmethod
¶
from_pitches(
pitches: List[Union[Pitch, int, float]],
name: str = "Pitch Distribution",
weights: Optional[List[float]] = None,
buffer: int = 2,
use_spelling: Optional[bool] = None,
) -> Distribution
Build a 1-D Distribution of raw pitch (not pitch class) from a list of pitches,
e.g., to plot a vocal or instrumental range.
Bins are one per semitone across the observed range.
Parameters:
-
pitches(list of Pitch | int | float) –The pitches to histogram. Entries may be
amads.core.pitch.Pitchinstances, or raw numeric MIDI key numbers (usually ints; any floats are binned to the nearest semitone). The two kinds may be mixed in one list. -
name(str, default:'Pitch Distribution') –Name used for the distribution and as the plot title.
-
weights(list of float, optional Per-pitch weights,, default:None) –e.g., note durations, aligned element-for-element with
pitches. Defaults to a weight of 1 per pitch, i.e. a plain count histogram. -
buffer(int, default:2) –Semitones of empty margin added on each side of the observed min/max pitch so extreme values aren't plotted right at the axis edge (default 2). Use 0 for no buffer.
-
use_spelling(bool, default:None) –If True, x-axis bin labels are spelled note names (e.g., "C#4") taken from the
Pitchobjects inpitches; every entry inpitchesmust then be aPitch(raw numbers have no spelling to draw on). If False, labels are plain MIDI key numbers. If None (default), spelling is used automatically when every entry inpitchesis aPitch, and MIDI numbers are used otherwise.
Returns:
-
Distribution–A 1-D distribution with
distribution_type="pitch". Bin values are raw (weighted) counts; call.normalize()for a probability distribution. Bins with no observed pitch get a value of 0. For ranges wider thanDistribution.PITCH_WIDE_RANGE_SEMITONES, all but one x-axis label per octave are blanked out so they stay legible; the underlying bins/data are unaffected.
Raises:
-
ValueError–If
pitchesis empty; ifweightsis provided and its length doesn't matchpitches; if any entry ofpitchesis not aPitch,int, orfloat; if anyPitchis unpitched (key_num is None); or ifuse_spelling=Truebut not every entry ofpitchesis aPitch.
Examples:
>>> from amads.core.pitch import Pitch
>>> notes = [Pitch("C4"), Pitch("E4"), Pitch("G4"), Pitch("C5"), Pitch("E5"), Pitch("G5")]
>>> dist = Distribution.from_pitches(notes, name="Soprano range example")
>>> dist.distribution_type
'pitch'
Source code in amads/core/distribution.py
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 | |
plot
¶
plot(
color: Optional[str] = None,
option: Optional[str] = None,
show: bool = True,
fig: Optional[Figure] = None,
ax: Optional[Axes] = None,
) -> Figure
Virtual plot function for Distribution. Allows standalone plotting of a Distribution (when fig and ax are None), while providing enough extensibility to invoke this plot function or its overwritten variants for subplotting when fig and ax are provided as arguments.
Parameters:
-
color(Optional[str], default:None) –Plot color string specification. In this particular plot function, it is handled in 1-D distributions and ignored in 2-D distributions. None for default option (Distribution.DEFAULT_BAR_COLOR).
-
option(Optional[str], default:None) –Plot style string specification. In this particular plot function, only {"bar", "line"} are valid string arguments that will be handled in a 1-D distribution, while any argument is ignored in 2-D distributions. None for default option ("bar").
-
show(bool, default:True) –Whether to call
plt.show()at the end. -
fig(Figure, default:None) –Provide existing Figure to draw on; if omitted, a new figure is created.
-
ax(Axes, default:None) –Provide existing axes to draw on; if omitted, a new figure and axes are created.
Raises:
-
ValueError–A ValueError is raised if:
ax(axes) but notfig(Figure) is provideddimsis not 1 or 2
Notes
Behavior to this specific plot method:
- 1-D: bar (default) or line when kind is "line"
- 2-D: heatmap
Source code in amads/core/distribution.py
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 | |
show
¶
show() -> None
Print information about the distribution
Source code in amads/core/distribution.py
508 509 510 511 512 513 514 515 516 | |
plot_multiple
classmethod
¶
plot_multiple(
dists: List[Distribution],
show: bool = True,
options: Optional[Union[str, List[str]]] = None,
colors: Optional[Union[str, List[str]]] = None,
) -> Optional[Figure]
Plot multiple distributions into a single Figure using vertically stacked subplots.
Returns:
-
Figure or None–A matplotlib Figure when at least one distribution is plotted; otherwise None when
distsis empty.
Parameters:
-
dists(list[Distribution]) –Distributions to plot. 2-D are rendered as heatmaps; 1-D below them.
-
show(bool, default:True) –Whether to call
plt.show()at the end. -
options(str | list[str] | None, default:None) –plot style per distribution (e.g., "bar" or "line"). If a single string is given, it is broadcast to all distributions. If None, defaults to "bar".
-
colors(str | list[str] | None, default:None) –color option per distribution. If a single string is given, it is broadcast to all 1-D distributions. If None, defaults to the single color Distribution.DEFAULT_BAR_COLOR.
Notes
- distributions are plotted in the same order they were presented in dists list
- as long as a Distribution or inherited class has a valid plot function implemented, the relevant plot will be added to the figure at the specified axes.
optionsandcolorsapply to all distributions- Although the original plot function is only limited to
optionandcolorbeing used in the 1-D case, it is not to say that a class inheriting Distribution won't leverage these arguments. - You can pass either a list (per-series) or a single string. When a single string is provided, it will be broadcast to all inputs. For example, kinds="line" makes all 1-D plots line charts.
Source code in amads/core/distribution.py
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 | |
plot_grouped_1d
classmethod
¶
plot_grouped_1d(
dists: List[Distribution],
show: bool = True,
options: Optional[Union[str, List[str]]] = None,
colors: Optional[Union[str, List[str]]] = None,
) -> Optional[Figure]
Overlay multiple 1-D distributions on a single axes.
This function draws all input 1-D distributions in one matplotlib
Axes so that each category (x bin) shows a "group" of values—one
per distribution. You can mix plotting styles using the kinds
argument (for example, some as bars and others as lines with
markers. Colors are controlled via the colors argument.
Parameters:
-
dists(list[Distribution]) –1-D distributions to compare in a single plot.
-
show(bool, default:True) –Whether to call
plt.show()at the end. -
options(str | list[str] | None, default:None) –Per-distribution plot style. Allowed values: "bar" or "line". You can provide a single string to apply to all series (broadcast), or a list with length
len(dists). If None, all series default to "bar". -
colors(str | list[str] | None, default:None) –Per-distribution color list. You can provide a single string to apply to all series (broadcast), or a list with length
len(dists). If None, a distinct default color palette is applied (rcParams cycle or the tab10 palette).
Returns:
-
Figure or None–A matplotlib Figure if any distributions are plotted; None when
distsis empty.
Constraints
- Only 1-D distributions are accepted. All inputs must have the same length (number of categories) so they can be grouped per category.
- The x/y labels and category names are taken from the first
distribution in
dists. Hence, this function does not support overlaying 1-D distributions with different categories and labels.
How this differs from plot_multiple
- plot_grouped_1d overlays all 1-D distributions on a single axes
to allow:
- per-category (bin-by-bin) comparison intuitive and compact for grouped bar graphs
- intuitive and compact gradient comparison for overlaid line graphs.
Since all distributions are plotted in a single plot, we can compare all plots within a single legend. - plot_multiple creates a vertical stack of subplots, one per distribution, while leveraging the plot attribute of each Distribution (and also supports 2-D heatmaps).
Source code in amads/core/distribution.py
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 | |
Histogram Module¶
histogram
¶
Compute histograms and distributions.
This module provides Histogram1D and Histogram2D classes for computing one-dimensional and two-dimensional histograms, respectively. Histograms can be normalized to form probability distributions.
The bins attribute can be directly assigned to the data attribute of
the Distribution class in core.distribution.
Histogram bins can be specified either by their centers or their boundaries. When centers are provided:
- the number of centers gives the number of bins
- if ignore_extrema is False, the first and last bins are open-ended, extending to -infinity and +infinity, respectively. Boundaries can be computed from centers using either linear or logarithmic interpolation. If provided, boundaries can be of length len(centers) + 1, in which case the first and last values are ignored (since the bins are open-ended); otherwise, boundaries have length len(centers) - 1.
- if ignore_extrema is True, the first and last bins are closed, and values outside the bin boundaries are ignored. In this case, boundaries must be provided and have length len(centers) + 1.
When centers are not provided, boundaries must be provided:
- the number of bins is len(boundaries) - 1
- bin centers can be computed as arithmetic or geometric means of boundaries.
- if ignore_extrema is False, the upper and lower boundaries are ignored, making the first and last bins open-ended.
- if ignore_extrema is True, the first and last bins are closed, and values outside the bin boundaries are ignored.
Data is placed in a bin when it is greater or equal to the lower boundary and less than the upper boundary in keeping with NumPy / Matplotlib / Pandas histogram behavior. Be aware that when boundaries are computed from centers that float boundary values may be inexact.
Author: Roger Dannenberg
Classes¶
Histogram1D
¶
Histogram1D(
bin_centers: Optional[list[float]] = None,
bin_boundaries: Optional[list[float]] = None,
interpolation: str = "linear",
ignore_extrema: bool = False,
initial_value: float = 0.0,
)
Class for computing one-dimensional histograms.
Parameters:
-
bin_centers(list of float, default:None) –Centers of the histogram bins.
-
bin_boundaries(list of float, default:None) –boundaries of the histogram bins.
-
interpolation(str, default:'linear') –Interpolation method for missing bin_centers or bin_boundaries. "linear" to use the average of neighboring values, "log" for geometric mean.
-
ignore_extrema(bool, default:False) –If True, values below the lowest bin edge and above the highest bin edge are ignored. If False, they are counted in the first and last bins, respectively. Default is False.
-
initial_value(float, default:0.0) –The initial bin values are all set to this value (default is 0). This avoids a divide-by-a-zero-total problem when normalizing bins that are all zero. This can also avoid zero-probability bins by giving all bins a non-zero "prior." The divide-by-zero problem is avoided in any case: When normalizing and all bins are zero, the bin values are left at zero.
Attributes:
-
bin_boundaries(list of float) –Boundaries of the histogram bins. If ignore_extrema is True, bin_boundaries has length len(bin_centers) + 1 and surround all bins. If ignore_extrema is False, bin_boundaries has length len(bin_centers) - 1 and the first and last bins are open-ended, so bin_boundaries are boundaries between bins only.
-
bin_centers(list of float) –Centers of the histogram bins (used for plot labels)
-
bins(list of float) –(weighted) counts or probability of data points in each bin.
-
ignore_extrema(bool) –If True, values outside the bin boundaries are ignored.
Source code in amads/core/histogram.py
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 | |
Functions¶
find_bin
¶
find_bin(value: float)
find the bin index for a given value such that i indexes the next boundary above value. If the value is greater or equal to the highest boundary, len(bin_boundaries) is returned.
Source code in amads/core/histogram.py
221 222 223 224 225 226 227 228 229 230 231 | |
add_point
¶
add_point(data: float, weight: float = 1.0)
Record one count or weight update to the histogram
Parameters:
-
data(float) –value to be recorded in the histogram
-
weight(float, default:1.0) –weight to add to the appropriate bin (default is 1.0)
Returns:
-
Optional[int]–bin number where the data point was recorded or None if data was out of bounds
Source code in amads/core/histogram.py
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 | |
normalize
¶
normalize()
Convert the histogram into a probability distribution. If all bins are zero, the resulting bins remain at zero.
Source code in amads/core/histogram.py
260 261 262 263 264 265 266 267 | |
Histogram2D
¶
Histogram2D(
bin_centers: Optional[list[float]] = None,
bin_boundaries: Optional[list[float]] = None,
interpolation: str = "linear",
ignore_extrema: bool = False,
initial_value: float = 0.0,
)
Bases: Histogram1D
Class for computing two-dimensional histograms.
Parameters:
-
bin_centers(list of float, default:None) –Centers of the histogram bins.
-
bin_boundaries(list of float, default:None) –boundaries of the histogram bins.
-
interpolation(str, default:'linear') –Interpolation method for missing bin_centers or bin_boundaries. "linear" to use the average of neighboring values, "log" for geometric mean.
-
ignore_extrema(bool, default:False) –If True, values below the lowest bin edge and above the highest bin edge are ignored. If False, they are counted in the first and last bins, respectively. Default is False.
Attributes:
-
bin_boundaries(list of float) –Boundaries of the histogram bins.
-
bin_centers(list of float) –Centers of the histogram bins (used for plot labels)
-
bins(list of float) –(weighted) counts or probability of data points in each bin.
-
ignore_extrema(bool) –If True, values outside the bin boundaries are ignored.
Source code in amads/core/histogram.py
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 | |
Functions¶
find_bin
¶
find_bin(value: float)
find the bin index for a given value such that i indexes the next boundary above value. If the value is greater or equal to the highest boundary, len(bin_boundaries) is returned.
Source code in amads/core/histogram.py
221 222 223 224 225 226 227 228 229 230 231 | |
add_point
¶
add_point(data: float, weight: float = 1.0)
Record one count or weight update to the histogram
Parameters:
-
data(float) –value to be recorded in the histogram
-
weight(float, default:1.0) –weight to add to the appropriate bin (default is 1.0)
Returns:
-
Optional[int]–bin number where the data point was recorded or None if data was out of bounds
Source code in amads/core/histogram.py
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 | |
add_point_2d
¶
add_point_2d(
data1: Optional[float],
data2: float,
weight: float = 1.0,
prev: Optional[int] = None,
)
Record one count or weight update to the histogram
A typical use is to record consecutive elements of a sequence as data1 along with the next element as data2. In this case, data2 will become data1 in the next call, so the returned bin index for data2 can be provided as prev in the next call to avoid re-compmuting the bin index for data1.
To further support this use case, if data1 is None, the histogram is not changed, but the bin index for data2 is still computed and returned. Thus, you can pass None for data1 and the first element as data2 to get things started.
If the histogram is not updated (because data1 is None or because data1 or data2 are out of bounds and ignore_extrema is True), None is returned, in which case data1 should be passed as None in the next call as if starting a new sequence.
Parameters:
-
data1(float) –value for dimension 1 (or None to skip)
-
data2(float) –value for dimension 2
-
weight(float, default:1.0) –weight to add to the appropriate bin (default is 1.0)
-
prev(Optional(int), default:None) –optional previous bin index for data1; if provided, this value is used instead of recomputing the bin index for data1.
Returns:
-
int–bin number for data2 if data were used to add to the histogram, else None (which means the bin must be calculated).
Source code in amads/core/histogram.py
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 | |
Functions¶
boundaries_to_centers
¶
boundaries_to_centers(
boundaries: list[float], interpolation: str = "linear"
) -> list[float]
Convert bin boundaries to bin centers.
The lower and upper boundaries are only used to compute the centers of the bins in between, so the returned list has length len(boundaries) - 1, so the lower bin will count all values below boundaries[1], and the upper bin will count all values above boundaries[-2].
If interpolation is linear, the center between two boundaries x1 and x2 is (x1 + x2) / 2. If interpolation is 'log', the center is sqrt(x1 * x2).
Parameters:
-
boundaries(list[float]) –List of bin boundaries.
-
interpolation(str, default:'linear') –"linear" for arithmetic mean, "log" for geometric mean.
Returns:
-
list[float]–List of bin centers.
Source code in amads/core/histogram.py
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 | |
centers_to_boundaries
¶
centers_to_boundaries(
centers: list[float], interpolation: str = "linear"
) -> list[float]
Convert bin centers to bin boundaries.
The returned list has length len(centers) - 1, with the first and last bins being open-ended.
To get a closed interval around upper or lower centers, simply add an additional center below or above and ignore the resulting values. In the case of a distribution, to truly throw out the outliers, you will need to extract the desired sub-vector or sub-matrix and re-normalize.
If interpolation is "linear", the boundary between two centers x1 and x2 is (x1 + x2) / 2. If interpolation is "log", the boundary is sqrt(x1 * x2).
Parameters:
-
centers(list[float]) –List of bin centers.
-
interpolation(str, default:'linear') –"linear" for arithmetic mean, "log" for geometric mean.
Returns:
-
list[float]–List of bin boundaries.
Source code in amads/core/histogram.py
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 | |