コード例 #1
0
ファイル: __init__.py プロジェクト: johndpope/jazzparser
    def run(self):
        start_time = pgmidi.time() + 3000

        times = iter(sorted(self._queue.keys()))
        while True:
            if self._stopped:
                return
            # Get all the events that should be within the buffer
            event_times = []
            now = pgmidi.time()
            while len(
                    event_times
            ) == 0 or event_times[-1] + start_time < now + self.buffer_time:
                event_times.append(times.next())

            events = sum([[[bytes, ms_time + start_time]
                           for bytes in self._queue[ms_time]]
                          for ms_time in event_times], [])
            print len(events), now, (now + self.buffer_time)
            print event_times[-1] + start_time
            self.output.write(events)
            finished_time = pgmidi.time()
            print finished_time
            sleep_for = float(event_times[-1] + start_time - finished_time -
                              self.buffer_advance) / 1000
            if sleep_for > 0.0:
                sleep(sleep_for)
            print "Continuing"
コード例 #2
0
ファイル: touchapp.py プロジェクト: carpevitam/Miditype
    def _on_keyboard_down(self, keyboard, keycode, text, modifiers):
        # Keycode is composed of an integer + a string
        # If we hit escape, release the keyboard
        global initial
        global start_time
        
        if keycode[1] == 'escape':
            keyboard.release()

            binfile = open("output" + str(midi.time()) + ".mid",'wb')
            MyMIDI.writeFile(binfile)
            binfile.close()
        if keycode[0] in keys.keys() and keycode[0] not in active:
            if initial:
                initial = False
                start_time = midi.time()

            player.note_on(keys[keycode[0]],127,1)
            active.add(keycode[0])

            noteinfo[keycode[0],'time'] = tempo / 60000 * (midi.time()-start_time)

        # Return True to accept the key. Otherwise, it will be used by
        # the system.
        return True
コード例 #3
0
ファイル: midiBuffer.py プロジェクト: jmmcd/drum-manifold
        def _put(self,item):
                t=pm.time()
                if t<0:
                    if t>-500:
                        time.sleep(abs(t)/1000.0)
                        t=pm.time()

                if t<0:raise PmTimeNegative

                if t>=item[0]-self.appLatency:
                        self.MidiOut.write(item[1])
                else:
                        self.incoming.put(item)
コード例 #4
0
ファイル: touchapp.py プロジェクト: carpevitam/Miditype
    def _on_keyboard_up(self,keyboard,keycode):
        if keycode[0] in active and keycode[0] in keys.keys():
            player.note_off(keys[keycode[0]],127,1)
            active.remove(keycode[0])

            time = noteinfo[keycode[0],'time']
            MyMIDI.addNote(0,0,keys[keycode[0]],time,(tempo / 60000 * (midi.time()-start_time))-time,100)
コード例 #5
0
ファイル: touchapp.py プロジェクト: carpevitam/Miditype
    def on_touch_down(self,touch): # need to implement gliss

        partition = self.width / 10;
        tempDict = {}
        if touch.y < self.height / 2:
            temp = [122,120,99,118,98,  97,115,100,102,103] 
        else:
            temp = [110,109,44,46,47,104,106,107,108,59,39]
        for i in range(10):
            tempDict[i] = temp[i]
            # tempDict[i] = keys.keys()[i]
        if int(touch.x*10/self.width) in tempDict.keys() and tempDict[int(touch.x*10/self.width)] not in active:
            note = tempDict[int(touch.x*10/self.width)]
            player.note_on(keys[note],127,1)
            active.add(note)
            noteinfo[note,'time'] = tempo / 60000 * (midi.time()-start_time)
        # if keycode[0] in keys.keys() and keycode[0] not in active:

        #     player.note_on(keys[keycode[0]],127,1)
        #     active.add(keycode[0])

        #     noteinfo[keycode[0],'time'] = tempo / 60000 * (midi.time()-start_time)



        if touch.x > 400:
            player.note_off(60,127,1)
コード例 #6
0
ファイル: midiBuffer.py プロジェクト: jmmcd/drum-manifold
        def run(self):
            t=0

            if self.verbose:
                class report():pass
                rpt=report()
                rpt.sleeps=0
                rpt.latencies=[]

            try:
                while (not self.stop) or (self.incoming!=[] and not(self.incoming.empty())):

                    while pm.time()<=t:
                        if self.verbose: rpt.sleeps+=1
                        time.sleep(.0003) #prevent proc hog - is this too small to actually sleep?  don't want to miss transition to next millisecond...

                    t=pm.time()

                    while (not self.immediately) and self.incoming.queue!=[] and t>=self.incoming.queue[0][0]-self.appLatency: #accessing incoming.queue epends on private implementation of queue.PriorityQueue, hack cuz no peek method provided
                                                                                                    #note a technical concurrency bug here -- queue may become [] after checking for that and before asking for queue[0][0], but since this is the only consumer, shouldn't happen
                            try:
                                    s,e=self.incoming.get_nowait()
                                    if self.verbose: rpt.latencies.append(s-t)
                                    self.MidiOut.write(e)
                            except queue.Empty:
                                    if self.verbose: print("non empty queue throwing empties")
                                    break
            finally:
                if self.immediately:
                    def allNotesOff(m):
                        for i in range(NUM_MIDI_CHANS):
                            for j in range(MIDI_MAX):
                                m.write([[[NOTE_ON + i,j,0],0]])
                    allNotesOff(self.MidiOut)
                if self.verbose and len(rpt.latencies)>0:
                    #print("sleeps: " + str(rpt.sleeps))
                    misses=len(list(filter(lambda x:x<0,rpt.latencies)))
                    def mean(x):
                        return sum(x)/len(x)
                    def std(x):
                        m=mean(x)
                        return mean(list(map(lambda y:abs(y-m),x)))
                    print("latencies (ms, negative=late): mean=" + str(mean(rpt.latencies)) + " std=" + str(std(rpt.latencies)) + " misses=" + str(misses) + " of " + str(len(rpt.latencies)) + " (" + str(100*misses/len(rpt.latencies)) +"%)")
                del self.MidiOut
                pm.quit()
コード例 #7
0
ファイル: MidiUtil.py プロジェクト: Yzp109062/programming
def send_data_to_midi_out(data, midi_output):
    pygame_time_ms = midi.time()
    transform = lambda lst, timestamp: [lst, timestamp + pygame_time_ms + 1000]
    data = [transform(*x) for x in data]

    final_timestamp = data[-1][-1]

    # kill time so program doesn't end before midi is done playing

    i = 0
    MAX_OUTPUT_LENGTH = 1024  # due to pypm
    while i < len(data):
        sub_data = data[i:i + MAX_OUTPUT_LENGTH]
        midi_output.write(sub_data)
        i += MAX_OUTPUT_LENGTH

    while midi.time() < final_timestamp:
        time.sleep(0.1)
コード例 #8
0
 def _send(self, message):
     if message.type == 'sysex':
         # Python 2 version of Pygame accepts a bytes or list here
         # while Python 3 version requires bytes.
         # According to the docs it should accept both so this may be
         # a bug in Pygame:
         # https://www.pygame.org/docs/ref/midi.html#pygame.midi.Output.write_sys_ex
         self._port.write_sys_ex(midi.time(), bytes(message.bin()))
     else:
         self._port.write_short(*message.bytes())
コード例 #9
0
ファイル: pygame.py プロジェクト: olemb/mido
 def _send(self, message):
     if message.type == 'sysex':
         # Python 2 version of Pygame accepts a bytes or list here
         # while Python 3 version requires bytes.
         # According to the docs it should accept both so this may be
         # a bug in Pygame:
         # https://www.pygame.org/docs/ref/midi.html#pygame.midi.Output.write_sys_ex
         self._port.write_sys_ex(midi.time(), bytes(message.bin()))
     else:
         self._port.write_short(*message.bytes())
コード例 #10
0
ファイル: input.py プロジェクト: mkovacs/clavius
 def yield_event(self):
     while True:
         while self.midi_input.poll():
             [[data, timestamp]] = self.midi_input.read(1)
             if data[0] & 0xE0 == 0x80:
                 print "%010d: %s" % (timestamp, data)
                 return (timestamp, "midi", data)
         if self.video_input.grab():
             timestamp = midi.time()
             (_, data) = self.video_input.retrieve()
             return (timestamp, "video", data)
コード例 #11
0
ファイル: __init__.py プロジェクト: johndpope/jazzparser
 def run(self):
     start_time = pgmidi.time() + 3000
     
     times = iter(sorted(self._queue.keys()))
     while True:
         if self._stopped:
             return
         # Get all the events that should be within the buffer
         event_times = []
         now = pgmidi.time()
         while len(event_times) == 0 or event_times[-1]+start_time < now + self.buffer_time:
             event_times.append(times.next())
         
         events = sum([[[bytes,ms_time+start_time] for bytes in self._queue[ms_time]] for ms_time in event_times], [])
         print len(events), now, (now+self.buffer_time)
         print event_times[-1]+start_time
         self.output.write(events)
         finished_time = pgmidi.time()
         print finished_time
         sleep_for = float(event_times[-1]+start_time-finished_time-self.buffer_advance)/1000
         if sleep_for > 0.0:
             sleep(sleep_for)
         print "Continuing"
コード例 #12
0
ファイル: __init__.py プロジェクト: johndpope/jazzparser
    def write(self, events, time_offset=0):
        """
        Plays a list of events through the output device. Delta times 
        between the events are preserved, but the first event is played 
        immediately, or after the given offset (in miliseconds)
        
        """
        if len(events) == 0:
            return

        # Encode all the events as PyGame needs them
        event_list = []
        raw_events = []
        for ev in events:
            # Ignore meta events, as they only make sense in a file
            if isinstance(ev, (MetaEvent, SysExEvent)):
                # TODO: do something special with sysexs
                continue
            # Set all the deltas to 0 for now
            data = ev.encode(last_tick=ev.tick)
            # Get each byte as an int in a list (ignore the tick)
            data = [ord(b) for b in data[1:]] + [0] * (5 - len(data))
            event_list.append((data, ev.msdelay + time_offset))
            raw_events.append(ev)

        # Ask for everything to be played this offset from now
        now = pgmidi.time() + 4000

        # Make all times relative to now
        event_list = [[bytes, time + now] for (bytes, time) in event_list]

        ####
        #for bytes,time in event_list:
        #    self.queue_event(bytes, time)
        #
        #self.play()
        #return

        for event in event_list[:2000]:
            self.output.write([event])
        return
コード例 #13
0
ファイル: __init__.py プロジェクト: johndpope/jazzparser
 def write(self, events, time_offset=0):
     """
     Plays a list of events through the output device. Delta times 
     between the events are preserved, but the first event is played 
     immediately, or after the given offset (in miliseconds)
     
     """
     if len(events) == 0:
         return
     
     # Encode all the events as PyGame needs them
     event_list = []
     raw_events = []
     for ev in events:
         # Ignore meta events, as they only make sense in a file
         if isinstance(ev, (MetaEvent,SysExEvent)):
             # TODO: do something special with sysexs
             continue
         # Set all the deltas to 0 for now
         data = ev.encode(last_tick=ev.tick)
         # Get each byte as an int in a list (ignore the tick)
         data = [ord(b) for b in data[1:]] + [0]*(5-len(data))
         event_list.append((data,ev.msdelay+time_offset))
         raw_events.append(ev)
     
     # Ask for everything to be played this offset from now
     now = pgmidi.time()+4000
     
     # Make all times relative to now
     event_list = [[bytes,time+now] for (bytes,time) in event_list]
     
     ####
     #for bytes,time in event_list:
     #    self.queue_event(bytes, time)
     #
     #self.play()
     #return
     
     for event in event_list[:2000]:
         self.output.write([event])
     return
コード例 #14
0
ファイル: touchapp.py プロジェクト: carpevitam/Miditype
    def on_touch_up(self,touch): 
        print(self.width)
        print(self.height)

        partition = self.width / 10;
        tempDict = {}
        if touch.y < self.height / 2:
            temp = [122,120,99,118,98,  97,115,100,102,103] 
        else:
            temp = [110,109,44,46,47,104,106,107,108,59,39]
        for i in range(10):
            tempDict[i] = temp[i]
            # tempDict[i] = keys.keys()[i]
        if int(touch.x*10/self.width) in tempDict.keys() and tempDict[int(touch.x*10/self.width)] in active:
            note = tempDict[int(touch.x*10/self.width)]
            player.note_off(keys[note],127,1)
            active.remove(note)


            time = noteinfo[note,'time']
            MyMIDI.addNote(0,0,keys[note],time,(tempo / 60000 * (midi.time()-start_time))-time,100)
コード例 #15
0
ファイル: MidiUtil.py プロジェクト: Yzp109062/programming
def read_data_from_midi_in(midi_input, max_silence_seconds):
    data = []
    t0 = time.time()
    last_time = None
    note_imbalance = 0
    while True:
        if midi_input.poll():
            new_data = midi_input.read(1)
            assert len(new_data) == 1
            new_data = new_data[0]
            data.append(new_data)
            print(new_data)
            event = MidiEvent.from_raw_data(new_data)
            last_time = event.timestamp

            note_imbalance += 1 if event.event_name == "note_on" else -1 if event.event_name == "note_off" else 0
            # ? = data3
            print("notes on:", note_imbalance)
        elif note_imbalance == 0 and last_time is not None and midi.time(
        ) - last_time > max_silence_seconds * 1000:
            print("data collection timed out")
            break
    return data
コード例 #16
0
ファイル: devices.py プロジェクト: d3ld0t/pycr0n
def poll():
    global shell, rand_mode, sample_mode
    seen_stuff = False

    if config.launchpad_set:
        if launchpad_in.poll():
            seen_stuff = True
            data = launchpad_in.read(1)
            control = data[0][0][0]
            note = data[0][0][1]
            row = (note-8)/16
            position = note - 8*(note/16)
            
            velocity = data[0][0][2]
            
            if rand_mode == 'off':
                if velocity == 127:
                    #if lt.logitech_in.get_button(1):
                    #    navigation.switch_fx(note/16*8 + note%16)
                    if control == 176:
                        launchpad.clear(note - 104)
                    elif note%16 < 8:
                        launchpad.toggle(note)
                 
                    elif note%16 == 8:
                        launchpad.rand(row)
            elif rand_mode == 'on':
                if control == 176 and velocity == 127:
                    if note == 104:
                        # Randomize which knobs controllable for on devices
                        for i in xrange(64):
                            if launchpad.buttons[i][0] == 1:
                                rand_param(launchpad.buttons[i][1])
                    elif note == 105:
                        # Randomize which knobs controllable + randomize position of all knobs
                        # for on devices
                        for i in xrange(64):
                            if launchpad.buttons[i][0] == 1:
                                rand_param(launchpad.buttons[i][1])
                                rand_param_val(i,launchpad.buttons[i][1]) 

                elif note%16 < 8:
                    rand_param(launchpad.buttons[position][1])

    if config.remotesl_set:

        if remotesl_in.poll():
	    print "remotesl!"
            seen_stuff = True
            remotesl_data = remotesl_in.read(1)
            sl_type = remotesl_data[0][0][0]
            sl_control = remotesl_data[0][0][1]
            sl_value = remotesl_data[0][0][2]
    

            if sl_type == 178:
                midiout(velocity=sl_value,note=sl_control,channel=9,device=yoke4)

                if sl_control == 16:         # Duration
                    gradient.parent.send([8.0*(sl_value + 1)/(127 + 1),'duration'])

                elif sl_control == 17:       # Sparsity
                    config.sparsity=float(sl_value)/127
                elif sl_control == 18:       # Sparsity_param
                    config.sparsity_param = float(sl_value)/127

                elif (sl_control > 23 and sl_control < 32): # Butter/No butter
		    print "slider"
                    launchpad.armed[sl_control -24] = sl_value/127
            elif sl_type == 146: 
                # Touch pads
                yoke4.write([[[144,sl_control,127],midi.time()],
                [[128,sl_control,64],midi.time()+int(float(sl_value)/127*4000) + 200]])
    # nanokontrol CCs all on channel 0
    # knobs 16-23
    # sliders 0-7
    # solo 32-39
    # mute 48-55
    # rec 64-71
    # rew 43
    # ff 44
    # stop 42
    # play 41
    # record 45
    # cycle 46
    # set left right 60-62
    # trackleft trackright 58-59

    if config.nanokontrol_set:
        if nanokontrol_in.poll():
            seen_stuff = True
            data = nanokontrol_in.read(1)
            note = data[0][0][1]
            velocity = data[0][0][2]
            if (note > 31 and note < 40):
                midiout(note=note,velocity=127,channel=12,device=yoke3)
            elif (note > 47 and note < 56):
                midiout(note=note, velocity=127 if velocity == 0 else 0, channel=12,device=yoke3)
            elif (note > 63 and note < 72):
                midiout(note=note,velocity=127,channel=12,device=yoke3)
            elif (note > 15 and note < 24):
                if velocity < 64:
                    midiout(note=note+56,velocity = int( 127*max(min((velocity/(63.0 - 64.0*plateu_range)),1.0),0.0)    ) ,channel=12,device=yoke3)
                else:
                    midiout(note=note+64,velocity=int( 127*max(min(((velocity - 64 - 64.0*plateu_range)/(63.0 - 64.0*plateu_range)),1.0),0.0)    ),channel=12,device=yoke3)
            else:
                midiout(note=note,velocity=velocity,channel=12,device=yoke3)

    if config.nanokey_set:
        if nanokey_in.poll():
            data = nanokey_in.read(1)
            status = data[0][0][0]
            note = data[0][0][1]
            velocity = data[0][0][2]
            channel = data[0][0][3]
            timestamp = data[0][1]
            max_time = 4000 #ms
            if config.verbose: print "Velocity: %i note: %i status %i channel %i timestamp %i" \
                    % (velocity,note,status,channel,timestamp)

            if status == 144:
                yoke4.write_short(144,note,127)
                sample_off_queue.append([note,timestamp + int(random.uniform(0.0,1.0)*max_time)])
       
            seen_stuff = True

        for item in sample_off_queue[:]: # a copy
            if midi.time() > item[1]:
                yoke4.write_short(128,item[0],64)
                sample_off_queue.remove(item)

    if config.joystick_set: 
        

        #global lt.pad_state, lt.axis2_state
        tmpevent = pygame.event.poll()

        if tmpevent.type == buttondown:
            seen_stuff = True
            if tmpevent.button == 0:
                midiout(note=0,velocity=127,channel=13,device=yoke3)
            #UNDO PT	
            elif tmpevent.button == 4:
                rand_mode = 'on'
                launchpad.flash(0,48,'on')
            elif tmpevent.button == 5:
                sample_mode = 'on'
                rand_param(samplebox.samplebox)
                launchpad.flash(0,3,'on')
            elif tmpevent.button == 6:
                lt.start_axis = (lt.logitech_in.get_axis(0) + lt.logitech_in.get_axis(1))/6
                lt.old_axis = lt.axis_state
            elif tmpevent.button == 7:
                lt.start_axis2 = (lt.logitech_in.get_axis(2) + lt.logitech_in.get_axis(3))/6
                lt.old_axis2 = lt.axis_state2
            elif tmpevent.button == 9:
                parent.send('reload')
            elif tmpevent.button == 10:
                if lt.logitech_in.get_button(6): lt.start_axis = (lt.logitech_in.get_axis(0) + lt.logitech_in.get_axis(1))/6
                else: lt.start_axis = (lt.logitech_in.get_axis(0) + lt.logitech_in.get_axis(1))/16
                if lt.axis_button_state == 'off': 
                    lt.axis_button_state = 'on'
            elif tmpevent.button == 11:
                if lt.logitech_in.get_button(7): lt.start_axis2 = (lt.logitech_in.get_axis(2) + lt.logitech_in.get_axis(3))/6
                else: lt.start_axis2 = (lt.logitech_in.get_axis(2) + lt.logitech_in.get_axis(3))/16
                if lt.axis_button_state2 == 'off': 
                    lt.axis_button_state2 = 'on'

        if tmpevent.type == buttonup:
            seen_stuff = True
            for i in xrange(12):
                if not lt.logitech_in.get_button(i):
                    if i == 4: 
                        rand_mode = 'off'
                        launchpad.flash(0,0,'off')
                    if i == 5:
                        sample_mode = 'off'
                        launchpad.flash(0,3,'off')
                    if i == 6:
                        lt.start_axis = (lt.logitech_in.get_axis(0) + lt.logitech_in.get_axis(1))/16
                        lt.old_axis = lt.axis_state
                    if i == 7:
                        lt.start_axis2 = (lt.logitech_in.get_axis(2) + lt.logitech_in.get_axis(3))/16
                        lt.old_axis2 = lt.axis_state2
                    if i == 10:
                        if lt.axis_button_state == 'on': 
                            lt.old_axis = lt.axis_state
                            lt.axis_button_state = 'off'
                    if i == 11:
                        if lt.axis_button_state2 == 'on': 
                            lt.old_axis2 = lt.axis_state2
                            lt.axis_button_state2 = 'off'

        if tmpevent.type == controlpad:
            seen_stuff = True

        if tmpevent.type == axismotion: 
                
            seen_stuff = True

            if sample_mode == 'off':

                if lt.axis_button_state == 'on':
                    if lt.logitech_in.get_button(6):
                        tmp = (lt.logitech_in.get_axis(0) + lt.logitech_in.get_axis(1))/6 - lt.start_axis + lt.old_axis
                    else:
                        tmp = (lt.logitech_in.get_axis(0) + lt.logitech_in.get_axis(1))/16 - lt.start_axis + lt.old_axis
                    if tmp != lt.axis_state:
                        lt.axis_state = tmp
                        launchpad.push_params(lt.axis_state)
            else:
                if lt.axis_button_state2 == 'on':
                    if lt.logitech_in.get_button(7):
                        tmp2 = (lt.logitech_in.get_axis(2) + lt.logitech_in.get_axis(3))/6 - lt.start_axis2 + lt.old_axis2
                    else:
                        tmp2 = (lt.logitech_in.get_axis(2) + lt.logitech_in.get_axis(3))/16 - lt.start_axis2 + lt.old_axis2
                    if tmp2 != lt.axis_state2:
                        lt.axis_state2 = tmp2
                        # for all in samplebox param state push out 
                        for note in xrange(8):
                            if samplebox.samplebox[note][0] == 1:
                                midiout(device=yoke7, note=note,
                                        velocity=samplebox.samplebox[note][1].push_out(lt.axis_state2),channel=10)
                
            

                """
                if lt.logitech_in.get_button(6):
                    tmp = lt.logitech_in.get_axis(0)
                    pygame.event.clear()
                    if (lt.axis_state != tmp) and lt.logitech_in.get_button(10):
                    lt.axis_state = tmp
                    launchpad.push_params(lt.axis_state + lt.axis2_state)
                else:
                    tmp2 = lt.logitech_in.get_axis(0)/8
                    pygame.event.clear()
                    if (lt.axis2_state != tmp2) and lt.logitech_in.get_button(10):
                    lt.axis2_state = tmp2
                    launchpad.push_params(lt.axis_state + lt.axis2_state)
                #Coarse
                """

    return seen_stuff
コード例 #17
0
while (boolean):

    # Detect keypress on input
    if input.poll():

        # Get MIDI event information
        eventlist = input.read(1000)
        print(eventlist)
        for e in eventlist:
            print(e)
            print(e[1])
            if (e[0][1] == 36):
                mid.save('new_song1.mid')
                boolean = False
                break
            if (e[0][0] == KEYDOWN):
                track.append(
                    Message('note_on',
                            note=e[0][1],
                            velocity=e[0][2],
                            time=midi.time()))
            elif (e[0][0] == KEYUP):
                track.append(
                    Message('note_off',
                            note=e[0][1],
                            velocity=e[0][2],
                            time=midi.time()))
input.close()
# Close the midi interface
midi.quit()
コード例 #18
0
ファイル: main.py プロジェクト: maddy-tod/unitary-fingerboard
def main():
    pygame.display.set_caption('Unitary Fingerboard')

    screen.blit(background, (0, 0))
    pygame.display.flip()

    # Prepare objects
    clock = pygame.time.Clock()

    circuit_grid_model = CircuitGridModel(NUM_QUBITS, 18)

    circuit_grid_model.set_node(0, 1, CircuitGridNode(node_types.Y))
    circuit_grid_model.set_node(2, 1, CircuitGridNode(node_types.Y))

    circuit_grid_model.set_node(1, 2, CircuitGridNode(node_types.X, 0, 0))
    circuit_grid_model.set_node(2, 3, CircuitGridNode(node_types.X, 0, 1))

    circuit_grid_model.set_node(1, 4, CircuitGridNode(node_types.Y))
    circuit_grid_model.set_node(3, 4, CircuitGridNode(node_types.Y))

    # print("str(circuit_grid_model): ", str(circuit_grid_model))

    circuit = circuit_grid_model.compute_circuit()

    unitary_grid = UnitaryGrid(circuit)

    middle_sprites = VBox(400, 10, unitary_grid)

    circuit_grid = CircuitGrid(10, 600, circuit_grid_model)
    screen.blit(background, (0, 0))

    middle_sprites.draw(screen)
    # right_sprites.draw(screen)
    circuit_grid.draw(screen)
    pygame.display.flip()

    gamepad_repeat_delay = 100
    gamepad_neutral = True
    gamepad_pressed_timer = 0
    gamepad_last_update = pygame.time.get_ticks()

    pygame.fastevent.init()
    event_get = pygame.fastevent.get

    # MIDI setup
    # TODO: Put in functions or class/methods
    pygame.midi.init()

    print_midi_device_info()

    device_id = 0
    if device_id is None:
        input_id = pygame.midi.get_default_input_id()
    else:
        input_id = device_id

    # input_id = 0
    print("using input_id :%s:" % input_id)
    i = pygame.midi.Input(input_id)

    # sending midi to the output
    output_id = pygame.midi.get_default_output_id()
    ## output_id = 1
    print("using output_id :%s:" % output_id)

    global midi_output
    midi_output = pygame.midi.Output(output_id)
    midi_output.set_instrument(0)

    # end of sending midi to output

    bit_str_meas = '0000'

    #
    prev_roli_block_y = -1
    prev_roli_block_x = -1

    # Clear Roli Block and update unitary
    update_roli_block_unitary(unitary_grid)

    beg_time = time()
    recent_note_time = beg_time

    # Main Loop
    going = True
    while going:
        clock.tick(30)

        pygame.time.wait(10)

        if time() > recent_note_time:
            melody_circ = circuit_grid_model.latest_computed_circuit
            if not melody_circ:
                melody_circ = circuit_grid_model.compute_circuit()

            # TODO: Consider moving measure_circuit into circuit_grid_model
            init_bit_str = bit_str_meas
            bit_str_meas = measure_circuit(melody_circ, bit_str_meas,
                                           unitary_grid)

            screen.blit(background, (0, 0))
            unitary_grid.draw_unitary_grid(None, None)
            unitary_grid.highlight_measured_state(init_bit_str, bit_str_meas)
            middle_sprites.arrange()
            middle_sprites.draw(screen)
            circuit_grid.draw(screen)
            pygame.display.flip()

            pitch_meas = compute_pitch_by_bitstr(bit_str_meas)

            if prev_roli_block_y >= 0 and prev_roli_block_x >= 0:
                # Remove the previous note from Roli block
                prob_midi_val = int(
                    abs(unitary_grid.unitary[prev_roli_block_y]
                        [prev_roli_block_x])**2 * 127)
                midi_output.write([[[
                    0xb0 + prev_roli_block_y, prev_roli_block_x,
                    int(prob_midi_val)
                ], 0]])

            # Save the coordinates that the measurement will be displayed
            prev_roli_block_y = int(init_bit_str, 2)
            prev_roli_block_x = int(bit_str_meas, 2)

            # Send MIDI to Roli Block that indicates updating display for this note
            midi_output.write([[[0xa0, prev_roli_block_y, prev_roli_block_x],
                                0]])

            recent_note_time += 750
            # midi_output.write([[[0x90, pitch_meas, 127], recent_note_time + 0],
            #                    [[0x90, pitch_meas, 0], recent_note_time + 500]])
            midi_output.write([[[0x90, pitch_meas, 127],
                                recent_note_time + 0]])
            # melody_circ = createTransitionCircuit(cur_mel_midi_vals)

        if joystick:
            gamepad_move = False
            joystick_hat = joystick.get_hat(0)

            if joystick_hat == (0, 0):
                gamepad_neutral = True
                gamepad_pressed_timer = 0
            else:
                if gamepad_neutral:
                    gamepad_move = True
                    gamepad_neutral = False
                else:
                    gamepad_pressed_timer += pygame.time.get_ticks(
                    ) - gamepad_last_update
            if gamepad_pressed_timer > gamepad_repeat_delay:
                gamepad_move = True
                gamepad_pressed_timer -= gamepad_repeat_delay
            if gamepad_move:
                if joystick_hat == (-1, 0):
                    move_update_circuit_grid_display(circuit_grid, MOVE_LEFT)
                elif joystick_hat == (1, 0):
                    move_update_circuit_grid_display(circuit_grid, MOVE_RIGHT)
                elif joystick_hat == (0, 1):
                    move_update_circuit_grid_display(circuit_grid, MOVE_UP)
                elif joystick_hat == (0, -1):
                    move_update_circuit_grid_display(circuit_grid, MOVE_DOWN)
            gamepad_last_update = pygame.time.get_ticks()

            # Check left thumbstick position
            # left_thumb_x = joystick.get_axis(0)
            # left_thumb_y = joystick.get_axis(1)

        # Handle Input Events
        for event in pygame.event.get():
            pygame.event.pump()

            # if event.type != MOUSEMOTION:
            #     print("event: ", event)
            if event.type == QUIT:
                going = False
            elif event.type in [pygame.midi.MIDIIN]:
                print("MIDI event: ", event)

            elif event.type == JOYBUTTONDOWN:
                if event.button == BTN_A:
                    # Place X gate
                    circuit_grid.handle_input_x()
                    update_circ_viz(circuit, circuit_grid_model, circuit_grid,
                                    middle_sprites, unitary_grid)
                    pygame.display.flip()
                elif event.button == BTN_X:
                    # Place Y gate
                    circuit_grid.handle_input_y()
                    update_circ_viz(circuit, circuit_grid_model, circuit_grid,
                                    middle_sprites, unitary_grid)
                    pygame.display.flip()
                elif event.button == BTN_B:
                    # Place Z gate
                    circuit_grid.handle_input_z()
                    update_circ_viz(circuit, circuit_grid_model, circuit_grid,
                                    middle_sprites, unitary_grid)
                    pygame.display.flip()
                elif event.button == BTN_Y:
                    # Place Hadamard gate
                    circuit_grid.handle_input_h()
                    update_circ_viz(circuit, circuit_grid_model, circuit_grid,
                                    middle_sprites, unitary_grid)
                    pygame.display.flip()
                elif event.button == BTN_RIGHT_TRIGGER:
                    # Delete gate
                    circuit_grid.handle_input_delete()
                    update_circ_viz(circuit, circuit_grid_model, circuit_grid,
                                    middle_sprites, unitary_grid)
                    pygame.display.flip()
                elif event.button == BTN_RIGHT_THUMB:
                    # Add or remove a control
                    circuit_grid.handle_input_ctrl()
                    update_circ_viz(circuit, circuit_grid_model, circuit_grid,
                                    middle_sprites, unitary_grid)
                    pygame.display.flip()

            elif event.type == JOYAXISMOTION:
                # print("event: ", event)
                if event.axis == AXIS_RIGHT_THUMB_X and joystick.get_axis(
                        AXIS_RIGHT_THUMB_X) >= 0.95:
                    circuit_grid.handle_input_rotate(np.pi / 8)
                    update_circ_viz(circuit, circuit_grid_model, circuit_grid,
                                    middle_sprites, unitary_grid)
                    pygame.display.flip()
                if event.axis == AXIS_RIGHT_THUMB_X and joystick.get_axis(
                        AXIS_RIGHT_THUMB_X) <= -0.95:
                    circuit_grid.handle_input_rotate(-np.pi / 8)
                    update_circ_viz(circuit, circuit_grid_model, circuit_grid,
                                    middle_sprites, unitary_grid)
                    pygame.display.flip()
                if event.axis == AXIS_RIGHT_THUMB_Y and joystick.get_axis(
                        AXIS_RIGHT_THUMB_Y) <= -0.95:
                    circuit_grid.handle_input_move_ctrl(MOVE_UP)
                    update_circ_viz(circuit, circuit_grid_model, circuit_grid,
                                    middle_sprites, unitary_grid)
                    pygame.display.flip()
                if event.axis == AXIS_RIGHT_THUMB_Y and joystick.get_axis(
                        AXIS_RIGHT_THUMB_Y) >= 0.95:
                    circuit_grid.handle_input_move_ctrl(MOVE_DOWN)
                    update_circ_viz(circuit, circuit_grid_model, circuit_grid,
                                    middle_sprites, unitary_grid)
                    pygame.display.flip()

            elif event.type == KEYDOWN:
                index_increment = 0
                if event.key == K_ESCAPE:
                    going = False
                elif event.key == K_a:
                    circuit_grid.move_to_adjacent_node(MOVE_LEFT)
                    circuit_grid.draw(screen)
                    pygame.display.flip()
                elif event.key == K_d:
                    circuit_grid.move_to_adjacent_node(MOVE_RIGHT)
                    circuit_grid.draw(screen)
                    pygame.display.flip()
                elif event.key == K_w:
                    circuit_grid.move_to_adjacent_node(MOVE_UP)
                    circuit_grid.draw(screen)
                    pygame.display.flip()
                elif event.key == K_s:
                    circuit_grid.move_to_adjacent_node(MOVE_DOWN)
                    circuit_grid.draw(screen)
                    pygame.display.flip()
                elif event.key == K_x:
                    circuit_grid.handle_input_x()
                    update_circ_viz(circuit, circuit_grid_model, circuit_grid,
                                    middle_sprites, unitary_grid)
                    pygame.display.flip()
                elif event.key == K_y:
                    circuit_grid.handle_input_y()
                    update_circ_viz(circuit, circuit_grid_model, circuit_grid,
                                    middle_sprites, unitary_grid)
                    pygame.display.flip()
                elif event.key == K_z:
                    circuit_grid.handle_input_z()
                    update_circ_viz(circuit, circuit_grid_model, circuit_grid,
                                    middle_sprites, unitary_grid)
                    pygame.display.flip()
                elif event.key == K_h:
                    circuit_grid.handle_input_h()
                    update_circ_viz(circuit, circuit_grid_model, circuit_grid,
                                    middle_sprites, unitary_grid)
                    pygame.display.flip()
                elif event.key == K_BACKSLASH:
                    circuit_grid.handle_input_delete()
                    update_circ_viz(circuit, circuit_grid_model, circuit_grid,
                                    middle_sprites, unitary_grid)
                    pygame.display.flip()
                elif event.key == K_c:
                    # Add or remove a control
                    circuit_grid.handle_input_ctrl()
                    update_circ_viz(circuit, circuit_grid_model, circuit_grid,
                                    middle_sprites, unitary_grid)
                    pygame.display.flip()
                elif event.key == K_UP:
                    # Move a control qubit up
                    circuit_grid.handle_input_move_ctrl(MOVE_UP)
                    update_circ_viz(circuit, circuit_grid_model, circuit_grid,
                                    middle_sprites, unitary_grid)
                    pygame.display.flip()
                elif event.key == K_DOWN:
                    # Move a control qubit down
                    circuit_grid.handle_input_move_ctrl(MOVE_DOWN)
                    update_circ_viz(circuit, circuit_grid_model, circuit_grid,
                                    middle_sprites, unitary_grid)
                    pygame.display.flip()
                elif event.key == K_LEFT:
                    # Rotate a gate
                    circuit_grid.handle_input_rotate(-np.pi / 8)
                    update_circ_viz(circuit, circuit_grid_model, circuit_grid,
                                    middle_sprites, unitary_grid)
                    pygame.display.flip()
                elif event.key == K_RIGHT:
                    # Rotate a gate
                    circuit_grid.handle_input_rotate(np.pi / 8)
                    update_circ_viz(circuit, circuit_grid_model, circuit_grid,
                                    middle_sprites, unitary_grid)
                    pygame.display.flip()

        # TODO: Put this flag in unitary_grid, making methods to
        # TODO:     update respective matrices
        desired_vs_unitary_dirty = False
        if i.poll():
            midi_events = i.read(1000)

            # convert them into pygame events.
            midi_evs = pygame.midi.midis2events(midi_events, i.device_id)

            for index, midi_ev in enumerate(midi_evs):
                if 160 <= midi_ev.status < 176:
                    if unitary_grid.desired_stochastic_matrix is not None:
                        row_num = midi_ev.status - 160
                        col_num = midi_ev.data1
                        unitary_grid.desired_stochastic_matrix[row_num, col_num] = \
                            max(unitary_grid.desired_stochastic_matrix[row_num, col_num], midi_ev.data2 / 127.0)
                elif midi_ev.status == 176:
                    if midi_ev.data1 == 0 and midi_ev.data2 == 0:
                        desired_vs_unitary_dirty = True

            if desired_vs_unitary_dirty:
                unitary_grid.normalize_desired_unitary()
                unitary_grid.draw_unitary_grid(None, None)
                print('after block swipe, mse: ',
                      unitary_grid.cost_desired_vs_unitary())

                # TODO: Apply optimization
                rotation_gate_nodes = circuit_grid_model.get_rotation_gate_nodes(
                )

                # initial_rotations = np.zeros(len(rotation_gate_nodes))
                initial_rotations = np.full(len(rotation_gate_nodes), np.pi)

                rotation_bounds = np.zeros((len(rotation_gate_nodes), 2))
                # for idx in range(len(rotation_gate_nodes)):
                # circuit_grid.rotate_gate_absolute(rot_gate_node, random.uniform(0, np.pi))
                # initial_rotations[idx] = rotation_gate_nodes[idx].radians
                # rotation_bounds[idx] = [np.pi / 8, 7 * np.pi / 8]

                # results = scipy.optimize.fmin_l_bfgs_b(desired_vs_unitary_objective_function,
                #                                        x0=initial_rotations,
                #                                        args=(circuit_grid, unitary_grid, rotation_gate_nodes),
                #                                        approx_grad=True,
                #                                        bounds=rotation_bounds)
                # print('results: ', results)

                opt_rotations = optimize_rotations(
                    desired_vs_unitary_objective_function, initial_rotations,
                    circuit_grid, unitary_grid, rotation_gate_nodes)
                print('opt_rotations: ', opt_rotations)

                update_circ_viz(circuit, circuit_grid_model, circuit_grid,
                                middle_sprites, unitary_grid)

                unitary_grid.zero_desired_unitary()
                desired_vs_unitary_dirty = False

    del i
    pygame.quit()
コード例 #19
0
ファイル: pygame.py プロジェクト: ViktorNova/musikernel
 def _send(self, message):
     if message.type == 'sysex':
         self._port.write_sys_ex(midi.time(), message.bytes())
     else:
         self._port.write_short(*message.bytes())
コード例 #20
0
ファイル: midiBuffer.py プロジェクト: jmmcd/drum-manifold
        def getTime(self):
            """
get current time in ms, use to generate onset timestamps to send to midiBuffer.playChord()
            """
            return pm.time()
コード例 #21
0
 def GetTime(self):
     return midi.time()
コード例 #22
0
ファイル: midi.py プロジェクト: UltrasonicNXT/launchpad
 def send(self):
     data = [[[0b10010000, self.number, self.velocity, 0], midi.time()]]
     self.connection.output.write(data)
コード例 #23
0
 def _send(self, message):
     if message.type == 'sysex':
         self._port.write_sys_ex(midi.time(), message.bytes())
     else:
         self._port.write_short(*message.bytes())
コード例 #24
0
ファイル: launchpad.py プロジェクト: AMertgens/launchpad.py
		def GetTime( self ):
			return midi.time()
コード例 #25
0
ファイル: midi.py プロジェクト: UltrasonicNXT/launchpad
 def close(self):
     self.output.write_sys_ex(midi.time(),
                              [0b11110000, 00, 32, 41, 2, 24, 14, 0, 247])
     self.input.close()
     self.output.close()
     midi.quit()