All files / src/model constraints3.js

100% Statements 186/186
100% Branches 87/87
100% Functions 71/71
100% Lines 161/161

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 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                        21x 21x         32x                     1949x             21x 21x 21x 21x   147x     21x 128x 128x   21x 21x   128x 204x 105x     99x         204x 1215x 1215x 204x       21x                 21x 14x   7x 7x 7x 21x 84x           21x 21x 21x 128x 204x 204x 105x   99x 204x             21x 21x 14x   7x 152x 7x 7x   44x 76x 76x 76x 46x   30x 30x 30x 30x             744x     14x 10x 21x       14x 54x     14x 170x           67x 32x   32x 32x       32x   20x     32x 32x 99x 79x   20x 20x 2x   18x 156x 99x 12x   18x 15x 109x   18x 12x 58x   18x 4x   14x 14x 14x 14x           12x 12x 36x   18x 18x     18x 2x   16x   128x 127x             21x 19x   2x 2x 2x 12x   6x 6x 6x 6x           14x 31x       21x 21x 19x   2x 2x 52x 2x 35x 5x 40x 5x 40x 5x 4x 12x 4x   5x           21x 21x 67x 32x 67x 32x 67x 67x 67x           67x 67x             21x 20x   1x 1x 8x   1x 4x 64x 1x 8x 1x 8x           21x 128x 204x     21x 78x 78x   21x    
import { CHORDS } from "./theory.js";
 
/**
 * Builds the MiniZinc CSP for Step 3:
 * assigns one note per active sub-beat and voice.
 * Encodes T1-T3, R4, R9, H12, H19, M1, M9, M14 from the Thesis.
 * @param {Object} parameters - Step-3 form params plus chord progression and tempo; see {@link Step3Notes#schema}.
 * @param {{subdivision: number, subBeatsPerBar: number, numSubBeats: number, activeBeats: Set<number>[]}} time
 *  R4+R9: Time-grid built by Step 3: subdivision (tau), T, per-voice onset sets (omicron).
 * @return {string} MiniZinc source.
 */
export function modelNotes(parameters, time) {
  const pitch = pitchGrid(parameters, time);
  return [
    'include "globals.mzn";',
    ...varDecls(parameters, time, pitch.varDomains),
    ...dissonanceConstraints(parameters, time, pitch),
    ...range(parameters.voices).flatMap((s) =>
      seedOneVoice(parameters, time, pitch, s),
    ),
    ...forbidUnisons(parameters, time),
    ...restsBudget(parameters, time),
    ...melodicConstraints(parameters, time),
    ...forbidParallels(parameters, time),
    `solve :: ${searchAnnotation(time)} satisfy;`,
  ].join("\n");
}
 
/** @private 0..n-1 index range. */
const range = (n) => Array.from({ length: n }, (_, i) => i);
 
/**
 * @private T1+T2+T3 + H19 setup: pitch domain per (s,t) within ambitus [alpha, beta];
 * chord/scale tones from gamma_t; dissonance set.
 */
function pitchGrid(parameters, time) {
  const { voice, voices, mode, key, chords } = parameters;
  const { numSubBeats, activeBeats, subBeatsPerBar } = time;
  const chordTones = { ...CHORDS.major, ...CHORDS.minor };
  const scaleTones = new Set(
    (mode === "major" ? [0, 2, 4, 5, 7, 9, 11] : [0, 2, 3, 5, 7, 8, 10]).map(
      (p) => (p + key) % 12,
    ),
  );
  const tonesPerBeat = range(numSubBeats).map((t) => {
    const base = chordTones[chords[Math.floor(t / subBeatsPerBar)]];
    return base ? new Set(base.map((p) => (p + key) % 12)) : scaleTones;
  });
  const withRest = parameters.rest_pct > 0;
  const varDomains = Object.fromEntries(
    range(numSubBeats).flatMap((t) =>
      voice.slice(0, voices).flatMap((v, s) => {
        if (!activeBeats[s].has(t)) {
          return [];
        }
        const allowed =
          v.chord_tones === "chord" || v.chord_tones === true
            ? tonesPerBeat[t]
            : v.chord_tones === "scale"
              ? scaleTones
              : null;
        const ps = range(v.max_pitch - v.min_pitch + 1)
          .map((k) => v.min_pitch + k)
          .filter((p) => !allowed || allowed.has(p % 12));
        return [[`note_${s}_${t}`, withRest ? [-2, ...ps] : ps]];
      }),
    ),
  );
  return {
    varDomains,
    dissAllowedSet: dissSet(parameters.dissonance, voices),
    seededValues: {},
  };
}
 
/** @private H19 setup: dissonance-cost array (chi) thresholded by phi; null = no H19. */
function dissSet(dissonance, voices) {
  if (dissonance === 0.5 || voices <= 1) {
    return null;
  }
  const cost = [0, 4, 2, 1, 1, 0, 3, 0, 1, 1, 2, 4];
  const cons = dissonance < 0.5;
  const th = cons ? (dissonance <= 0.2 ? 1 : 2) : dissonance >= 0.8 ? 3 : 2;
  return new Set(
    cost.flatMap((c, i) => ((cons ? c <= th : c >= th) ? [i] : [])),
  );
}
 
/** @private Build var declarations note_s_t (varDomains already has hold sentinel when restsEnabled). */
function varDecls(parameters, time, varDomains) {
  const { numSubBeats, activeBeats } = time;
  const withRest = parameters.rest_pct > 0;
  return range(numSubBeats).flatMap((t) =>
    activeBeats.map((set, s) => {
      const n = `note_${s}_${t}`;
      if (!set.has(t)) {
        return `var int: ${n} = -2;`;
      }
      const dom = withRest ? [-1, ...varDomains[n]] : varDomains[n];
      return `var {${dom.join(",")}}: ${n};`;
    }),
  );
}
 
/** @private H19: per voice-pair, per sub-beat, interval class must be in allowed set. */
function dissonanceConstraints(parameters, time, pitch) {
  const { dissAllowedSet, varDomains } = pitch;
  if (dissAllowedSet === null) {
    return [];
  }
  const setLit = `{${[...dissAllowedSet].join(",")}}`;
  const real = (k, t) => realPitches(varDomains[`note_${k}_${t}`]);
  const pairs = voicePairs(parameters.voices);
  return [
    ...range(time.numSubBeats).flatMap((t) =>
      pairs.flatMap(([a, b]) => {
        const rA = real(a, t);
        const rB = real(b, t);
        if (!rA.length || !rB.length || !anyAllowed(rA, rB, dissAllowedSet)) {
          return [];
        }
        const na = `note_${a}_${t}`;
        const nb = `note_${b}_${t}`;
        const body = `(abs(${na} - ${nb}) mod 12) in ${setLit}`;
        return [guarded(parameters, na, nb, body)];
      }),
    ),
  ];
}
 
/** @private Real-pitch subset of a domain (drops -1/-2 sentinels). */
const realPitches = (domain) => (domain || []).filter((p) => p >= 0);
 
/** @private Unordered voice index pairs (a < b). */
const voicePairs = (voices) =>
  range(voices).flatMap((a) =>
    range(voices - a - 1).map((k) => [a, a + 1 + k]),
  );
 
/** @private True iff some pair (x in xs, y in ys) has interval class in allowed set. */
const anyAllowed = (xs, ys, allowed) =>
  xs.some((x) => ys.some((y) => allowed.has(Math.abs(x - y) % 12)));
 
/** @private Wrap MZN body with rest/hold sentinel guard when rest_pct > 0. */
const guarded = (parameters, a, b, body) =>
  parameters.rest_pct > 0
    ? `constraint (${a} >= 0 /\\ ${b} >= 0) -> ${body};`
    : `constraint ${body};`;
 
/** @private Seed xi-percent of voice s; emits constraints and mutates pitch.seededValues for cross-voice filtering. */
function seedOneVoice(parameters, time, pitch, s) {
  const active = [...time.activeBeats[s]].sort((a, b) => a - b);
  const pct = parameters.seed_pct;
  const numSeeds =
    pct > 0 ? Math.max(1, Math.floor((active.length * pct) / 100)) : 0;
  const spacing = Math.max(
    1,
    Math.floor(active.length / Math.max(1, numSeeds)),
  );
  const positions = new Set(
    range(numSeeds).map(
      (k) => active[Math.min(k * spacing, active.length - 1)],
    ),
  );
  const seedOrder = [];
  return active.flatMap((t) => {
    if (!positions.has(t)) {
      return [];
    }
    const ps = pitch.varDomains[`note_${s}_${t}`];
    if (ps.length < 3) {
      return [];
    }
    const used = pitch.seededValues[t] || {};
    let cs = ps.filter((p) => !Object.values(used).includes(p));
    if (pitch.dissAllowedSet !== null) {
      cs = filterByDissonance(time, pitch, cs, { s, t });
    }
    if (seedOrder.length > 0) {
      const prev = seedOrder.at(-1)[1];
      cs = cs.filter((p) => Math.abs(p - prev) <= parameters.max_interval);
    }
    if (seedOrder.length > 1) {
      const prevPrev = seedOrder.at(-2)[1];
      cs = cs.filter((p) => p !== prevPrev);
    }
    if (cs.length === 0) {
      return [];
    }
    const pick = cs[Math.floor(Math.random() * cs.length)];
    seedOrder.push([t, pick]);
    (pitch.seededValues[t] ||= {})[s] = pick;
    return [`constraint note_${s}_${t} = ${pick};`];
  });
}
 
/** @private H19-aware filter: drop candidates whose interval class to other voices is forbidden at sub-beat (s, t). */
function filterByDissonance(time, pitch, candidates, subbeat) {
  const { s, t } = subbeat;
  return range(time.activeBeats.length)
    .filter((k) => k !== s && time.activeBeats[k].has(t))
    .reduce((acc, k) => {
      const seeded = pitch.seededValues[t]?.[k];
      const others = realPitches(
        seeded !== undefined ? [seeded] : pitch.varDomains[`note_${k}_${t}`],
      );
      if (others.length === 0) {
        return acc;
      }
      return acc.filter(
        (p) =>
          p < 0 ||
          others.some((q) => pitch.dissAllowedSet.has(Math.abs(p - q) % 12)),
      );
    }, candidates);
}
 
/** @private H12: pairwise note_a_t != note_b_t for real pitches (skip holds/rests). */
function forbidUnisons(parameters, time) {
  if (!parameters.forbid_unisons || parameters.voices <= 1) {
    return [];
  }
  const { numSubBeats, activeBeats } = time;
  const pairs = voicePairs(parameters.voices);
  return range(numSubBeats)
    .filter((t) => everyVoiceActive(activeBeats, t))
    .flatMap((t) =>
      pairs.map(([a, b]) => {
        const na = `note_${a}_${t}`;
        const nb = `note_${b}_${t}`;
        return guarded(parameters, na, nb, `${na} != ${nb}`);
      }),
    );
}
 
/** @private True iff every voice is active at sub-beat t. */
const everyVoiceActive = (activeBeats, t) =>
  activeBeats.every((set) => set.has(t));
 
/** @private Per-voice holds/rests budget (rest_pct, UI-driven; not a chapter4 constraint). */
function restsBudget(parameters, time) {
  const pct = parameters.rest_pct;
  if (pct <= 0) {
    return [];
  }
  const sb = time.subBeatsPerBar;
  const term = (s, t) =>
    `bool2int(note_${s}_${t} == -1) + bool2int(note_${s}_${t} == -2)`;
  return range(parameters.voices).flatMap((s) => {
    const active = [...time.activeBeats[s]].sort((a, b) => a - b);
    const maxHR = Math.max(1, Math.floor((active.length * pct) / 100));
    const terms = active.map((t) => term(s, t)).join(" + ");
    const out = [`constraint ${terms} <= ${maxHR};`];
    const downbeats = active.filter((t) => t % sb === 0);
    if (downbeats.length >= 2 && active.length - downbeats.length >= maxHR) {
      const maxDB = Math.max(1, Math.floor(downbeats.length / 4));
      const dbTerms = downbeats.map((t) => term(s, t)).join(" + ");
      out.push(`constraint ${dbTerms} <= ${maxDB};`);
    }
    return out;
  });
}
 
/** @private M1 (max semitone jump delta) + M9 (per-voice no immediate repetition) per voice. */
function melodicConstraints(parameters, time) {
  const max = parameters.max_interval;
  return range(time.activeBeats.length).flatMap((s) => {
    const active = [...time.activeBeats[s]].sort((a, b) => a - b);
    const noRep = !parameters.voice[s].allow_repetitions;
    const transitions = active.slice(1).map((t2, k) => [active[k], t2]);
    return transitions.flatMap(([t1, t2]) => {
      const prev = `note_${s}_${t1}`;
      const curr = `note_${s}_${t2}`;
      const m1 = guarded(
        parameters,
        prev,
        curr,
        `abs(${prev} - ${curr}) <= ${max}`,
      );
      const m9 = guarded(parameters, prev, curr, `${prev} != ${curr}`);
      return noRep ? [m1, m9] : [m1];
    });
  });
}
 
/** @private M14: forbid parallel fifths and octaves between consecutive shared-active beats. */
function forbidParallels(parameters, time) {
  if (!parameters.forbid_parallels || parameters.voices <= 1) {
    return [];
  }
  const { numSubBeats, activeBeats } = time;
  const shared = range(numSubBeats).filter((t) =>
    everyVoiceActive(activeBeats, t),
  );
  const pairs = voicePairs(parameters.voices);
  const transitions = shared.slice(1).map((t2, k) => [shared[k], t2]);
  const n = (v, t) => `note_${v}_${t}`;
  const line = ({ a, b, t1, t2 }, i) =>
    `constraint not (abs(${n(a, t1)} - ${n(b, t1)}) mod 12 == ${i} /\\ abs(${n(a, t2)} - ${n(b, t2)}) mod 12 == ${i} /\\ (${n(a, t2)} - ${n(a, t1)}) * (${n(b, t2)} - ${n(b, t1)}) > 0);`;
  return transitions.flatMap(([t1, t2]) =>
    pairs.flatMap(([a, b]) => [7, 0].map((i) => line({ a, b, t1, t2 }, i))),
  );
}
 
/** @private Fisher-Yates-shuffled int_search annotation over all active note vars. */
function searchAnnotation(time) {
  const allVars = range(time.numSubBeats).flatMap((t) =>
    time.activeBeats.flatMap((set, s) =>
      set.has(t) ? [`note_${s}_${t}`] : [],
    ),
  );
  for (let i = allVars.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [allVars[i], allVars[j]] = [allVars[j], allVars[i]];
  }
  return `int_search([${allVars.join(", ")}], input_order, indomain_min)`;
}