def main(): """The main routine, which is called automatically by pgs4a""" if android is not None: sys.stdout = stdout_file(sys.stdout) # First check if an autorun file has been specified. This is a yaml file # with the experiment path, subject nr, and logfile in it. for folder in sdcard_folders: path = os.path.join(folder, 'opensesame-autorun.yml') print(path) if os.path.exists(path): d = yaml.load(open(path)) experiment_path = d['experiment'] subject_nr = d['subject_nr'] logfile = d['logfile'] break # If no autorun file has been specified, we launch the menu experiment. else: src = 'opensesame_resources/android/menu.osexp' print('Launching %s' % src) menu = experiment('Experiment', src) menu.experiment_path = None menu.run() menu.end() clean_up(menu.debug) experiment_path = menu._experiment subject_nr = menu._subject_nr logfile = menu._logfile # Next run the actual experiment! try: exp = experiment(name='Experiment', string=experiment_path, experiment_path=os.path.dirname(experiment_path)) except Exception as e: for s in traceback.format_exc(e).split("\n"): print(s) print('Launching %s' % experiment_path) exp.set_subject(subject_nr) exp.logfile = logfile # Capture exceptions and write them to the standard output so they can be # inspected try: exp.run() except Exception as e: for s in traceback.format_exc(e).split("\n"): print(s) try: exp.end() except Exception as e: for s in traceback.format_exc(e).split("\n"): print(s) clean_up(exp.debug) pygame.display.quit()
def checkExample(self, expPath): """ desc: Checks whether a given experiment can be parsed. arguments: expPath: desc: A path to an experiment type: unicode """ print(u'Checking %s ...' % expPath) from libopensesame.experiment import experiment experiment(u'dummy', expPath, experiment_path=os.path.dirname(expPath)) print(u'Done!')
def add_experiment(self, path): """ desc: Processes one experiment. arguments: path: desc: The experiment folder name. type: str """ src = os.path.join(self.example_folder, path, u'experiment.osexp') if not os.path.exists(src): return try: e = experiment(u'dummy', src, experiment_path=os.path.dirname(src)) except: return d = e.front_matter d[u'src'] = src if u'Title' not in d: d[u'Title'] = u'No title' if u'Description' not in d: d[u'Description'] = u'No description' self.experiments.append(d)
def runTest(self): """ desc: Runs the response test. """ print(u'Checking response handling') self.exp = experiment() with self.assertRaises(osexception) as cm: self.exp.set_response(correct='A') with self.assertRaises(osexception) as cm: self.exp.set_response(response_time='A') for i in range(2): self.exp.reset_feedback() self.exp.set_response() self.assertState(None, None, u'undefined', 1, 0, 0) self.exp.set_response(response='A') self.assertState('A', None, u'undefined', 2, 0, 0) self.exp.set_response(response='B', response_time=1000) self.assertState('B', 1000, u'undefined', 3, 1000, 0) self.exp.set_response(response='C', response_time=1000, correct=1) self.assertState('C', 1000, 1, 4, 2000, 1) self.exp.set_response(response='D', response_time=1, correct=0) self.assertState('D', 1, 0, 5, 2001, 1)
def _get_osexp(self, json): t0 = time.time() for f in json['files']: if not f['type'] == 'experiment': continue path = f['path'] updated_at = f['updated_at'] size = f['size'] break else: raise InvalidJSON(safe_decode(json)) cache_path = os.path.join( tempfile.gettempdir(), hashlib.md5(safe_encode(path + updated_at)).hexdigest() + '.osexp') # If a cached file that matches in name and size exists, we re-use it. # The file name also includes the updated_at fields, and thus # re-uploading a new experiment with the same size will still refresh # the cache. if os.path.exists(cache_path) and os.path.getsize(cache_path) == size: oslogger.info('using cached {}'.format(cache_path)) else: response = requests.get(self._osexp_url + path) if not response.ok: raise FailedToDownloadExperiment() with open(cache_path, 'wb') as fd: fd.write(response.content) oslogger.info('caching {} to {}'.format(path, cache_path)) self._experiment = experiment(string=cache_path) oslogger.info('building experiment ({:.3f} s)'.format(time.time() - t0)) return self._experiment
def run(self): """ Everything in this function is run in a new process, therefore all import statements are put in here. The function reroutes all output to stdin and stderr to the pipe to the main process so OpenSesame can handle all prints and errors. """ import os import sys from libopensesame import misc from libopensesame.experiment import experiment from libopensesame.exceptions import osexception # Under Windows, change the working directory to the OpenSesame folder, # so that the new process can find the main script. if os.name == u'nt': os.chdir(misc.opensesame_folder()) # Reroute output to OpenSesame main process, so everything will be # printed in the Debug window there. pipeToMainProcess = OutputChannel(self.output) sys.stdout = pipeToMainProcess sys.stderr = pipeToMainProcess # First initialize the experiment and catch any resulting Exceptions try: exp = experiment(string=self.script, pool_folder= self.pool_folder, experiment_path=self.experiment_path, fullscreen=self.fullscreen, auto_response=self.auto_response, subject_nr=self.subject_nr, logfile=self.logfile) except Exception as e: if not isinstance(e, osexception): e = osexception(u'Unexpected error', exception=e) # Communicate the exception and exit with error self.output.put(e) sys.exit(1) print(u'Starting experiment as %s' % self.name) # Run the experiment and catch any Exceptions. e_run = None exp.set_output_channel(self.output) try: exp.run() print('done!') except Exception as e_run: if not isinstance(e_run, osexception): e_run = osexception(u'Unexpected error', exception=e_run) exp.transmit_workspace() # End the experiment and catch any Exceptions. These exceptions are just # printed out and not explicitly passed on to the user, because they are # less important than the run-related exceptions. try: exp.end() except Exception as e_exp: print(u'An Exception occurred during exp.end(): %s' % e_exp) # Communicate the exception and exit with error if e_run is not None: self.output.put(e_run) sys.exit(1) # Exit with success sys.exit(0)
def run(self): """ Everything in this function is run in a new process, therefore all import statements are put in here. The function reroutes all output to stdin and stderr to the pipe to the main process so OpenSesame can handle all prints and errors. """ import os import sys from libopensesame import misc from libopensesame.experiment import experiment from libopensesame.exceptions import osexception # Under Windows, change the working directory to the OpenSesame folder, # so that the new process can find the main script. if os.name == u'nt': os.chdir(misc.opensesame_folder()) # Reroute output to OpenSesame main process, so everything will be # printed in the Debug window there. pipeToMainProcess = OutputChannel(self.output) sys.stdout = pipeToMainProcess sys.stderr = pipeToMainProcess # First initialize the experiment and catch any resulting Exceptions try: exp = experiment(string=self.script, pool_folder= \ self.pool_folder, experiment_path=self.experiment_path, \ fullscreen=self.fullscreen, auto_response=self.auto_response, \ subject_nr=self.subject_nr, logfile=self.logfile) except Exception as e: if not isinstance(e, osexception): e = osexception(u'Unexpected error', exception=e) # Communicate the exception and exit with error self.output.put(e) sys.exit(1) print(u'Starting experiment as %s' % self.name) # Run the experiment and catch any Exceptions. e_run = None try: exp.run() except Exception as e_run: if not isinstance(e_run, osexception): e_run = osexception(u'Unexpected error', exception=e_run) # End the experiment and catch any Exceptions. These exceptions are just # printed out and not explicitly passed on to the user, because they are # less important than the run-related exceptions. try: exp.end() except Exception as e_exp: print(u'An Exception occurred during exp.end(): %s' % e_exp) # Communicate the exception and exit with error if e_run != None: self.output.put(e_run) sys.exit(1) # Exit with success sys.exit(0)
def announce(self, participant): self._participant = participant if self._participant not in self._jobs: raise NoJobsForParticipant(participant) if not self._jobs[self._participant][0]['jobs']: self._jobs[self._participant].pop(0) if not self._jobs[self._participant]: raise NoJobsForParticipant(participant) path = self._experiment_path(self._jobs[self._participant][0]['exp']) self._experiment = experiment(string=path) return self._experiment
def runTest(self): """ desc: Walk through the test """ self.exp = experiment() self.checkCmd(u'widget 0 0 1 1 label text="Tést 123"', u'widget', [0, 0, 1, 1, u'label'], {u'text': u'Tést 123'}) self.checkCmd(u'test', u'test', [], {}) self.checkCmd(u'set test "c:\\\\" x="d:\\\\"', u'set', [u'test', u'c:\\'], {u'x': u'd:\\'}) self.checkCmd(u'test "\\"quoted\\""', u'test', [u'\"quoted\"'], {}) self.checkCmd( u'test test="\\"quoted\\""', u'test', [], {u'test': u'\"quoted\"'}, ) with self.assertRaises(osexception): print(u'Testing exception ...') self.checkCmd(u'widget 0 0 1 1 label text="Tést 123', u'widget', [0, 0, 1, 1, u'label'], {u'text': u'Tést 123'}) self.checkEvalText(r'\\[width] = \[width] = [width]', r'\1024 = [width] = 1024') self.checkEvalText(u'[no var]', u'[no var]') self.checkEvalText(u'[nóvar]', u'[nóvar]') self.checkEvalText(u'\[width]', u'[width]') self.checkEvalText(r'\\[width]', r'\1024') self.checkEvalText(u'[width] x [height]', u'1024 x 768') self.checkEvalText(u'[=10*10]', u'100') self.checkEvalText(r'\[=10*10]', u'[=10*10]') self.checkEvalText(r'\\[=10*10]', r'\100') self.checkEvalText(u'[=u"tést"]', u'tést') self.checkEvalText(u'[="\[test\]"]', u'[test]') self.checkCnd(u'[width] > 100', u'var.width > 100') self.checkCnd(u'[width] >= 100', u'var.width >= 100') self.checkCnd(u'[width] <= 100', u'var.width <= 100') self.checkCnd(u'always', u'True') self.checkCnd(u'ALWAYS', u'True') self.checkCnd(u'never', u'False') self.checkCnd(u'NEVER', u'False') self.checkCnd(u'[width] = 1024', u'var.width == 1024') self.checkCnd(u'[width] = 1024 and [height] == 768', u'var.width == 1024 and var.height == 768') self.checkCnd(u'=var.width > 100', u'var.width > 100') self.checkCnd(u'"yes" = yes', u'"yes" == "yes"') self.checkCnd(u'yes = \'yes\'', u'"yes" == \'yes\'') self.checkCnd(u'"y\'es" = \'y"es\'', u'"y\'es" == \'y"es\'') self.checkCnd( u'("a b c" = abc) or (x != 10) and ([width] == 100)', u'("a b c" == "abc") or ("x" != 10) and (var.width == 100)')
def runTest(self): """ desc: Walk through the test """ self.exp = experiment() self.checkCmd(u'widget 0 0 1 1 label text="Tést 123"', u'widget', [0, 0, 1, 1, u'label'], {u'text' : u'Tést 123'}) self.checkCmd(u'test', u'test', [], {}) self.checkCmd(u'set test "c:\\\\" x="d:\\\\"', u'set', [u'test', u'c:\\'], {u'x' : u'd:\\'}) self.checkCmd(u'test "\\"quoted\\""', u'test', [u'\"quoted\"'], {}) self.checkCmd(u'test test="\\"quoted\\""', u'test', [], {u'test' : u'\"quoted\"'},) with self.assertRaises(osexception): print(u'Testing exception ...') self.checkCmd(u'widget 0 0 1 1 label text="Tést 123', u'widget', [0, 0, 1, 1, u'label'], {u'text' : u'Tést 123'}) self.checkEvalText(r'\\[width] = \[width] = [width]', r'\1024 = [width] = 1024') self.checkEvalText(u'[no var]', u'[no var]') self.checkEvalText(u'[nóvar]', u'[nóvar]') self.checkEvalText(u'\[width]', u'[width]') self.checkEvalText(r'\\[width]', r'\1024') self.checkEvalText(u'[width] x [height]', u'1024 x 768') self.checkEvalText(u'[=10*10]', u'100') self.checkEvalText(r'\[=10*10]', u'[=10*10]') self.checkEvalText(r'\\[=10*10]', r'\100') self.checkEvalText(u'[=u"tést"]', u'tést') self.checkEvalText(u'[="\[test\]"]', u'[test]') self.checkCnd(u'[width] > 100', u'var.width > 100') self.checkCnd(u'[width] >= 100', u'var.width >= 100') self.checkCnd(u'[width] <= 100', u'var.width <= 100') self.checkCnd(u'always', u'True') self.checkCnd(u'ALWAYS', u'True') self.checkCnd(u'never', u'False') self.checkCnd(u'NEVER', u'False') self.checkCnd(u'[width] = 1024', u'var.width == 1024') self.checkCnd(u'[width] = 1024 and [height] == 768', u'var.width == 1024 and var.height == 768') self.checkCnd(u'=var.width > 100', u'var.width > 100') self.checkCnd(u'"yes" = yes', u'"yes" == "yes"') self.checkCnd(u'yes = \'yes\'', u'"yes" == \'yes\'') self.checkCnd(u'"y\'es" = \'y"es\'', u'"y\'es" == \'y"es\'') self.checkCnd(u'("a b c" = abc) or (x != 10) and ([width] == 100)', u'("a b c" == "abc") or ("x" != 10) and (var.width == 100)')
def init_experiment(self, quick=False, fullscreen=False, auto_response= \ False): """ Initializes a new experiment, which is a newly generated instance of the experiment currently active in the user interface. Keyword arguments: quick -- Indicates whether we are quickrunning the experiment. (default=False) Returns: True if the experiment was successfully initiated, False it was not. """ # First tell the experiment to get ready, to apply any pending changes, # and then initialize the script. This can trigger errors. try: self.main_window.get_ready() script = self.main_window.experiment.to_string() except Exception as e: if not isinstance(e, osexception): e = osexception(u'Unexpected error', exception=e) md = _(u'# Error\n\nFailed to generate experiment for the ' u'following reason:\n\n- ') + e.markdown() self.console.write(e) self.tabwidget.open_markdown(md) return False # Get and set the subject number subject_nr = self.get_subject_nr(quick=quick) if subject_nr is None: return False # Get and set the logfile logfile = self.get_logfile(quick=quick, subject_nr=subject_nr) if logfile is None: return False # Build a new experiment. This can trigger a script error. try: self.experiment = experiment(string=script, pool_folder= \ self.main_window.experiment.pool.folder(), experiment_path= \ self.main_window.experiment.experiment_path, fullscreen= \ fullscreen, auto_response=auto_response, subject_nr= \ subject_nr, logfile=logfile) except Exception as e: if not isinstance(e, osexception): e = osexception(u'Unexpected error', exception=e) md = _(u'# Error\n\nFailed to parse experiment for the ' u'following reason:\n\n- ') + e.markdown() self.console.write(e) self.tabwidget.open_markdown(md) return True
def init_experiment(self, quick=False, fullscreen=False, auto_response=False): """ Initializes a new experiment, which is a newly generated instance of the experiment currently active in the user interface. Keyword arguments: quick -- Indicates whether we are quickrunning the experiment. (default=False) Returns: True if the experiment was successfully initiated, False it was not. """ # First tell the experiment to get ready, to apply any pending changes, # and then initialize the script. This can trigger errors. try: self.main_window.get_ready() script = self.main_window.experiment.to_string() except Exception as e: if not isinstance(e, osexception): e = osexception(u"Unexpected error", exception=e) self.main_window.print_debug_window(e) self.main_window.experiment.notify(e.html()) return False # Get and set the subject number subject_nr = self.get_subject_nr(quick=quick) if subject_nr == None: return False # Get and set the logfile logfile = self.get_logfile(quick=quick, subject_nr=subject_nr) if logfile == None: return False # Build a new experiment. This can trigger a script error. try: self.experiment = experiment( string=script, pool_folder=self.main_window.experiment.pool_folder, experiment_path=self.main_window.experiment.experiment_path, fullscreen=fullscreen, auto_response=auto_response, subject_nr=subject_nr, logfile=logfile, ) except Exception as e: if not isinstance(e, osexception): e = osexception(u"Unexpected error", exception=e) self.main_window.print_debug_window(e) self.main_window.experiment.notify(e.html()) return True
def main(): """The main routine, which is called automatically by pgs4a""" sys.argv.append('--debug') if android != None: sys.stdout = stdout_file(sys.stdout) # First start the menu experiment src = 'resources/android/menu.opensesame' print 'Launching %s' % src menu = experiment('Experiment', src) menu.run() menu.end() clean_up(menu.debug) # Next run the actual experiment! exp = experiment('Experiment', menu._experiment) print 'Launching %s' % menu._experiment exp.subject_nr = menu._subject_nr exp.logfile = menu._logfile # Capture exceptions and write them to the standard output so they can be # inspected try: exp.run() except Exception as e: for s in traceback.format_exc(e).split("\n"): print s try: exp.end() except Exception as e: for s in traceback.format_exc(e).split("\n"): print s clean_up(exp.debug) pygame.display.quit()
def runTest(self): """ desc: Walks through the test. """ experiment_path = os.path.join(os.path.dirname(__file__), u'data') for experiment_file in [u'response_test.osexp', u'sketchpad_test.osexp']: print(u'Testing %s' % experiment_file) e = experiment( experiment_path=experiment_path, string=os.path.join(experiment_path, experiment_file)) e.run()
def runTest(self): """ desc: Walks through the test. """ from qtpy.QtWidgets import QApplication app = QApplication([]) experiment_path = os.path.join(os.path.dirname(__file__), u'data') for experiment_file in [ u'sketchpad_test.osexp', u'response_test.osexp', u'loop_test.osexp' ]: print(u'Testing %s' % experiment_file) for backend in (u'legacy', ): e = experiment(logfile=u'/tmp/tmp.csv', experiment_path=experiment_path, string=os.path.join(experiment_path, experiment_file)) e.var.canvas_backend = backend e.run()
def main(): """The main routine, which is called automatically by pgs4a""" sys.argv.append('--debug') if android != None: sys.stdout = stdout_file(sys.stdout) # Instead of calling the menu, we skip straight to opening our experiment src = 'resources/android/AndroidReady.opensesame' print 'Launching %s' % src exp = experiment('Experiment', src) exp.subject_nr = 0 exp.logfile = 'resources/android/log.csv' print exp #exp.run() #exp.end() #clean_up(exp.debug) # The following used to set parameters in the experiement. # Although not currently used, some of it may be useful in future. #exp.subject_nr = menu._subject_nr #exp.logfile = menu._logfile # Capture exceptions and write them to the standard output so they can be # inspected try: exp.run() except Exception as e: for s in traceback.format_exc(e).split("\n"): print s try: exp.end() except Exception as e: for s in traceback.format_exc(e).split("\n"): print s clean_up(exp.debug) pygame.display.quit()
def checkRead(self, path, fmt, pool=[]): """ desc: Checks whether a single experiment can be read, written, and then read again. arguments: path: The path to the experiment file, or script of the experiment file. fmt: The expected format of the experiment file when re-opening it. keywords: pool: A list of filenames that should be in the file pool. """ e = experiment(string=path) self.assertEqual(e.var.title, u'New experiment') for basename in pool: self.assertIn(basename, e.pool) osexpwriter(e, 'tmp.osexp') r = osexpreader(e, 'tmp.osexp') self.assertEqual(r.format, fmt)
def run(self): """ Everything in this function is run in a new process, therefore all import statements are put in here. The function reroutes all output to stdin and stderr to the pipe to the main process so OpenSesame can handle all prints and errors. """ import os import sys from libopensesame.experiment import experiment from libopensesame.exceptions import osexception # Determines the directory name of the script or the directory name # of the executable after being packaged with py2exe. This has to be done # so the child process can find all relevant modules too. # See http://www.py2exe.org/index.cgi/HowToDetermineIfRunningFromExe if os.name == u'nt': import imp if (hasattr(sys, u'frozen') or hasattr(sys, u'importers') or \ imp.is_frozen(u'__main__')): path = os.path.dirname(sys.executable) else: path = os.path.dirname(__file__) if path != u'': os.chdir(path) if path not in sys.path: sys.path.append(path) # Reroute output to OpenSesame main process, so everything will be # printed in the Debug window there. pipeToMainProcess = OutputChannel(self.output) sys.stdout = pipeToMainProcess sys.stderr = pipeToMainProcess # When a module is run in a new process, by default the current directory # is set to where this module is located, which in this case will be # /libqtopensesame/misc/ # Because all plugins are referenced from the OpenSesame root dir, we # need to change the current folder back to that location. os.chdir(u'../..') # First initialize the experiment and catch any resulting Exceptions try: exp = experiment(string=self.script, pool_folder= \ self.pool_folder, experiment_path=self.experiment_path, \ fullscreen=self.fullscreen, auto_response=self.auto_response, \ subject_nr=self.subject_nr, logfile=self.logfile) except Exception as e: if not isinstance(e, osexception): e = osexception(u'Unexpected error', exception=e) # Communicate the exception and exit with error self.output.put(e) sys.exit(1) print u'Starting experiment as %s' % self.name # Run the experiment and catch any Exceptions. e_run = None try: exp.run() except Exception as e_run: if not isinstance(e_run, osexception): e_run = osexception(u'Unexpected error', exception=e_run) # End the experiment and catch any Exceptions. These exceptions are just # printed out and not explicitly passed on to the user, because they are # less important than the run-related exceptions. try: exp.end() except Exception as e_exp: print u'An Exception occurred during exp.end(): %s' % e_exp # Communicate the exception and exit with error if e_run != None: self.output.put(e_run) sys.exit(1) # Exit with success sys.exit(0)
# example script for using PyGaze import random from pygaze import Display, Screen, Keyboard, defaults, EyeTracker, libtime from libopensesame.experiment import experiment src = '/home/sebastiaan/git/opensesame/resources/templates/default.opensesame' exp = experiment(string=src) exp.init_display() defaults.DISPTYPE = 'opensesame' defaults.osexperiment = exp defaults.FGC = 255,255,255 defaults.BGC = 0,0,0 w, h = defaults.DISPSIZE = exp.resolution() # # # # # # setup the experiment # create display object disp = Display(disptype='opensesame') tracker = EyeTracker(disp, trackertype='dummy') tracker.calibrate() # create keyboard object kb = Keyboard(disptype='opensesame', keylist=['left','right', \ 'escape'], timeout=2000) # create screens fixscreen = Screen(disptype='opensesame') fixscreen.draw_fixation(fixtype='cross',pw=2) targetscreens = {}
from libopensesame.experiment import experiment # A very basic experiment in OpenSesame script exp_str = u''' set start my_sketchpad define sketchpad my_sketchpad draw textline 0 0 "Dummy text" ''' # Parse the OpenSesame script into an experiment object exp = experiment(string=exp_str) # Calling the `experiment.run()` method will launch the full experiment exp.run() # Access the `my_sketchpad` item my_sketchpad = exp.items[u'my_sketchpad'] print my_sketchpad # The item in turn contains a reference to the `experiment` object print my_sketchpad.experiment
import sys sys.path.append( '/home/sebastiaan/git/omm-client/opensesame_plugins/OMMConditioner' ) from libopensesame.experiment import experiment from conditioners import SeedDispenser exp = experiment(string='') exp.init_clock() sd = SeedDispenser(experiment=exp, port='/dev/ttyUSB0') input('reward') sd.reward() input('sound left') sd.sound_left() input('off') sd.sound_off() input('sound right') sd.sound_right() input('off') sd.sound_off() input('sound both') sd.sound_both() input('off') sd.sound_off()
# example script for using PyGaze from libopensesame.experiment import experiment #src = '/home/sebastiaan/git/opensesame/resources/templates/default.opensesame' exp = experiment(string=src) exp.init_display() # # # # # # importing the relevant libraries import random from pygaze import libscreen from pygaze import libtime from pygaze import libinput from pygaze import liblog from pygaze import defaults defaults.osexperiment = exp w = 1024 h = 768 # # # # # # setup the experiment # create display object disp = libscreen.Display(disptype='opensesame') # create keyboard object kb = libinput.Keyboard(disptype='opensesame', keylist=['left','right','escape'], timeout=2000) # create logfile object log = liblog.Logfile()
def _fallback_experiment(self): if not os.path.exists(self.var.omm_fallback_experiment): raise FileNotFoundError('no fallback experiment: {}'.format( self.var.omm_fallback_experiment)) return experiment(string=self.var.omm_fallback_experiment)