'Converts the PianorollSequence to NoteSequence proto.
Args:
velocity: Midi velocity to give each note. Between 1 and 127 (inclusive).
instrument: Midi instrument to give each note.
program: Midi program to give each note.
qpm: Quarter notes per minute (float).
base_note_sequence: A NoteSequence to use a starting point. Must match the
specified qpm.
Raises:
ValueError: if an unknown event is encountered.
Returns:
A NoteSequence proto.'

def to_sequence(self, velocity=100, instrument=0, program=0, qpm=constants.DEFAULT_QUARTERS_PER_MINUTE, base_note_sequence=None):

    seconds_per_step = ((60.0 / qpm) / self._steps_per_quarter)
    sequence_start_time = (self.start_step * seconds_per_step)
    if base_note_sequence:
        sequence = copy.deepcopy(base_note_sequence)
        if (sequence.tempos[0].qpm != qpm):
            raise ValueError(('Supplied    QPM    (%d)    does    not    match    QPM    of    base_note_sequence    (%d)' % (qpm, sequence.tempos[0].qpm)))
    else:
        sequence = music_pb2.NoteSequence()
        sequence.tempos.add().qpm = qpm
        sequence.ticks_per_quarter = STANDARD_PPQ
    step = 0
    open_notes = {}
    for (step, event) in enumerate(self):
        frame_pitches = set(event)
        open_pitches = set(open_notes)
        for pitch_to_close in (open_pitches - frame_pitches):
            note_to_close = open_notes[pitch_to_close]
            note_to_close.end_time = ((step * seconds_per_step) + sequence_start_time)
            del open_notes[pitch_to_close]
        for pitch_to_open in (frame_pitches - open_pitches):
            new_note = sequence.notes.add()
            new_note.start_time = ((step * seconds_per_step) + sequence_start_time)
            new_note.pitch = (pitch_to_open + self._min_pitch)
            new_note.velocity = velocity
            new_note.instrument = instrument
            new_note.program = program
            open_notes[pitch_to_open] = new_note
    final_step = (step + (len(open_notes) > 0))
    for note_to_close in open_notes.values():
        note_to_close.end_time = ((final_step * seconds_per_step) + sequence_start_time)
    sequence.total_time = ((seconds_per_step * final_step) + sequence_start_time)
    if sequence.notes:
        assert (sequence.total_time >= sequence.notes[(-1)].end_time)
    return sequence
