当前位置: 首页>>代码示例>>Python>>正文


Python misc.fromFile函数代码示例

本文整理汇总了Python中psychopy.misc.fromFile函数的典型用法代码示例。如果您正苦于以下问题:Python fromFile函数的具体用法?Python fromFile怎么用?Python fromFile使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了fromFile函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: enterSubjInfo

def enterSubjInfo(expName,optionList):
	""" Brings up a GUI in which to enter all the subject info."""

	def inputsOK(optionList,expInfo):
		for curOption in sorted(optionList.items()):
			if curOption[1]['options'] != 'any' and expInfo[curOption[1]['name']] not in curOption[1]['options']:
				return [False,"The option you entered for " + curOption[1]['name'] + " is not in the allowable list of options: " + str(curOption[1]['options'])]
		print "inputsOK passed"
		return [True,'']

	try:
		expInfo = misc.fromFile(expName+'_lastParams.pickle')
	except:
		expInfo={} #make the kind of dictionary that this gui can understand
		for curOption in sorted(optionList.items()):
			expInfo[curOption[1]['name']]=curOption[1]['default']
	#load the tips
	tips={}
	for curOption in sorted(optionList.items()):
		tips[curOption[1]['name']]=curOption[1]['prompt']
	expInfo['dateStr']= data.getDateStr()
	expInfo['expName']= expName
	dlg = gui.DlgFromDict(expInfo, title=expName, fixed=['dateStr','expName'],order=[optionName[1]['name'] for optionName in sorted(optionList.items())],tip=tips)
	if dlg.OK:
		misc.toFile(expName+'_lastParams.pickle', expInfo)
		[success,error] = inputsOK(optionList,expInfo)
		if success:
			return [True,expInfo]
		else:
			return [False,error]
	else:
		core.quit()
开发者ID:bastienboutonnet,项目名称:AccPred,代码行数:32,代码来源:auditorySentence.py

示例2: test_multiKeyResponses

 def test_multiKeyResponses(self):
     dat = misc.fromFile(os.path.join(fixturesPath,'multiKeypressTrialhandler.psydat'))
     #test csv output
     dat.saveAsText(pjoin(self.temp_dir, 'testMultiKeyTrials.csv'), appendFile=False)
     utils.compareTextFiles(pjoin(self.temp_dir, 'testMultiKeyTrials.csv'), pjoin(fixturesPath,'corrMultiKeyTrials.csv'))
     #test xlsx output
     dat.saveAsExcel(pjoin(self.temp_dir, 'testMultiKeyTrials.xlsx'), appendFile=False)
     utils.compareXlsxFiles(pjoin(self.temp_dir, 'testMultiKeyTrials.xlsx'), pjoin(fixturesPath,'corrMultiKeyTrials.xlsx'))
开发者ID:DiogoamCoutinho,项目名称:stimulus.py,代码行数:8,代码来源:test_TrialHandler.py

示例3: checkPsychoDone

def checkPsychoDone(subject, node):
    tab = int(lib.get_node(node,'id')[0])
    expName = os.path.splitext(os.path.basename(node['file']))[0]
    filename = expName + getTimestamp(node, -2) + 'trials.psydat'
    doneFile = os.path.abspath(os.path.join(lib.SUBJS, subject, "session%d"%tab, 'ltTaskData', expName, filename))
    print "Psychopy complete? Checking", doneFile
    if os.path.exists(doneFile):
        datFile = fromFile(doneFile)
        print "Found .psydat file. Collected",datFile.thisN, "trials, so finished is",datFile.finished
        return datFile.finished
    else:
        return False
开发者ID:satra,项目名称:realtime,代码行数:12,代码来源:buttonlib.py

示例4: get_subject_info

def get_subject_info():
    try:
        expInfo = fromFile('../data/lastParams.pickle') # check existence of previous parameter file
    except:
        expInfo = {'pseudo':'pseudo'}
        expInfo['date']= data.getDateStr() #add current time
    #present a dialog box to get user info
    dlg = gui.DlgFromDict(expInfo, title='Experiment', fixed=['date'])
    if dlg.OK:
        toFile('../data/lastParams.pickle', expInfo)#save params to file for next time
    else:
        core.quit()#cancel -> exit
    return expInfo
开发者ID:vincentadam87,项目名称:pitch_experiment,代码行数:13,代码来源:run_experimentAXB.py

示例5: testReadWriteData

 def testReadWriteData(self):
     dat = misc.fromFile(os.path.join(thisDir, 'data.psydat'))
     dat.saveAsExcel(name,
         stimOut=['text', 'congruent', 'corrAns', 'letterColor', ],
         dataOut=['n','all_mean','all_std', 'all_raw'])
     
     # Make sure the file is there
     assert os.path.isfile(fullName)
     expBook = load_workbook(os.path.join(thisDir,'data.xlsx'))
     actBook = load_workbook(fullName)
     
     for wsN, expWS in enumerate(expBook.worksheets):
         actWS = actBook.worksheets[wsN]
         for key, expVal in expWS._cells.items():
             actVal = actWS._cells[key]
             try:#convert to float if possible (to get around 2.15E-2 probs)
                 expVal.value = float(expVal.value)
             except:
                 pass
             nose.tools.eq_(expVal.value, actVal.value, 
                 msg="expected %s but got %s" %(expVal.value, actVal.value))
开发者ID:bjanus,项目名称:psychopy,代码行数:21,代码来源:testXlsx.py

示例6: get_subj_info

def get_subj_info(gui_yaml, check_exists, save_order=True):
    """ Create a psychopy.gui from a yaml config file.

    The first time the experiment is run, a pickle of that subject's settings
    is saved. On subsequent runs, the experiment tries to prepopulate the
    settings with those of the previous subject.

    Parameters
    ----------
    gui_yaml: str, Path to config file in yaml format.
    check_exists: function, Computes a data file path from the gui data, and
        checks for its existence. If the file exists, an error is displayed.
    save_order: bool, Should the key order be saved in "_order"? Defaults to
        True.

    Returns
    -------
    dict, with key order saved in "_order", if specified.
    """
    with open(gui_yaml, 'r') as f:
        gui_info = yaml.load(f)

    ordered_fields = [field for _, field in sorted(gui_info.items())]

    # Determine order and tips
    ordered_names = [field['name'] for field in ordered_fields]
    field_tips = {field['name']: field['prompt'] for field in ordered_fields}

    # Load the last participant's options or use the defaults
    last_subj_info = gui_yaml + '.pickle'
    try:
        gui_data = misc.fromFile(last_subj_info)
        for yaml_name in ordered_names:
            if yaml_name not in gui_data:
                # Invalid pickle
                raise AssertionError
    except IOError, AssertionError:
        gui_data = {field['name']: field['default'] for field in ordered_fields}
开发者ID:lupyanlab,项目名称:motivated-arrows,代码行数:38,代码来源:psychopy_helper.py

示例7: testReadWriteData

 def testReadWriteData(self):
     dat = misc.fromFile(os.path.join(thisDir, 'data.psydat'))
     dat.saveAsExcel(name,
         stimOut=['text', 'congruent', 'corrAns', 'letterColor', ],
         dataOut=['n','all_mean','all_std', 'all_raw'])
     
     # Make sure the file is there
     assert os.path.isfile(fullName)
     expBook = load_workbook(os.path.join(thisDir,'data.xlsx'))
     actBook = load_workbook(fullName)
     
     for wsN, expWS in enumerate(expBook.worksheets):
         actWS = actBook.worksheets[wsN]
         for key, expVal in expWS._cells.items():
             actVal = actWS._cells[key]
             try:
                 # convert to float if possible and compare with a reasonable
                 # (default) precision
                 expVal.value = float(expVal.value)
                 nose.tools.assert_almost_equals(expVal.value,
                                                 float(actVal.value))
             except:
                 # otherwise do precise comparison
                 nose.tools.assert_equal(expVal.value, actVal.value)
开发者ID:chrox,项目名称:psychopy,代码行数:24,代码来源:testXlsx.py

示例8: task

"""

# build basic task (practice, 1-back, 2-back)
# Decide to use animals for small children and other for adolecsents.
# -*- coding: utf-8 -*-

from psychopy import core, visual, gui, data, misc, event, sound
import time, os, random
# now turn to right folder
directory=os.getcwd()  # get folder
os.chdir(directory) # use it

#folder='/home/ord/Experiments_BP_Clinic/PCT/' #specify the folder of result files to be saved in
# savine last experiment data
try:#try to get a previous parameters file
    expInfo = misc.fromFile('nBack.pickle')
except:#if not there then use a default set
    expInfo = {'subject no':''}
expInfo['dateStr']= data.getDateStr() #add the current time
# dialouge box for name of subject and file
dlg = gui.DlgFromDict(expInfo, title='nBack Task', fixed=['dateStr'])
if dlg.OK:
    misc.toFile('nBack.pickle', expInfo)#save params to file for next time
else:
    core.quit()#the user hit cancel so exit

# check if folder exist and if not, create it
if not os.path.exists('results'):
    os.makedirs('results')

fileName = expInfo['subject no'] + expInfo['dateStr']
开发者ID:orduek,项目名称:TBI_Research,代码行数:31,代码来源:nBack.py

示例9: fromFile

import pylab

if __name__ == "__main__":

    cond_colors = {"pre": "g", "stim": "r", "post": "b"}
    # Open a dialog box to select files from
    files = gui.fileOpenDlg(".")
    if not files:
        core.quit()

    coherence_resp = {}
    coherence_rt = {}
    # get the data from all the files
    allCoherenceLevels, allResponses, allRTs = {}, {}, {}
    for thisFileName in files:
        thisDat = fromFile(thisFileName)

        condition = thisDat.extraInfo["condition"].lower()
        if not condition in coherence_resp:
            coherence_resp[condition] = {}
            coherence_rt[condition] = {}
            allCoherenceLevels[condition] = []
            allResponses[condition] = []
            allRTs[condition] = []

        trialList = thisDat.trialList

        for i in range(thisDat.data["response"].shape[0]):
            for j in range(thisDat.data["response"].shape[1]):
                trialIdx = thisDat.sequenceIndices[i, j]
开发者ID:jbonaiuto,项目名称:rdmd,代码行数:30,代码来源:test_analysis.py

示例10:

from psychopy import data, gui, misc, core
import matplotlib
matplotlib.use('WXAgg')
import pylab, scipy, numpy

files = gui.fileOpenDlg('.')
if not files:
    core.quit()

#Get the individual data from the files
indIntensities={}
indResponses={}


for thisFileName in files:
    thisIndDat = misc.fromFile(thisFileName)
    
    for imageName, array in thisIndDat.extraInfo.iteritems():
        thisImageName = imageName
        indIntensities[thisImageName]=[]
        indResponses[thisImageName]=[]
        
        thisIntensity = thisIndDat.reversalIntensities[-10:]
        thisResponse = thisIndDat.data[-10:]
        indIntensities[thisImageName].extend(thisIntensity)
        indResponses[thisImageName].extend(thisResponse)
        
        #get individual data
        thisNewIntensity = indIntensities[thisImageName]
        thisNewResponse = indResponses[thisImageName]
        
开发者ID:RSharman,项目名称:Experiments,代码行数:30,代码来源:Colour_lastReversals_analysis.py

示例11:

@author: orduek
Corsi Block Expreiment in Psychopy.
This experiment is spatial memory experiment as in the WMS
"""

from psychopy import core, visual, gui, data, misc, event, sound
import time, os
# now turn to right folder
directory=os.getcwd()  # get folder
os.chdir(directory) # use it

#folder='/home/ord/Experiments_BP_Clinic/PCT/' #specify the folder of result files to be saved in
# savine last experiment data
try:#try to get a previous parameters file
    expInfo = misc.fromFile('corsi.pickle')
except:#if not there then use a default set
    expInfo = {'subject no':''}
expInfo['dateStr']= data.getDateStr() #add the current time
# dialouge box for name of subject and file
dlg = gui.DlgFromDict(expInfo, title='Corsi Task', fixed=['dateStr'])
if dlg.OK:
    misc.toFile('corsi.pickle', expInfo)#save params to file for next time
else:
    core.quit()#the user hit cancel so exit

# check if folder exist and if not, create it
if not os.path.exists('results'):
    os.makedirs('results')

fileName = expInfo['subject no'] + expInfo['dateStr']
开发者ID:orduek,项目名称:TBI_Research,代码行数:30,代码来源:corsi.py

示例12: range

bootLMLumStd = []
bootSLumStd = []
bootLMSStd = []

everything={}
everything['bootStd'] = {}
everything['bootLin'] = {}
everything['StdHiLowCI'] = {}
everything['LinHiLowCI']={}
everything['LMLumLin']=[]
everything['SLumLin']=[]
everything['LMSLin']=[]

#Open files
for thisFileName in files:
    dat = misc.fromFile(thisFileName)
    conditions = dat.trialList
    #Extract edge positions relative to the markers
    for n in range(len(dat.data['Condition'])):
        for m in range(dat.nReps):
            markerPos = dat.data['Marker'][n][m]
            finalPos = (markerPos - dat.data['LumEdge'][n][m])
            if dat.data['Condition'][n][m]=='Lum':
                LumPositions.append(finalPos)
            if dat.data['Condition'][n][m]=='LM':
                LMPositions.append(finalPos)
            if dat.data['Condition'][n][m]=='S':
                SPositions.append(finalPos)
            if dat.data['Condition'][n][m]=='LMLum':
                LMLumPositions.append(finalPos)
            if dat.data['Condition'][n][m]=='SLum':
开发者ID:RSharman,项目名称:Experiments,代码行数:31,代码来源:0.02MOABoots.py

示例13: plotDataAndPsychometricCurve

def plotDataAndPsychometricCurve(df, dataFileName):
    """
    Plot data, and fit and plot psychometric curve
    If df is not None then get data from dataFileName
    """
    if df is None:
        if type(dataFileName) is not str:
            print 'dataFileName = ', dataFileName
            raise Exception("No df supplied and no string dataFileName supplied")
        if dataFileName.endswith('.pickle'):
            df = fromFile(dataFileName)
        elif dataFileName.endswith('.txt'):
            df = pd.read_csv(dataFileName, delimiter='\t')
        elif dataFileName.endswith('.psydat'):
            trialHandler = fromFile(dataFileName)
            raise Exception('Cant handle .psydat file, because first Alex has to write a toDataFrame function for experimentHandler, so that its data can be analyzed.')
            #or would have to save to save trialHandler saveAsWideText to dummy file, and use returned dataframe
        #dat = tools.filetools.fromFile(dataFileName) #<class 'psychopy.data.DataHandler'>
    if not isinstance(df, pd.core.frame.DataFrame):
        raise Exception("Don't have viable DataFrame still")

    if np.all(df.dtypes==object):
        raise Exception("I thought you'd give me some numbers to work with, but everything in this dataframe is an object")
    #Need to convert_
    
    #add overcorrect to cases where tilt==0
    tilt = df.loc[:,'tilt']
    neutralStimIdxs = (tilt==0)
    #print('neutralStimIdxs=\n',neutralStimIdxs)
    if len(neutralStimIdxs)>1:
      if neutralStimIdxs.any(): #Calculate over/under-correction, which is only interpretable when tilt=0
        forCalculatn = df.loc[neutralStimIdxs, ['tilt','startLeft','upDown','respLeftRight']]
        overCorrected = calcOverCorrected( forCalculatn )
        df['overCorrected']= np.nan
        df.loc[neutralStimIdxs, 'overCorrected'] = overCorrected
        
    #test plotting of data
    usePsychopy_ext = False
    if usePsychopy_ext:
        #have to use psychopy_ext to aggregate
        ag = psychopy_ext.stats.aggregate(df, values="respLeftRight", cols="tilt") #, values=None, subplots=None, yerr=None, aggfunc='mean', order='natural')
        print "ag = \n", ag
        plt = psychopy_ext.plot.Plot()
        plt.plot(ag, kind='line')
        print "Showing plot with psychopy_ext.stats.aggregate"
        plt.show()
        
    #dataframe aggregate
    grouped = df.groupby(['startLeft','tilt'])
    dirTilt = grouped.mean() #this is a dataframe, not a DataFrameGroupBy
    print "mean at each dir, tilt =\n", dirTilt
    #print "dirTilt.index = ", dirTilt.index #there is no column called 'tilt', instead it's the actual index, kinda like row names
    # MultiIndex [(False, -0.4), (False, 0.0), (False, 0.4), (True, -0.4), (True, 0.0), (True, 0.4)]
    #dirTilt.groups  no groups, maybe because dataframe?
    
    dirTilt = dirTilt.reset_index() #flatten MultiIndex back into columns with rows (simple dataframe)
    leftwardM = dirTilt[ dirTilt['startLeft']==False ]
    rightwardM = dirTilt[ dirTilt['startLeft']==True ]
    
    ax1 = pylab.subplot(121)
    pylab.scatter(leftwardM['tilt'], leftwardM['respLeftRight'],
                          edgecolors=(1,0,0), facecolor=(1,0,0), label='leftward saccade')
    pylab.scatter(rightwardM['tilt'], rightwardM['respLeftRight'],
                          edgecolors=(0,1,0), facecolor=(0,1,0), label='rightward saccade')
    pylab.legend()
    print  str( round( 100*df['overCorrected'].mean(), 2) )
    msg = 'proportn overCorrected at 0 tilt = ' +  str( round( 100*df['overCorrected'].mean(), 2) ) + \
                      '% of ' + str( df['overCorrected'].count() ) + ' trials' 
    msg2= ' 95% Agresti-Coull CI = ' + \
                       str( np.round( agrestiCoull95CI(df['overCorrected'].sum(), df['overCorrected'].count()), 2) )
    pylab.text(0.52, 0.85, msg, horizontalalignment='left', fontsize=12)
    pylab.text(0.52,0.75, msg2, horizontalalignment='left', fontsize=12)
    
    #pylab.ylim([-0.01,1.01])
    pylab.xlabel("tilt")
    pylab.ylabel("proportion respond 'right'")
    
    #psychometric curve basics
    tiltMin = min( df['tilt'] )
    tiltMax = max( df['tilt'] )
    x = np.linspace(tiltMin, tiltMax, 50)
    
    #test function fitting
    #fit curve
    def logistic(x, x0, k):
         y = 1 / (1 + np.exp(-k*(x-x0)))
         return y
    def inverseLogistic(y, x0, k):
        linear = np.log ( y / (1-y) )
        #linear = -k*(x-x0)
        #x-x0 = linear/-k
        #x= linear/-k + x0
        x = linear/-k + x0
        return x
    
    #scipy.stats.logistic.fit
    paramsLeft = None; paramsRight = None
    try:
        paramsLeft, pcov = scipy.optimize.curve_fit(logistic, leftwardM['tilt'], leftwardM['respLeftRight'], p0 = [0, 6])
    except Exception as e:
#.........这里部分代码省略.........
开发者ID:alexholcombe,项目名称:spatiotopic-motion,代码行数:101,代码来源:plotHelpers.py

示例14: zip

import numpy as np
np.set_printoptions(precision=3, suppress=True)
import pylab
import matplotlib.pyplot as plt

import glob
from psychopy import misc
fig = plt.figure()
ax = fig.add_subplot(111)
for fn in glob.glob('results/*npy'):
    data = misc.fromFile(fn.replace('npy', 'pickle'))
    print data
    results = np.load(fn)
    print 'experiment ', fn, ', # trials=', results.shape[1]
    ax.scatter(results[2, :], results[0, :])
#_ = ax.axis([0., 1., -1.1, 1.1])
_ = ax.set_xlabel('shift')
_ = ax.set_ylabel('perceived direction')

plt.hist(results[2,:])

alpha = .3
fig = plt.figure(figsize=(12,5))
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
data = []
for fn in glob.glob('results/*npy'):
    results = np.load(fn)
    # phi motion
    ind_phi = results[1, :]==1
    for i_fig, color in zip(range(1,4), ['r', 'g', 'b']):
开发者ID:jspezia,项目名称:reverse-phi,代码行数:31,代码来源:analyse.py

示例15:

#Blur width is also a fraction of the overall stimulus i.e. a blur of 0.1 would be 10% of the stimulus or 1 degree
#Marker position - the output from the staircase - is between 0 and 10 and is in degrees
#lumEdgePos - is a randomly generated number which positions the luminance edge, this is a fraction of the stim
#i.e. lumEdgePos = 0.2 the luminance edge will be 2 degrees from the left
#the LM edge is positioned relative to the luminance edge - i.e. lm edge position = lumEdgePos+Gap

from psychopy import visual, event, filters, monitors, data, sound, gui, misc, core
import numpy as np
import random, time, os, cPickle
from numpy.random import shuffle

DEBUG=True

#Create a dialog box for settings and participant information
try:
    info=misc.fromFile('conflictParams.pickle')
except:
    info = {'participant' : 'RJS',
                'Gap' : 0,
                'Edge Contrast LM' : 0.1,
                'Edge Contrast S' : 0.1,
                'Edge Contrast Lum' : 0.1,
                'Flip' : 'n',
                'Choose' : 'none'}
info['dateStr']=time.strftime("%b%d_%H%M", time.localtime())
dlg = gui.DlgFromDict(info, title='Synthetic Edge Experiment', fixed=['dateStr'])
if dlg.OK:
    misc.toFile('conflictParams.pickle', info)
else:
    core.quit()
开发者ID:RSharman,项目名称:Experiments,代码行数:30,代码来源:ConflictMOAMultiStairs.py


注:本文中的psychopy.misc.fromFile函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。