| Reference | Downloads | Github

Import functions create problems for Pavlovia

URL of experiment:

Description of the problem:
I have a color working memory experiment that works just fine on PsychoPy. To code it up, I have an initExperiment routine at the beginning, in which I added codes to specify conditions. For those codes to work, I had to insert import a few things under “Begin Experiment”:

import random
import math
import numpy as np

These are necessary for my condition set up that involves a lot of array manipulations. Although the script runs well in PsychoPy, it does not run on Pavlovia. Instead, it gets stuck on initiating experiment…

In the HTML console, the error message says
SyntaxError: import declarations may only appear at top level of a module

The lines that cause the SyntaxError are those import lines. If I eliminate them, PsychoPy simply would not run. It seems that those lines need to go to the beginning of the experiment, but I if I manually edit this, I lose the Builder’s JS conversion function.

Any advice on how to create codes (import) that run in PsychoPy but don’t break Pavlovia?

Unfortunately importing python libraries like that in JS is just not possible. There are a restricted set of libraries available to PsychoJS, and custom import statements are simply calling on things that don’t exist.

Now, you may be able to use other tools that come with JavaScript to emulate the same behavior, without those import statements. JavaScript has a native Math library, and it has randomization. I’m not sure why you need numpy specifically, but check out this thread and see if it helps: Converting python to JS - NumPy and and random.normal function

1 Like

Do you have suggestions for built-in packages that won’t need to be imported? I used numpy to create an integer array that can then be shuffled. Array can do th same (but more clunky than numpy), but then I have to import array. I imported math to do a simple round up (ceil) function. What are good alternatives to these? If I simply specify a list with integers (e.g., x = [1,2,3]), I am unable to randomize it (e.g., shuffle(x) would not work, neither can I index the content properly with, e.g., x[0]).

Integer arrays are easy to make in JavaScript. You can just write

var exampleArr = [1,2,3,4];

For rounding up, Math.ceil is built in to JavaScript itself (all of the Math.[function] things are), you can call it freely.

For shuffle, you can create your own:

  var currentIndex = array.length, temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;

  return array;