Example #1
0
    def __init__(self, osg_file):
        # the proxy instance allows us to talk to the display server
        self.ds_proxy = JSONStimulusOSGController()
        # create the observer
        self.observer = CarModelSocketObserver(self._observer_callback)
        # load the provided OSG file
        self.ds_proxy.set_stimulus_plugin('StimulusOSG')
        self.ds_proxy.load_osg(osg_file)

        self.expTrial = -1
        self.replicate = -1
        self.tSwitch = 0
        self.tExp = 0
        self.dateStart = ''

        # set starting position for stimuli
        self.rootPosition = np.zeros((1, 2))
        self.postPosition = np.zeros((numberPost, 2))
        self.postDistance = 5.0

        # set starting position of fly
        self.start_position = {'x': 0.0, 'y': 0.0, 'z': -0.07}
        self.ds_proxy.set_position(**self.start_position)

        # assign experiment a unique id
        self.expId = uuid.uuid4()
        # get experiment conditions from database
        self.getExperiment()
        # start every experiment with a no post condition
        self.updateStimuli(0)
        emailer.twitStatus(self.expId, status=0, t=self.tExp)
        self.running = True
        # event counter (number of times fly position is reset)
        self.cntr = 0
Example #2
0
 def __init__(self, osg_file, csv_output=sys.stdout):
     # the proxy instance allows us to talk to the display server
     self.ds_proxy = JSONStimulusOSGController()
     # create the observer
     self.observer = CarModelSocketObserver(self._observer_callback)
     # load the provided OSG file
     self.ds_proxy.set_stimulus_plugin('StimulusOSG')
     self.ds_proxy.load_osg(osg_file)
     # default state
     self.experiment_setup()
Example #3
0
class MyCustomExperiment(object):
    def __init__(self, osg_file, csv_output=sys.stdout):
        # the proxy instance allows us to talk to the display server
        self.ds_proxy = JSONStimulusOSGController()
        # create the observer
        self.observer = CarModelSocketObserver(self._observer_callback)
        # load the provided OSG file
        self.ds_proxy.set_stimulus_plugin('StimulusOSG')
        self.ds_proxy.load_osg(osg_file)
        # default state
        self.experiment_setup()

    def _observer_callback(self, info_dict):
        print info_dict
        self.move_fixed_observer(**info_dict)

    def move_fixed_observer(self, **kwargs):
        x = -kwargs.get('x')
        y = -kwargs.get('y')
        z = -kwargs.get('z')

        p0_x, p0_y = self.post0_position['x'], self.post0_position['y']
        p1_x, p1_y = self.post1_position['x'], self.post1_position['y']
        p2_x, p2_y = self.post2_position['x'], self.post2_position['y']

        self.ds_proxy.move_node('post0', x + p0_x, y + p0_y, 0)
        self.ds_proxy.move_node('post1', x + p1_x, y + p1_y, 0)
        self.ds_proxy.move_node('post2', x + p2_x, y + p2_y, 0)

    def experiment_start(self):
        # self.recorder.start()
        self.observer.start_observer()
        self.experiment_conditions_main_loop()

    def experiment_stop(self):
        # self.observer.stop()
        # self.recorder.stop()
        pass

    def randomize_post_positions(self):
        circle_idxs = set()
        while len(circle_idxs) < 3:
            circle_idxs.add(random.randint(0, 29))

        phi = math.pi * 2 / 30.0
        R = 0.3
        idxs = list(circle_idxs)

        self.post0_position['x'] = R * math.cos(phi * idxs[0])
        self.post0_position['y'] = R * math.sin(phi * idxs[0])
        self.post1_position['x'] = R * math.cos(phi * idxs[1])
        self.post1_position['y'] = R * math.sin(phi * idxs[1])
        self.post2_position['x'] = R * math.cos(phi * idxs[2])
        self.post2_position['y'] = R * math.sin(phi * idxs[2])

    def experiment_setup(self):
        """implement your custom experiment setup here"""
        # set initial observer position
        self.start_position = {'x': 0.0, 'y': 0.0, 'z': -0.07}
        self.ds_proxy.set_position(**self.start_position)

        self.post0_position = {'x': 0.0, 'y': 0.0, 'z': 0}
        self.post1_position = {'x': 0.0, 'y': 0.0, 'z': 0}
        self.post2_position = {'x': 0.0, 'y': 0.0, 'z': 0}

        self.randomize_post_positions()

        self.counter = {'post0': 0, 'post1': 0, 'post2': 0, 'outofbounds': 0}

    def experiment_logic(self):
        pass

    def experiment_conditions_main_loop(self):
        """implement your custom conditions here"""
        t0 = time.time()
        with open('output-%f.csv' % time.time(), 'w') as output:
            while True:
                t = time.time() - t0
                pos = self.observer.position
                if distance(pos, self.post0_position) < 0.1:
                    # reached post 0
                    self.counter['post0'] += 1
                    self.observer.reset_to(**self.start_position)
                    self.randomize_post_positions()

                elif distance(pos, self.post1_position) < 0.1:
                    # reached post 0
                    self.counter['post1'] += 1
                    self.observer.reset_to(**self.start_position)
                    self.randomize_post_positions()

                elif distance(pos, self.post2_position) < 0.1:
                    # reached post 0
                    self.counter['post2'] += 1
                    self.observer.reset_to(**self.start_position)
                    self.randomize_post_positions()

                elif distance(pos, self.start_position) > 0.5:
                    self.counter['outofbounds'] += 1
                    self.observer.reset_to(**self.start_position)
                    self.randomize_post_positions()

                time.sleep(0.005)
                #print "XYZ(%3.2f, %3.2f, %3.2f)" % (pos['x'], pos['y'], pos['z']), self.counter
                output.write('%.8f, %.8f, %.8f, %s\n' %
                             (pos['x'], pos['y'], t, str(self.counter)))
Example #4
0
class MyExperiment(object):
    def __init__(self, osg_file):
        # the proxy instance allows us to talk to the display server
        self.ds_proxy = JSONStimulusOSGController()
        # create the observer
        self.observer = CarModelSocketObserver(self._observer_callback)
        # load the provided OSG file
        self.ds_proxy.set_stimulus_plugin('StimulusOSG')
        self.ds_proxy.load_osg(osg_file)

        self.expTrial = -1
        self.replicate = -1
        self.tSwitch = 0
        self.tExp = 0
        self.dateStart = ''

        # set starting position for stimuli
        self.rootPosition = np.zeros((1, 2))
        self.postPosition = np.zeros((numberPost, 2))
        self.postDistance = 5.0

        # set starting position of fly
        self.start_position = {'x': 0.0, 'y': 0.0, 'z': -0.07}
        self.ds_proxy.set_position(**self.start_position)

        # assign experiment a unique id
        self.expId = uuid.uuid4()
        # get experiment conditions from database
        self.getExperiment()
        # start every experiment with a no post condition
        self.updateStimuli(0)
        emailer.twitStatus(self.expId, status=0, t=self.tExp)
        self.running = True
        # event counter (number of times fly position is reset)
        self.cntr = 0

    def _observer_callback(self, info_dict):
        #print info_dict
        self.move_fixed_observer(**info_dict)

    def move_fixed_observer(self, **kwargs):
        x = -kwargs.get('x')
        y = -kwargs.get('y')
        z = -kwargs.get('z')

        self.ds_proxy.move_node('Root', x, y, 0)
        #for n in range(0,10):
        #self.ds_proxy.move_node('Cylinder' + str(n), x + self.postPosition[n,0], y + self.postPosition[n,1], 0)

    def getExperiment(self):
        # establish a connecttion to the project database
        conn = sqlite3.connect(projectDB)
        # connect a cursor that goes through the project database
        cursorProject = conn.cursor()
        # establish a second connecttion to the experiment database
        conn2 = sqlite3.connect(expDB)
        # connect a cursor that goes through the experiment database
        cursorExperiment = conn2.cursor()

        # pick a random experiment from specified project
        cursorProject.execute("Select exp from projects where project = ? ",
                              (project, ))
        fetched = cursorProject.fetchall()
        print('fetched : ' + str(fetched))

        expType = np.unique(fetched)
        print('the type of experiment i have in stock are ' + str(expType))
        self.expTrial = -1

        # if number of replicates is not met, run experiment
        for k in range(0, len(expType)):
            expTemp = int(expType[k])
            print((
                project,
                expTemp,
            ))
            cursorExperiment.execute(
                "Select * from experiments where project = ? and exp = ? ", (
                    project,
                    expTemp,
                ))
            fetched2 = cursorExperiment.fetchall()
            print('We already have ' + str(len(fetched2)) + ' replicates')
            if len(fetched2) < replication:
                self.expTrial = expTemp
                break

        if self.expTrial > -1:
            cursorProject.execute(
                "Select replicate from projects where project = ? and exp = ? ",
                (
                    project,
                    self.expTrial,
                ))
            fetched = cursorProject.fetchall()
            repType = np.unique(fetched)
            print('plenty of replicates : ' + str(repType))
            repIdx = np.random.randint(len(repType), size=1)
            print(repType)
            self.replicate = int(repType[repIdx])
            print('so lets pick ' + str(self.replicate))
            cursorProject.execute(
                "Select tSwitch from projects where project = ? and exp = ? and replicate = ?",
                (
                    project,
                    self.expTrial,
                    self.replicate,
                ))
            fetched = cursorProject.fetchall()
            print('fetched : ' + str(fetched))
            self.tSwitch = np.unique(fetched)
            cursorProject.execute(
                "Select tExp from projects where project = ? and exp = ? and replicate = ?",
                (
                    project,
                    self.expTrial,
                    self.replicate,
                ))
            self.tExp = np.unique(cursorProject.fetchall())
            self.dateStart = datetime.datetime.now()
        else:
            tExp = 0

        # close all established connections
        conn.close()
        conn2.close()

    def experiment_start(self):
        # self.recorder.start()
        self.observer.start_observer()
        self.loop()

    def loop(self):

        nStimuli = 0
        t0 = time.time()
        sl_t0 = time.time()

        lastMessage = True

        # write output file in specified directory
        path = pathDefine(pathData, self.expId)
        with open(path + '/results.csv', 'w') as output:
            while self.running:
                pos = self.observer.position
                direc = self.observer.azimuth
                t = time.time() - t0
                sl_t = time.time() - sl_t0

                if sl_t < 3:
                    self.observer.velocity = 0.0
                else:
                    self.observer.velocity = 0.20

                if t > self.tExp * 60 * .9 and lastMessage:

                    try:
                        emailer.twitStatus(self.expId,
                                           status=1,
                                           t=self.tExp * .1)
                    except:
                        pass
                    lastMessage = False

                if t > self.tExp * 60:
                    self.running = False
                    self.writeInDb()
                    emailer.twitStatus(self.expId, status=2, t=self.tExp)
                elif t > (nStimuli + 1) * self.tSwitch * 60:
                    nStimuli = nStimuli + 1
                    self.observer.reset_to(**self.start_position)
                    self.updateStimuli(nStimuli)
                    sl_t0 = time.time()
                    self.cntr = 0

                for nPost in range(0, 10):
                    if distance(pos, self.postPosition[nPost, :], True) < 0.5:
                        self.observer.reset_to(**self.start_position)
                        self.cntr += 1
                        sl_t0 = time.time()
                        break
                if distance(pos, self.start_position,
                            False) > self.postDistance:
                    self.observer.reset_to(**self.start_position)
                    self.cntr += 1
                    sl_t0 = time.time()

            #print "XYZ(%3.2f, %3.2f, %3.2f)" % (pos['x'], pos['y'], pos['z']), self.counter
            #print(t)
                output.write('%.8f, %.8f, %.8f, %.4f, %d, %.8f, %s\n' %
                             (pos['x'], pos['y'], pos['z'], direc, self.cntr,
                              t, str(nStimuli)))
                time.sleep(0.005)

    def updateStimuli(self, nStimuli):
        # establish a connecttion to the project database
        conn = sqlite3.connect(projectDB)
        # connect a cursor that goes through the project database
        cursorProject = conn.cursor()
        # pick a new stimulus from available permutations
        for nPost in range(0, 10):
            print((project, self.expTrial, self.replicate, nStimuli))
            cursorProject.execute(
                "Select post" + str(nPost) +
                " from projects where project = ? and exp = ? and replicate = ? and nStimuli =?",
                (project, self.expTrial, self.replicate, nStimuli))
            fetched = cursorProject.fetchall()

            data = fetched[0][0]
            #print(data)
            if data == 'None':
                #Should be the name of the blender file
                self.postPosition[nPost, :] = [1000, 1000]
            else:
                dictData = eval(data)
                print(dictData['position'])
                self.postPosition[nPost, :] = dictData['position']
                self.postDistance = dictData['distance']
            self.ds_proxy.move_node('Cylinder' + str(nPost),
                                    self.postPosition[nPost, 0],
                                    self.postPosition[nPost, 1], 0)
            #print(self.postPosition)

        # close connection
        conn.close()

    def writeInDb(self):
        todayDate = self.dateStart.strftime('%Y-%m-%d')
        self.startTime = self.dateStart.strftime('%H:%M')
        self.endTime = datetime.datetime.now().strftime('%H:%M')
        # establish a connection to the experiment database
        conn2 = sqlite3.connect(expDB)
        # connect a cursor that goes through the experiment database
        cursorExperiment = conn2.cursor()

        expId = 0
        values = [
            project, self.expTrial, self.replicate, todayDate, self.startTime,
            self.endTime, experimenter,
            str(self.expId)
        ]
        cursorExperiment.execute(
            "INSERT INTO experiments VALUES (?,?,?,?,?,?,?,?)", values)

        # commit and close connection
        conn2.commit()
        conn2.close()