示例#1
0
    def timer_event(self):
        done = False
        while not done:
            msg = CMessage()
            rcv = self.mod.ReadMessage(msg, 0)
            if rcv == 1:
                msg_type = msg.GetHeader().msg_type
            
                if msg_type == rc.MT_TASK_STATE_CONFIG:
                    mdf = rc.MDF_TASK_STATE_CONFIG()
                    copy_from_msg(mdf, msg)
                    x = mdf.target[0]
                    y = mdf.target[1]
                    self.setTargetPos(x, y)

                    #print "x: ", x, "|", self.tgt2pix(x) , " y: ", y, "|", self.tgt2pix(y)
                
                elif msg_type == rc.MT_ROBOT_CONTROL_SPACE_ACTUAL_STATE:
                    mdf = rc.MDF_ROBOT_CONTROL_SPACE_ACTUAL_STATE()
                    copy_from_msg(mdf, msg)
                    x = mdf.pos[0]
                    y = mdf.pos[1]
                    self.setCursorPos(x, y)

                    #print "x: ", mdf.pos[0], "y: ", mdf.pos[1]
                
                elif msg_type == rc.MT_PING:
                    respond_to_ping(self.mod, msg, 'CursorDisplay')

                elif msg_type == MT_EXIT:
                    self.exit()
                    done = True
                
            else:
                done = True                
示例#2
0
    def timer_event(self):
        done = False
        while not done:
            msg = CMessage()
            rcv = self.mod.ReadMessage(msg, 0)
            if rcv == 1:
                msg_type = msg.GetHeader().msg_type

                if msg_type == rc.MT_HOTSPOT_POSITION: #rc.MT_RAW_SPIKECOUNT: #rc.MT_SPM_SPIKECOUNT:
                    mdf = rc.MDF_HOTSPOT_POSITION()
                    copy_from_msg(mdf, msg)
                    self.coil_tail = np.array(in_mdf.xyz[:])
                    self.coil_head = np.array(in_mdf.ori[:3])
                    self.update_judging_data()
                
                elif msg_type == rc.MT_PING:
                    respond_to_ping(self.mod, msg, 'PolarisDragonfly')

                #elif msg_type == MT_EXIT:
                #    self.exit()
                #    done = True

            else:
                done = True

        self.update_plot()
示例#3
0
    def process_message(self, msg):
        msg_type = msg.GetHeader().msg_type
        if msg_type == rc.MT_INPUT_DOF_DATA:
            mdf = rc.MDF_INPUT_DOF_DATA()
            copy_from_msg(mdf, msg)
            tag = mdf.tag
            if tag in self.inputs.keys():
                dof_vals = np.asarray(mdf.dof_vals[:], dtype=float)
                cid = int(mdf.tag[-1])
                pressed = ~self.was_pressed[cid] & (dof_vals > btn_threshold)
                started = self.bounce_start[cid] > 0

                # start timers on previously unstarted counters
                self.bounce_start[cid, pressed & ~started] = time.time()

                dt = time.time() - self.bounce_start[cid]
                held = dt > bounce_threshold
                valid_held = pressed & held

                for vh in np.flatnonzero(valid_held):
                    if vh in name_lookup.keys():
                        self.was_pressed[cid, vh] = True
                        self.send_btn_press(name_lookup[vh], cid)

                released = self.was_pressed[cid] & (dof_vals < btn_threshold)
                valid_released = released & held & ~valid_held

                for vr in np.flatnonzero(valid_released):
                    if vr in name_lookup.keys():
                        self.was_pressed[cid, vr] = False
                        self.send_btn_release(name_lookup[vr], cid)
                        self.bounce_start[cid, vr] = -1
示例#4
0
    def get_frequency(self):
        # loop over receiving messages until we get a POLARIS_POSITION message
        while True:
            msg = CMessage()
            rcv = self.mod.ReadMessage(msg, 0.001)
            if rcv == 1:
                msg_type = msg.GetHeader().msg_type
                dest_mod_id = msg.GetHeader().dest_mod_id
                if msg_type == MT_EXIT:
                    if (dest_mod_id == 0) or (dest_mod_id == self.mod.GetModuleID()):
                        print "Received MT_EXIT, disconnecting..."
                        self.mod.SendSignal(rc.MT_EXIT_ACK)
                        self.mod.DisconnectFromMMM()
                        break
                elif msg_type == rc.MT_PING:
                    respond_to_ping(self.mod, msg, "PolarisDragonfly")
                else:
                    msg_type = msg.GetHeader().msg_type
                    if msg_type == rc.MT_POLARIS_POSITION:
                        # handling input message
                        mdf = rc.MDF_POLARIS_POSITION()
                        copy_from_msg(mdf, msg)
                        self.fsamp = 1 / mdf.sample_header.DeltaTime
                        if self.fsamp != 0:
                            break

        self.user_start_calibrate()
示例#5
0
    def process_message(self, in_msg):

        msg_type = in_msg.GetHeader().msg_type
        if msg_type == rc.MT_POLARIS_POSITION:
            # handling input message
            in_mdf = rc.MDF_POLARIS_POSITION()
            copy_from_msg(in_mdf, in_msg)
            positions = np.array(in_mdf.xyz[:])
            orientations = self.shuffle_q(np.array(in_mdf.ori[:]))

            # np.testing.assert_array_equal(positions[:,0], orientations[:,0], err_msg='Samples are not aligned')

            if self.calibrated:
                if in_mdf.tool_id == (self.marker + 1):
                    # calculating output
                    self.Qk = qa.norm(
                        orientations
                    )  # need to find a way to discriminate the tools files in the messages???
                    Qr = qa.mult(self.Qk, qa.inv(self.Qi)).flatten()
                    Tk = positions
                    hotspot_position = (qa.rotate(Qr, self.Xi) + Tk).flatten()
                    hotspot_vector_head = qa.rotate(Qr, plate_vector)
                    if np.any(np.isnan(hotspot_position)) == True:
                        print "x",
                        # print '         *****nan present, check coil is within frame!*****'

                    # creating output message
                    out_mdf = rc.MDF_HOTSPOT_POSITION()
                    out_mdf.xyz[:] = hotspot_position
                    out_mdf.ori[:3] = hotspot_vector_head  # Qk - coil active orientation
                    out_mdf.sample_header = in_mdf.sample_header
                    msg = CMessage(rc.MT_HOTSPOT_POSITION)
                    copy_to_msg(out_mdf, msg)
                    self.mod.SendMessage(msg)
                    sys.stdout.write("o")

            else:
                if np.any(np.isnan(positions)) == True:
                    raise Exception, "nan present"
                if np.any(np.isnan(orientations)) == True:
                    raise Exception, "nan present"
                if (
                    (self.store_plate >= self.store_plate_pos.shape[0])
                    & (self.store_plate >= self.store_plate_ori.shape[0])
                    & (self.store_coil >= self.store_coil_pos.shape[0])
                    & (self.store_coil >= self.store_coil_ori.shape[0])
                ):
                    self.calibrating = False
                    self.make_calibration_vector()
                elif in_mdf.tool_id == (self.marker + 1):
                    self.store_coil_pos[self.store_coil, :] = positions
                    self.store_coil_ori[self.store_coil, :] = orientations
                    self.store_coil += 1
                elif in_mdf.tool_id == (self.plate + 1):
                    self.store_plate_pos[self.store_plate, :] = positions
                    self.store_plate_ori[self.store_plate, :] = orientations
                    self.store_plate += 1
示例#6
0
def respond_to_ping(mod, msg, module_name):
    dest_mod_id = msg.GetHeader().dest_mod_id
    p = rc.MDF_PING()
    copy_from_msg(p, msg)

    # print "PING received for '{0}'".format(p.module_name)

    if (p.module_name.lower() == module_name.lower()) or (p.module_name == "*") or (dest_mod_id == mod.GetModuleID()):
        mdf = rc.MDF_PING_ACK()
        mdf.module_name = module_name
        msg_out = CMessage(rc.MT_PING_ACK)
        copy_to_msg(mdf, msg_out)
        mod.SendMessage(msg_out)
示例#7
0
    def run(self):
        while True:
            msg = CMessage()
            rcv = self.mod.ReadMessage(msg, 0.1)
            if rcv == 1:
                msg_type = msg.GetHeader().msg_type

                if msg_type == rc.MT_APP_START:

                    try:
                        mdf = rc.MDF_APP_START()
                        copy_from_msg(mdf, msg) 
                        config = mdf.config
                        
                        print "Config: %s" % config

                        # -- to do --
                        # get a list of all modules in appman.conf for this host
                        # see if any of the modules above are already/still running
                        # start non-running modules
                        # -- to do --
                        
                        print "Creating scripts"
                        appman.create_script(config, self.host_name)
                        print "Starting modules on host: %s" % self.host_name
                        appman.run_script(self.host_name)

                        self.mod.SendSignal(rc.MT_APP_START_COMPLETE)

                    except Exception, e:
                        print "ERROR: %s" % (e)
                    
                elif msg_type == rc.MT_PING:
                    print 'got ping'
                    self.respond_to_ping(msg, 'AppStarter')
                    
                # we use this msg to stop modules individually
                elif msg_type == MT_EXIT:
                    print 'got exit'
                    
                elif msg_type == MT_KILL:
                    print 'got kill'
                    appman.kill_modules()
 def process_message(self, msg):
     # read a Dragonfly message
     msg_type = msg.GetHeader().msg_type
     dest_mod_id = msg.GetHeader().dest_mod_id
     if  msg_type == MT_EXIT:
         if (dest_mod_id == 0) or (dest_mod_id == self.mod.GetModuleID()):
             print 'Received MT_EXIT, disconnecting...'
             self.mod.SendSignal(rc.MT_EXIT_ACK)
             self.mod.DisconnectFromMMM()
             return
     elif msg_type == rc.MT_PING:
         respond_to_ping(self.mod, msg, 'FastDisplay')
     else:
         # if it is a NiDAQ message from channels 0-7, plot the data
         #self.counter += 1
         if msg_type == rc.MT_TRIGNO_DATA:
             sys.stdout.write("*")
             #sys.stdout.flush()
             mdf = rc.MDF_TRIGNO_DATA()
             copy_from_msg(mdf, msg)
             # add data to data buffers (necessary, or just use graphics buffers?)
             # update plots to new data buffers
             buf = mdf.T
         elif msg_type == rc.MT_SAMPLE_GENERATED:
             sys.stdout.write("#")
             sys.stdout.flush()
             buf = np.random.normal(1, 1, size=(432,))
         else:
             return False
             
         self.new_data[:,:-self.config.perchan] = self.old_data[:,self.config.perchan:]
         print (buf[0:2])
         for i in xrange(self.config.nchan):
             #if i == 0:
             #    print mdf.buffer[perchan * i:perchan * (i + 1)].size
             self.new_data[i, -self.config.perchan:] = buf[i:self.config.nchan * self.config.perchan:self.config.nchan]
             self.axes.flat[i].setData(self.new_data[i])
             #sys.stdout.write("*")
             #sys.stdout.flush()
         self.old_data[:] = self.new_data[:]
示例#9
0
    def timer_event(self):
        done = False
        while not done:
            msg = CMessage()
            rcv = self.mod.ReadMessage(msg, 0)
            if rcv == 1:
                msg_type = msg.GetHeader().msg_type

                # SESSION_CONFIG => start of session
                if msg_type == rc.MT_SESSION_CONFIG:
                    #self.msg_cnt += 1
                    self.num_trials = 0
                    self.reset_counters()
                    self.update_gui_label_data()


                # EM_DECODER_CONFIGURATION => end of an adaptation round
                elif msg_type == rc.MT_EM_DECODER_CONFIGURATION:
                    #self.msg_cnt += 1
                    self.reset_counters()
                    self.update_gui_label_data()

                # END_TASK_STATE => end of a task
                elif msg_type == rc.MT_END_TASK_STATE:
                    #self.msg_cnt += 1
                    mdf = rc.MDF_END_TASK_STATE()
                    copy_from_msg(mdf, msg)

                    # need to know:
                    #    begin task state code
                    #    final task state code
                    #    intertrial state code

                    if (mdf.id == 1):
                        self.trial_sync = 1
                        self.shadow_started_window.append(0)

                    if (mdf.id == self.task_state_codes['begin']) & (mdf.outcome == 1):
                        if self.trial_sync:
                            #print "*** trial started ***"
                            #self.rewards_given += 1
                            self.shadow_num_trial_started_postcalib += 1
                            self.shadow_success_window.append(0)
                            self.shadow_givenup_window.append(0)
                            self.shadow_started_window[-1] = 1

                    if mdf.reason == "JV_IDLE_TIMEOUT":
                        if self.trial_sync:
                            self.shadow_num_trial_givenup_postcalib += 1
                            self.shadow_givenup_window[-1] = 1

                    if (mdf.id == self.task_state_codes['final']) & (mdf.outcome == 1):
                        if self.trial_sync:
                            #print "*** trial complete and successful"
                            self.shadow_num_trial_successful_postcalib += 1
                            self.shadow_success_window[-1] = 1

                    if (mdf.id == self.task_state_codes['intertrial']):
                        if self.trial_sync:
                            # do end-of-trial stuff here
                            self.num_trials += 1
                            self.num_trials_postcalib += 1
                            self.num_trial_started_postcalib = self.shadow_num_trial_started_postcalib
                            self.num_trial_successful_postcalib = self.shadow_num_trial_successful_postcalib
                            self.num_trial_givenup_postcalib = self.shadow_num_trial_givenup_postcalib

                            if len(self.shadow_success_window) > self.window_wide: #self.window_narrow:
                                self.shadow_success_window.pop(0)

                            if len(self.shadow_givenup_window) > self.window_wide: #self.window_narrow:
                                self.shadow_givenup_window.pop(0)

                            if len(self.shadow_started_window) > self.window_wide: #self.window_narrow:
                                self.shadow_started_window.pop(0)

                            self.success_window = copy.deepcopy(self.shadow_success_window)
                            self.started_window = copy.deepcopy(self.shadow_started_window)
                            self.givenup_window = copy.deepcopy(self.shadow_givenup_window)

                            if self.num_trials_postcalib > 0:
                                self.percent_start = 100 * self.num_trial_started_postcalib / self.num_trials_postcalib
                                self.percent_givenup = 100 * self.num_trial_givenup_postcalib / self.num_trials_postcalib
                                self.percent_success = 100 * self.num_trial_successful_postcalib / self.num_trials_postcalib


                            percent_success_wide_window = np.NAN
                            if len(self.success_window) >= self.window_wide:
                                num_success_window = np.sum(self.success_window)
                                percent_success_wide_window = 100 * num_success_window / len(self.success_window)

                            percent_givenup_wide_window = np.NAN
                            if len(self.givenup_window) >= self.window_wide:
                                num_givenup_window = np.sum(self.givenup_window)
                                percent_givenup_wide_window = 100 * num_givenup_window / len(self.givenup_window)

                            percent_started_wide_window = np.NAN
                            if len(self.started_window) >= self.window_wide:
                                num_started_window = np.sum(self.started_window)
                                percent_started_wide_window = 100 * num_started_window / len(self.started_window)

                            percent_success_narrow_window = np.NAN
                            if len(self.success_window) >= self.window_narrow:
                                success_window_narrow = self.success_window[len(self.success_window)-self.window_narrow:]
                                num_success_window = np.sum(success_window_narrow)
                                percent_success_narrow_window = 100 * num_success_window / len(success_window_narrow)

                            percent_givenup_narrow_window = np.NAN
                            if len(self.givenup_window) >= self.window_narrow:
                                givenup_window_narrow = self.givenup_window[len(self.givenup_window)-self.window_narrow:]
                                num_givenup_window = np.sum(givenup_window_narrow)
                                percent_givenup_narrow_window = 100 * num_givenup_window / len(givenup_window_narrow)

                            if len(self.started_window) >= self.window_narrow:
                                started_window_narrow = self.started_window[len(self.started_window)-self.window_narrow:]
                                num_started_window = np.sum(started_window_narrow)
                                percent_started_narrow_window = 100 * num_started_window / len(started_window_narrow)
                                self.hist_narrow_STR.append(percent_started_narrow_window)
                                self.hist_narrow_SUR.append(percent_success_narrow_window)
                                self.hist_narrow_GUR.append(percent_givenup_narrow_window)

                                self.hist_wide_STR.append(percent_started_wide_window)
                                self.hist_wide_SUR.append(percent_success_wide_window)
                                self.hist_wide_GUR.append(percent_givenup_wide_window)

                            self.update_gui_label_data()


                elif msg_type == rc.MT_PING:
                    respond_to_ping(self.mod, msg, 'TrialStatusDisplay')

                elif msg_type == MT_EXIT:
                    self.exit()
                    done = True

            else:
                done = True

                self.console_disp_cnt += 1
                if self.console_disp_cnt == 50:
                    self.update_plot()
                    self.console_disp_cnt = 0
示例#10
0
#!/usr/bin/python
import time
import PyDragonfly
from PyDragonfly import copy_from_msg
import message_defs as mdefs
import sys

MID_CONSUMER = 11

if __name__ == "__main__":
    mod = PyDragonfly.Dragonfly_Module(MID_CONSUMER, 0)
    mod.ConnectToMMM("localhost:7111")
    mod.Subscribe(mdefs.MT_TEST_DATA)
    
    print "Consumer running...\n"
    
    while (1):
        msg = PyDragonfly.CMessage()
        mod.ReadMessage(msg)    # blocking read
        print "Received message ", msg.GetHeader().msg_type

        if msg.GetHeader().msg_type == mdefs.MT_TEST_DATA:
            msg_data = mdefs.MDF_TEST_DATA()
            copy_from_msg(msg_data, msg)
            print "  Data = [a: %d, b: %d, x: %f]" % (msg_data.a, msg_data.b, msg_data.x)
        
    mod.DisconnectFromMMM()
        
示例#11
0
    def process_message(self, msg):
        """
        Needs to:
        1) combine non-conflicting controlledDims e.g. from
        OPERATOR_MOVEMENT_COMMANDs, into either extrinsic or
        intrinsic commands
        2) combine intrinsic and extrinsic commands into final command
        """
        msg_type = msg.GetHeader().msg_type
        if msg_type in [
            rc.MT_OPERATOR_MOVEMENT_COMMAND,
            rc.MT_PLANNER_MOVEMENT_COMMAND,
            rc.MT_EM_MOVEMENT_COMMAND,
            rc.MT_FIXTURED_MOVEMENT_COMMAND,
        ]:

            if msg_type == rc.MT_OPERATOR_MOVEMENT_COMMAND:
                mdf = rc.MDF_OPERATOR_MOVEMENT_COMMAND()

            elif msg_type == rc.MT_PLANNER_MOVEMENT_COMMAND:
                mdf = rc.MDF_PLANNER_MOVEMENT_COMMAND()

            elif msg_type == rc.MT_EM_MOVEMENT_COMMAND:
                mdf = rc.MDF_EM_MOVEMENT_COMMAND()

            elif msg_type == rc.MT_FIXTURED_MOVEMENT_COMMAND:
                mdf = rc.MDF_FIXTURED_MOVEMENT_COMMAND()

            # MOVEMENT_COMMAND
            # ----------------
            # controlledDims
            # pos
            # sample_header
            # sample_interval
            # tag
            # vel
            # ----------------

            copy_from_msg(mdf, msg)
            tag = mdf.tag
            # if not tag in self.accepted_tags:
            #    return
            dim = np.asarray(mdf.controlledDims, dtype=bool)  # .astype(bool)
            if mdf.tag in self.intrinsic_tags:
                # intrinsic is AUTO command
                self.intrinsic_vel[dim] = np.asarray(mdf.vel, dtype=float)[dim]
                # print "intr_vel = " + " ".join(["%5.2f" % (x) for x in self.intrinsic_vel])
            elif mdf.tag in self.extrinsic_tags:
                # print "!"
                # extrinsic is non-AUTO, i.e. EM, command
                self.extrinsic_vel[dim] = np.asarray(mdf.vel, dtype=float)[dim]
                # self.extrinsic_vel[:8] *= self.gate

            if tag == self.timer_tag:
                self.send_output(mdf.sample_header)
        elif msg_type == rc.MT_ROBOT_CONTROL_CONFIG:
            mdf = rc.MDF_ROBOT_CONTROL_CONFIG()
            copy_from_msg(mdf, msg)
            self.autoVelControlFraction[:] = mdf.autoVelControlFraction
        elif msg_type == rc.MT_IDLE:
            mdf = rc.MDF_IDLE()
            copy_from_msg(mdf, msg)
            self.gate = float(np.asarray(mdf.gain, dtype=float).item())
        elif msg_type == rc.MT_IDLE_DETECTION_ENDED:
            self.gate = 1.0
        elif msg_type == rc.MT_TASK_STATE_CONFIG:
            mdf = rc.MDF_TASK_STATE_CONFIG()
            copy_from_msg(mdf, msg)
            self.idle_gateable = mdf.idle_gateable
示例#12
0
    def process_message(self, in_msg):
        msg_type = in_msg.GetHeader().msg_type
        if not msg_type in self.msg_nums:
            return

        # SESSION_CONFIG => start of session
        if msg_type == rc.MT_SESSION_CONFIG:
            self.num_trials = 0
            self.reset_counters()

        # EM_DECODER_CONFIGURATION => end of an adaptation round
        elif msg_type == rc.MT_EM_DECODER_CONFIGURATION:
            self.reset_counters()

        # END_TASK_STATE => end of a task
        elif msg_type == rc.MT_END_TASK_STATE:
            mdf = rc.MDF_END_TASK_STATE()
            copy_from_msg(mdf, in_msg)

            # need to know:
            #    begin task state code
            #    final task state code
            #    intertrial state code

            if mdf.id == 1:
                self.trial_sync = 1
                self.shadow_started_window.append(0)

            if (mdf.id == self.task_state_codes["begin"]) & (mdf.outcome == 1):
                if self.trial_sync:
                    # print "*** trial started ***"
                    # self.rewards_given += 1
                    self.shadow_num_trial_started_postcalib += 1
                    self.shadow_success_window.append(0)
                    self.shadow_givenup_window.append(0)
                    self.shadow_started_window[-1] = 1

            if mdf.reason == "JV_IDLE_TIMEOUT":
                if self.trial_sync:
                    self.shadow_num_trial_givenup_postcalib += 1
                    self.shadow_givenup_window[-1] = 1

            if (mdf.id == self.task_state_codes["final"]) & (mdf.outcome == 1):
                if self.trial_sync:
                    # print "*** trial complete and successful"
                    self.shadow_num_trial_successful_postcalib += 1
                    self.shadow_success_window[-1] = 1

            if mdf.id == self.task_state_codes["intertrial"]:
                if self.trial_sync:
                    # do end-of-trial stuff here
                    self.num_trials += 1
                    self.num_trials_postcalib += 1
                    self.num_trial_started_postcalib = self.shadow_num_trial_started_postcalib
                    self.num_trial_successful_postcalib = self.shadow_num_trial_successful_postcalib
                    self.num_trial_givenup_postcalib = self.shadow_num_trial_givenup_postcalib

                    if len(self.shadow_success_window) > self.window_len:
                        self.shadow_success_window.pop(0)

                    if len(self.shadow_givenup_window) > self.window_len:
                        self.shadow_givenup_window.pop(0)

                    if len(self.shadow_started_window) > self.window_len:
                        self.shadow_started_window.pop(0)

                    self.success_window = copy.deepcopy(self.shadow_success_window)
                    self.started_window = copy.deepcopy(self.shadow_started_window)
                    self.givenup_window = copy.deepcopy(self.shadow_givenup_window)