Hello,
I am currently developing an experiment on Pavlovia using PsychoJS. I would like to extract a set of numbers that represent indices in a list of stimuli. While testing my experiment locally, I created a Python code component that worked:
import numpy as np
# Generate random sample
selected_rows = np.random.choice(range(0, 5), 5, replace=False) # Non-repeating sample
selected_rows_str = ','.join(map(str, selected_rows)) # Convert to string
However, the JavaScript version does not work. I saw on previous forums that this is likely due to using NumPy, so I tried creating a JS version to do this randomly:
let indices = [...Array(20).keys()]; // Creates an array [0, 1, 2, 3, 4]
// Shuffle the array randomly (Fisher-Yates shuffle)
for (let i = indices.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1));
[indices[i], indices[j]] = [indices[j], indices[i]];
}
// Select the first 5 elements (guaranteed unique)
let selectedRows = indices.slice(0, 5);
// Convert to a comma-separated string
let selected_rows_str = selectedRows.join(',');
But it still doesn’t work, and the experiment fails to initialize. I am unsure how to proceed. Any help would be greatly appreciated.
Thanks in advance!
Please could you clarify what you are trying to do? I assume it is more complicated that present trials 0 to 4 in a random order.
I have stimulus combinations consisting of images and sounds, which are stored in a large Excel file (2000 items). I want to randomly present 5 of these stimuli in each trial.
Locally, I created this Python code, which worked, and in my trial, I specified the list of indices; otherwise, it would play all the items from the Excel file.
The goal is to randomly select a small number of stimulus combinations from this dataset. If there is another possible strategy to achieve this, I would be open to trying it.
The easiest way to present 5 random trials from your spreadsheet is to leave Selected rows blank and then put the following code in End Routine
if trials.thisN == 4:
trials.finished = True
1 Like
Thanks , the experiment loaded but I have this error now.
Where did you put the code? It should be in an End Routine (or Begin Routine) tab of a code component inside your trials loop.
That is the correct routine.
I recommend putting code components at the top, but that isn’t important in this case.
In the code component, which tab did you use?
I don’t know what do you
I put it in a End Routine tab
Do you get the TypeError if you run the experiment in an incognito tab?
If so, then I suspect you are using trials for something else as well. Do you mention trials in any other code components?
1 Like
I moved it to the begin routine and it work !! Thank for the answer 