All files / src/pipeline step2chords.js

100% Statements 32/32
100% Branches 20/20
100% Functions 11/11
100% Lines 30/30

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                              2x 2x 2x 2x 1x 1x 1x 1x     1x   2x 6x       10x                                           3x 3x 3x 1x             2x 2x 1x             3x 3x 1x 2x   1x 3x   1x                             14x 14x                                                       70x                           168x                                                                                      
import { Step, Solvable } from "./step.js";
import { modelChords } from "../model/constraints2.js";
import { noteNames, chordGraph, chordName } from "../model/theory.js";
 
/**
 * Step 2: chord-progression solving as shortest path of fixed length over the
 * weighted chord graph G = (V, E, w); emits Roman-numeral progression + SVG.
 * @implements {Step}
 */
export class Step2Chords extends Solvable(Step) {
  /**
   * @override
   * @return {Promise<Object[]>} SCHEMA with the part.style preset options patched in.
   */
  async schema() {
    const presetOptions = ["manual"];
    const presetLabels = ["Manual"];
    try {
      const resp = await fetch("scripts/presets/index.json");
      const index = await resp.json();
      for (const p of index) {
        presetOptions.push(p.id);
        presetLabels.push(`${p.name} (${p.works})`);
      }
    } catch {
      console.warn("No preset index found, using manual only");
    }
    return SCHEMA.map((field) =>
      field.name === "part"
        ? {
            ...field,
            template: field.template.map((t) =>
              t.name === "style"
                ? { ...t, options: presetOptions, labels: presetLabels }
                : t,
            ),
          }
        : field,
    );
  }
 
  /**
   * @override
   * Build chord-progression model, solve, render result with chord-graph data plus
   * Roman-numeral progression (NC-filled when disabled, empty on UNSAT) and a concrete
   * chord-name display string.
   * @param {Object} parameters - Per-part form values; see {@link Step2Chords#schema}.
   * @param {function(model: string): Promise<Object|null>} solver
   *  Pre-bound solver callback returning the MZN solution {path: number[], total_cost: number} or null.
   * @return {Promise<Object>}
   *  Resolves to {textOutput, chordGraph: {graph, path, key, mode}, chords, concreteProgression};
   *  path is {nodes: string[], edges: Set<string>} on success, null otherwise.
   */
  async solve(parameters, solver) {
    const { key, mode, enable, preset, bars } = parameters;
    const graph = chordGraph(mode, preset);
    if (!enable) {
      return {
        textOutput: "Chord progression disabled.",
        chordGraph: { graph, path: null, key, mode },
        chords: Array(bars).fill("NC"),
        concreteProgression: "",
      };
    }
    const solution = await solver(modelChords(parameters, graph));
    if (!solution) {
      return {
        textOutput: "No chord progression found.",
        chordGraph: { graph, path: null, key, mode },
        chords: [],
        concreteProgression: "",
      };
    }
    const pathNodes = solution.path.map((i) => graph.nodes[i - 1]);
    const concreteNames = pathNodes.map((n) => chordName(n, key));
    const pathEdges = new Set(
      pathNodes.slice(0, -1).map((n, i) => `${n}->${pathNodes[i + 1]}`),
    );
    const labeled = pathNodes
      .map((n, i) => `${n} (${concreteNames[i]})`)
      .join(" -> ");
    return {
      textOutput: `Chord Progression Found:\n${labeled}\nTotal cost: ${solution.total_cost}`,
      chordGraph: {
        graph,
        path: { nodes: pathNodes, edges: pathEdges },
        key,
        mode,
      },
      chords: pathNodes,
      concreteProgression: concreteNames.join(" -> "),
    };
  }
}
 
/** @private */
const SCHEMA = (() => {
  return [
    {
      name: "enable",
      type: "bool",
      label: "Enable",
      tooltip: "Disable for atonal music without chord progression",
      default: true,
      ariaInvalid: "false",
    },
    {
      name: "creativity",
      type: "float",
      label: "Creativity",
      tooltip: "Higher values allow more unusual chord transitions",
      default: 0.5,
      min: 0,
      max: 1,
      step: 0.1,
      showIf: "enable",
    },
    {
      name: "part",
      type: "nested",
      label: "Part",
      tooltip: "Editable in Step 1",
      counter: "step1.parts",
      showIf: "enable",
      firstColumn: { type: "text", key: "label", readonly: true },
      defaults: ["A", "B", "A", "C", "A"].map((label) => ({
        key: label === "B" ? 7 : label === "C" ? 9 : 0,
        mode: label === "C" ? "minor" : "major",
        style: "manual",
        start_chord: label === "C" ? "i" : "I",
        end_chord: label === "B" ? "V" : label === "C" ? "V" : "I",
      })),
      template: [
        {
          name: "key",
          type: "select",
          label: "Key",
          tooltip: "Tonal center for this part",
          default: 0,
          options: Array.from({ length: 12 }, (_, i) => i),
          labels: noteNames(),
        },
        {
          name: "mode",
          type: "select",
          label: "Mode",
          tooltip: "Major or minor tonality",
          default: "major",
          options: ["major", "minor"],
          labels: ["Major", "Minor"],
        },
        {
          name: "style",
          type: "select",
          label: "Style",
          tooltip: "Chord transition costs learned from analyzed works",
          default: "manual",
          options: ["manual"],
          labels: ["Manual"],
        },
        {
          name: "start_chord",
          type: "select",
          label: "Start Chord",
          tooltip:
            "First chord of the progression. The label (e.g. Dominant) shows the harmonic function",
          default: "I",
          dynamic: "chord",
        },
        {
          name: "end_chord",
          type: "select",
          label: "End Chord",
          tooltip:
            "Last chord of the progression. I/i = resolved cadence, V = open half cadence",
          default: "I",
          dynamic: "chord",
        },
      ],
    },
  ];
})();