Exemple #1
0
    def startLogging(self):
        """
        Start sending synchs and logging.
        """
        # start logging
        LogTrack.startLogging(self)

        # check record state, maybe get new file, start recording
        if self.record_mode == "S":
            # is scalp, so start recording to new file
            self.dat_filename = 'eeg0.dat'

            # make sure we have a file name that doesn't already exist...
            n = 0
            while self.archive.exists(self.dat_filename):
                n += 1
                self.dat_filename = 'eeg%d.dat' % n
            self.dat_file = self.archive.createFile(self.dat_filename)
            self.dat_file.close()
            EEGRecStart(self.dat_file.name)

            # setup scalp callback
            self.last_align = timing.now()
            self.align_interval = 1000
            addPollCallback(self.scalpCallback)

        elif self.record_mode == "P":
            # is pulse, so setup pulse callback
            self.last_align = timing.now()
            self.align_interval = 1000
            self.pulseTrain(10, "EXPSTART_")
            addPollCallback(self.pulseCallback)
Exemple #2
0
def test_all():
    """
    Runs a number of tests to check whether the python scripts of archive-update perform correctly.
    The name of the method needs to start with "test_" so that it gets picked up by py.test.
    """
    import timing

    prepare_archive_data()
    timing.log('prepare_archive_data done', timing.now())

    run_archive_update()
    timing.log('run_archive_update done', timing.now())

    run_archive_reformat()
    timing.log('run_archive_reformat done', timing.now())

    run_archive_split()
    timing.log('run_archive_split done', timing.now())

    run_archive_thinning()
    timing.log('run_archive_thinning done', timing.now())

    run_archive_analysis()
    timing.log('run_archive_analysis done', timing.now())

    run_archive_difference()
    timing.log('run_archive_difference done', timing.now())

    run_extract_extremes()
    timing.log('run_extract_extremes done', timing.now())

    cleanup_archive_data()
    timing.log('cleanup_archive_data done', timing.now())
def test_all():
    """
    Runs a number of tests to check whether the python scripts of archive-update perform correctly.
    The name of the method needs to start with "test_" so that it gets picked up by py.test.
    """
    import timing

    prepare_archive_data()
    timing.log('prepare_archive_data done', timing.now())

    run_archive_update()
    timing.log('run_archive_update done', timing.now())

    run_archive_reformat()
    timing.log('run_archive_reformat done', timing.now())

    run_archive_split()
    timing.log('run_archive_split done', timing.now())

    run_archive_thinning()
    timing.log('run_archive_thinning done', timing.now())

    run_archive_analysis()
    timing.log('run_archive_analysis done', timing.now())

    run_archive_difference()
    timing.log('run_archive_difference done', timing.now())

    run_extract_extremes()
    timing.log('run_extract_extremes done', timing.now())

    cleanup_archive_data()
    timing.log('cleanup_archive_data done', timing.now())
Exemple #4
0
 def callback(self, change):
     """
     Callback used to communicate with parent Roller.  The parent
     roller passes the amount that it is changeing to the callback.
     """
     thistime = timing.now()
     elapsed = thistime - self.lasttime
     if not elapsed:
         self.accum = self.accum + change
         return
     change = change + self.accum
     self.accum = 0.0
     thisvelocity = change / elapsed
     if self.maxAccel:
         if abs(thisvelocity - self.lastvelocity) / elapsed > self.maxAccel:
             if thisvelocity < self.lastvelocity:
                 thisvelocity = self.lastvelocity - self.maxAccel * elapsed
             else:
                 thisvelocity = self.lastvelocity + self.maxAccel * elapsed
     if self.maxVel:
         if thisvelocity > self.maxVel:
             thisvelocity = self.maxVel
         elif thisvelocity < -self.maxVel:
             thisvelocity = -self.maxVel
     self.lasttime = thistime
     self.lastvelocity = thisvelocity
     self.move(thisvelocity * elapsed)
Exemple #5
0
 def __init__(self,
              inc_button,
              dec_button,
              speed=1.0,
              backspeed=None,
              name=None):
     """
     Create ButtonRoller where inc_button being pressed causes
     positive movement at speed roller units per millisecond and
     dec_button being pressed causes negative movement at speed
     roller units per millisecond.
     """
     if name is None:
         name = "ButtonRoller from %s and %s" % (inc_button.name,
                                                 dec_button.name)
     else:
         name = name
     if backspeed is None:
         backspeed = speed
     Roller.__init__(self, name)
     self.inc_button = inc_button
     self.dec_button = dec_button
     self.speed = speed
     self.backspeed = backspeed
     self.lasttime = timing.now()
Exemple #6
0
    def __playCallback__(self, s, ow, ampFactor):
        """
	Timer for appending the remainder of a sound.
	"""
        currentTime = timing.now()

        if self.playing and currentTime >= self.last_play + self.play_interval:
            # see if stop the time
            if self.startInd < self.endInd:

                # determine how much to append
                actualInd = self.startInd + self.bytes_per_append

                # make sure it's not beyond the end
                if actualInd > self.endInd:
                    # just set to the end
                    actualInd = self.endInd

                # append the sound
                appended = self.eplsound.append(
                    s[self.startInd:actualInd],
                    len(s[self.startInd:actualInd]) /
                    self.eplsound.FORMAT_SIZE, 0, ampFactor)

                self.last_play = currentTime

                # update the startInd
                if appended > 0:
                    self.startInd += appended * self.eplsound.FORMAT_SIZE

            else:
                # no more sound
                if (self.eplsound.getSamplesPlayed() *
                        self.eplsound.NUM_CHANNELS) >= self.total_samples:
                    self.playStop()
Exemple #7
0
    def sendFreq(self, duration, freqhz, duration_is_cycles=False):
        """
        Sends a train of pulses at a given frequency on TTL2
        NOTE: MUST CALL configFreq FIRST TO GET ACCURATE RESULTS

        INPUT ARGS:
            duration - Duration of the train (defaults to seconds,
                       can override with 3rd argument)
            freqhz   - Frequency at which to stimulate in Hz
            duration_is_cycles - Whether duration provided is 
                                 in seconds or number of pulses
                                 (default: False)
        """

        if not self.labjack:
            raise (Exception('CAN ONLY USE THIS FUNCTION ON LABJACK'))

        # Time at which to send the pulse
        trainTime = timing.now()
        (timeInterval, returnValue) = timing.timedCall(\
                trainTime,\
                self.labjack.pulseTrain,\
                duration,\
                freqhz,\
                duration_is_cycles)

        if duration_is_cycles:
            self.logMessage(
                'STIM_TRAIN\t%d\t%d' %
                (int(round(float(duration) / freqhz)), freqhz), timeInterval)
        else:
            self.logMessage('STIM_TRAIN\t%d\t%d' % (duration, freqhz),
                            timeInterval)

        return timeInterval
Exemple #8
0
 def process(self):
     if timing.now() < self.next_process:
         return 0
     log.debug("Beginning Pool processing.")
     smtp = smtplib.SMTP(config.get('mail', 'server'))
     for fn in self.pick_files():
         if not fn.startswith('m'):
             # Currently all messages are prefixed with an m.
             continue
         fqfn = os.path.join(config.get('paths', 'pool'), fn)
         f = open(fqfn, 'r')
         msg = email.message_from_file(f)
         f.close()
         log.debug("Pool processing: %s", fn)
         if not 'To' in msg:
             log.warn("%s: Malformed pool message. No recipient "
                      "specified.", fn)
             continue
         msg["Message-ID"] = Utils.msgid()
         msg["Date"] = email.Utils.formatdate()
         msg["From"] = "%s <%s>" % (config.get('general', 'longname'),
                                    config.get('mail', 'address'))
         try:
             smtp.sendmail(msg["From"], msg["To"], msg.as_string())
             log.debug("Email sent to: %s", msg["To"])
         except smtplib.SMTPRecipientsRefused, e:
             log.warn("SMTP failed with: %s", e)
         self.delete(fqfn)
Exemple #9
0
 def date_expired(self, expires):
     if type(expires) == str:
         expires = timing.dateobj(expires)
     try:
         return expires < timing.now()
     except ValueError:
         # If the date is corrupt, assume it's expired
         return True
Exemple #10
0
 def date_prevalid(self, created):
     if type(created) == str:
         created = timing.dateobj(created)
     try:
         return created > timing.now()
     except ValueError:
         # If the date is corrupt, assume it's prevalid
         return True
Exemple #11
0
 def setPosition(self, p, timestamp=None):
     """
     Set the position of this axis between 1.0 and -1.0.
     """
     if p != self.position:
         if timestamp == None:
             timestamp = (timing.now(), long(0))
         self.position = p
         for c, args in self.callbacks.items():
             c(p, timestamp, *args)
Exemple #12
0
 def setPressed(self, p, timestamp=None):
     """
     Set the pressed state of this button (True or False).
     """
     if p != self.pressed:
         if timestamp == None:
             timestamp = (timing.now(), long(0))
         self.presstime = timestamp
         self.pressed = p
         for c, args in self.callbacks.items():
             c(p, timestamp, *args)
Exemple #13
0
 def prune(self):
     if timing.now() > self.nextday:
         log.info("Performing daily prune of partial chunk log.")
         for messageid in self.pktlog.keys():
             if self.pktlog[messageid]['age'] > self.pktexp:
                 log.info("Deleting chunks due to packet expiration. "
                          "A message will be lost but we can't wait "
                          "forever.")
                 self.delete(messageid)
             else:
                 self.pktlog[messageid]['age'] += 1
         self.nextday = timing.future(days=1)
Exemple #14
0
 def update(self):
     """
     Update the Roller's movement in a time-consistent manner.
     """
     Roller.update(self)
     thistime = timing.now()
     elapsed = thistime - self.lasttime
     if elapsed:
         if (self.inc_button.isPressed()):
             self.move(elapsed * self.speed)
         if (self.dec_button.isPressed()):
             self.move(elapsed * -self.backspeed)
         self.lasttime = thistime
Exemple #15
0
    def flush(self):
        """
        Flush the recording buffer.
        """
        currentTime = timing.now()
        newstuff = self.getBuffData()

        # Update the last time
        self.last_rec = currentTime

        if len(newstuff) > 0:
            # append the data to the clip
            self.recClip.append(newstuff, self.eplsound.getRecChans())
Exemple #16
0
    def scalpCallback(self):
        """
        Callback to make logs using the real-time scalp interface.
        """
        # is it time to do another alignment?
        if timing.now() >= self.last_align + self.align_interval:
            # query for offset
            (timeInterval, offset) = timing.timedCall(None, EEGGetOffset)
            # get info for log message
            self.logMessage("%s\t%s" % (self.dat_filename, offset),
                            timeInterval)

            # update last_align
            self.last_align = timeInterval[0]
Exemple #17
0
 def update(self):
     """
     Update the change for this roller in a time-consistent manner.
     """
     Roller.update(self)
     thistime = timing.now()
     elapsed = thistime - self.lasttime
     if elapsed:
         norm = self.axis.getNormalized()
         if norm > 0:
             self.move(elapsed * self.speedfactor * norm)
         else:
             self.move(elapsed * self.backwardspeedfactor * norm)
         self.lasttime = thistime
Exemple #18
0
    def __recCallback__(self):
        """
        Internal callback function, only for use by pyEpl functions.
        Thread function for recording, called by startRecording.
        """
        currentTime = timing.now()
        if self.recording and currentTime >= self.last_rec + self.rec_interval:
            newstuff = self.getBuffData()

            # Update the last time
            self.last_rec = currentTime

            if len(newstuff) > 0:
                # append the data to the clip
                self.recClip.append(newstuff, self.eplsound.getRecChans())
Exemple #19
0
 def clientLowNow(self, clk=None):
     """
     Do a non-blocking low on channel 2
     """
     if self.labjack == None:
         raise EPLPulseEEGException(
             "Client pulse methods are only callable with multiple outputs."
         )
     if clk is None:
         # no clock, so use time
         clk = timing.now()
     (timeInterval,
      returnValue) = timing.timedCall(clk, self.labjack.setChannel2Low)
     pulsePrefix = "CHANNEL_2_"
     self.logMessage("%s" % pulsePrefix + "DN", timeInterval)
Exemple #20
0
    def pulseCallback(self):
        """
        Callback to manage sending pulses.
        """
        minInterPulsetime = 750
        maxInterPulseTime = 1250
        pulseLen = 10  #in milliseconds
        if timing.now() >= self.last_align + self.align_interval:
            timeInterval = self.timedPulse(pulseLen)

            # randomize the alignment interval
            self.align_interval = random.uniform(minInterPulsetime,
                                                 maxInterPulseTime)

            # update last_align
            self.last_align = timeInterval[0]
Exemple #21
0
 def __init__(self, axis, maxVel=None, maxAccel=None, name=None):
     """
     """
     if name == None:
         name = "ThrottledAxis from %s" % axis.name
     else:
         name = name
     Axis.__init__(self, name, axis.posmin, axis.posmax)
     self.axis = axis
     self.lasttime = timing.now()
     self.lastpos = axis.getPosition()
     self.lastspeed = 0.0
     self.maxVel = maxVel
     self.maxAccel = maxAccel
     self.cb = MethodCallback(self.callback)
     axis.addCallback(self.cb)
     self.parents = (axis, )
    def logMessage(self, message, timestamp=None):
        """
        Add message to log.

        INPUT ARGS:
        message- String to add to log.
        timestamp- Timestamp for this log entry.  If this is None,
        then the current time used as the timestamp.
        """
        if self.logall:
            if isinstance(timestamp, exputils.PresentationClock):
                timestamp = (timestamp.get(), 0L)
            elif timestamp is None:
                timestamp = (timing.now(), 0L)
            elif not isinstance(timestamp, tuple):
                timestamp = (timestamp, 0L)
            self.dataFile.seek(0, 2)  # seek to end of file
            self.dataFile.write("%s\t%s\t%s\n" %
                                (timestamp[0], timestamp[1], message))
Exemple #23
0
 def prune(self):
     """Check if a day has passed since the last prune operation.  If it
        has, increment the day counter on each stored packetid.  If the
        count exceeeds the expiry period then delete the id from the log.
     """
     if timing.now() > self.nextday:
         log.info("Performing daily prune of packetid log.")
         before = len(self.idlog)
         deleted = 0
         for k in self.idlog.keys():
             if self.idlog[k] > self.idexp:
                 del self.idlog[k]
                 deleted += 1
             else:
                 self.idlog[k] += 1
         self.idlog.sync()
         self.nextday = timing.future(days=1)
         after = len(self.idlog)
         log.info("Packet ID prune complete. Before=%s, Deleted=%s, "
                  "After=%s.", before, deleted, after)
Exemple #24
0
 def __init__(self,
              axis,
              speedfactor=1.0,
              backwardspeedfactor=None,
              name=None):
     """
     Create AxisRoller from axis with specified speedfactor
     (defaults to 1.0).  Speedfactor units are roller units per
     millisecond per axis unit.
     """
     if name == None:
         name = "AxisRoller from %s" % axis.name
     else:
         name = name
     if backwardspeedfactor is None:
         backwardspeedfactor = speedfactor
     Roller.__init__(self, name)
     self.axis = axis
     self.speedfactor = speedfactor
     self.backwardspeedfactor = backwardspeedfactor
     self.lasttime = timing.now()
Exemple #25
0
    def __playLoopCallback__(self, ow, ampFactor):
        """
	Timer for appending the remainder of a sound.
	"""
        currentTime = timing.now()

        if self.playing and currentTime >= self.last_play + self.play_interval:
            # see if stop the time
            if self.startInd < self.endInd:
                # do the sound
                s = self.currentClip.snd

                # determine how much to append
                toplay = self.eplsound.getBufferUsed()
                toappend = self.bytes_per_append - toplay
                if toappend <= 0:
                    return

                actualInd = self.startInd + toappend  # self.bytes_per_append

                # make sure it's not beyond the end
                if actualInd > self.endInd:
                    # just set to the end
                    actualInd = self.endInd

        # append the sound
                appended = self.eplsound.append(
                    s[self.startInd:actualInd],
                    len(s[self.startInd:actualInd]) /
                    self.eplsound.FORMAT_SIZE, 0, ampFactor)

                self.last_play = currentTime

                # update the startInd
                if appended > 0:
                    self.startInd += appended * self.eplsound.FORMAT_SIZE

            else:
                # no more sound, so start again right away
                self.startInd = 0
Exemple #26
0
 def __init__(self, roller, maxAccel=None, maxVel=None, name=None):
     """
     Create a ThrottledRoller with maxAccel roller units per
     millisecond per millisecond maximum acceleration and maxVel
     roller units per millisecond maximum velocity.  None for
     either of those values means that the constraint will not be
     applied.
     """
     if name == None:
         name = "ThrottledRoller from %s" % roller.name
     else:
         name = name
     Roller.__init__(self, name)
     self.roller = roller
     self.parents = [roller]
     self.maxAccel = maxAccel
     self.maxVel = maxVel
     self.accum = 0.0
     self.lastvelocity = 0.0
     self.lasttime = timing.now()
     self.cb = MethodCallback(self.callback)
     roller.addCallback(self.cb)
Exemple #27
0
    def record(self, duration, basename=None, t=None, **sfargs):
        """
        Perform a blocked recording for a specified duration (in milliseconds).

        INPUT ARGS:
          duration- length of time (in ms.) to record for.
          basename- filename to save recorded data to.
          t- optional PresentationClock for timing.
	  sfargs- keyword arguments passed to FileAudioClip constructor

        OUTPUT ARGS:
          recClip- The AudioClip object that contains the recorded data.
          timestamp- time and latency when sound recording began.
        """
        if not t:
            t = timing.now()
        elif isinstance(t, exputils.PresentationClock):
            clk = t
            t = clk.get()
            clk.delay(duration)
        (r, starttime) = self.startRecording(basename, t=t, **sfargs)
        (r, stoptime) = self.stopRecording(t=t + duration)
        return (r, starttime)
Exemple #28
0
    def configFreq(self, frequency):
        """
        Configures stimulation so that stimulation trains can happen
        more quickly
         
        NOTE: ONLY FUNCTIONS ON TTL2

        INPUT ARGS:
            frequency - the frequency (Hz) at which to configure

        """

        # Log the frequency
        self.logMessage("CONFIG\t%d" % frequency)

        # Set the time at which to configure
        configTime = timing.now()
        if not self.labjack:
            raise (Exception('CAN ONLY CONFIGURE FREQUENCY ON LABJACK'))
        (timeInterval, returnValue)=timing.timedCall(configTime,\
                self.labjack.configFreq,\
                frequency)
        return timeInterval
Exemple #29
0
    def pulseTrain(self, numPulses, trainName=""):
        """
        Send a train of pulses.

        INPUT ARGS:
          numPulses- Number of pulses in train.
          trainName- Name to use in the log.
        """
        #trainLen denotes the number of pulses in this train
        pulseLen = 10  #in milliseconds
        interPulseInterval = 5

        self.logMessage(trainName + "TRAIN")

        # set the desired pulsetime
        pulseTime = timing.now()
        for i in range(numPulses):
            # send a pulse
            (timeInterval,
             returnValue) = timing.timedCall(pulseTime, self.timedPulse,
                                             pulseLen, 'TRAIN_')
            # pause for the next pulse
            pulseTime += interPulseInterval
Exemple #30
0
    def timedStim(self, duration, freq, doRelay=False):
        '''
        Start a sync box controlled train of pulses to trigger a stimulator.
        
        INPUT ARGS:
          duration - duration of stimulation (s)
          freq - frequency to send pulse (Hz)
        '''

        # use the current time
        clk = timing.now()

        # only labjack boxes support stimulation
        if self.labjack:
            (timeInterval,
             returnValue) = timing.timedCall(clk, self.labjack.StartStim,
                                             duration, freq, doRelay)

            # log start of stimulation
            self.logMessage("STIM_ON", timeInterval)
            return timeInterval
        else:
            raise EPLPulseEEGException(
                "timedStim only functions with labjack autostim boards.")
Exemple #31
0
 def trigger(self):
     return timing.now() >= self.trigger_time
Exemple #32
0
    parser = argparse.ArgumentParser()
    parser.add_argument('-f', '--functions', type=parse_range, default=range(1, 56),
                        help='function numbers to be included in the processing of archives')
    parser.add_argument('-i', '--instances', type=parse_range, default=range(1, 11),
                        help='instance numbers to be included in the processing of archives')
    parser.add_argument('-d', '--dimensions', type=parse_range, default=[2, 3, 5],
                        help='dimensions to be included in the processing of archives')
    parser.add_argument('-l', '--lower_bound', type=float, default=-5.0,
                        help='lower bound of the decision space')
    parser.add_argument('-u', '--upper_bound', type=float, default=5.0,
                        help='upper bound of the decision space')
    parser.add_argument('output', help='path to the output folder')
    parser.add_argument('summary', help='file name for the summary')
    parser.add_argument('input',  help='path to the input folder')
    args = parser.parse_args()

    print('Program called with arguments: \ninput folder = {}\noutput folder = {}'.format(args.input, args.output))
    print('summary file = {}'.format(args.summary))
    print('functions = {} \ninstances = {}\ndimensions = {}'.format(args.functions, args.instances, args.dimensions))
    print('lower bound = {} \nupper bound = {}\n'.format(args.lower_bound, args.upper_bound))

    # Analyze the archives
    archive_analysis(args.input, args.output, args.lower_bound, args.upper_bound, args.functions, args.instances,
                     args.dimensions)

    timing.log('Finished reading data', timing.now())

    summary_analysis(args.output, args.summary, args.lower_bound, args.upper_bound, args.functions, args.instances,
                     args.dimensions)
Exemple #33
0
    parser.add_argument('input',
                        default=[],
                        nargs='+',
                        help='path(s) to the input folder(s)')
    args = parser.parse_args()

    print(
        'Program called with arguments: \ninput folders = {}\noutput folder = {}'
        .format(args.input, args.output))
    print('functions = {} \ninstances = {}\ndimensions = {}\n'.format(
        args.functions, args.instances, args.dimensions))

    # Merge the archives
    new_hypervolumes = merge_archives(args.input, args.output, args.functions,
                                      args.instances, args.dimensions,
                                      args.crop_variables)

    timing.log('Finished merging', timing.now())

    # Use files with best hypervolume values from the src folder and update them with the new best values
    if not args.merge_only:
        base_path = os.path.dirname(__file__)
        file_names = ['suite_biobj_best_values_hyp.c']
        file_names = [
            os.path.abspath(
                os.path.join(base_path, '..', '..', 'code-experiments/src',
                             file_name)) for file_name in file_names
        ]
        update_best_hypervolume(file_names, new_hypervolumes,
                                os.path.join(args.output, '..', args.hyp_file))
def mathDistract(clk=None,
                 mathlog=None,
                 problemTimeLimit=None,
                 numVars=2,
                 maxNum=9,
                 minNum=1,
                 maxProbs=50,
                 plusAndMinus=False,
                 minDuration=20000,
                 textSize=None,
                 correctBeepDur=500,
                 correctBeepFreq=400,
                 correctBeepRF=50,
                 correctSndFile=None,
                 incorrectBeepDur=500,
                 incorrectBeepFreq=200,
                 incorrectBeepRF=50,
                 incorrectSndFile=None,
                 tfKeys=None,
                 ansMod=[0, 1, -1, 10, -10],
                 ansProb=[.5, .125, .125, .125, .125],
                 visualFeedback=False):
    """
    Math distractor for specified period of time.  Logs to a math_distract.log
    if no log is passed in.

    INPUT ARGS:
      clk - Optional PresentationClock for timing.
      mathlog - Optional Logtrack for logging.
      problemTimeLimit - set this param for non-self-paced distractor;
                         buzzer sounds when time's up; you get at least
                         minDuration/problemTimeLimit problems.
      numVars - Number of variables in the problem.
      maxNum - Max possible number for each variable.
      minNum - Min possible number for each varialbe.
      maxProbs - Max number of problems.
      plusAndMinus - True will have both plus and minus.
      minDuration - Minimum duration of distractor.
      textSize - Vertical height of the text.
      correctBeepDur - Duration of correct beep.
      correctBeepFreq - Frequency of correct beep.
      correctBeepRF - Rise/Fall of correct beep.
      correctSndFile - Optional Audio clip to use for correct notification.
      incorrectBeepDur - Duration of incorrect beep.
      incorrectBeepFreq - Frequency of incorrect beep.
      incorrectBeepRF - Rise/Fall of incorrect beep
      incorrectSndFile - Optional AudioClip used for incorrect notification.
      tfKeys - Tuple of keys for true/false problems. e.g., tfKeys = ('T','F')
      ansMod - For True/False problems, the possible values to add to correct answer.
      ansProb - The probability of each modifer on ansMod (must add to 1).
      visualFeedback - Whether to provide visual feedback to indicate correctness.
    """

    # start the timing
    start_time = timing.now()

    # get the tracks
    v = display.VideoTrack.lastInstance()
    a = sound.AudioTrack.lastInstance()
    k = keyboard.KeyTrack.lastInstance()

    # see if need logtrack
    if mathlog is None:
        mathlog = LogTrack('math_distract')

    # log the start
    mathlog.logMessage('START')

    # start timing
    if clk is None:
        clk = exputils.PresentationClock()

    # set the stop time
    if not minDuration is None:
        stop_time = start_time + minDuration
    else:
        stop_time = None

    # generate the beeps
    correctBeep = sound.Beep(correctBeepFreq, correctBeepDur, correctBeepRF)
    incorrectBeep = sound.Beep(incorrectBeepFreq, incorrectBeepDur,
                               incorrectBeepRF)

    # clear the screen (now left up to caller of function)
    #v.clear("black")

    # generate a bunch of math problems
    vars = numpy.random.randint(minNum, maxNum + 1, [maxProbs, numVars])
    if plusAndMinus:
        pm = numpy.sign(numpy.random.uniform(-1, 1, [maxProbs, numVars - 1]))
    else:
        pm = numpy.ones([maxProbs, numVars - 1])

    # see if T/F or numeric answers
    if isinstance(tfKeys, tuple):
        # do true/false problems
        tfProblems = True

        # check the ansMod and ansProb
        if len(ansMod) != len(ansProb):
            # raise error
            pass
        if sum(ansProb) != 1.0:
            # raise error
            pass
        ansProb = numpy.cumsum(ansProb)
    else:
        # not t/f problems
        tfProblems = False

    # set up the answer button
    if tfProblems:
        # set up t/f keys
        ans_but = k.keyChooser(*tfKeys)
    else:
        # set up numeric entry
        ans_but = k.keyChooser('0', '1', '2', '3', '4', '5', '6', '7', '8',
                               '9', '-', 'RETURN', '[0]', '[1]', '[2]', '[3]',
                               '[4]', '[5]', '[6]', '[7]', '[8]', '[9]', '[-]',
                               'ENTER', 'BACKSPACE')

    # do equations till the time is up
    curProb = 0
    while not (not stop_time is None
               and timing.now() >= stop_time) and curProb < maxProbs:
        # generate the string and result

        # loop over each variable to generate the problem
        probtxt = ''
        for i, x in enumerate(vars[curProb, :]):
            if i > 0:
                # add the sign
                if pm[curProb, i - 1] > 0:
                    probtxt += ' + '
                else:
                    probtxt += ' - '

            # add the number
            probtxt += str(x)

        # calc the correct answer
        cor_ans = eval(probtxt)

        # add the equal sign
        probtxt += ' = '

        # do tf or numeric problem
        if tfProblems:
            # determine the displayed answer
            # see which answermod
            ansInd = numpy.nonzero(ansProb >= numpy.random.uniform(0, 1))
            if isinstance(ansInd, tuple):
                ansInd = ansInd[0]
            ansInd = min(ansInd)
            disp_ans = cor_ans + ansMod[ansInd]

            # see if is True or False
            if disp_ans == cor_ans:
                # correct response is true
                corRsp = tfKeys[0]
            else:
                # correct response is false
                corRsp = tfKeys[1]

            # set response str
            rstr = str(disp_ans)
        else:
            rstr = ''

        # display it on the screen
        pt = v.showProportional(display.Text(probtxt, size=textSize), .4, .5)
        rt = v.showRelative(display.Text(rstr, size=textSize), display.RIGHT,
                            pt)
        probstart = v.updateScreen(clk)

        # wait for input
        answer = .12345  # not an int
        hasMinus = False
        if problemTimeLimit:
            probStart = timing.now()
            probEnd = probStart + problemTimeLimit
            curProbTimeLimit = probEnd - probStart
        else:
            curProbTimeLimit = None

        # wait for keypress
        kret, timestamp = ans_but.waitWithTime(maxDuration=curProbTimeLimit,
                                               clock=clk)

        # process as T/F or as numeric answer
        if tfProblems:
            # check the answer
            if not kret is None and kret.name == corRsp:
                isCorrect = 1
            else:
                isCorrect = 0
        else:
            # is part of numeric answer
            while kret and \
                      ((kret.name != "RETURN" and kret.name != "ENTER") or \
                       (hasMinus is True and len(rstr)<=1) or (len(rstr)==0)):
                # process the response
                if kret.name == 'BACKSPACE':
                    # remove last char
                    if len(rstr) > 0:
                        rstr = rstr[:-1]
                        if len(rstr) == 0:
                            hasMinus = False
                elif kret.name == '-' or kret.name == '[-]':
                    if len(rstr) == 0 and plusAndMinus:
                        # append it
                        rstr = '-'
                        hasMinus = True
                elif kret.name == 'RETURN' or kret.name == 'ENTER':
                    # ignore cause have minus without number
                    pass
                elif len(rstr) == 0 and (kret.name == '0'
                                         or kret.name == '[0]'):
                    # Can't start a number with 0, so pass
                    pass
                else:
                    # if its a number, just append
                    numstr = kret.name.strip('[]')
                    rstr = rstr + numstr

                # update the text
                rt = v.replace(rt, display.Text(rstr, size=textSize))
                v.updateScreen(clk)

                # wait for another response
                if problemTimeLimit:
                    curProbTimeLimit = probEnd - timing.now()
                else:
                    curProbTimeLimit = None
                kret, timestamp = ans_but.waitWithTime(
                    maxDuration=curProbTimeLimit, clock=clk)

            # check the answer
            if len(rstr) == 0 or eval(rstr) != cor_ans:
                isCorrect = 0
            else:
                isCorrect = 1

        # give feedback
        if isCorrect == 1:
            # play the beep
            pTime = a.play(correctBeep, t=clk, doDelay=False)
            #clk.tare(pTime[0])
            #correctBeep.present(clk)

            # see if set color of text
            if visualFeedback:
                pt = v.replace(
                    pt, display.Text(probtxt, size=textSize, color='green'))
                rt = v.replace(
                    rt, display.Text(rstr, size=textSize, color='green'))
                v.updateScreen(clk)
                clk.delay(correctBeepDur)
        else:
            # play the beep
            pTime = a.play(incorrectBeep, t=clk, doDelay=False)
            #clk.tare(pTime[0])
            #incorrectBeep.present(clk)

            # see if set color of text
            if visualFeedback:
                pt = v.replace(
                    pt, display.Text(probtxt, size=textSize, color='red'))
                rt = v.replace(rt,
                               display.Text(rstr, size=textSize, color='red'))
                v.updateScreen(clk)
                clk.delay(incorrectBeepDur)

        # calc the RT as (RT, maxlatency)
        prob_rt = (timestamp[0] - probstart[0], timestamp[1] + probstart[1])

        # log it
        # probstart, PROB, prob_txt, ans_txt, Correct(1/0), RT
        mathlog.logMessage(
            'PROB\t%r\t%r\t%d\t%ld\t%d' %
            (probtxt, rstr, isCorrect, prob_rt[0], prob_rt[1]), probstart)

        # clear the problem
        v.unshow(pt, rt)
        v.updateScreen(clk)

        # increment the curprob
        curProb += 1

    # log the end
    mathlog.logMessage('STOP', timestamp)
Exemple #35
0
    def timedPulse(self,
                   pulseTime,
                   pulsePrefix='',
                   signal='',
                   clk=None,
                   output_channel=0):
        """
        Send a pulse and log it.

        INPUT ARGS:
          pulseTime- Duration of pulse.
          pulsePrefix- Name to log the pulse.
        """
        # see if using clock
        usingClock = True
        if clk is None:
            # no clock, so use time
            clk = timing.now()
            usingClock = False

        if self.awCard:
            if len(signal) > 0:
                (timeInterval,
                 returnValue) = timing.timedCall(clk, self.awCard.write,
                                                 signal)
            else:
                (timeInterval,
                 returnValue) = timing.timedCall(clk, self.awCard.allOn)
        elif self.labjack:
            (timeInterval,
             returnValue) = timing.timedCall(clk, self.labjack.setFIOState,
                                             output_channel,
                                             0 if output_channel == 4 else 1)
            pulsePrefix = "CHANNEL_" + str(output_channel) + "_"
        else:
            if len(signal) > 0:
                (timeInterval,
                 returnValue) = timing.timedCall(clk, self.parallel.setSignal,
                                                 True, signal)
            else:
                (timeInterval,
                 returnValue) = timing.timedCall(clk, self.parallel.setState,
                                                 True)
        self.logMessage("%s" % pulsePrefix + "UP", timeInterval)

        # wait for the pulse time
        if usingClock:
            clk.delay(pulseTime)
        else:
            clk = clk + pulseTime

        if self.awCard:
            (timeInterval,
             returnValue) = timing.timedCall(clk, self.awCard.allOff)
        elif self.labjack:
            (timeInterval,
             returnValue) = timing.timedCall(clk, self.labjack.setFIOState,
                                             output_channel,
                                             1 if output_channel == 4 else 0)
        else:
            (timeInterval,
             returnValue) = timing.timedCall(clk, self.parallel.setState,
                                             False)

        self.logMessage("%s" % pulsePrefix + "DN", timeInterval)

        # I'm not sure when if you want this to be the start or end of the pulse
        return timeInterval
Exemple #36
0
    parser = argparse.ArgumentParser()
    parser.add_argument('-f', '--functions', type=parse_range, default=range(1, 56),
                        help='function numbers to be included in the processing of archives')
    parser.add_argument('-i', '--instances', type=parse_range, default=range(1, 11),
                        help='instance numbers to be included in the processing of archives')
    parser.add_argument('-d', '--dimensions', type=parse_range, default=[2, 3, 5],
                        help='dimensions to be included in the processing of archives')
    parser.add_argument('-l', '--lower_bound', type=float, default=-5.0,
                        help='lower bound of the decision space')
    parser.add_argument('-u', '--upper_bound', type=float, default=5.0,
                        help='upper bound of the decision space')
    parser.add_argument('output', help='path to the output folder')
    parser.add_argument('summary', help='file name for the summary')
    parser.add_argument('input', default=[], nargs='+', help='path(s) to the input folder(s)')
    args = parser.parse_args()

    print('Program called with arguments: \ninput folders = {}\noutput folder = {}'.format(args.input, args.output))
    print('summary file = {}'.format(args.summary))
    print('functions = {} \ninstances = {}\ndimensions = {}'.format(args.functions, args.instances, args.dimensions))
    print('lower bound = {} \nupper bound = {}\n'.format(args.lower_bound, args.upper_bound))

    # Analyze the archives
    archive_analysis(args.input, args.output, args.lower_bound, args.upper_bound, args.functions, args.instances,
                     args.dimensions)

    timing.log('Finished reading data', timing.now())

    summary_analysis(args.output, args.summary, args.lower_bound, args.upper_bound, args.functions, args.instances,
                     args.dimensions)
    parser.add_argument('-i', '--instances', type=parse_range, default=range(1, 16),
                        help='instance numbers to be included in the processing of archives')
    parser.add_argument('-d', '--dimensions', type=parse_range, default=[2, 3, 5, 10, 20, 40],
                        help='dimensions to be included in the processing of archives')
    parser.add_argument('--merge-only', action='store_true',
                        help='perform only merging of archives, do not update hypervolume values')
    parser.add_argument('--crop-variables', action='store_true',
                        help='don\'t include information on the variables in the output archives')
    parser.add_argument('--hyp-file', default='new_best_values_hyp.c',
                        help='name of the file to store new hypervolume values')
    parser.add_argument('output', help='path to the output folder')
    parser.add_argument('input', default=[], nargs='+', help='path(s) to the input folder(s)')
    args = parser.parse_args()

    print('Program called with arguments: \ninput folders = {}\noutput folder = {}'.format(args.input, args.output))
    print('functions = {} \ninstances = {}\ndimensions = {}\n'.format(args.functions, args.instances, args.dimensions))

    # Merge the archives
    new_hypervolumes = merge_archives(args.input, args.output, args.functions, args.instances, args.dimensions,
                                      args.crop_variables)

    timing.log('Finished merging', timing.now())

    # Use files with best hypervolume values from the src folder and update them with the new best values
    if not args.merge_only:
        base_path = os.path.dirname(__file__)
        file_names = ['suite_biobj_best_values_hyp.c']
        file_names = [os.path.abspath(os.path.join(base_path, '..', '..', 'code-experiments/src', file_name))
                      for file_name in file_names]
        update_best_hypervolume(file_names, new_hypervolumes, os.path.join(args.output, '..', args.hyp_file))
Exemple #38
0
 def update(self):
     """
     """
     self.callback(self.axis.getPosition(), (timing.now(), long(0)))