PsyScriptIcon.png PsyScript: getting experiments done

$query\n"; } $result = mysql_db_query($database, $query, $connection) or die("ack! query failed: " ."
  • errorno=".mysql_errno() ."
  • error=".mysql_error() ."
  • query=".$query ); return $result; } $Base = "http://www.maccs.mq.edu.au"; $URL= $PHP_SELF; $connection = mysql_connect('localhost', 'tim', 'connect2'); if (!$connection) { print("Cannot connect to database. Call Tim.
    "); exit(); } $result=safe_db_query("Counters","SELECT * FROM Count WHERE Base='$Base' AND URL='$URL'", $connection); while ($row = mysql_fetch_row($result)) { $ChkBase=$row[0]; $ChkURL=$row[1]; $ChkCount=$row[2]; $Count=$ChkCount; } if ($ChkURL == ""){ safe_db_query("Counters","INSERT INTO Count VALUES ('$Base','$URL','0')", $connection); $Count=0; } $Count++; safe_db_query("Counters","UPDATE Count SET Number='$Count' WHERE Base='$Base' AND URL='$URL'"); $result=safe_db_query("Counters","SELECT * FROM Count WHERE Base='$Base' AND URL='$URL'", $connection); while ($row = mysql_fetch_row($result)) { $Base=$row[0]; $URL=$row[1]; $Count=$row[2]; } echo $Count; */ ?>hits
  • PsyScript 5.1 Documentation

    Introduction
    AppleScript Equivalents for ECL Constructs
    Multiple Responses
    Other PsyScript Features
    Changed Trial Commands
    EyeLink Support
    ActiveWire Support
    New Trial Commands
    Additional Features
    Tips

    Introduction

    PsyScript is a derivative of RSVP, based on code kindly made available by Pepper Williams and the RSVP team. Thanks guys.

    PsyScript includes full support for AppleScript as a replacement for ECL. The only remnants of ECL still supported are “trial” strings—these carry over largely unchanged. All the functionality of PsyScript is available through the cleaner and more regular AppleScript syntax. AppleScript also allows you to do some things that cannot be done via ECL: for example, various settings that could be changed but not examined from ECL, may be both examined and changed from AppleScript.

    For more information about AppleScript, visit Apple’s Web site.

    An experiment script put together using the functions in this document must have somewhere near its beginning the command

    begin experiment

    and end with the command

    end experiment

    In-between, you may use any of the other AppleScript constructs described in this document. You may also specify most settings prior to the “begin experiment” command, but use of the “display instructions” command, and changes to the screen size and screen depth properties, are only valid between “begin experiment” and “end experiment”.

    AppleScript Equivalents for ECL Constructs

    This table lists every ECL construct in alphabetical order, together with a suggested AppleScript equivalent.

    ECLAppleScriptNotes
    [' comment]
    [comment comment]
    AppleScript comments either start with “--” and end with the end of the line, or they are bracketed between “(*” and “*)” and can extend across multiple lines.
    [debug cmd] if debugging then
      cmd
    end if
    debugging property is read/write from AppleScript.
    [do check_debug] None. AppleScript can use the value of the debugging property directly. This property can also be modified from AppleScript.
    [do check_version version] None. Version check not needed for AppleScript.
    [do default_folder folderspec] set default folder to folderspec folderspec may be an AppleScript file or alias specification, or it may be an absolute or relative pathname string. If it is a relative pathname string, it is interpreted relative to the current default folder setting.
    [do define_click index left top right bottom] set bounds of click area index to {left, top, right, bottom}
    [do flash_instructions milliseconds instruction_text] display instructions instruction_text for milliseconds Only valid within an experiment.
    [do init_bbox] initialize bbox
    [do init_mappings] initialize mappings
    [do init_positions] initialize positions
    [do instruction_file filename] display instructions from filename Only valid within an experiment. AppleScript version also allows “for”-option to flash instructions from a file.
    [do instructions instruction_text] display instructions instruction_text Only valid within an experiment. In AppleScript, the instruction_text can be a single text string or a list of text strings.
    [do itpause milliseconds] pause milliseconds
    [do kill_perm_stims] delete every permanent stimulus AppleScript allows selective deletion of individual stimuli. Because this can cause the numbering of remaining stimuli to change, you should always use stimulus names, not numbers, with the “•” trial command.
    [do load_ctab srcname] load color table srcname
    [do load_perm_stim srcname stimname] load permanent stimulus srcname name stimname [as picture stimulus/masked picture stimulus/sound stimulus/movie stimulus/word stimulus] The AppleScript version returns a reference to the loaded stimulus. It also allows you to omit the initial type character on the front of srcname, and specify the type as an additional argument to the command.
    [do map_bbox_key keyindex mapstring] set mapping of bbox key keyindex to mapstring
    [do map_click clickindex mapstring] set mapping of click area clickindex to mapstring
    [do map_key character mapstring] set mapping of key character to mapstring
    [do map_mouse mapstring] No direct equivalent; use a click area as per notice_all_clicks below.
    [do map_vtrig mapstring] set vtrig mapping to mapstring
    No ECL equivalent set mapping of current sound to mapstring Sound responses are specific to PsyScript.
    No ECL equivalent set mapping of eyelink button n to mapstring Eyelink support is specific to PsyScript.
    set noticed of eyelink button n to true/false
    No ECL equivalent set mapping of activewire pin n to mapstring ActiveWire support is specific to PsyScript.
    set noticed of activewire pin n to true/false
    [do notice_all_bbox_keys y/n] set noticed of every bbox key to true/false
    [do notice_all_clicks y/n] No direct equivalent: instead, set the bounds of a single click area to the entire screen to pick up all clicks, eg
    set bounds of click area 1 to {0, 0} & (screen size)
    set noticed of click area 1 to true/false
    [do notice_all_keys y/n] set noticed of every key to true/false
    [do notice_bbox_key keyindex y/n] set noticed of bbox key keyindex to true/false
    [do notice_click clickindex y/n] set noticed of click area clickindex to true/false
    [do notice_key character y/n] set noticed of key character to true/false
    [do pict_folder folderspec] set default picture folder to folderspec folderspec may be an AppleScript file or alias specification, or it may be an absolute or relative pathname string. If it is a relative pathname string, it is interpreted relative to the current default folder setting.
    [do res_file resfilename] open resource resfilename In AppleScript, resfilename can be a string, a filespec or an alias.
    [do set auto_events auto_events_string] set auto events to auto_events_string
    [do set back_color color] set background color to color Also see additional notes on color specifications, below.
    [do set beep y/n] set beeping to true/false AppleScript wants true or false, not “yes” or “no”.
    [do set jitter jitter_value] set jitter to jitter_value
    [do set justify l/c/r] set word alignment to left aligned/centered/right aligned ECL uses the term “justify” incorrectly.
    [do set left_margin left_margin] set left margin to left_margin
    [do set line_height line_height] set line height to line_height
    [do set load_ctab_automatically y/n] set loading ctab automatically to true/false
    [do set pict_type s/a] set simple picture type to true/false The true value of the AppleScript property corresponds to the “s[imple]” ECL setting, and the false value to “a[dvanced]”.
    [do set position i h v] set value of position i to {h, v} In AppleScript, undefined positions are initialized to (-1, -1). In ECL, it is an error to access positions before they have been defined.
    [do set response_type k/m/r/v/c/b/s] set response type to keyboard response/mouse response/mouse moved response/mouse up response/reply response/vtrig response/bbox response/sound response/eyelink response/activewire response Sound responses are specific to PsyScript.
    [do set right_margin right_margin] set right margin to right_margin
    [do set screen_depth depth] set screen depth to depth Only valid within an experiment.
    [do set screen_size h v ] set screen size to {h, v}
    [do set word_color color] set word color to color See additional notes on color specifications, below.
    [do set word_font font_name] set word font to font_name
    [do set word_size word_size] set word size to word_size
    [do set word_style styles] set word style to {on styles:on_styles , off styles: off_styles} See additional notes on text styles, below.
    [do set_tick_time] None. AppleScript can use the value of the tick time property directly.
    [do shuffle_file fromfile tofile [only nrsteps] [step nrlines] [into nrfiles] [pseudorandom] ] None. It is not hard to write an AppleScript routine to arrange a list of items into random order.
    [dumpstate] None. It is not hard to write an AppleScript sequence to dump out whatever information you need.
    [echo ...] None. It is not hard to write an AppleScript sequence that uses the standard file commands to write information about variables to a file.
    [float varname ...] None. AppleScript variables are dynamically-typed.
    [fn ...] No exact equivalent, but you can define an AppleScript procedure with the “on”-construct. AppleScript procedures can also return values and be used in expressions.
    [if ...] Use any appropriate form of the AppleScript if-statement. AppleScript also has looping and exception-control constructs with no ECL equivalents.
    [include ...] None. If you want to include a separately-compiled script, you can use the AppleScript “load script” command to load it into a script object.
    [integer varname ...]
    [long varname ...]
    None. AppleScript variables are dynamically-typed.
    [number varname ...] None.
    [outfmt ...] None. It is not hard to write an AppleScript sequence that uses the standard file commands to write information about variables to a file.
    [params varnamelist] None. See additional notes on defining trial fields, below.
    [prompt varname promptstring] None. You can use the standard AppleScript “display dialog” command to display a dialog with a prompt string and obtain a user response.
    [record ...] None. It is not hard to write an AppleScript sequence that uses the standard file commands to write information about variables to a file.
    [set varname expr] set varname to expr AppleScript expressions are much more powerful than those in ECL.
    [short varname ...] None. AppleScript variables are dynamically-typed.
    [string varname ...] None.
    [trial varvalue1 varvalue2 ... trialstring] do trial trialstring Only valid within an experiment. Also see additional notes on defining trial fields and template substitutions.
    [trialfields varnamelist] None. See additional notes on defining trial fields, below.

    In addition, the following predefined ECL variables have been replaced with read/write application properties in AppleScript:

    Variable NameProperty NameType
    good_responsegood responsestring
    reaction_timeRT or
    reaction time
    real
    replysubject replystring
    response_correct_idNone—no more graded responses
    response_wrong_id
    subject_responsesubject responsestring
    timeout_idgrade for timeoutstring

    Additional Notes

    Defining Trial Fields

    In ECL, you specify a list of variables for which values will be specified in each trial by using the params or trialfields command, as follows:

    [trialfields varname1 varname2 ...]

    Then the trial command specifies the values of these variables, followed by the trial string:

    [trial varvalue1 varvalue2 ... trialstring]

    In AppleScript, there is no direct equivalent to the params or trialfields command. However, you could use the given argument on the do trial command to perform general wildcard substitutions on the trial string template.

    No More Secondary & Graded Responses

    PsyScript 5.0 drops support for secondary responses, the combo response type and graded responses. Grading can be done in AppleScript, while secondary and combination responses have been superseded by the much more powerful multiple responses feature.

    Text Styles

    A text style specification takes the form of an AppleScript record with two fields, both optional: “on styles” and “off styles”. The value of each field is a list of one or more of the words plain, bold, italic, outline, shadow, underline, condensed and expanded. First the items listed in the on styles (if any) are turned on, then the ones listed in the off styles are turned off.

    Thus,

    {on styles: {bold}}

    turns on bolding without affecting the settings of the other style options, while

    {on styles: {underline}, off styles:{italic, shadow}}

    turns on underlining and turns off italic and shadow. To turn off all styles, include plain in the on styles; thus

    {on styles: {plain, condensed, shadow}}

    first turns off all styles, then turns on condensed and shadow.

    Color Specifications

    A color can be specified most generally as an “RGB color”, which is a list of three numbers:

    {red, green, blue}

    where each of red, green and blue specifies the corresponding component of the color as an integer in the range [0 .. 65535].

    For convenience, the eight “Classic QuickDraw” colors can be specified with one of the words black, yellow, magenta, red, cyan, green, blue or white. The colors that these represent are as follows:

    black{0, 0, 0}
    yellow{64512, 62333, 1327}
    magenta{62167, 2134, 34028}
    red{56683, 2242, 1698}
    cyan{577, 43860, 60159}
    green{0, 32768, 4528}
    blue{0, 0, 54272}
    white{65535, 65535, 65535}

    These words are also returned for a color property that is set to the exact corresponding color. For example, the two statements

    set word color to green

    and

    set word color to {0, 32768, 4528}

    are exactly equivalent: after executing either of them, the expression

    word color

    will return the value green.

    Folder Specifications

    A relative path is one with either no colons in it, or one with a colon at the start. If it has colons in it but doesn’t begin with a colon, then it’s an absolute path.

    If a path begins with two or more colons, then each extra colon takes you up one folder level from the current default.

    Examples:

    Enhanced Responses in PsyScript 5.0

    Multiple Responses

    New in PsyScript 5.0 is the ability to collect multiple responses from a single trial. You specify the number of responses you expect in the “responses per trial” application property, for example

    set responses per trial to 3

    specifies that subsequent trials are to collect 3 responses each. The value of “responses per trial” defaults to 1, and is automatically reset to 1 each time a “reset all” command is executed.

    The “response type” application property can now be set to a list of more than one of the available response types; this enables the collection of responses of all of the listed types at once. In PsyScript 5.1, this is reset to just “keyboard response” when a “reset all” command is executed.

    Information about multiple responses is saved as a new type of application element, called a “response”. This has the following properties:

    response type identifies the type of the response.
    RT/reaction time the time at which the response was recorded.
    label the mapping string corresponding to the particular keystroke, click area etc for the response. Also the subject reply for a reply response.
    mouse location the position of the click—only valid for mouse responses

    If the specified number of responses is not received within the specified trial duration, a response of type “timeout response” will be generated, and the trial will terminate.

    For backward compatibility, the application properties “subject response”, “subject reply” “RT/reaction time” and “mouse location” will continue to be set to the same values from the first response received. However, the use of these properties is deprecated in new code.

    Mouse-Up & Mouse-Moved Responses

    PsyScript 5.0 and later also allow the release of the mouse button, and movement of the mouse while the button is down, to be collected as responses for a trial. The AppleScript enumeration values are “mouse up response” and “mouse moved response” respectively. Note that, by default, mouse-moved responses do not count towards the responses per trial limit, but this can be controlled in PsyScript 5.1 by setting the uncounted response types property.

    There is also a new application property, “echoing mouse to screen” which allows the drawing of a line on screen tracking the mouse position as mouse-moved responses are collected.

    For example, a script like

    begin experiment

    set ScreenSize to screen size

    set bounds of click area 1 to {0, 0, item 1 of ScreenSize, item 2 of ScreenSize}

    set noticed of click area 1 to true

    set response type to {mouse response, mouse moved response, mouse up response}

    set responses per trial to 2

    set echoing mouse to screen to true

    do trial "'You have 20 seconds to draw.' !t(20000)"

    end experiment

    will collect a mouse down anywhere on the screen, followed by any number of mouse movements (drawing a line on screen following these) followed by a mouse up, waiting up to a maximum of 20 seconds after the prompt is displayed.

    The uncounted response types Property

    Beginning with PsyScript 5.1, it is possible to control the set of response types which, while still being collected in the response list, do not count towards the responses per trial limit. This is done by setting the desired set of response types as the value of the uncounted response types property. For example, if the appropriate lines of the above script were modified to

    set response type to {mouse response, mouse up response, ¬

    mouse moved response, keyboard response}

    set uncounted response types to {mouse response, ¬

    mouse up response, mouse moved response}

    then the subject could release and press the mouse button to draw any number of disjoint line segments, stopping the trial either by pressing a key, or by waiting for the 20-second time limit to elapse.

    Other PsyScript Features

    Sound Input

    PsyScript allows the use of sound input as a response type. When this is enabled, the sound input is continuously monitored during an experiment, and the moment the input level exceeds a predetermined threshold, a sound response is recognized and can be returned as the response to the experiment. It is also possible, via AppleScript, to obtain the actual sound data that was captured around the time of the response.

    All these features are controlled via the following fields of the application’s current sound property:
    mapping The mapping string to return for a sound response (analogous to mouse mapping, vtrig mapping etc).
    recording Whether to recognize sound responses or not. The initial value is false. If this property is true, then the sound input is opened when begin experiment is executed, and closed when end experiment is executed.
    response threshold The sound amplitude threshold which, when reached, indicates that a sound response has taken place. Values can range from 0 to 1 inclusive, where 1 is the maximum amplitude the sound input can record; the initial value is 0.5.
    response duration The total duration, in milliseconds, of sound data to save around the trigger point. Initially 1000.
    response pretrigger The duration, in milliseconds, of the part of the saved sound data preceding the trigger point. Initially 0. The duration of the part from the trigger point onwards is (response duration - response pretrigger) milliseconds.
    input The sound input device to use, or null to use the default input device (as selected in the “Sound” or “Monitors & Sound” control panel, depending on your MacOS version). Initially null.

    To find out what sound inputs are available on your machine, try a short script like this in the Script Editor:

    tell application "PsyScript"

    every sound input

    end tell

    and look at the list of sound input objects that appears in the result window.

    sample rate The rate, in samples per second, at which to capture sound. When opened, the sound input device will be configured to capture at the rate it supports which is closest to this value. Initially 22254.
    sample size The number of bits to store for each captured sound sample. Valid values would either be 8 or 16, depending on what your sound hardware supports. Initially 8, which is probably good enough for most sound-detection purposes.
    current source index Some sound input devices support multiple alternative “sources” that they can get sound from. For example, the built-in sound input on many Macintoshes can source sound from either an external microphone or from the internal CD audio. Where the input device supports it, this property specifies the index number of the source to use. The name of the source can be found from the corresponding element of the sound input object’s available sources property.
    automatic gain control Whether to use the sound input device’s automatic gain control facility, if it has one. Initially false.
    input gain Lets you adjust the sensitivity of the sound input device when its automatic gain control is turned off, if this facility is supported by the device.
    response data Returns the actual sound data captured when the response was detected.

    Most of these settings (except AGC, gain and sample size) can also be interactively examined and changed from the Sound Settings dialog:

    The waveform display shows a running monitor of whatever the sound input is currently picking up, which stops as soon as the threshold is exceeded. When it stops, you can use the “Listen” button to restart it, or you can drag the red guides to modify the threshold and pre-trigger, as an alternative to typing into the text fields.

    As an alternative to accessing the (unwieldy) sound response data property, you can save the sound data directly to a file with the “save sound response data to filespec” command.

    Movie Stimuli

    Movie stimuli work differently in PsyScript from RSVP. For a start, movies can be loaded as permanent stimuli (which was not allowed in RSVP 4.0.5), and movies are displayed directly within the experiment window, instead of being in their own window. Thus the “k” trial command to kill the movie window is no longer needed, or supported.

    Also, movies can be displayed at a specified position, just like picture stimuli, using the same trial syntax: “stimname(position)”.

    Finally, a new feature in PsyScript 4.5 is the ability to animate the movie along a path as it plays. You control the path from AppleScript by setting the animation path property of the permanent movie stimulus. For example, the sequence

    load permanent stimulus "PathMovie" as movie stimulus
    set animation path of permanent stimulus "PathMovie" to ¬

    {{400, 100, true}, {100, 300, true}, ¬

    {400, 500, false}, {700, 300, true}, ¬

    {400, 100, true}}

    loads a movie and sets its animation path to a closed curve with a corner at the bottom.

    Note that the presence of an animation path overrides any position you may try to specify for the movie with the “•” or “°” trial commands. To remove the animation path, set it to an empty list: “{}”.

    For a fuller description of how to specify points on a curve, see the description of the “draw curve” command in the section on Drawing Commands, below.

    Masked Picture Stimuli

    This is like a picture stimulus except it consists of up to three pictures (the mask, foreground and background), such that the mask may be dynamically moved around the screen. There is also an option (only available when loading the masked picture as a permanent stimulus) to control whether the mask is peeking through the foreground or shading out the background. A masked picture loaded as a temporary stimulus always peeks through the foreground.

    When loading a masked stimulus, the file/resource name given is used as the name of the mask picture; the name with “.fg” appended is used as the name of the optional foreground picture; and the name with “.bg” appended is used as the name of the background picture.

    When loading a masked picture as a temporary stimulus, the prefix character to use is “µ”; when loading it as a permanent stimulus, use the stimulus type “masked picture stimulus” (the use of the prefix character is not currently valid in the latter case). The load permanent stimulus command also takes an optional mask type argument, with valid values “peeking through foreground” and “shade out background”.

    When showing a masked picture, you must specify two positions: “i(old)(new)” (replace the “•” with “*” to show a temporary instead of a permanent stimulus), where each of the old and new positions may be either a position index or an explicit coordinate pair. The old position should be the same as the new position on the previous showing of this stimulus (to allow correct erasing of its previous appearance). On the first call, the value of the old position doesn’t matter.

    Alternatively, instead of an integer position index, you can use the special codes “g” and “p” to represent the current and previous EyeLink gaze positions. Thus, repeatedly issuing the trial command “n(p p)(g g)” will continuously update the position of the masked picture named n, tracking the subject’s gaze around the screen.

    The foreground and background pictures are always drawn aligned with the top-left of the screen bounds, while the mask is moved to the specified position. The following table lists the valid combinations of present and omitted picture components, mask types, and their effects:

    MaskBackgroundForegroundMask TypeEffect
    yyy peeking through foreground background, with visibility controlled by mask, appears on top of foreground
    yyy shade out background foreground, with visibility controlled by mask, appears on top of background
    yyn peeking through foreground background visibility is controlled by mask
    yyn shade out background mask is drawn on top of background
    ynn (don’t care) mask is drawn at specified position

    Drawing Commands

    PsyScript has the ability to draw simple shapes in the experiment window under AppleScript control. The following commands are available:

    draw line from start to end

    where start and end are the starting and ending coordinate positions;

    draw rectangle in bounds [corner rounding corners] filling true/false

    where bounds specifies the bounds of the rectangle, corners is the optional dimensions of the rounding to apply to the corners (if omitted, defaults to {0, 0}), and the filling argument is true to fill the rectangle, false to frame it;

    draw oval in bounds filling true/false

    where bounds specifies the bounds of the oval, and the filling argument is true to fill the oval, false to frame it;

    draw arc in bounds starting angle start arc angle arc filling true/false

    where bounds specifies the bounds of the arc, start the starting angle in degrees (clockwise from the top), arc the length of the arc in degrees, and the filling argument is true to fill the arc, false to frame it;

    draw poly {point1, point2, ...} filling true/false closing true/false

    which draws a polygon with corners at the specified points, where the filling argument is true to fill the polygon, false to frame it, and the closing argument indicates whether to join the ending point back to the starting point when framing the polygon (ignored if the polygon is being filled);

    draw curve {point1, point2, ...} filling true/false closing true/false

    which draws a quadratic Bézier curve defined by the specified control points.

    All these commands also take an optional “using settings” argument, specifying the drawing settings to use. Any omitted settings take their defaults from the “default drawing settings” application property, the initial value of which is “{pen color: black, pen size: {1, 1}}”. Color specifications conform to the usual rules.

    The bounds arguments to the above commands is a QuickDraw rectangle specifying the bounds of the shape. In AppleScript, this typically appears as a list of four coordinates, “{left, top, right, bottom}”.

    A point as specified to the draw poly command is a QuickDraw point specifying the horizontal and vertical coordinates. In AppleScript, this typically appears as a list of two integers, “{hor, vert}”.

    For the draw curve command, each point specification can be augmented by a third field, a boolean indicating whether the point is off the curve or not (if omitted, it is assumed false). The curve always passes through an “on-curve” point, while it might not pass through an “off-curve” point, though it will always try to pass near it. Two successive on-curve points define a straight-line segment. Note that an open curve cannot begin or end with an off-curve point; if you try to draw one, it will automatically be closed.

    Examples:

    set default drawing settings to {pen size:{4, 4}}

    changes the default pen size without changing the default pen color.

    draw rectangle in {100, 100, 400, 400} using {pen color:yellow} with filling

    draws a filled yellow rectangle.

    draw arc in {150, 270, 350, 370} starting angle 90 arc angle 180 ¬

    using {pen color:red, pen size:{8, 32}} without filling

    draws an arc roughly in the shape of a smiling mouth.

    draw poly {{100, 100}, {200, 100}, {100, 200}} with closing without filling

    draws a right-angled triangle.

    draw curve {{100, 100, true}, {200, 100}, {100, 200}} ¬

    using {pen color:yellow} with filling

    fills in an arc within the above right-angled triangle.

    Generation of Picture Stimuli

    PsyScript lets you create your own picture stimuli on the fly. These can also be saved to disk as standard Macintosh PICT files.

    To create a new picture stimulus, use the usual AppleScript “make” command, like this:

    make new permanent stimulus with properties ¬

    {type: picture stimulus, name: name, dimensions: dimensions, pixel depth: depth}

    where the type must always be “picture stimulus”, the name must be unique among all currently-loaded permanent stimuli (if a permanent stimulus already exists with this name, it is replaced), the dimensions specify the width and height of the image, and the depth specifies the number of bits per pixel (valid values are 1, 2, 4, 8, 16 and 32). The make command will return a reference to the newly-created object.

    For example, the command

    set ThePicture to (make new permanent stimulus with properties ¬

    {type: picture stimulus, name: "My Picture", ¬

    dimensions: {400, 300}, pixel depth: 32})

    creates a new picture stimulus named “My Picture” which is 400 pixels wide and 300 pixels high with a depth of 32 bits per pixel, and assigns a reference to the created object to the AppleScript variable “ThePicture”.

    Having created the picture stimulus, you tell PsyScript to start drawing into it by setting it as the value of the “drawing target” property, for example:

    set drawing target to ThePicture

    Now, all subsequent drawing and “do trial” commands will do their drawing into this picture stimulus (nothing will appear on-screen). Note that you do not have to have an experiment in progress in order to do this.

    Finally, you can save any permanent picture stimulus to a file with a command of the form:

    save reference output to file [if exists overwrite/leave]

    where reference is a reference to the picture stimulus, file is the filespec to which to save the picture, and the “if exists” option specifies whether to replace any existing file with the same name, or return an error if it already exists (if omitted, the default is to return an error if the file already exists). For example:

    save ThePicture output to file "My Picture" if exists overwrite

    will save the picture stimulus created in the previous example to a standard Macintosh PICT file named "My Picture", replacing any existing file with the same name. The creator code assigned to the file will be taken from your mapping entry for the PICT file type in Internet Config.

    Trial Templates

    The AppleScript do trial command supports two optional arguments: given and with wildcard. The value of the given argument is a list of strings (or, beginning with PsyScript 4.5, a record with your own field names). These will be substituted into the trial string wherever a sequence of the form “?n” or “?(n)” occurs, where n is a decimal integer (or, beginning with PsyScript 4.5, the name of one of the fields in the record), indicating the string with the corresponding index in the given list, or the field with the specified name if it is a record. The “?” escape prefix defaults to the value of the wildcard prefix application property, which in turn defaults to the question mark. This may be overridden by specifying a different wildcard character with the with wildcard argument.

    To insert a literal wildcard character, write it twice.

    Example: the command

    do trial "!w(11) 'some' '?2'(-1) text ?? with more ?1 text" given {"a", "b"}

    is equivalent to

    do trial "!w(11) 'some' 'b'(-1) text ? with more a text"

    while

    do trial "!w(11) 'some' '~2'(-1) text with more ~1 text" given {"a", "b"} with wildcard "~"

    can also be done as

    set wildcard prefix to "~"

    do trial "!w(11) 'some' '~2'(-1) text with more ~1 text" given {"a", "b"}

    except that the setting of the application property takes effect until it is changed again (or you quit PsyScript), while the effect of the with wildcard argument only applies to its corresponding do trial command.

    Note that it is valid to specify a list as the actual value of a template argument; the list items will be concatenated into a string with spaces in-between. Example:

    do trial "'hello'(?location)" given {location:{300, 500}}

    is equivalent to

    do trial "'hello'(300 500)"

    Serial and Other I/O

    PsyScript allows you to open serial ports and perform I/O on them. Note this has been reworked and generalized in PsyScript 4.6, replacing the mechanism in earlier versions of PsyScript for opening a single serial port at a time.

    Connection Objects

    PsyScript 4.6 supports the notion of connection objects, of which you can have as many open at once as your hardware will allow.

    To open a new connection, use the following AppleScript sequence:

    make new connection with properties {name:name, ¬

    device type:type, device name:devname}

    This will create a new connection named name (which must be unique among all currently-open connections) and return a reference to it as the expression result. device type indicates the type of device to open: currently-supported values are serial device and activewire device. device name is something whose meaning depends on the device type; for serial devices, it is the name of the serial port to open. To check what ports are actually available, try a short script like this in the Script Editor:

    tell application "PsyScript"

    name of every serial port

    end tell

    and look at the list of port names that appears in the result window.

    Example:

    set TheConnection to

    make new connection with properties {name:"testconn", ¬

    device type:serial device, device name:"Modem Port"})

    opens a connection on the serial port named “Modem Port” and stores a reference to the new connection in the AppleScript variable TheConnection.

    An open connection can be closed using the close command, for example

    close connection "testconn"

    close TheConnection

    close every connection whose device type is serial device

    Also, PsyScript will automatically close any open connections when it quits.

    The settings property of a connection object allows you to examine and possibly change various device-specific connection settings. This is a record with fields that depend on the device type. For serial ports, these fields, all of which can be both examined and changed, are as follows:

    Two other useful properties of the connection object are available data, which returns the number of bytes of data which can be read immediately without blocking, and data read, which is used to hold data read on this connection with the “!ci” trial command (see below).

    I/O in AppleScript

    Once a connection has been opened, you can write to it (if the connection permits writing) using the write command, and read from it (if the connection permits reading) using the read command. Serial ports support both writing and reading.

    The write command takes the form

    write data to connection [waiting timeout]

    where connection is a reference to the connection to write to, data is the data to be written (typically a text string), and timeout is an optional maximum time in milliseconds to wait for the write to complete. If timeout is omitted, the command waits until the bytes are written, however long that takes.

    The read command takes the form

    read from connection for nrbytes [waiting timeout] [as type]

    where connection is a reference to the connection to read from, nrbytes specifies the number of bytes to read, timeout is an optional maximum time in milliseconds to wait for the read to complete, and type specifies the type in which the returned data will be represented (if omitted, defaults to a text string). The data read is returned as the result of the command. If timeout is omitted, the command waits until the specified number of bytes is read, however long that takes.

    Tip: if an I/O operation is taking too long, it can be aborted by hitting command-dot while PsyScript is frontmost. (Note that if you hit command-dot while the script is frontmost, or if the AppleEvent times out, the script will abort, but PsyScript will continue with the I/O operation. However, you can still switch PsyScript to the front and hit command-dot there to abort the operation. If you try to start another operation on the same connection while the previous one is still in progress, you will get an error indicating the connection is busy.)

    I/O in Trial Strings

    In trial strings, you use the “!co” command to write data on a connection, and “!ci” to read data from a connection.

    The “!co” command takes the form

    !co(name data)

    where name is the name of the connection, and data is the text string to write to the connection. For example,

    !co(testconn hello)

    The “!ci command takes one of the forms

    !ci(name nrbytes timeout)

    !ci(name nrbytes)

    !ci(name)

    where name is the name of the connection, nrbytes is the number of bytes to read, and timeout is the maximum amount of time in milliseconds to wait for the read to complete. If timeout is omitted, the command will wait indefinitely, and if nrbytes is omitted, the number of bytes read will be the current value of the available data property for the connection.

    All the data read with the “!ci command accumulates in the data read property of the connection, as a list of integer byte codes.

    Reported-Time Messages

    Every time you use the comment form of the report-time event “!r(comment)” in a trial string, the comment, together with the current time, is appended as a new element of the application’s reported time property. This is a list of strings, which is reset to the empty list when the experiment ends.

    Bit Manipulations & Base Conversions

    PsyScript includes a set of commands for doing bit manipulations on integers (“bitand”, “bitor” and “bitnot”) and converting integers from one base to another (“convert base”).

    bitand” and “bitor” take a list of one or more unsigned integers and respectively return the logical-and and the logical-or of those integers. “bitnot” takes a single unsigned integer and returns its logical negation. For example, the expression “bitand {3840, 960}“ returns the value 768, while the expression “bitor {3840, 960}“ returns the value 4032.

    The “convert base” command converts a list of unsigned integers from one base to another; call it from PsyScript as follows:

    convert base value [from frombase] [to tobase] [minimum digits digits]

    where value is the list of integers to be converted (as either AppleScript integers or strings), frombase is the base in which to interpret the digits of value if it is a string (if omitted, defaults to 10), tobase is the base to which to convert the value (if omitted, defaults to 10), and digits is the minimum number of digits to produce, including leading zeroes if necessary, if the result is a string (if omitted, the default is 1). If tobase is 10 and digits is 1, the result is a list of AppleScript integers. Otherwise, the result is a list of strings consisting of digits representing the integer in the specified base.

    Valid values for frombase and tobase are the integers from 2 to 36 inclusive. For bases greater than 10, the additional digits are represented by the letters from A to Z.

    Examples:
    Expression Result
    convert base 54321 to 16 "D431"
    convert base "D431" to 16 54321
    convert base {"707", "51"} from 8 to 2 minimum digits 12 {"000111000111", "000000101001"}
    convert base (9 * 6) to 13 "42"

    Changed Trial Commands

    Some RSVP trial commands have been changed in PsyScript, to make things more systematic and provide a basis for expandability in the future:

    RSVP Command PsyScript Equivalent Meaning
    !b #b wait for keyboard input
    !x #x wait for BBox input
    !i !ox set BBox line on/off

    The general rules are:

    In each case, the above sequence may be followed by further syntax specific to the extension. Not all functions may be available with a particular extension. Currently defined extensions, and the functions they support, are as follows:

    Letter Description Command
    !xx
    Wait
    #x
    Input
    !ix
    Output
    !ox
    a ActiveWire    
    b keyboard      
    i Eyelink    
    m millisecond timer      
    s serial I/O        
    x BBox    

    EyeLink Support

    PsyScript includes support for the EyeLink eye-tracker device from SensoMotoric Instruments. This allows tracking the gaze of the observer as they watch stimuli on the screen. Particularly useful with this is the masked picture stimulus type. PsyScript 4.5 also adds support for an Eyelink response type.

    Using the EyeLink with PsyScript

    Before you can use the EyeLink in an experiment, you must include the following call near the start of your script:

    initialize eyelink [with dummy open]

    The “with dummy open” option tells PsyScript 5.1d2 or later to simulate EyeLink data using the mouse, which can be used in the absence of an actual EyeLink device. In this mode, the mouse position simulates where the subject is supposedly looking, while a mouse click simulates a fixation.

    You can close the EyeLink interface with the “close eyelink” command; this is particularly useful in dummy mode, to restore normal mouse behaviour. Otherwise, the EyeLink is automatically closed when you quit PsyScript.

    You can send an arbitrary command to the EyeLink device with the AppleScript command

    send eyelink command command

    For example, to open an EDF data file for recording, you could use a command like

    send eyelink command "open_data_file filename"

    For additional commands you can use to set the calibration type, control filtering parameters and so on, see the EyeLink documentation.

    To record a custom text message in the data file, use

    send eyelink message message

    This message will appear during subsequent display of the contents of the file.

    The command

    do tracker setup

    brings up the setup screen on the EyeLink—note this must be done within a begin experiment/end experiment pair. When you select a camera display on the EyeLink, the same display will also appear on the Macintosh screen.

    To calibrate the EyeLink positioning system, use the command

    do drift correct [at position] [with drawing]

    where drawing indicates whether to draw a fixation marker (using the background color specified by the “eyelink target background color” property)—if omitted, the default is false, which means you must be doing your own separate drawing. position is the optional coordinates at which to draw the fixation marker—if omitted, this defaults to the center of the screen.

    To start recording EyeLink sample and event data into the data file, use the command

    start eyelink recording [with file samples] [with file events] [with link samples] [with link events]

    where the arguments indicate the types of data to record—at least one must be true.

    stop eyelink recording

    stops recording sample and event data on the EyeLink.

    set eyelink offline

    puts the EyeLink into “offline” mode. This is recommended before trying to send commands to draw on its screen, or retrieve a data file.

    To replay the last-recorded samples and events, use the command

    eyelink replay

    Note this must be done within a begin experiment/end experiment pair, and before the current EyeLink data file is closed. It will draw a series of lines onto the screen, connecting successive gaze positions, with a fixation symbol displayed at each fixation point.

    This command also rebuilds the list of EyeLink sample and event objects.

    Beginning with PsyScript 5.1d3, the display produced by eyelink replay is controlled by the value of the “current eyelink replay” application property. This is a record with the following fields:

    EyeLink Sample and Event Objects

    PsyScript defines “eyelink sample” and ”eyelink event” objects, which are elements of the application object. These are only valid after the eyelink replay command has been invoked.

    Both kinds of objects have a “timestamp” property, which is in milliseconds with a base defined by the EyeLink clock. They also have “coordinates” and “pupil size” properties. In addition, EyeLink events have an “event type” property, following the integer encoding defined in the eye_data.h interface file. For example, the value 8 denotes an end-fixation event. All properties are read-only.

    These objects may be queried in normal AppleScript fashion. For example,

    tell application "PsyScript"

    timestamp of every eyelink event whose event type = 8

    end tell

    will return a list of event times for end-fixation events.

    EyeLink Access in Trial Strings

    The following commands are available to manipulate the Eyelink device directly from within a trial string:

    EyeLink Responses

    PsyScript 4.5 added “eyelink response” to the available response types. Such a response is triggered by pressing one of the buttons on the Eyelink device.

    Configuration of this response type is done by manipulating the “eyelink button” application elements; there are 16 of these, corresponding to the Eyelink buttons. Each one has a “noticed” and a “mapping” property; set the former to true to recognize presses of that button, and set the latter to a nonempty string to be returned as the subject response when the button is pressed.

    ActiveWire Support

    PsyScript includes support for the ActiveWire USB interface card. This has 16 data pins, each of which may be independently configured as an input or an output. The driver interface allows each input pin to be polled, and each output pin to be set on or off.

    Using the ActiveWire with PsyScript

    Before you can use any of the ActiveWire features, you must open the ActiveWire device. To do this, use the AppleScript command

    initialize activewire

    (There is no command to close the ActiveWire device; this happens automatically when PsyScript quits.) Having done this, you can access the ActiveWire interface via two different AppleScript objects in PsyScript : the “current activewire” application property, and the “activewire pin” application element.

    The “current activewire” application property is a record of two fields: “direction” lets you configure the configure the direction (input or output) of each pin, while “data” lets you read the current input pin settings or write the output pin settings. In order to make sense of the values of these settings, you will need the following table:

    Pin Number Element Index Mask
    8 1 1
    9 2 2
    10 3 4
    11 4 8
    12 5 16
    13 6 32
    14 7 64
    15 8 128
    0 9 256
    1 10 512
    2 11 1024
    3 12 2048
    4 13 4096
    5 14 8192
    6 15 16384
    7 16 32768

    In this table, “Pin Number” refers to the numbering of the data pins according to the ActiveWire documentation, while “Element Index” refers to the index of the corresponding “activewire pin” application element in AppleScript. The latter are numbered from 1, not 0, because this is the way AppleScript prefers to do things.

    The “Mask” column gives the corresponding mask value. To construct a mask representing a given set of pins, either add together the masks for the individual pins, or combine them with bitor. You may notice that the bytes are swapped: this is because of the way the ActiveWire library code orders the bytes.

    Configuring the directions of the pins can be done in two ways: individually via the “activewire pin” objects, or all at once via the “direction of current activewire” property. For example, to set pins 6, 7 and 8 as output and the rest as inputs, you could use either

    tell application "PsyScript "

    set direction out of every activewire pin to false

    set direction out of activewire pin 6 to true

    set direction out of activewire pin 7 to true

    set direction out of activewire pin 8 to true

    end tell

    or

    tell application "PsyScript "

    set direction of current activewire to bitor {32, 64, 128}

    end tell

    Having configured the pin directions, you can read the state of all input pins simultaneously with the AppleScript expression “data of current activewire”. To set the state of the output pins, use a command like

    set data of current activewire to mask

    where mask is constructed from the masks of the output pins which you want to set to the on state.

    activewire pin” objects have two more properties: “noticed” and “mapping”. These are used to support ActiveWire input as a response type. To use these, set the response type PsyScript application property to activewire response, and set the noticed property of the desired pins to true (first making sure to configure them as input pins). Also set the mapping property of those pins to the appropriate strings you want returned as the value of the subject response when those pins are triggered.

    Tip: once an input pin is set on, it stays on until explicitly set to off. Depending on the hardware you have connected to the pin, this may not be an issue. But if it is, you may be able to clear the state of an input pin to off by changing it to an output pin and back to an input again.

    ActiveWire Access in Trial Strings

    The following commands are available to manipulate the ActiveWire device directly from within a trial string:

    Other New Trial Commands

    Asynchronous Stimulus Playback

    This feature is new with PsyScript 4.6d3, and works with sound and movie stimuli. To invoke it, use the “‡” character (option-shift-7 on the Mac Roman keyboard) instead of “*” to play a temporary stimulus asynchronously, and use the “°” character (option-shift-8 on the Mac Roman keyboard) instead of “•” (option-8) to play a permanent stimulus asynchronously. When you do this, PsyScript will continue executing the rest of the trial string while the stimulus continues playing.

    Last Wait Time and Pause Events

    The “#” (pause) trial command supports the following options:

    Waiting for Specified Numbers of Screen Refreshes

    The “!v” (wait for vertical refresh) trial command has been enhanced in PsyScript with the option to specify the number of refresh intervals that must elapsed before continuing. The new variant takes the form “!vn”, where n is an integer specifying the number of refresh intervals. The old form, “!v”, continues to be valid, and is equivalent to “!v1”.

    Additional Features

    The Script Menu

    This menu contains a list of AppleScript scripts which can be executed by selecting them from the menu. It is built from the contents of the folder named “Scripts” in the same folder as the PsyScript application. Any subfolders within this “Scripts” folder will be represented as submenus within the Script menu. Note that each menu and submenu is restricted to 31 items.

    Tips

    Enumerations Are Not Strings

    Where the AppleScript syntax lists a number of alternative words or phrases as the permissible values, you must use one of those words or phrases as is, without quotation marks and without abbreviating. Thus:

    set word alignment to left aligned -- correct

    set word alignment to "left aligned" -- incorrect

    Contrast this with ECL, where enumerations are specified with literal strings, typically only the first character is significant, and quote marks are optional since expressions are not allowed in those contexts. Thus:

    [do set justify l]

    Error Handling Without Aborting the Current Experiment

    As a safety feature, PsyScript always performs an implicit end experiment command on any error from executing an AppleEvent. This is to try to avoid the situation where the currently-running script has terminated with an error, but your machine remains apparently frozen with PsyScript still in full-screen mode.

    This should not cause any problems using any of PsyScript’s own scripting commands. However, some scripting additions (“OSAXes”) may be designed to return errors in common, normal-use situations. This necessitates the use of an AppleScript try ... end try block to recover from the error. But if the OSAX is executed within PsyScript’s application context, it will still abort the experiment. For example:

    tell application "PsyScript"

    ...

    try

    ...

    OSAX command which can fail

    ...

    on error

    ...

    end try

    ...

    end tell

    In this situation, the script may be able to recover from the error and continue, but PsyScript will still see the error and abort the experiment.

    To prevent this, invoke the OSAX outside the tell-block:

    tell application "PsyScript"

    ...

    end tell

    try

    ...

    OSAX command which can fail

    ...

    on error

    ...

    end try

    tell application "PsyScript"

    ...

    end tell

    Now PsyScript will not see the error returned from the OSAX, so the experiment will keep on running.

    Refer to Permanent Stimuli by Name

    Using names to refer to permanent stimuli in the “•” trial command is faster in PsyScript than using indexes. This is because the permanent stimuli are stored in a dynamically-sized hash table keyed on the name, instead of a fixed-size array accessed by index. This means that it is possible to selectively delete particular stimuli, for example

    delete permanent stimulus "FixationPicture"

    delete every permanent stimulus whose type is movie stimulus

    instead of having to delete them all and start again.

    However, this does mean that the indexes of the remaining stimuli are liable to change in unexpected ways, depending on the order in which the stimuli were loaded. Thus, it is recommended that you always refer to permanent stimuli by name, never by index.

    Created by Lawrence D’Oliveiro 1998 June 23, last modified 2002 July 19.
    MACCS PsyScriptIcon.png Documentation Downloads FAQ Mailing List
    Last change:
    Advanced Search

    Applescript in a Nutshell : A Desktop Quick Reference

    AppleScript for Applications: Visual QuickStart Guide

    AppleScript For Dummies

    Applescript for the Internet Visual Quickstart Guide

    Applescript Language Guide; English Dialect

    Danny Goodman's Applescript Handbook