public boolean execute() { // Initialize statistics IncrementalStats[] stats = new IncrementalStats[ID.BITS]; for (int i = 0; i < stats.length; i++) stats[i] = new IncrementalStats(); int size = Network.size(); for (int i = 0; i < size; i++) { Node node = Network.get(i); long lid = IDUtil.getID(node, hid); Chord chord = (Chord) node.getProtocol(pid); for (int j = 0; j < ID.BITS; j++) { Node finger = chord.getFinger(j); if (finger != null) { long rid = IDUtil.getID(finger, hid); long dist = ID.dist(lid, rid); stats[j].add(dist); } } } // Print final statistics for (int i = 0; i < stats.length; i++) { System.out.println(prefix + ": TIME " + CommonState.getTime() + " " + i + " " + stats[i]); stats[i] = new IncrementalStats(); } return false; }
// ParserListener methods public void noteEvent(Note note) { if (layer >= staves) { return; } // System.out.println(note.getMusicString() + " " + note.getMillisDuration() + " " + // note.getDecimalDuration()); Vector<Chord> currChords = chords[layer]; Iterator<NotePanel> currNote = currNotes[layer]; if (!currNote.hasNext()) { System.err.println("Received noteEvent, but no PostScript notes are left"); return; } if (note.getMillisDuration() > 0) { NotePanel notePanel = currNote.next(); // time the last chord ended long tempTime = 0; for (int i = currChords.size() - 1; i >= 0; --i) { if (!currChords.get(i).isTie()) { tempTime = currChords.get(i).getTime() + currChords.get(i).getDuration(); break; } } if (notePanel.isTie) { Chord chord = new Chord(); // for each note in the last chord, set the next note as a tied note for (int i = 0; i < currChords.lastElement().size(); ++i) { notePanel.setTie(true).setTime(Math.min(tempTime, time - 1)).setTempo(tempo); chord.addNote(notePanel); notePanel = currNote.next(); } currChords.add(chord); } while (notePanel.isRest) { notePanel .setTime(Math.min(tempTime, time - 1)) // hack, in case the rest should be trimmed .setTempo(tempo); tempTime += notePanel.getDuration(); Chord chord = new Chord(notePanel); currChords.add(chord); // System.out.println("REST: " + notePanel.getMusicString() + " " + // notePanel.getDuration()); notePanel = currNote.next(); } notePanel.setNote(note).setTime(time).setTempo(tempo); if (currChords.isEmpty() || currChords.lastElement().getTime() != time) { Chord chord = new Chord(notePanel); currChords.add(chord); } else { currChords.lastElement().addNote(notePanel); } } }
public static String transposeChords(final String text, final int transpose) { String result = text; final List<Chord> chords = getChords(text); for (final Chord chord : chords) { result = result.replaceAll("\\[" + chord.getChord() + "\\]", chord.getTransposedChord(transpose)); } return result; }
/** tests that getAllNotes works */ @Test public void basicGetAllNotesTest() { List<MusicElement> elements = new ArrayList<MusicElement>(); Note c = new Note(new Pitch('C'), new Fraction(1, 1), false); elements.add(c); Note b = new Note(new Pitch('B'), new Fraction(1, 1), false); elements.add(b); Chord chord = new Chord(elements); List<Note> notes = new ArrayList<Note>(); notes.add(c); notes.add(b); assertEquals(chord.getAllNotes(), notes); }
public boolean[] getCurrentEnharmonics(int index) { Polylist tones = new Polylist(); Chord currentChord = chordProg.getCurrentChord(index); if (currentChord != null && !currentChord.getName().equals(NOCHORD)) { try { tones = chordProg.getCurrentChord(index).getPriority(); } catch (NullPointerException e) { tones = new Polylist(); Trace.log(2, "Null pointer exception should be fixed in Score.getCurrentEnharmonics."); Trace.log(2, e.getStackTrace().toString()); } } return getCurrentEnharmonics(index, tones); }
private static void addAlbertiBass(Measure currentMeasure, Chord currentChord) { Triad currentTriad = currentChord.getTriad(); Note[] triad = new Note[3]; triad = currentTriad.getNotes().toArray(triad); int[] noteOctaves = getNoteOctaves(triad); Beat newBeat = new Beat(); Note currentNote = new Note(triad[0].getTone().toString(), BeatDuration.Eighth); currentNote.setOctave(new Octave(noteOctaves[0])); newBeat.addNote(currentNote); currentMeasure.addBeat(newBeat); newBeat = new Beat(); currentNote = new Note(triad[2].getTone().toString(), BeatDuration.Eighth); currentNote.setOctave(new Octave(noteOctaves[2])); newBeat.addNote(currentNote); currentMeasure.addBeat(newBeat); newBeat = new Beat(); currentNote = new Note(triad[1].getTone().toString(), BeatDuration.Eighth); currentNote.setOctave(new Octave(noteOctaves[1])); newBeat.addNote(currentNote); currentMeasure.addBeat(newBeat); newBeat = new Beat(); currentNote = new Note(triad[2].getTone().toString(), BeatDuration.Eighth); currentNote.setOctave(new Octave(noteOctaves[2])); newBeat.addNote(currentNote); currentMeasure.addBeat(newBeat); }
/** * Creates a new instance of Dynamics event * * @param measure measure that contains this mark * @param point location of mark * @param chord the chord related to the mark * @param glyph the underlying glyph */ public Dynamics(Measure measure, SystemPoint point, Chord chord, Glyph glyph) { super(measure, true, point, chord, glyph); if (chord != null) { chord.addDirection(this); // //// TODO: Not always !!!!!!!!!!!!!!!!!!! } }
/** * Writes the Score to the BufferedWriter passed to this method in Leadsheet notation. * * @param out a BufferedWriter to save the score onto */ public void saveLeadsheet(BufferedWriter out) throws IOException { Chord.initSaveToLeadsheet(); chordProg.saveLeadsheet(out, "chords"); out.newLine(); ListIterator<MelodyPart> i = partList.listIterator(); while (i.hasNext()) { ((MelodyPart) i.next()).saveLeadsheet(out, "melody"); out.newLine(); } }
/** * Writes the Part to the passed BufferedWriter in Leadsheet notation. * * @param out the BufferedWriter to write the Part onto */ public void saveLeadsheet(BufferedWriter out, String type) throws IOException { out.write("(part"); out.newLine(); out.write(" (type " + type + ")"); out.newLine(); out.write(" (title " + title + ")"); out.newLine(); out.write(" (composer " + composer + ")"); out.newLine(); out.write(" (instrument " + instrument + ")"); out.newLine(); out.write(" (volume " + volume + ")"); out.newLine(); out.write(" (key " + keySig + ")"); out.newLine(); if (this instanceof MelodyPart) { out.write(" (stave " + staveType.toString().toLowerCase() + ")"); out.newLine(); } // For now, saving roadmaps is disabled // else // { // out.write(Formatting.prettyFormat(4, ((ChordPart)this).getRoadMap() == null ? "" : // ((ChordPart)this).getRoadmapPoly())); // out.newLine(); // } out.write(")"); out.newLine(); Note.initializeSaveLeadsheet(); Part.PartIterator i = iterator(); // Should be refactored into separate methods for each derived class if (this instanceof MelodyPart) { while (i.hasNext()) { i.next().saveLeadsheet(out, metre); } } else { SectionInfo sectionInfo = ((ChordPart) this).getSectionInfo(); Iterator<SectionRecord> sec = sectionInfo.iterator(); SectionRecord record = sec.next(); boolean lastSection = !sec.hasNext(); Chord residualChord = null; int slot = 0; int slotLimit = size(); int nextSectionStart; // iSystem.out.println("slotLimit = " + slotLimit); Chord chord = null; int sectionsToGo = sectionInfo.size(); do // do-while { // System.out.println("\nrecord = " + record); // Save the section record saveSectionInfo(out, record); // Get the next section record, if any. if (sec.hasNext()) { record = sec.next(); nextSectionStart = record.getIndex(); } else { nextSectionStart = slotLimit; } // System.out.println("next section start = " + nextSectionStart); // Pack Chords into section while ((chord != null || i.hasNext()) && slot < nextSectionStart) { if (chord == null) { Chord nextChord = (Chord) i.next(); if (nextChord != null) { chord = nextChord.copy(); } } // Otherwise use the residue of previous chord assert chord != null; // Where the next slot would normally be int nextSlot = slot + chord.getRhythmValue(); if (nextSlot <= nextSectionStart) { // This chord fits in the current section. chord.saveLeadsheet(out, metre); chord = null; slot = nextSlot; } else { // This chord does not fit in the current section. // Calculate how much of this section can be used. int available = nextSectionStart - slot; chord.setRhythmValue(available); chord.saveLeadsheet(out, metre); // Determine what is left over. int residual = nextSlot - nextSectionStart; chord.setRhythmValue(residual); // System.out.println("overflow at slot " + slot + ", next section start = " + // nextSectionStart + " " + chord + ", residual = " + residual); // This should force the end of this while, among other things slot = nextSectionStart; } } sectionsToGo--; } while (sectionsToGo > 0); // end of do-while } }
// Determine whether '#' or 'b' is visible in the lick triage utility, based on // whatever the current chord is. public boolean[] getCurrentEnharmonics(int index, Polylist tones) { boolean[] enh = new boolean[5]; // We set the default visible accidental to '#' if we're in a sharp key; otherwise, set // the default to 'b'. if (keySig >= 0) { enh[CSHARP] = true; enh[DSHARP] = true; enh[FSHARP] = true; enh[GSHARP] = true; enh[ASHARP] = true; } else { enh[CSHARP] = false; enh[DSHARP] = false; enh[FSHARP] = false; enh[GSHARP] = false; enh[ASHARP] = false; } // Get the current chord if there is one. Chord current = chordProg.getCurrentChord(index); if (current == null || current.getName().equals(NOCHORD)) { return enh; } if (tones == null || tones.isEmpty()) { return enh; } // Look at all the chord tones in the list and determine whether we need to change // any accidental labels from '#' to 'b' while (tones.nonEmpty()) { NoteSymbol first = (NoteSymbol) tones.first(); tones = tones.rest(); if (first.getPitchString().length() > 1) { switch (first.getPitchString().charAt(0)) { case 'c': if (first.getPitchString().charAt(1) == '#') { enh[CSHARP] = true; } break; case 'd': if (first.getPitchString().charAt(1) == 'b') { enh[CSHARP] = false; } else if (first.getPitchString().charAt(1) == '#') { enh[DSHARP] = true; } break; case 'e': if (first.getPitchString().charAt(1) == 'b') { enh[DSHARP] = false; } break; case 'f': if (first.getPitchString().charAt(1) == '#') { enh[FSHARP] = true; } case 'g': if (first.getPitchString().charAt(1) == 'b') { enh[FSHARP] = false; } else if (first.getPitchString().charAt(1) == '#') { enh[GSHARP] = true; } break; case 'a': if (first.getPitchString().charAt(1) == 'b') { enh[GSHARP] = false; } else if (first.getPitchString().charAt(1) == '#') { enh[ASHARP] = true; } break; case 'b': if (first.getPitchString().charAt(1) == 'b') { enh[ASHARP] = false; } break; } } } return enh; }
/** tests that getAllNotes if no notes exist */ @Test public void zeroGetAllNotesTest() { List<MusicElement> elements = new ArrayList<MusicElement>(); Chord c = new Chord(elements); assertEquals(c.getAllNotes(), new ArrayList<Note>()); }
/** * Return true if this is a legal loop. A legal loop contains no function calls and has no scalar * variable cycles. A cycle exists when the variable is referenced before it is defed. We go to * some trouble to allow loops containing cycles such as * * <pre> * s = s + a(i,j) * </pre> * * to be permuted. */ private boolean legalLoop(LoopHeaderChord loop) { Stack<Chord> wl = WorkArea.<Chord>getStack("legalLoop"); References refs = scribble.getRefs(); Chord.nextVisit(); wl.push(loop); loop.setVisited(); int n = loop.numLoopExits(); for (int i = 0; i < n; i++) loop.getLoopExit(i).setVisited(); boolean legal = true; outer: while (!wl.empty()) { Chord c = wl.pop(); if (c.getCall(true) != null) { legal = false; break; } if ((c instanceof DecisionChord) && (c != loop.getLoopTest())) { legal = false; break; } if (c.isAssignChord() && !c.isPhiExpr()) { ExprChord ec = (ExprChord) c; Expr lhs = ec.getLValue(); Expr rhs = ec.getRValue(); // The variable is both defed and used in the loop and // we don't know how it is used. For example, it could be // s = s + 1 // c(i,j) = s // or // c(i,j) = s // s = s + 1 // We want to allow // s = s + c(i,j) // because we know that s is not used to specify the // value of an array element. We want to allow // s = ... // = s // since there is no cycle. if (lhs instanceof LoadDeclAddressExpr) { LoadDeclAddressExpr ldae = (LoadDeclAddressExpr) lhs; VariableDecl vd = ldae.getDecl().returnVariableDecl(); if ((vd != null) && !loop.isLoopIndex(vd)) { boolean cycle = false; Iterator<Chord> it1 = refs.getUseChords(vd); while (it1.hasNext()) { Chord s = it1.next(); cycle |= (s == c); } Iterator<Chord> it2 = refs.getUseChords(vd); while (it2.hasNext()) { Chord s = it2.next(); if (c == s) continue; if (s.getLoopHeader() != loop) continue; if (cycle) { // There was a cycle and another use. // s = s + 1 // = s legal = false; break outer; } // Check for a use before the def. while (true) { s = s.getNextChord(); if (s == null) break; if (s == c) { legal = false; break outer; } } } } } } c.pushOutCfgEdges(wl); } WorkArea.<Chord>returnStack(wl); return legal; }
// Transforms a Song in to language that can be fed to the MIDI Sequencer public void play() throws MidiUnavailableException, InvalidMidiDataException { // LCM calculations that ultimately give us how many ticks per beat we should have Fraction lcmCalc = defaultNoteLength; int lcm = 0; for (String voiceName : this.musicForVoiceName.keySet()) { for (Music m : this.musicForVoiceName.get(voiceName)) { lcmCalc = new Fraction( 1, Fraction.LCM(m.getDuration().getDenominator(), lcmCalc.getDenominator())); } if (lcmCalc.getDenominator() > lcm) { lcm = lcmCalc.getDenominator(); } } LyricListener listener = new LyricListener() { public void processLyricEvent(String text) { System.out.println(text); } }; // Initializes a new SequencePlayer that will make our notes audible SequencePlayer seqPlayer = new SequencePlayer(this.beatsPerMinute, lcm, listener); int startTick = 0; int duration; // Considers every Voice in our Song for (String voiceName : this.musicForVoiceName.keySet()) { String lyricsPrefix = ""; if (!voiceName.equals("THE_DEFAULT_VOICE")) lyricsPrefix = voiceName; startTick = 0; // Considers every Music element in our Voice for (Music m : this.musicForVoiceName.get(voiceName)) { duration = (int) (m.getDuration().toDouble() * defaultNoteLength.toDouble() / tempoBeat.toDouble() * lcm); if (m instanceof Note) { Note mNote = (Note) m; Pitch pitch = new Pitch(mNote.getNote().toString().charAt(0)) .transpose(mNote.getAccidental().getSemitoneOffset() + 12 * mNote.getOctave()); if (mNote.getSyllable() != null && !mNote.getSyllable().equals("")) { seqPlayer.addLyricEvent(lyricsPrefix + mNote.getSyllable(), startTick); } seqPlayer.addNote(pitch.toMidiNote(), startTick, duration); startTick += duration; } else if (m instanceof Chord) { Chord mChord = (Chord) m; if (mChord.getSyllable() != null && !mChord.getSyllable().equals("")) { seqPlayer.addLyricEvent(lyricsPrefix + mChord.getSyllable(), startTick); } for (Note n : mChord.getNotes()) { Pitch pitch = new Pitch(n.getNote().toString().charAt(0)) .transpose(n.getAccidental().getSemitoneOffset() + 12 * n.getOctave()); seqPlayer.addNote(pitch.toMidiNote(), startTick, duration); } startTick += duration; } else if (m instanceof Tuplet) { Tuplet mTuplet = (Tuplet) m; int tupleNoteDur = duration; tupleNoteDur = getTupleNoteDur(mTuplet.getType(), tupleNoteDur); for (Music tupletElem : mTuplet.getNotes()) { if (tupletElem instanceof Note) { Pitch pitch1 = null; Note n = (Note) tupletElem; pitch1 = new Pitch(n.getNote().toString().charAt(0)) .transpose(n.getAccidental().getSemitoneOffset() + 12 * n.getOctave()); if (n.getSyllable() != null && !n.getSyllable().equals("")) { seqPlayer.addLyricEvent(lyricsPrefix + n.getSyllable(), startTick); } seqPlayer.addNote(pitch1.toMidiNote(), startTick, tupleNoteDur); startTick += tupleNoteDur; } else if (tupletElem instanceof Chord) { Chord c = (Chord) tupletElem; if (c.getSyllable() != null && !c.getSyllable().equals("")) { seqPlayer.addLyricEvent(lyricsPrefix + c.getSyllable(), startTick); } for (Note note : c.getNotes()) { Pitch pitch2 = null; pitch2 = new Pitch(note.getNote().toString().charAt(0)) .transpose( note.getAccidental().getSemitoneOffset() + 12 * note.getOctave()); seqPlayer.addNote(pitch2.toMidiNote(), startTick, tupleNoteDur); } startTick += tupleNoteDur; } else if (tupletElem instanceof Rest) { startTick += tupleNoteDur; } else { throw new RuntimeException( "You cannot build a tuple out of anything but a Note, Chord, or Rest"); } } } else if (m instanceof Rest) { startTick += duration; } } } seqPlayer.play(); }