コード例 #1
0
ファイル: screens.py プロジェクト: michaelschulte/ThePyeTribe
 def run(self, debug_mode=False):
     self.t0 = getAbsTime()
     while not self.move_on_flag.is_set():
         if self.continue_button.clickable:
             if self.mouse.isPressedIn(self.continue_button._frame, [0]):
                 self.move_on_flag.set()
         elif self.wait_time > 0:
             if getAbsTime() - self.t0 > self.wait_time:
                 self.continue_button.clickable = True
         
         self.draw(debug_mode)
         self.window.flip()
         wait(0.016666, 0.016666)
     self.cleanup()
コード例 #2
0
    def _record(self, sec, filename='', block=True):
        while self.recorder.running:
            pass
        self.duration = float(sec)
        self.onset = core.getTime()  # for duration estimation, high precision
        self.fileOnset = core.getAbsTime()  # for log and filename, 1 sec precision
        logging.data('%s: Record: onset %d, capture %.3fs' %
                     (self.loggingId, self.fileOnset, self.duration) )
        if not file:
            onsettime = '-%d' % self.fileOnset
            self.savedFile = onsettime.join(os.path.splitext(self.wavOutFilename))
        else:
            self.savedFile = os.path.abspath(filename).strip('.wav') + '.wav'

        t0 = core.getTime()
        self.recorder.run(self.savedFile, self.duration, **self.options)

        self.rate = sound.pyoSndServer.getSamplingRate()
        if block:
            core.wait(self.duration, 0)
            logging.exp('%s: Record: stop. %.3f, capture %.3fs (est)' %
                     (self.loggingId, core.getTime(), core.getTime() - t0) )
            while self.recorder.running:
                core.wait(.001, 0)
        else:
            logging.exp('%s: Record: return immediately, no blocking' %
                     (self.loggingId) )

        return self.savedFile
コード例 #3
0
ファイル: microphone.py プロジェクト: rpbaxter/psychopy
    def _record(self, sec, filename="", block=True, log=True):
        while self.recorder.running:
            pass
        self.duration = float(sec)
        self.onset = core.getTime()  # for duration estimation, high precision
        self.fileOnset = core.getAbsTime()  # for log and filename, 1 sec precision
        ms = "%.3f" % (core.getTime() - int(core.getTime()))
        if log and self.autoLog:
            logging.data("%s: Record: onset %d, capture %.3fs" % (self.loggingId, self.fileOnset, self.duration))
        if not filename:
            onsettime = "-%d" % self.fileOnset + ms[1:]
            self.savedFile = onsettime.join(os.path.splitext(self.wavOutFilename))
        else:
            self.savedFile = os.path.abspath(filename).strip(".wav") + ".wav"

        t0 = core.getTime()
        self.recorder.run(self.savedFile, self.duration, **self.options)

        self.rate = sound.pyoSndServer.getSamplingRate()
        if block:
            core.wait(self.duration, 0)
            if log and self.autoLog:
                logging.exp(
                    "%s: Record: stop. %.3f, capture %.3fs (est)"
                    % (self.loggingId, core.getTime(), core.getTime() - t0)
                )
            while self.recorder.running:
                core.wait(0.001, 0)
        else:
            if log and self.autoLog:
                logging.exp("%s: Record: return immediately, no blocking" % (self.loggingId))

        return self.savedFile
コード例 #4
0
ファイル: microphone.py プロジェクト: thomastweets/psychopy
    def _record(self, sec, filename='', block=True, log=True):
        while self.recorder.running:
            pass
        self.duration = float(sec)
        self.onset = core.getTime()  # for duration estimation, high precision
        self.fileOnset = core.getAbsTime()  # for log and filename, 1 sec precision
        ms = "%.3f" % (core.getTime() - int(core.getTime()))
        if log and self.autoLog:
            logging.data('%s: Record: onset %d, capture %.3fs' %
                     (self.loggingId, self.fileOnset, self.duration))
        if not filename:
            onsettime = '-%d' % self.fileOnset + ms[1:]
            self.savedFile = onsettime.join(os.path.splitext(self.wavOutFilename))
        else:
            self.savedFile = os.path.abspath(filename)
            if not self.savedFile.endswith('.wav'):
                self.savedFile += '.wav'

        t0 = core.getTime()
        self.recorder.run(self.savedFile, self.duration, **self.options)

        self.rate = sound.pyoSndServer.getSamplingRate()
        if block:
            core.wait(self.duration, 0)
            if log and self.autoLog:
                logging.exp('%s: Record: stop. %.3f, capture %.3fs (est)' %
                     (self.loggingId, core.getTime(), core.getTime() - t0))
            while self.recorder.running:
                core.wait(.001, 0)
        else:
            if log and self.autoLog:
                logging.exp('%s: Record: return immediately, no blocking' %
                     (self.loggingId))

        return self.savedFile
コード例 #5
0
ファイル: info.py プロジェクト: alexholcombe/psychopy
    def _setExperimentInfo(self, author, version, verbose):
        # try to auto-detect __author__ and __version__ in sys.argv[0] (= the users's script)
        if not author or not version:
            if os.path.isfile(sys.argv[0]):
                f = open(sys.argv[0], 'r')
                lines = f.read()
                f.close()
            if not author and '__author__' in lines:
                linespl = lines.splitlines()
                while linespl[0].find('__author__') == -1:
                    linespl.pop(0)
                auth = linespl[0]
                if len(auth) and '=' in auth:
                    try:
                        author = str(eval(auth[auth.find('=')+1 :]))
                    except:
                        pass
            if not version and '__version__' in lines:
                linespl = lines.splitlines()
                while linespl[0].find('__version__') == -1:
                    linespl.pop(0)
                ver = linespl[0]
                if len(ver) and ver.find('=') > 0:
                    try:
                        version = str(eval(ver[ver.find('=')+1 :]))
                    except:
                        pass

        if author or verbose:
            self['experimentAuthor'] = author
        if version or verbose:
            self['experimentAuthVersion'] = version

        # script identity & integrity information:
        self['experimentScript'] = os.path.basename(sys.argv[0])  # file name
        scriptDir = os.path.dirname(os.path.abspath(sys.argv[0]))
        self['experimentScript.directory'] = scriptDir
        # sha1 digest, text-format compatibility
        self['experimentScript.digestSHA1'] = _getSha1hexDigest(os.path.abspath(sys.argv[0]), isfile=True)
        # subversion revision?
        try:
            svnrev, last, url = _getSvnVersion(os.path.abspath(sys.argv[0]))  # svn revision
            if svnrev: # or verbose:
                self['experimentScript.svnRevision'] = svnrev
                self['experimentScript.svnRevLast'] = last
                self['experimentScript.svnRevURL'] = url
        except:
            pass
        # mercurical revision?
        try:
            hgChangeSet = _getHgVersion(os.path.abspath(sys.argv[0]))
            if hgChangeSet: # or verbose:
                self['experimentScript.hgChangeSet'] = hgChangeSet
        except:
            pass

        # when was this run?
        self['experimentRunTime.epoch'] = core.getAbsTime()
        self['experimentRunTime'] = data.getDateStr(format="%Y_%m_%d %H:%M (Year_Month_Day Hour:Min)")
コード例 #6
0
ファイル: screens.py プロジェクト: michaelschulte/ThePyeTribe
 def draw(self, debug_mode=False):
     if not self.continue_button.clickable:
         if getAbsTime() - self.t0 > self.wait_time:
             self.continue_button.clickable = True
     self.continue_button.draw()
     self.text_stim.draw()
     for stim in self.extra_draw_stims:
         stim.draw()     
コード例 #7
0
    def _setExperimentInfo(self, author, version, verbose):
        # try to auto-detect __author__ and __version__ in sys.argv[0] (= the users's script)
        if not author or not version:
            f = open(sys.argv[0], 'r')
            lines = f.read()
            f.close()
        if not author and '__author__' in lines:
            linespl = lines.splitlines()
            while linespl[0].find('__author__') == -1:
                linespl.pop(0)
            auth = linespl[0]
            if len(auth) and '=' in auth:
                try:
                    author = str(eval(auth[auth.find('=')+1 :]))
                except:
                    pass
        if not version and '__version__' in lines:
            linespl = lines.splitlines()
            while linespl[0].find('__version__') == -1:
                linespl.pop(0)
            ver = linespl[0]
            if len(ver) and ver.find('=') > 0:
                try:
                    version = str(eval(ver[ver.find('=')+1 :]))
                except:
                    pass

        if author or verbose:
            self['experimentAuthor'] = author
        if version or verbose:
            self['experimentAuthVersion'] = version

        # script identity & integrity information:
        self['experimentScript'] = os.path.basename(sys.argv[0])  # file name
        scriptDir = os.path.dirname(os.path.abspath(sys.argv[0]))
        self['experimentScript.directory'] = scriptDir
        # sha1 digest, text-format compatibility
        self['experimentScript.digestSHA1'] = _getSha1hexDigest(os.path.abspath(sys.argv[0]), isfile=True)
        # subversion revision?
        try:
            svnrev, last, url = _getSvnVersion(os.path.abspath(sys.argv[0]))  # svn revision
            if svnrev: # or verbose:
                self['experimentScript.svnRevision'] = svnrev
                self['experimentScript.svnRevLast'] = last
                self['experimentScript.svnRevURL'] = url
        except:
            pass
        # mercurical revision?
        try:
            hgChangeSet = _getHgVersion(os.path.abspath(sys.argv[0]))
            if hgChangeSet: # or verbose:
                self['experimentScript.hgChangeSet'] = hgChangeSet
        except:
            pass

        # when was this run?
        self['experimentRunTime.epoch'] = core.getAbsTime()
        self['experimentRunTime'] = data.getDateStr(format="%Y_%m_%d %H:%M (Year_Month_Day Hour:Min)")
コード例 #8
0
 def draw(self, debug_mode=False):
     if getAbsTime() - self.t0 > 30:
         self.move_on_flag.set()   
     
     for i in range(self.nrows):
         self.label_col[i].draw()
         self.contr_col[i].draw()
         self.payof_col[i].draw()
     self.continue_button.draw()
コード例 #9
0
 def draw(self, debug_mode=False):
     for img_stim in self.extra_image_stims:
         img_stim.draw()
     self.continue_button.draw()
     self.text_stim.draw()
     self.img_stim.draw()
     
     if not self.continue_button.clickable:
         if getAbsTime() - self.t0 > self.wait_time:
             self.continue_button.clickable = True
コード例 #10
0
def mkDirs(params):
    #  Save directory
    params['saveDir'] = os.getcwd() + '/data'
    # make the save folder if it doesnt exist
    if os.path.exists(params['saveDir']) == False:
        os.mkdir(params['saveDir'])

    # generate unique subj ID - this will be overwritten by prompt
    params['subj'] = str(core.getAbsTime())

    # Prompt ask for subj and session ID. This will overwrite default subj ID created during initialization
    subj = input("Enter Subject ID :")
    sess = input("Enter Session number:")

    # parse subj id
    if len(subj) > 0:
        # this means we entered a new subj ID. If empty, it will use the unique code generated at the beginning of the tast.
        params['subj'] = subj

    # check if we have a subject directory already, if not, create  a subject directory
    params['subjDir'] = params['saveDir'] + '/' + params['subj']
    if os.path.exists(params['subjDir']) == False:
        os.mkdir(params['subjDir'])

    # parse sess id
    if len(sess) > 0:
        # this means we entered a session ID. If empty, it will create a new session based on the folders already in the subjDir
        params['sess'] = sess
    else:
        # look for folders in the subjDir
        fold_list = os.listdir(params['subjDir'])

        # find session folders
        sess_fold_list = [i for i in fold_list if 'session' in i]

        # infer session id based on folders in the subject directory
        params['sess'] = len(sess_fold_list)  # zero indexed

    # sess dir
    params['sessDir'] = params['subjDir'] + '/session' + str(params['sess'])

    # make session directory
    if os.path.exists(params['sessDir']) == False:
        os.mkdir(params['sessDir'])

    # return updated params
    return params
コード例 #11
0
ファイル: microphone.py プロジェクト: dgfitch/psychopy
    def _record(self, sec, filename='', block=True, log=True):
        filename = pathToString(filename)
        while self.recorder.running:
            pass
        self.duration = float(sec)
        # for duration estimation, high precision:
        self.onset = core.getTime()
        # use time for unique log and filename, 1 sec precision
        self.fileOnset = core.getAbsTime()
        ms = "%.3f" % (core.getTime() - int(core.getTime()))
        if log and self.autoLog:
            msg = '%s: Record: onset %d, capture %.3fs'
            logging.data(msg % (self.loggingId, self.fileOnset,
                                self.duration))
        if not filename:
            onsettime = '-%d' % self.fileOnset + ms[1:]
            self.savedFile = onsettime.join(
                os.path.splitext(self.wavOutFilename))
        else:
            self.savedFile = os.path.abspath(filename)
            if not self.savedFile.endswith('.wav'):
                self.savedFile += '.wav'

        t0 = core.getTime()
        self.recorder.run(self.savedFile, self.duration, **self.options)

        self.rate = sound.backend.pyoSndServer.getSamplingRate()
        if block:
            core.wait(self.duration, 0)
            if log and self.autoLog:
                msg = '%s: Record: stop. %.3f, capture %.3fs (est)'
                logging.exp(msg % (self.loggingId, core.getTime(),
                                   core.getTime() - t0))
            while self.recorder.running:
                core.wait(.001, 0)
        else:
            if log and self.autoLog:
                msg = '%s: Record: return immediately, no blocking'
                logging.exp(msg % (self.loggingId))

        return self.savedFile
コード例 #12
0
ファイル: screens.py プロジェクト: michaelschulte/ThePyeTribe
 def draw(self, debug_mode=False):
     if getAbsTime() - self.t0 > 30:
         self.move_on_flag.set()
         
     if self.AOIs != [] and self.gaze_pos_getter is not None:
         self.gaze.pos = self.coords(self.gaze_pos_getter())
         for shape in self.AOIs:
             if shape.contains(self.gaze.pos):
                 shape.setFillColor('slateblue')
             else:
                 shape.setFillColor('steelblue')
         for shape in self.AOIs:
             shape.draw()
         self.gaze.draw()
         
     
     for i in range(self.nrows):
         self.label_col[i].draw()
         self.contr_col[i].draw()
         self.payof_col[i].draw()
     self.continue_button.draw()
コード例 #13
0
ファイル: runexp.py プロジェクト: drordotan/digposmeg
                    monitor="testMonitor",
                    units="pix",
                    color='Black',
                    screen=1)
myMouse = event.Mouse(win=win)
myMouse.setVisible(0)  # Make mouse invisible

#-- Load configuration
print("Load config...")
params = loadConfig(configFN)
trialData = loadTrialData(params)

outFN = params.outFilenameMask % {
    'subjid': subjID,
    'comment': configFnComment,
    'time': core.getAbsTime()
}
outFN = OUT_PATH + os.path.sep + outFN
print('Results will be saved to %s' % outFN)

if params.responses == RESPONSE_ASYNC:
    responsesOutFN = params.outFilenameMask % {
        'subjid': subjID + '-responses',
        'comment': configFnComment,
        'time': core.getAbsTime()
    }
    responsesOutFN = OUT_PATH + os.path.sep + responsesOutFN

#-- Prepare visual elements
print("Prepare visual elements...")
fixation = prepareFixation(win, params)
コード例 #14
0
ファイル: info.py プロジェクト: del82/psychopy
    def _setExperimentInfo(self, author, version, verbose, randomSeedFlag=None):
        # try to auto-detect __author__ and __version__ in sys.argv[0] (= the users's script)
        if not author or not version:
            f = open(sys.argv[0],'r')
            lines = f.read()
            f.close()
        if not author and lines.find('__author__')>-1:
            linespl = lines.splitlines()
            while linespl[0].find('__author__') == -1:
                linespl.pop(0)
            auth = linespl[0]
            if len(auth) and auth.find('=') > 0:
                try:
                    author = str(eval(auth[auth.find('=')+1 :]))
                except:
                    pass
        if not version and lines.find('__version__')>-1:
            linespl = lines.splitlines()
            while linespl[0].find('__version__') == -1:
                linespl.pop(0)
            ver = linespl[0]
            if len(ver) and ver.find('=') > 0:
                try:
                    version = str(eval(ver[ver.find('=')+1 :]))
                except:
                    pass

        if author or verbose:
            self['experimentAuthor'] = author
        if version or verbose:
            self['experimentAuthVersion'] = version

        # script identity & integrity information:
        self['experimentScript'] = os.path.basename(sys.argv[0])  # file name
        scriptDir = os.path.dirname(os.path.abspath(sys.argv[0]))
        self['experimentScript.directory'] = scriptDir
        # sha1 digest, text-format compatibility
        self['experimentScript.digestSHA1'] = _getSha1hexDigest(os.path.abspath(sys.argv[0]), file=True)
        # subversion revision?
        try:
            svnrev, last, url = _getSvnVersion(os.path.abspath(sys.argv[0])) # svn revision
            if svnrev: # or verbose:
                self['experimentScript.svnRevision'] = svnrev
                self['experimentScript.svnRevLast'] = last
                self['experimentScript.svnRevURL'] = url
        except:
            pass
        # mercurical revision?
        try:
            hgChangeSet = _getHgVersion(os.path.abspath(sys.argv[0]))
            if hgChangeSet: # or verbose:
                self['experimentScript.hgChangeSet'] = hgChangeSet
        except:
            pass

        # when was this run?
        self['experimentRunTime.epoch'] = core.getAbsTime()  # basis for default random.seed()
        self['experimentRunTime'] = data.getDateStr(format="%Y_%m_%d %H:%M (Year_Month_Day Hour:Min)")

        # random.seed -- record the value, and initialize random.seed() if 'set:'
        if randomSeedFlag:
            randomSeedFlag = str(randomSeedFlag)
            while randomSeedFlag.find('set: ') == 0:
                randomSeedFlag = randomSeedFlag.replace('set: ','set:',1) # spaces between set: and value could be confusing after deleting 'set:'
            randomSeed = randomSeedFlag.replace('set:','',1).strip()
            if randomSeed in ['time']:
                randomSeed = self['experimentRunTime.epoch']
            self['experimentRandomSeed.string'] = randomSeed
            if randomSeedFlag.find('set:') == 0:
                random.seed(self['experimentRandomSeed.string']) # seed it
                self['experimentRandomSeed.isSet'] = True
            else:
                self['experimentRandomSeed.isSet'] = False
        else:
            self['experimentRandomSeed.string'] = None
            self['experimentRandomSeed.isSet'] = False
コード例 #15
0
 def draw(self, debug_mode=False):
     self.instructions_text.draw()
     self.continue_button.draw()
     if not self.continue_button.clickable:
         if getAbsTime() - self.t0 > self.wait_time:
             self.continue_button.clickable = True
コード例 #16
0
 def draw(self, debug_mode=False):
     self.instructions_text.draw()
     if getAbsTime() - self.t0 > self.disp_time:
         self.move_on_flag.set()
コード例 #17
0
 def draw(self, debug_mode=False):
     if getAbsTime() - self.t0 > self.duration:
         self.move_on_flag.set()
コード例 #18
0
ttype_labels = {'adv': 'Adversarial Trial', 'flp': 'Flip Trial', 'img': 'Image Trial', 'prac': 'Practice Trial'}
false_labels = {'cat': 'flt', 'dog': 'fls', 'neither': 'img'}

fixation_min_time = .500
fixation_max_time = 1.000
stim_presentation_time = .063
mask_presentation_time = .020
trial_time = 2.200

fixation_min_frames = round(fixation_min_time / frame_rate)
fixation_max_frames = round(fixation_max_time / frame_rate)
stim_presentation_frames = round(stim_presentation_time / frame_rate)
mask_presentation_frames = round(mask_presentation_time / frame_rate)
trial_frames = round(trial_time / frame_rate)

subject_id = core.getAbsTime()
key_assignment = np.random.randint(0, 2)
response_keys = {'Cat': keys[key_assignment], 'Dog': keys[not key_assignment]}

screen_width = 800
screen_height = 800

instruction_text = \
"On each trial of this experiment, you will see a + in the center of the screen. Stare at the +. After a moment, an \
image will briefly appear and disappear, followed by irrelevant scrambled images. Your job is to identify the image. \
You should try to make as few mistakes as possible, but you should also always try to respond as fast as you can. You \
will first do some practice trials. \n \
\n \
Press any key to continue."

practice_text = \
コード例 #19
0
    int(subject_info['Number']) % 2
) + 1  # Group 1 for even participant numbers, group 2 for odd participant numbers
subject_info[
    'Group'] = group  # Group 1 evaluates 1st stim, group 2 evaluates 2nd stim

blocks = range(4)  # Blocks : training, music, speech, scream
skip_training = False
only_first_block = False
only_second_block = False
only_third_block = False
numPad = True
dummy_test = False
dummy = 6
pause_time = 300
pause_multiple = 70  # Number of trials before a forced pause. Must be an integer multiple of total trials
start_e = core.getAbsTime()  # Experiment start time for savefile
general_clock = core.Clock()  # initialize clock
start_r = general_clock.getTime()  # experiment start time in relative time
instructions = []
output_data = []
sounds_all = []
RS_valence = []
RS_arousal = []
RT_valence = []
RT_arousal = []

if numPad:
    respKeys = ['num_1', 'num_2', 'num_3', 'num_4', 'num_5', 'num_6', 'num_7']
else:
    respKeys = ['1', '2', '3', '4', '5', '6', '7']
acceptKey = ['return', 'num_enter']
コード例 #20
0
 def presentTrial(self,trial):
     """
     This function presents a stimuli, waits for a response, tracks the
     response and RT and presents appropriate feedback. If a bot was loaded
     the bot interacts with the experiment through this function by supplying
     'actions' and 'RTs'. This function also controls the timing of FB 
     presentation.
     """
     trialClock = core.Clock()
     self.trialnum += 1
     self.stims[trial['stim']].draw()
     self.win.flip()
     trialClock.reset()
     event.clearEvents()
     FBtext = [('Lose\n\n -1',u'red'), ('Win\n\n +1!',u'lime')]
     trial['actualOnsetTime']=core.getTime() - self.startTime
     trial['stimulusCleared']=0
     trial['response']=[]
     trial['rt']=[]
     trial['FB'] = []
     while trialClock.getTime() < (self.stimulusDuration):
         key_response=event.getKeys(None,True)
         if self.bot:
             choice = self.bot.choose(trial['stim'])
             core.wait(choice[1])
             key_response = [(choice[0], core.getAbsTime())]
         if len(key_response)==0:
             continue
         for key,response_time in key_response:
             if self.quit_key==key:
                 self.shutDownEarly()
             elif self.trigger_key==key:
                 self.trigger_times.append(response_time-self.startTime)
                 continue
             elif key in self.action_keys:
                 trial['response'].append(key)
                 trial['rt'].append(trialClock.getTime())
                 if self.clearAfterResponse and trial['stimulusCleared']==0:
                     self.clearWindow()
                     #trial['stimulusCleared']=core.getTime()-onsetTime
                     trial['stimulusCleared']=trialClock.getTime()
                     core.wait(trial['FBonset'])    
                     #If training, present FB
                     if self.mode != "noFB":
                         trial['actualFBOnsetTime'] = trialClock.getTime()-trial['stimulusCleared']
                         if key == trial['correct_action']:
                             self.pointtracker += 1
                             if trial['PosFB_correct'] == 1:                       
                                 FB = 1
                             else: 
                                 FB = 0
                         else:
                             if trial['PosFB_incorrect'] == 1:                           
                                 FB = 1
                             else: 
                                 FB = 0
                         if self.bot:
                             self.bot.learn(FB)
                             print(self.bot.Q.Qstates)
                         trial['FB'] = FB
                         self.presentTextToWindow(FBtext[FB][0], FBtext[FB][1])
                         core.wait(self.FBDuration)
                         self.clearWindow()     
     #If subject did not respond within the stimulus window clear the stim
     #and admonish the subject
     if trial['stimulusCleared']==0:
         self.clearWindow()
         trial['stimulusCleared']=trialClock.getTime()
         trial['response'].append('NA')
         trial['rt'].append(999)
         core.wait(.5)
         self.presentTextToWindow('Please Respond Faster')
         core.wait(1)
         self.clearWindow()
     return trial
コード例 #21
0
            timeElapsed=timeAllowed #ends while loop, comment out if multiple selections to be allowed
theWin.close()

#Results

#resultsIm = np.zeros(variations)
#for i in range(0,variations):
#    resultsIm[i]=theGrad[stimSize/2,stimSize/2]
#
#print resultsIm 

#trials.printAsText(stimOut=['dpX','dpY','ori'], #write summary data to screen 
#                  dataOut=['x-co_raw','y-co_raw','magnitude_raw','direction_raw','toc_raw'])
#
trials.saveAsExcel(fileName='200s', 
                  sheetName = 'Data_'+str(core.getAbsTime()),
                  stimOut=['dpX','dpY','ori'], 
                  dataOut=['x-co_raw','y-co_raw','magnitude_raw','direction_raw','toc_raw']
                  )
                  

#Polar plot
r = magnitude
theta = direction / (180 /np.pi)
ax = plt.subplot(111, projection='polar')
ax.plot(theta, r, color='r', linewidth=1)
ax.set_rmax(max(r+50))
ax.grid(True)
#ax.set_title("A line plot on a polar axis", va='bottom')
plt.show()
コード例 #22
0
def getDate(time=core.getAbsTime(), format='%Y-%m-%d'):
    timeNowString = datetime.datetime.fromtimestamp(time).strftime(format)
    return timeNowString
コード例 #23
0
    def _setExperimentInfo(self,
                           author,
                           version,
                           verbose,
                           randomSeedFlag=None):
        # try to auto-detect __author__ and __version__ in sys.argv[0] (= the users's script)
        if not author or not version:
            f = open(sys.argv[0], 'r')
            lines = f.read()
            f.close()
        if not author and lines.find('__author__') > -1:
            linespl = lines.splitlines()
            while linespl[0].find('__author__') == -1:
                linespl.pop(0)
            auth = linespl[0]
            if len(auth) and auth.find('=') > 0:
                try:
                    author = str(eval(auth[auth.find('=') + 1:]))
                except:
                    pass
        if not version and lines.find('__version__') > -1:
            linespl = lines.splitlines()
            while linespl[0].find('__version__') == -1:
                linespl.pop(0)
            ver = linespl[0]
            if len(ver) and ver.find('=') > 0:
                try:
                    version = str(eval(ver[ver.find('=') + 1:]))
                except:
                    pass

        if author or verbose:
            self['experimentAuthor'] = author
        if version or verbose:
            self['experimentAuthVersion'] = version

        # script identity & integrity information:
        self['experimentScript'] = os.path.basename(sys.argv[0])  # file name
        scriptDir = os.path.dirname(os.path.abspath(sys.argv[0]))
        self['experimentScript.directory'] = scriptDir
        # sha1 digest, text-format compatibility
        self['experimentScript.digestSHA1'] = _getSha1hexDigest(
            os.path.abspath(sys.argv[0]), file=True)
        # subversion revision?
        try:
            svnrev, last, url = _getSvnVersion(os.path.abspath(
                sys.argv[0]))  # svn revision
            if svnrev:  # or verbose:
                self['experimentScript.svnRevision'] = svnrev
                self['experimentScript.svnRevLast'] = last
                self['experimentScript.svnRevURL'] = url
        except:
            pass
        # mercurical revision?
        try:
            hgChangeSet = _getHgVersion(os.path.abspath(sys.argv[0]))
            if hgChangeSet:  # or verbose:
                self['experimentScript.hgChangeSet'] = hgChangeSet
        except:
            pass

        # when was this run?
        self['experimentRunTime.epoch'] = core.getAbsTime(
        )  # basis for default random.seed()
        self['experimentRunTime'] = data.getDateStr(
            format="%Y_%m_%d %H:%M (Year_Month_Day Hour:Min)")

        # random.seed -- record the value, and initialize random.seed() if 'set:'
        if randomSeedFlag:
            randomSeedFlag = str(randomSeedFlag)
            while randomSeedFlag.find('set: ') == 0:
                randomSeedFlag = randomSeedFlag.replace(
                    'set: ', 'set:', 1
                )  # spaces between set: and value could be confusing after deleting 'set:'
            randomSeed = randomSeedFlag.replace('set:', '', 1).strip()
            if randomSeed in ['time']:
                randomSeed = self['experimentRunTime.epoch']
            self['experimentRandomSeed.string'] = randomSeed
            if randomSeedFlag.find('set:') == 0:
                random.seed(self['experimentRandomSeed.string'])  # seed it
                self['experimentRandomSeed.isSet'] = True
            else:
                self['experimentRandomSeed.isSet'] = False
        else:
            self['experimentRandomSeed.string'] = None
            self['experimentRandomSeed.isSet'] = False
コード例 #24
0
def get_timestamp(time="", format='%Y-%m-%d %H:%M:%S'):
    if time == "": return get_timestamp(core.getAbsTime(), format)
    return datetime.datetime.fromtimestamp(time).strftime(format)