Initial commit

This commit is contained in:
Kasiaaaaaa committed 2026-09-22 11:52:03 +02:00
commit d89b82be4a
103 files changed
+23110

No files matched your search

+16
View File
@@ -0,0 +1,16 @@
stimuli_store/
results/
tmp/
logs/
tmp2/
logs/
other/
.DS_Store
*.wav
*.pyc
genPythonCode.py
*.xar
*.xml
*.pml
*.mp3
*.MTSq
+162
View File
@@ -0,0 +1,162 @@
<img src="https://github.com/egaudrain/PICKA/raw/master/Resources/images/html/PICKA-3-600dpi.png" width="150">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <img src="https://github.com/egaudrain/PICKA/raw/master/Resources/images/html/rug.png" height="50">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <img src="https://github.com/egaudrain/PICKA/raw/master/Resources/images/html/umcg.png" height="55">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
<img src="./html/nao_sayingvvvv.png" height="150">
# PICKA – Perception of Indexical Cues in Kids and Adults
PICKA is a test battery developed by the University Medical Center Groningen to evaluate the development of the perception of indexical cues through childhood.
## Requirements
The following requirements are necessary for both PyWORLD and naoqi to run
- python 2.7.10+
+ __Note:__ naoqi is not yet comaptible with python 3
- Linux (Ubuntu 14.04 or 16.04) or Mac OS (appears to work up to Catalina - further testing may still be required)
+ __Note:__ Although naoqi can run on Windows, PyWORLD is not compatible with python 2.7+ on Windows, only python 3+
- naoqi (currently tested and working on version 2.5.5)
+ Can be downloaded from <a href="https://community.ald.softbankrobotics.com/en/resources/software/language/en-gb">SoftBank Robotics Community Website</a>
+ __Note:__ This requires you to have a SoftBank Robotics account to access
+ __Note:__ naoqi cannot be installed with PyPi (i.e. pip)
+ Installation instructions for python SDK can be found in the <a href="http://doc.aldebaran.com/2-5/dev/python/install_guide.html">SoftBank Robotics Documentation</a>
## Installation
Run the requirements.txt file to install the necessary python packages. The package that generates the stimuli is WORLD, which is python wrapped with PyWORLD. This can cause some difficulties when installing. If installing directly from pip doesn't work, see the <a href="https://github.com/JeremyCCHsu/Python-Wrapper-for-World-Vocoder">PyWORLD Github page</a>.
```
$ pip install -r requirements.txt
```
## Running PICKA on Nao
### Webserver
The webserver that runs the experiments can be started using the `app.py` script in the `www/` by simply running `python app.py`. The website can then be accessed by going to `http://[IP of either Nao or laptop]:5000`. The specific game can then be selected. A pop-up box will then open where the participant information can be filled in. This will then check if the participant already has a file assigned to them, or if a new one should be created.
The following data is requred for the pop-up box:
- Participant ID following the template: `[NH|CI|HI][A|K][000]`, that is a description of the group (in capitals, normal hearing: `NH`, hearing-impaired: `HI` or cochlear implant: `CI`), immediately followed by the age group (`A` for adults and `K` for kids), and finally the subject number as a 3-digit zero-padded number. Here are a few examples:
- `NHA001`
- `CIK123`
- Phase of the experiment (training or test)
- Language the experiment should be conducted in (English or Dutch)
### Without webserver
The experiment can also be run by executing the `picka.py` file with python from a terminal session on Nao. The file takes multiple arguments to run. Required arguments are game, subject, phase, language, ip, and port.
```
$ python picka.py --help
usage: picka.py [-h] [-ip IPADRESS] [-pp PORT] -g {gender,fishy} [--version]
-s SUBJECT -p PHASE -l {EN,NL}
The main script used to run SAM
optional arguments:
-h, --help show this help message and exit
-ip IPADRESS, --ipadress IPADRESS
The ipadress of SAM.
-pp PORT, --port PORT
Port that SAM has open for connection.
-g {gender,fishy}, --game {gender,fishy}
The game for the current experiment.
--version Displays current version
-s SUBJECT, --subject SUBJECT
Name of the subject perfomring the test.
-p PHASE, --phase PHASE
Phase of testing. Test or training
-l {EN,NL}, --lang {EN,NL}
Language in which experiment should be conducted.
Written by Luke Meyer <l.meyer.5@student.rug.nl>, adapted from MATLAB script by Etienne Gaudrain <etienne.gaudrain@cnrs.fr>
Copyright 2017 CNRS (FR), UMCG (NL)
```
The naming convention for participant ID must be kept identical to that for the webserver.
If a participant already exists, you will receive a message in the terminal console, as well as asking if you want to continue with the selected file. If the file does not exist, you will be asked if you want to create it. It should also be checked here if the correct ID format has been followed.
## Experiments
The current version of PICKA on a Nao humanoid robot contains 4 experiments:
- **fishy**: an adaptive tracking of the just-noticeable-difference for F0 and VTL (see [details](Experiments/fishy/README.md)).
- **gender**: subjective categorisation of gender based on F0 anf VTL vocal cues (see [details](Experiments/gender/README.md))
- **emotion**: classification of emotion based on a presented voice (see [details](Experiments/emotion/README.md))
- **speech-on-speech**: speech-on-speech perception based on the coordinate response method (see [details](Experiments/crm/README.md))
## Results files
Each experiment is storing its own results in the form of a single MAT file per subject. These files are located in the `results` folder, and should not be renamed or deleted. You should make a backup of these files regularly, preferably at the end of each testing session.
**Renaming the file has no effect on the subject name!** See the section "Ensuring data consistency" for more details.
### Export formats
<!-- Each experiment folder contains an `export_results` script. With that script you can export results in one format: JSON. -->
There is a `createJson.py` script that will export the results value of the experiment into JSON.
<!-- TODO Add these at some point SQLite, CSV or XLS -->
<!-- __SQLite__ is a database format based on SQL that is ubiquitous on all systems nowadays. It is easy to import results in R, Python, or any modern data manipulation software. All data is exported into SQLite before being converted into another format. To view an SQLite file, you can use, e.g. Valentina Studio. -->
__CSV__ is comma separated values. It is widely recognized, including by Excel, R and Python. (Note that non-English Excel can sometimes struggle CSV files when the decimal separation symbol is a comma. In that case, LibreOffice provides a more reliable way of opening CSV files for visual inspection.)
<!--
__XLS__ files are provided here only for convenience. Remember that the data is not supposed to be manipulated manually, so only use Excel for visualisation. -->
__JSON__ stands for “JavaScript Object Notation”, It’s used to store and exchange data as an alternative solution for XML. JSON is easier to parse, quicker to read and write. JSON sytnax is based on JavaScript Object Literals, But it’s a text format.
### Ensuring data consistency
The experiments are coded in a way that prevents data to be overwritten or lost. If an experiment crashes in the middle, restarting it with the same participant ID will continue where it stopped. This ensures the robustness of the data collection, but has two downsides:
- The participant ID is extremely important. If there is a mix up, e.g. if participant John Doe is tested on day 1 with ID `nl_NHA003` but on day 2 with ID `nl_NHA008`, the experiment will either restart from the beginning; or if `nl_NHA008` already existed and had started the experiment, the data will get mixed in the result file with no way of knowing which one belong to which one apart from the date and time of testing. **So it is imperative to keep a lab book and an up to date list of the link between ID and name.** Also, it means that merely renaming the file will not solve the problem. The participant ID is stored in the file as well as in the filename. **Don't rename the files!**
- The result file contains all the options, which makes it self reliable, and prevents option details to be lost. However, if the option file (`expe_build_conditions.py`) is modified during the experiment, the options for all the participants who had started before that will remain unchanged. What we gain in robustness, we lose in flexibility.
## Calibration
Calibration is an important part of any psychophysical experiment, especially when a population with hearing deficiencies is tested. The calibration procedure not only ensures that the experiment is repeatable, but also that the presentation level is appropriate for the listeners taking part in the experiment.
For PICKA, the aim of the calibration is that all stimuli are presented at a sound pressure level of __70 dB(A)__. This level ensures audibility in normal hearing listeners, as well as hearing impaired listeners using a prosthetic device.
Calibration is easiest done locally on the Nao robot by using ssh.
```
$ ssh nao@[Nao IP address]
Password: nao
```
You can then navigate to `~/pyworld-test/pyworld-0.2.8/`. The file `sam_calibration.py` can then be run.
Then, take the following steps:
1. Set the volume on the Nao robot to __75__ by navigating to the robot's home page (enter the IP address into a web browser).
2. Run the `sam_calibration.py` file passing in a language parameter i.e.
```
$ python sam_calibration.py EN
```
- This will generate a single `calibration.wav`file in the current directory made up of a random selection of previously generated files in the `./tmp/` folder.
1. Measure the sound level from a KEMAR attached to a sound level meter.
2. Adjust the gain field so reach a level of 70 dB(A). Larger values will attenuate the sound where 0 is no attenuation. This value can be changed in the `expe_build_conditions.py` file under the variable `options["attenuation_dB"]`.
## Folder tree
Here's a description of the content of the PICKA folder:
- `Python_scripts` contains all the python scripts relevant to running the just noticeable difference experiment on the Nao robot.
+ `logs` contains logging files. This includes files that track the time for generation of the stimuli files, tracking of the adaptive procedure, and general logging of information and warnings
+ `pyworld` contains the `pyworld.so` (may need to be regenerated upon installing - see able for PYWORLD Github) and the `pyworld.pyx` files used to communicate with WORLD.
+ `results` contains the `.mat` and `.json` files for each of the participants
+ `stimuli` contains the sound files used for the experiment. This is further subdivided into the two language directories `en` and `nl`.
+ `stimuli_store` contains the `.mat` files containing the data of the stimuli files in `./stimlui`
+ `tmp` contains the cache of generated files using PyWORLD
+772
View File
@@ -0,0 +1,772 @@
# --------------------------------------------------------------------------
# Authors:
# 2017-03-06: Thirsa
# 2020-01-28: Luke Meyer < l.meyer.5@student.rug.nl >
# Copyright MRC-CBSU(UK), CNRS(FR), UMCG(NL) and the author(s).
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY
# without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see < http: // www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
from naoqi import ALProxy
import random
import math
import time
import paramiko
import sys
import tools.settings as settings
import qi
class Robot(object):
def __init__(self, IPADRESS, PORT, LANG, SUBJECT):
self.language = LANG
self.ipadress = str(IPADRESS)
# port = 54011
self.port = int(PORT)
self.subject = SUBJECT
# self.speaking_volume = 65
# self.stimulus_volume = 75
self.speaking_volume = 40
self.stimulus_volume = 45
self.say_0 = ''
self.say_1 = ''
self.say_2 = ''
self.say_3 = ''
self.say_4 = ''
self.say_5 = ''
self.encouragement_pos = []
self.encouragement_neg = []
self.hips = ["LHipYawPitch", "RHipYawPitch", "LHipPitch", "RHipPitch"]
from naoqi import ALProxy
self.mtn = ALProxy("ALMotion", self.ipadress, self.port)
self.tts = ALProxy("ALTextToSpeech", self.ipadress, self.port)
self.mem = ALProxy("ALMemory", self.ipadress, self.port)
self.pst = ALProxy("ALRobotPosture", self.ipadress, self.port)
self.aas = ALProxy("ALAnimatedSpeech", self.ipadress, self.port)
self.aap = ALProxy("ALAudioPlayer", self.ipadress, self.port)
self.aad = ALProxy("ALAudioDevice", self.ipadress, self.port)
self.all = ALProxy("ALLeds", self.ipadress, self.port)
self.asr = ALProxy("ALSpeechRecognition", self.ipadress, self.port)
self.bms = ALProxy("ALBehaviorManager", self.ipadress, self.port)
self.aad.setOutputVolume(self.speaking_volume)
if self.language == 'EN':
self.tts.setLanguage("English")
elif self.language == 'NL':
self.tts.setLanguage("Dutch")
# Only work when connecting to an actual robot. Does not work with a virtual robot.
# self.afr = ALProxy("ALFaceDetection",self.ipadress,self.port)
def buiging(self):
'''
Choregraphe bezier export in Python.
Bowing gesture
'''
self.mtn.wakeUp()
names = list()
times = list()
keys = list()
names.append("HeadPitch")
times.append([0.6, 1.84, 3])
keys.append([[-0.159578, [3, -0.2, 0], [3, 0.413333, 0]],
[-0.116626, [3, -0.413333, 0], [3, 0.386667, 0]],
[-0.159578, [3, -0.386667, 0], [3, 0, 0]]])
names.append("HeadYaw")
times.append([0.6, 1.84, 3])
keys.append([[-0.0123138, [3, -0.2, 0], [3, 0.413333, 0]],
[-0.0123138, [3, -0.413333, 0], [3, 0.386667, 0]],
[-0.0123138, [3, -0.386667, 0], [3, 0, 0]]])
names.append("LAnklePitch")
times.append([0.6, 1.84, 3])
keys.append([[0.0904641, [3, -0.2, 0], [3, 0.413333, 0]],
[0.115008, [3, -0.413333, 0], [3, 0.386667, 0]],
[0.0904641, [3, -0.386667, 0], [3, 0, 0]]])
names.append("LAnkleRoll")
times.append([0.6, 1.84, 3])
keys.append([[-0.12728, [3, -0.2, 0], [3, 0.413333, 0]],
[-0.151824, [3, -0.413333, 0], [3, 0.386667, 0]],
[-0.12728, [3, -0.386667, 0], [3, 0, 0]]])
names.append("LElbowRoll")
times.append([0.6, 1.84, 3])
keys.append([[-0.45709, [3, -0.2, 0], [3, 0.413333, 0]],
[-1.50481, [3, -0.413333, 0], [3, 0.386667, 0]],
[-0.45709, [3, -0.386667, 0], [3, 0, 0]]])
names.append("LElbowYaw")
times.append([0.6, 1.84, 3])
keys.append([[-1.15054, [3, -0.2, 0], [3, 0.413333, 0]],
[-0.529273, [3, -0.413333, 0], [3, 0.386667, 0]],
[-1.15054, [3, -0.386667, 0], [3, 0, 0]]])
names.append("LHand")
times.append([0.6, 1.84, 3])
keys.append([[0.2832, [3, -0.2, 0], [3, 0.413333, 0]],
[0.2832, [3, -0.413333, 0], [3, 0.386667, 0]],
[0.2832, [3, -0.386667, 0], [3, 0, 0]]])
names.append("LHipPitch")
times.append([0.6, 1.84, 3])
keys.append([[0.131966, [3, -0.2, 0], [3, 0.413333, 0]],
[-0.363515, [3, -0.413333, 0], [3, 0.386667, 0]],
[0.131966, [3, -0.386667, 0], [3, 0, 0]]])
names.append("LHipRoll")
times.append([0.6, 1.84, 3])
keys.append([[0.107422, [3, -0.2, 0], [3, 0.413333, 0]],
[0.0951499, [3, -0.413333, 0], [3, 0.386667, 0]],
[0.107422, [3, -0.386667, 0], [3, 0, 0]]])
names.append("LHipYawPitch")
times.append([0.6, 1.84, 3])
keys.append([[-0.162562, [3, -0.2, 0], [3, 0.413333, 0]],
[-0.25767, [3, -0.413333, 0], [3, 0.386667, 0]],
[-0.162562, [3, -0.386667, 0], [3, 0, 0]]])
names.append("LKneePitch")
times.append([0.6, 1.84, 3])
keys.append([[-0.0844118, [3, -0.2, 0], [3, 0.413333, 0]],
[-0.0844118, [3, -0.413333, 0], [3, 0.386667, 0]],
[-0.0844118, [3, -0.386667, 0], [3, 0, 0]]])
names.append("LShoulderPitch")
times.append([0.6, 1.84, 3])
keys.append([[1.48334, [3, -0.2, 0], [3, 0.413333, 0]],
[1.14432, [3, -0.413333, 0], [3, 0.386667, 0]],
[1.48334, [3, -0.386667, 0], [3, 0, 0]]])
names.append("LShoulderRoll")
times.append([0.6, 1.84, 3])
keys.append([[0.11194, [3, -0.2, 0], [3, 0.413333, 0]],
[0.130348, [3, -0.413333, 0], [3, 0.386667, 0]],
[0.11194, [3, -0.386667, 0], [3, 0, 0]]])
names.append("LWristYaw")
times.append([0.6, 1.84, 3])
keys.append([[0.0459781, [3, -0.2, 0], [3, 0.413333, 0]],
[-1.09225, [3, -0.413333, 0], [3, 0.386667, 0]],
[0.0459781, [3, -0.386667, 0], [3, 0, 0]]])
names.append("RAnklePitch")
times.append([0.6, 1.84, 3])
keys.append([[0.0982179, [3, -0.2, 0], [3, 0.413333, 0]],
[0.0798099, [3, -0.413333, 0], [3, 0.386667, 0]],
[0.0982179, [3, -0.386667, 0], [3, 0, 0]]])
names.append("RAnkleRoll")
times.append([0.6, 1.84, 3])
keys.append([[0.135034, [3, -0.2, 0], [3, 0.413333, 0]],
[0.145772, [3, -0.413333, 0], [3, 0.386667, 0]],
[0.135034, [3, -0.386667, 0], [3, 0, 0]]])
names.append("RElbowRoll")
times.append([0.6, 1.84, 3])
keys.append([[0.385075, [3, -0.2, 0], [3, 0.413333, 0]],
[0.360533, [3, -0.413333, 0], [3, 0.386667, 0]],
[0.385075, [3, -0.386667, 0], [3, 0, 0]]])
names.append("RElbowYaw")
times.append([0.6, 1.84, 3])
keys.append([[1.20415, [3, -0.2, 0], [3, 0.413333, 0]],
[1.39897, [3, -0.413333, 0], [3, 0.386667, 0]],
[1.20415, [3, -0.386667, 0], [3, 0, 0]]])
names.append("RHand")
times.append([0.6, 1.84, 3])
keys.append([[0.2916, [3, -0.2, 0], [3, 0.413333, 0]],
[0.2916, [3, -0.413333, 0], [3, 0.386667, 0]],
[0.2916, [3, -0.386667, 0], [3, 0, 0]]])
names.append("RHipPitch")
times.append([0.6, 1.84, 3])
keys.append([[0.130348, [3, -0.2, 0], [3, 0.413333, 0]],
[-0.322183, [3, -0.413333, 0], [3, 0.386667, 0]],
[0.130348, [3, -0.386667, 0], [3, 0, 0]]])
names.append("RHipRoll")
times.append([0.6, 1.84, 3])
keys.append([[-0.0996681, [3, -0.2, 0], [3, 0.413333, 0]],
[-0.0413762, [3, -0.413333, 0], [3, 0.386667, 0]],
[-0.0996681, [3, -0.386667, 0], [3, 0, 0]]])
names.append("RHipYawPitch")
times.append([0.6, 1.84, 3])
keys.append([[-0.162562, [3, -0.2, 0], [3, 0.413333, 0]],
[-0.25767, [3, -0.413333, 0], [3, 0.386667, 0]],
[-0.162562, [3, -0.386667, 0], [3, 0, 0]]])
names.append("RKneePitch")
times.append([0.6, 1.84, 3])
keys.append([[-0.0858622, [3, -0.2, 0], [3, 0.413333, 0]],
[-0.0923279, [3, -0.413333, 0], [3, 0.386667, 0]],
[-0.0858622, [3, -0.386667, 0], [3, 0, 0]]])
names.append("RShoulderPitch")
times.append([0.6, 1.84, 3])
keys.append([[1.46961, [3, -0.2, 0], [3, 0.413333, 0]],
[0.93118, [3, -0.413333, 0], [3, 0.386667, 0]],
[1.46961, [3, -0.386667, 0], [3, 0, 0]]])
names.append("RShoulderRoll")
times.append([0.6, 1.84, 3])
keys.append([[-0.136568, [3, -0.2, 0], [3, 0.413333, 0]],
[-0.306841, [3, -0.413333, 0], [3, 0.386667, 0]],
[-0.136568, [3, -0.386667, 0], [3, 0, 0]]])
names.append("RWristYaw")
times.append([0.6, 1.84, 3])
keys.append([[0.076658, [3, -0.2, 0], [3, 0.413333, 0]],
[-0.372804, [3, -0.413333, 0], [3, 0.386667, 0]],
[0.076658, [3, -0.386667, 0], [3, 0, 0]]])
try:
self.mtn.angleInterpolationBezier(names, times, keys)
self.aas.say(
"^start(animations/Stand/Gestures/Explain_2)Je gaat 3 keer een triplet van verschillende lettergrepen horen. 1 van de tripletten wordt gezegd met een andere stem. Het is jouw taak om aan te geven welke anders klinkt. Je kunt antwoorden door je hand op mijn rechterhand, \\pau=500\\ hoofd \\pau=500\\of linkerhand te leggen. Laten we het proberen. ^wait(animations/Stand/Gestures/Explain_2)"
)
except BaseException, err:
print err
self.mtn.rest()
self.mtn.setStiffnesses(self.hips, 1.0)
def intro(self):
'''
The intriduction to the experiment. Sam explains how the task will
work and what to do, as well as a demonstration on how to touch
the head and hands
'''
if self.language == "EN":
self.say_0 = "^start(animations/stand/Gestures/Enthusiastic_4) Hi there! My name is Sammmy.\\pau=500\\ Welcome to the PICKA auditory performance game.\\pau=500\\ Lets have some fun!"
elif self.language == 'NL':
if "HIK" in self.subject:
self.say_0 = "^start(animations/stand/Gestures/Enthusiastic_4) Hoi! \\pau=250\\ Ik ben Sam."
else:
self.say_0 = "^start(animations/stand/Gestures/Enthusiastic_4) Hallo! \\pau=250\\ Ik ben Sammmy. \\pau=500\\ Welkom bij de PICKA auditieve optreden spelletje. \\pau=500\\ Laten we wat plezier hebben!"
self.mtn.wakeUp()
self.aas.say(self.say_0)
def play_audio(self, stimulus):
'''
Uploads the stimuli files to Sam using a paramiko sftp server.
Sam then plays the files, then deletes them off its main storage.
'''
NAO_USERNAME = "nao"
NAO_PASSWORD = "nao"
t = paramiko.Transport((self.ipadress, 22))
t.connect(username=NAO_USERNAME, password=NAO_PASSWORD)
sftp = paramiko.SFTPClient.from_transport(t)
sftp.chdir('/home/nao/tests/')
remotepath = str('/home/nao/tests/' + stimulus)
try:
print "Uploading file..."
sftp.put(stimulus, remotepath)
print "File Uploaded"
except:
raise ValueError('No file provided for upload.')
for i in range(1, 1000):
dir_list = sftp.listdir()
if stimulus in dir_list:
break
else:
time.sleep(0.01)
if i == 999:
raise ValueError('File was not uploaded to nao')
# localpath = (
# 'C:\\Users\\Nao\\Documents\\Nao scripts\\Expe_files\\' + soundfile)
try:
# aap = self.aap.playFile(remotepath)
qi.async(self.aap.playFile, remotepath, delay=0)
except RuntimeError as e:
print e
sys.exit(0)
# sftp.remove(stimulus)
time.sleep(0.5)
return True
def game_break(self):
'''
Waits for a response from the subject to start the experiment.
'''
if self.language == 'EN':
self.say_1 = "When you're ready to begin, you can start the game by touching the top of my head."
self.say_2 = "Let's begin!"
self.say_3 = "Ok. Goodbye."
elif self.language == 'NL':
self.say_1 = "Wanneer je klaar bent om te beginnen, kun je het experiment starten door je hand op mijn hoofd te leggen."
self.say_2 = 'Hier gaan we'
self.say_3 = "Ok. Tot ziens."
self.tts.say(self.say_1)
self.mtn.setStiffnesses(["HeadYaw", "HeadPitch"], [1.0, 1.0])
self.hoofd_beweging()
# current_running_time = 0
# start_time = time.time()
# while current_running_time < (start_time+120):
# # check the data continously for 120 seconds
# head1 = self.mem.getData('RearTactilTouched')
# head2 = self.mem.getData('FrontTactilTouched')ell
# head = [head1, head2, head3]
# if any(head):
# break
# current_running_time = time.time()
self.tts.say(self.say_2)
def encouragement(self, robot_input):
'''Issues an encouragement message depending on how the subject is doing.'''
if self.language == 'EN':
self.encouragement_pos = [
"\\vct=110\\You're doing great!\\vct=100\\",
'\\vct=110\\ Keep going! \\vct=100\\',
'\\vct=110\\ Doing well!\\vct=100\\',
"\\vct=110\\ Great!\\vct=100\\"
]
self.encouragement_neg = [
"\\vct=110\\ You can do it! \\vct=100\\",
"\\vct=110\\ Keep trying! \\vct=100\\",
"\\vct=110\\ Give it another go! \\vct=100\\",
"\\vct=110\\ Don't give up!\\vct=100\\"
]
elif self.language == 'NL':
self.encouragement_pos = [
"\\vct=110\\ Goed bezig!\\vct=100\\",
'\\vct=110\\ Ga zo door! \\vct=100\\',
'\\vct=110\\ Je doet het super!\\vct=100\\',
"\\vct=110\\ Super!\\vct=100\\"
]
self.encouragement_neg = [
"\\vct=110\\ Je kunt het! \\vct=100\\",
"\\vct=110\\ Blijf proberen! \\vct=100\\",
"\\vct=110\\ Nog even doorgaan! \\vct=100\\",
"\\vct=110\\ Niet opgeven!\\vct=100\\"
]
answer = str(robot_input)
if answer == 'correct':
encouragement_options_positive = self.encouragement_pos
prob = random.randint(0, len(encouragement_options_positive) - 1)
encou = encouragement_options_positive[prob]
else:
encouragement_options_negative = self.encouragement_neg
prob = random.randint(0, len(encouragement_options_negative) - 1)
encou = encouragement_options_negative[prob]
self.tts.say(encou)
def ending(self):
'''Performs the ending of the experiment.'''
if self.language == 'EN':
self.say_1 = '^start(animations/Stand/Gestures/Enthusiastic_5) That\'s the end of our game! ^wait(animations/Stand/Gestures/Enthusiastic_5) \\pau=200\\ ^start(animations/Stand/Gestures/Explain_1)Thank you for playing with me! ^wait(animations/Stand/Gestures/Explain_1) ^start(animations/Stand/Gestures/Hey_6) Goodbye! ^wait(animations/Stand/Gestures/Hey_6)'
elif self.language == 'NL':
self.say_1 = '^start(animations/Stand/Gestures/Enthusiastic_5) Dit is het einde van ons spel! ^wait(animations/Stand/Gestures/Enthusiastic_5) \\pau=200\\ ^start(animations/Stand/Gestures/Explain_1)Dankjewel voor het meespelen ^wait(animations/Stand/Gestures/Explain_1) ^start(animations/Stand/Gestures/Hey_6)en tot ziens! ^wait(animations/Stand/Gestures/Hey_6)'
self.mtn.wakeUp()
self.aas.setBodyLanguageMode = 2
self.aas.say(self.say_1)
self.mtn.rest()
def head_shake(self):
# Choregraphe bezier export in Python.
names = list()
times = list()
keys = list()
names.append("HeadPitch")
times.append([0.8, 1.6, 2.4])
keys.append([[-0.0782759, [3, -0.266667, 0], [3, 0.266667, 0]],
[-0.090548, [3, -0.266667, 0], [3, 0.266667, 0]],
[-0.07214, [3, -0.266667, 0], [3, 0, 0]]])
names.append("HeadYaw")
times.append([0.8, 1.6, 2.4])
keys.append([[-0.842209, [3, -0.266667, 0], [3, 0.266667, 0]],
[0.619695, [3, -0.266667, 0], [3, 0.266667, 0]],
[-0.0107799, [3, -0.266667, 0], [3, 0, 0]]])
try:
self.mtn.angleInterpolationBezier(names, times, keys)
except BaseException, err:
print err
def head_nod(self):
# Choregraphe bezier export in Python.
names = list()
times = list()
keys = list()
names.append("HeadPitch")
times.append([0.8, 1.6])
keys.append([[0.18864, [3, -0.266667, 0], [3, 0.266667, 0]],
[-0.0567999, [3, -0.266667, 0], [3, 0, 0]]])
names.append("HeadYaw")
times.append([0.8, 1.6])
keys.append([[-0.0567999, [3, -0.266667, 0], [3, 0.266667, 0]],
[-0.0322559, [3, -0.266667, 0], [3, 0, 0]]])
try:
self.mtn.angleInterpolationBezier(names, times, keys)
except BaseException, err:
print err
def retry(self):
if self.language == 'EN':
# \\pau=500\\ If yes \\pau=500\\ touch my head \\pau=500\\ if no \\pau=500\\ touch my left or right hand."
self.say_1 = "Would you like to try again?"
self.tts.say(self.say_1)
current_running_time = 0
start_time = time.time()
self.asr.subscribe("retry")
while current_running_time < (start_time + 120):
if self.mem.getData("WordRecognized")[0] == "yes":
self.asr.unsubscribe("retry")
return True
elif self.mem.getData("WordRecognized")[0] == "no":
self.asr.unsubscribe("retry")
return False
def simple_say(self, msg):
self.tts.say(msg)
def take_break(self):
behaviour_name = "custom_packages-8cd326/take_break"
if self.bms.isBehaviorInstalled(behaviour_name):
if self.bms.isBehaviorRunning(behaviour_name) == True:
self.bms.stopBehavior(behaviour_name)
self.mtn.setStiffnesses(self.hips, 0.0)
self.bms.runBehavior(behaviour_name)
else:
self.tts.say(
"I don't appear to be able to take a break right now.")
self.mtn.setStiffnesses(self.hips, 1.0)
def hoofd_beweging(self):
'''Moves the head down for the subject to test the tactile function of Sam during the introduction.'''
names = list()
times = list()
keys = list()
names.append("HeadPitch")
times.append([0.7])
keys.append([[0.35738, [3, -0.133333, 0], [3, 0, 0]]])
names.append("HeadYaw")
times.append([0.7])
keys.append([[-0.0399261, [3, -0.133333, 0], [3, 0, 0]]])
try:
self.mtn.angleInterpolationBezier(names, times, keys)
except BaseException, err:
print err
start_time = time.time()
current_running_time = 0
while current_running_time < (start_time + 120):
# check the data continously for 7 seconds
head1 = self.mem.getData('RearTactilTouched')
head2 = self.mem.getData('FrontTactilTouched')
head3 = self.mem.getData('MiddleTactilTouched')
head = [head1, head2, head3]
if any(head):
answer_given = 2
break
current_running_time = time.time()
names = list()
times = list()
keys = list()
names.append("HeadPitch")
times.append([0.7])
keys.append([[-0.17185, [3, -0.133333, 0], [3, 0, 0]]])
names.append("HeadYaw")
times.append([0.7])
keys.append([[-0.0153821, [3, -0.133333, 0], [3, 0, 0]]])
try:
self.mtn.angleInterpolationBezier(names, times, keys)
except BaseException, err:
print err
def rechterhand_beweging(self):
'''Moves the right hand up for the subject to test the tactile function of Sam during the introduction.'''
names = list()
times = list()
keys = list()
names.append("LElbowRoll")
times.append([0.7])
keys.append([[-0.412604, [3, -0.133333, 0], [3, 0, 0]]])
names.append("LElbowYaw")
times.append([0.7])
keys.append([[-1.19349, [3, -0.133333, 0], [3, 0, 0]]])
names.append("LHand")
times.append([0.7])
keys.append([[0.2904, [3, -0.133333, 0], [3, 0, 0]]])
names.append("LShoulderPitch")
times.append([0.7])
keys.append([[1.52169, [3, -0.133333, 0], [3, 0, 0]]])
names.append("LShoulderRoll")
times.append([0.7])
keys.append([[0.10427, [3, -0.133333, 0], [3, 0, 0]]])
names.append("LWristYaw")
times.append([0.7])
keys.append([[0.108872, [3, -0.133333, 0], [3, 0, 0]]])
names.append("RElbowRoll")
times.append([0.7])
keys.append([[0.04146, [3, -0.133333, 0], [3, 0, 0]]])
names.append("RElbowYaw")
times.append([0.7])
keys.append([[1.12131, [3, -0.133333, 0], [3, 0, 0]]])
names.append("RHand")
times.append([0.7])
keys.append([[0.29, [3, -0.133333, 0], [3, 0, 0]]])
names.append("RShoulderPitch")
times.append([0.7])
keys.append([[0.457174, [3, -0.133333, 0], [3, 0, 0]]])
names.append("RShoulderRoll")
times.append([0.7])
keys.append([[0.254602, [3, -0.133333, 0], [3, 0, 0]]])
names.append("RWristYaw")
times.append([0.7])
keys.append([[-1.03549, [3, -0.133333, 0], [3, 0, 0]]])
try:
self.mtn.angleInterpolationBezier(names, times, keys)
except BaseException, err:
print err
start_time = time.time()
current_running_time = 0
while current_running_time < (start_time + 120):
right1 = self.mem.getData('HandRightRightTouched')
right2 = self.mem.getData('HandRightBackTouched')
right3 = self.mem.getData('HandRightLeftTouched')
right = [right1, right2, right3]
if any(right):
break
current_running_time = time.time()
names = list()
times = list()
keys = list()
names.append("LElbowRoll")
times.append([0.7])
keys.append([[-0.412604, [3, -0.133333, 0], [3, 0, 0]]])
names.append("LElbowYaw")
times.append([0.7])
keys.append([[-1.19349, [3, -0.133333, 0], [3, 0, 0]]])
names.append("LHand")
times.append([0.7])
keys.append([[0.2904, [3, -0.133333, 0], [3, 0, 0]]])
names.append("LShoulderPitch")
times.append([0.7])
keys.append([[1.52169, [3, -0.133333, 0], [3, 0, 0]]])
names.append("LShoulderRoll")
times.append([0.7])
keys.append([[0.102736, [3, -0.133333, 0], [3, 0, 0]]])
names.append("LWristYaw")
times.append([0.7])
keys.append([[0.108872, [3, -0.133333, 0], [3, 0, 0]]])
names.append("RElbowRoll")
times.append([0.7])
keys.append([[0.382008, [3, -0.133333, 0], [3, 0, 0]]])
names.append("RElbowYaw")
times.append([0.7])
keys.append([[1.16733, [3, -0.133333, 0], [3, 0, 0]]])
names.append("RHand")
times.append([0.7])
keys.append([[0.29, [3, -0.133333, 0], [3, 0, 0]]])
names.append("RShoulderPitch")
times.append([0.7])
keys.append([[1.45274, [3, -0.133333, 0], [3, 0, 0]]])
names.append("RShoulderRoll")
times.append([0.7])
keys.append([[-0.0752079, [3, -0.133333, 0], [3, 0, 0]]])
names.append("RWristYaw")
times.append([0.7])
keys.append([[0.0413761, [3, -0.133333, 0], [3, 0, 0]]])
try:
self.mtn.angleInterpolationBezier(names, times, keys)
except BaseException, err:
print err
def linkerhand_beweging(self):
'''Moves the left hand up for the subject to test the tactile function of Sam during the introduction.'''
names = list()
times = list()
keys = list()
names.append("LElbowRoll")
times.append([0.7])
keys.append([[-0.0367742, [3, -0.133333, 0], [3, 0, 0]]])
names.append("LElbowYaw")
times.append([0.7])
keys.append([[-0.974132, [3, -0.133333, 0], [3, 0, 0]]])
names.append("LHand")
times.append([0.7])
keys.append([[0.2904, [3, -0.133333, 0], [3, 0, 0]]])
names.append("LShoulderPitch")
times.append([0.7])
keys.append([[0.624296, [3, -0.133333, 0], [3, 0, 0]]])
names.append("LShoulderRoll")
times.append([0.7])
keys.append([[-0.227074, [3, -0.133333, 0], [3, 0, 0]]])
names.append("LWristYaw")
times.append([0.7])
keys.append([[0.88661, [3, -0.133333, 0], [3, 0, 0]]])
names.append("RElbowRoll")
times.append([0.7])
keys.append([[0.382008, [3, -0.133333, 0], [3, 0, 0]]])
names.append("RElbowYaw")
times.append([0.7])
keys.append([[1.16733, [3, -0.133333, 0], [3, 0, 0]]])
names.append("RHand")
times.append([0.7])
keys.append([[0.29, [3, -0.133333, 0], [3, 0, 0]]])
names.append("RShoulderPitch")
times.append([0.7])
keys.append([[1.45274, [3, -0.133333, 0], [3, 0, 0]]])
names.append("RShoulderRoll")
times.append([0.7])
keys.append([[-0.0752079, [3, -0.133333, 0], [3, 0, 0]]])
names.append("RWristYaw")
times.append([0.7])
keys.append([[0.0413761, [3, -0.133333, 0], [3, 0, 0]]])
try:
self.mtn.angleInterpolationBezier(names, times, keys)
except BaseException, err:
print err
current_running_time = 0
start_time = time.time()
while current_running_time < (start_time + 120):
left1 = self.mem.getData('HandLeftRightTouched')
left2 = self.mem.getData('HandLeftBackTouched')
left3 = self.mem.getData('HandLeftLeftTouched')
left = [left1, left2, left3]
if any(left):
break
current_running_time = time.time()
names = list()
times = list()
keys = list()
names.append("LElbowRoll")
times.append([0.7])
keys.append([[-0.412604, [3, -0.133333, 0], [3, 0, 0]]])
names.append("LElbowYaw")
times.append([0.7])
keys.append([[-1.19349, [3, -0.133333, 0], [3, 0, 0]]])
names.append("LHand")
times.append([0.7])
keys.append([[0.2904, [3, -0.133333, 0], [3, 0, 0]]])
names.append("LShoulderPitch")
times.append([0.7])
keys.append([[1.52169, [3, -0.133333, 0], [3, 0, 0]]])
names.append("LShoulderRoll")
times.append([0.7])
keys.append([[0.102736, [3, -0.133333, 0], [3, 0, 0]]])
names.append("LWristYaw")
times.append([0.7])
keys.append([[0.108872, [3, -0.133333, 0], [3, 0, 0]]])
names.append("RElbowRoll")
times.append([0.7])
keys.append([[0.382008, [3, -0.133333, 0], [3, 0, 0]]])
names.append("RElbowYaw")
times.append([0.7])
keys.append([[1.16733, [3, -0.133333, 0], [3, 0, 0]]])
names.append("RHand")
times.append([0.7])
keys.append([[0.29, [3, -0.133333, 0], [3, 0, 0]]])
names.append("RShoulderPitch")
times.append([0.7])
keys.append([[1.45274, [3, -0.133333, 0], [3, 0, 0]]])
names.append("RShoulderRoll")
times.append([0.7])
keys.append([[-0.0752079, [3, -0.133333, 0], [3, 0, 0]]])
names.append("RWristYaw")
times.append([0.7])
keys.append([[0.0413761, [3, -0.133333, 0], [3, 0, 0]]])
try:
self.mtn.angleInterpolationBezier(names, times, keys)
except BaseException, err:
print err
if __name__ == "__main__":
nao = Robot('127.0.0.1', 9559, "EN")
nao.buiging()
+121
View File
@@ -0,0 +1,121 @@
from Robot import Robot
import paramiko
import os
import sys
import cPickle as pickle
import time
from naoqi import ALProxy
class RobotCRM(Robot):
def crmIntro(self):
if self.language == "EN":
self.say_1 = "^start(animations/Stand/Gestures/Explain_2)You are going to hear a sentence that sounds like it is spoken in a noisy room. \\pau=500\\ \
It is your task to determine what was said in the sentence. An example sentence is, show the dog where the green 4 is.\\pau=500\\ \
To enter your answer, you will have to use the coloured grid on the tablet provided. You must choose both the correct color and number that was spoken.\
^wait(animations/Stand/Gestures/Explain_2)"
self.say_2 = "\\pau=500\\ During the experiment, when my eyes turn green like this,"
self.say_3 = "I am ready for your answer. \\pau=500\\"
self.say_4 = "Now I will try to make myself as quiet as possible."
elif self.language == "NL":
self.say_1 = "^start(animations/Stand/Gestures/Explain_2)You are going to hear a sentence that sounds like it is spoken in a noisy room. \\pau=500\\ \
It is your task to determine what was said in the sentence. An example sentence is, show the dog where the green 4 is.\\pau=500\\ \
To enter your answer, you will have to use the coloured grid on the tablet provided. You must choose both the correct color and number that was spoken.\
^wait(animations/Stand/Gestures/Explain_2)"
self.say_2 = "\\pau=500\\ During the experiment, when my eyes turn green like this,"
self.say_3 = "I am ready for your answer. \\pau=500\\"
self.say_4 = "Now I will try to make myself as quiet as possible."
self.mtn.wakeUp()
self.aas.say(self.say_1)
self.aas.say(self.say_2)
self.all.fadeRGB("FaceLeds", "green", 0.01)
self.tts.say("\\pau=500\\")
self.aas.say(self.say_3)
self.all.fadeRGB("FaceLeds", "white", 0.01)
self.aas.say(self.say_4)
self.mtn.rest()
self.mtn.setStiffnesses(self.hips, 1.0)
def play_sounds(self, stimulus, lang):
'''
Uploads the stimuli files to Sam using a paramiko sftp server.
Sam then plays the files, then deletes them off its main storage.
'''
NAO_USERNAME = "nao"
NAO_PASSWORD = "nao"
t = paramiko.Transport((self.ipadress, 22))
t.connect(username=NAO_USERNAME, password=NAO_PASSWORD)
sftp = paramiko.SFTPClient.from_transport(t)
sftp.chdir('/home/nao/tests/')
remotepath = str('/home/nao/tests/' + stimulus)
print "trying to upload"
try:
sftp.put(stimulus, remotepath)
except:
raise ValueError('No file provided for upload.')
for i in range(1, 1000):
dir_list = sftp.listdir()
if stimulus in dir_list:
break
else:
time.sleep(0.01)
if i == 999:
raise ValueError('File was not uploaded to nao')
# localpath = (
# 'C:\\Users\\Nao\\Documents\\Nao scripts\\Expe_files\\' + soundfile)
remotepath = str('/home/nao/tests/' + stimulus)
print "uploaded, now playing"
try:
self.aap.playFile(remotepath)
except RuntimeError:
sys.exit(0)
sftp.remove(stimulus)
time.sleep(0.5)
return True
def answer(self, correct_answer, feedback, current_trial, total_trials):
self.mtn.setStiffnesses(self.hips, 1.0)
self.all.fadeRGB("FaceLeds", "green", 0.01)
start_time = time.time()
current_running_time = 0
folder = os.path.dirname("./crm/")
ans_file = 'answer.p'
answer = {}
while current_running_time < start_time + 120:
dirs = os.listdir('./crm')
if ans_file in dirs:
try:
with open('./crm/answer.p', 'rb') as f:
answer = pickle.load(f)
break
except EOFError as e:
print e
current_running_time = time.time()
answer["number"] = int(answer["number"])
response_time = time.time() - start_time
if feedback:
self.mtn.setStiffnesses(["HeadYaw", "HeadPitch"], [1.0, 1.0])
if answer["colour"] == correct_answer["colour"] and answer["number"] == correct_answer["number"]:
self.head_nod()
else:
self.head_shake()
self.mtn.setStiffnesses(["HeadYaw", "HeadPitch"], [0.0, 0.0])
self.all.fadeRGB("FaceLeds", "white", 0.01)
os.remove(os.path.join(folder, ans_file))
trial_track = {"current_trial": current_trial + 1,
"total_trials": total_trials}
with open('./crm/trials.p', 'wb') as f:
pickle.dump(trial_track, f)
print current_trial
return answer, response_time
+190
View File
@@ -0,0 +1,190 @@
import paramiko
import time
import os
import sys
from naoqi import ALProxy
from Robot import Robot
from RobotGender import RobotGender
def printTotals(transferred, toBeTransferred):
print "Transferred: {0}\tOut of: {1}".format(transferred, toBeTransferred)
class RobotEmotion(RobotGender):
def emotionIntro(self):
if self.language == "EN":
self.say_1 = "^start(animations/Stand/Gestures/Explain_2)You are going to hear a voice that sounds either happy, sad, or angry. \
It is your task to determine the emotion of the voice. \
^wait(animations/Stand/Gestures/Explain_2)"
self.say_2 = "\\pau=500\\ During the experiment, when my eyes turn green like this,"
self.say_3 = "I am ready for your answer. You can answer by touching my right hand, head, or left hand. Let's try it. \\pau=500\\"
self.say_4 = "\\pau=500\\ Now I will try to make myself as quite as possible so we can get started."
self.say_5 = "Touch my right hand if the voice sounds happy"
self.say_6 = "My head if the voice sounds angry."
self.say_7 = "Or my left hand if the voice sounds sad."
elif self.language == "NL":
if "HIK" in self.subject:
self.say_1 = "^start(animations/Stand/Gestures/Explain_2)Je gaat een stem horen die blij, verdrietig, of boos klinkt. \
Jouw taak is om te zeggen welke emotie je hebt gehoord. \
^wait(animations/Stand/Gestures/Explain_2)"
self.say_2 = "Prima!\\pau=500\\ Tijdens het experiment, als mijn ogen zo groen worden,"
self.say_3 = "Mag jij antwoord geven."
self.say_4 = "Nog een ding. Als je het experiment tussendoor wilt stoppen, wacht dan tot ik ben gestopt met praten en raak dan mijn rechtervoet aan. \\pau=500\\ Nou zal ik me nu zo stil mogelijk maken."
self.say_5 = "Als de stem blij klinkt, raak dan mijn rechterhand aan. Probeer maar."
self.say_6 = "Super! \\pau=150\\ Als de stem boos klinkt, raak dan mijn hoofd aan."
self.say_7 = "Heel goed! \\pau=150\\ Of als de stem verdrietig klinkt, raak dan mijn linkerhand aan."
else:
self.say_1 = "^start(animations/Stand/Gestures/Explain_2)Je gaat een stem horen die blij, verdrietig, of boos klinkt. \
Jouw taak is om te zeggen welke emotie je hebt gehoord. \
^wait(animations/Stand/Gestures/Explain_2)"
self.say_2 = "Prima!\\pau=500\\ Tijdens het experiment, als mijn ogen zo groen worden,"
self.say_3 = "Mag jij antwoord geven."
self.say_4 = "Nog een ding. Als je het experiment tussendoor wilt stoppen, wacht dan tot ik ben gestopt met praten en raak dan mijn rechtervoet aan. \\pau=500\\ Nou zal ik me nu zo stil mogelijk maken."
self.say_5 = "Als de stem blij klinkt, raak dan mijn rechterhand aan. Probeer maar."
self.say_6 = "Super! \\pau=150\\ Als de stem boos klinkt, raak dan mijn hoofd aan."
self.say_7 = "Heel goed! \\pau=150\\ Of als de stem verdrietig klinkt, raak dan mijn linkerhand aan."
self.mtn.wakeUp()
self.aas.say(self.say_1)
self.aas.setBodyLanguageMode = 0
# self.pst.goToPosture("Stand", 0.7)
# self.rightHandMotion(self.say_5)
self.aas.say(self.say_2)
self.all.fadeRGB("FaceLeds", "green", 0.01)
self.tts.say("\\pau=500\\")
self.aas.say(self.say_3)
self.all.fadeRGB("FaceLeds", "white", 0.01)
self.aas.say(self.say_5)
self.rechterhand_beweging()
# self.tts.say("\\pau=250\\")
# self.headMovement(self.say_6)
self.aas.say(self.say_6)
self.hoofd_beweging()
# self.tts.say("\\pau=250\\")
# self.leftHandMove(self.say_7)
self.aas.say(self.say_7)
self.linkerhand_beweging()
self.aas.say(self.say_4)
self.mtn.rest()
self.mtn.setStiffnesses(self.hips, 1.0)
def play_sounds(self, stimulus, lang):
'''
Uploads the stimuli files to Sam using a paramiko sftp server.
Sam then plays the files, then deletes them off its main storage.
'''
NAO_USERNAME = "nao"
NAO_PASSWORD = "nao"
t = paramiko.Transport((self.ipadress, 22))
t.connect(username=NAO_USERNAME, password=NAO_PASSWORD)
sftp = paramiko.SFTPClient.from_transport(t)
sftp.chdir('/home/nao/tests/')
remotepath = str('/home/nao/tests/' + stimulus)
try:
sftp.put(stimulus, remotepath)
except:
raise ValueError('No file provided for upload.')
for i in range(1, 1000):
dir_list = sftp.listdir()
if stimulus in dir_list:
break
else:
time.sleep(0.01)
if i == 999:
raise ValueError('File was not uploaded to nao')
# localpath = (
# 'C:\\Users\\Nao\\Documents\\Nao scripts\\Expe_files\\' + soundfile)
try:
self.aap.playFile(remotepath)
except RuntimeError:
sys.exit(0)
sftp.remove(stimulus)
time.sleep(0.5)
def answer(self, correct_answer, feedback):
self.mtn.setStiffnesses(self.hips, 1.0)
start_time = time.time()
self.all.fadeRGB("FaceLeds", "green", 0.01)
current_running_time = 0
answer_given = 0
while current_running_time < (start_time + 120):
try:
head1 = self.mem.getData('RearTactilTouched')
head2 = self.mem.getData('FrontTactilTouched')
head3 = self.mem.getData('MiddleTactilTouched')
head = [head1, head2, head3]
left1 = self.mem.getData('HandLeftRightTouched')
left2 = self.mem.getData('HandLeftBackTouched')
left3 = self.mem.getData('HandLeftLeftTouched')
left = [left1, left2, left3]
right1 = self.mem.getData('HandRightRightTouched')
right2 = self.mem.getData('HandRightBackTouched')
right3 = self.mem.getData('HandRightLeftTouched')
right = [right1, right2, right3]
if any(right):
answer_given = "happy"
break
elif any(left):
answer_given = "sad"
break
elif any(head):
answer_given = "angry"
break
current_running_time = time.time()
except RuntimeError as e:
print e
sys.exit(0)
if feedback == 1:
self.mtn.setStiffnesses(["HeadYaw", "HeadPitch"], [1.0, 1.0])
if answer_given == correct_answer:
self.head_nod()
elif answer_given != correct_answer:
self.head_shake()
else:
self.tts.say(self.say_3)
self.mtn.setStiffnesses(["HeadYaw", "HeadPitch"], [0.0, 0.0])
self.all.fadeRGB("FaceLeds", "white", 0.01)
return answer_given
def headMovement(self, string):
'''Moves the head down for the subject to test the tactile function of Sam during the introduction.'''
names = list()
times = list()
keys = list()
names.append("HeadPitch")
times.append([0.7])
keys.append([[0.35738, [3, -0.133333, 0], [3, 0, 0]]])
names.append("HeadYaw")
times.append([0.7])
keys.append([[-0.0399261, [3, -0.133333, 0], [3, 0, 0]]])
try:
motion = ALProxy("ALMotion")
motion.moveInit()
w = motion.post.angleInterpolationBezier(names, times, keys)
self.tts.say(string)
motion.wait(w, 0)
except BaseException, err:
print err
names.append("HeadPitch")
times.append([0.7])
keys.append([[-0.17185, [3, -0.133333, 0], [3, 0, 0]]])
names.append("HeadYaw")
times.append([0.7])
keys.append([[-0.0153821, [3, -0.133333, 0], [3, 0, 0]]])
try:
self.mtn.angleInterpolationBezier(names, times, keys)
except BaseException, err:
print err
+180
View File
@@ -0,0 +1,180 @@
from Robot import Robot
import paramiko
import time
import sys
class RobotFishy(Robot):
def fishyIntro(self):
'''
The intriduction to the experiment. Sam explains how the task will
work and what to do, as well as a demonstration on how to touch
the head and hands
'''
if self.language == 'EN':
self.say_1 = "^start(animations/Stand/Gestures/Explain_2)You are goint to hear a triplet of three different syllables. \
One of the triplets is said in a different voice. \
It is your task to determine which triplet is said in a different voice. \
You can answer by touching my right hand, \\pau=500\\ head \\pau=500\\or left hand. \
Lets give it a try. ^wait(animations/Stand/Gestures/Explain_2)"
self.say_2 = "If the first word is said in a different voice, then touch the top of my right hand. Try it."
self.say_3 = "Great! \\pau=500\\ and if the second sound is said differently, then touch the top of my head."
self.say_4 = "Super! \\pau=500\\ and if the last sound is said in a different voice, then touch the top of my left hand."
self.say_5 = "Very good!. During the experiment, when my eyes turn green like this,"
self.say_6 = "I am ready for your answer."
# self.say_7 = "One last thing. If at any point you want to stop the experiment, wait for me to stop talking, and then press my right foot. \\pau=500\\ Now I will try to make myself as quite as possible."
self.say_7 = "\\pau=500\\ Now I will try to make myself as quite as possible."
elif self.language == 'NL':
self.say_1 = "^start(animations/Stand/Gestures/Explain_2)Je gaat 3 keer een triplet van verschillende lettergrepen horen.\
1 van de tripletten wordt gezegd met een andere stem. Het is jouw taak om aan te geven welke anders klinkt. \
Je kunt antwoorden door je hand op mijn rechterhand, \\pau=500\\ hoofd \\pau=500\\of linkerhand te leggen. \
Laten we het proberen. ^wait(animations/Stand/Gestures/Explain_2)"
self.say_2 = "Als het eerste woord met een andere stem gezegd wordt, leg je jouw hand op de bovenkant van mijn rechterhand. Probeer maar"
self.say_3 = "Heel goed \\pau=500\\ en als het tweede woord met een andere stem gezegd wordt, leg je jouw hand op de bovenkant van mijn hoofd"
self.say_4 = "Super \\pau=500\\ en als laatste de bovenkant van mijn linkerhand"
self.say_5 = "Heel goed. Dan zal ik me nu zo stil mogelijk maken"
self.mtn.wakeUp()
self.aas.say(self.say_1)
self.aas.setBodyLanguageMode = 0
self.pst.goToPosture("Stand", 0.7)
self.aas.say(self.say_2)
self.rechterhand_beweging()
self.aas.say(self.say_3)
self.hoofd_beweging()
self.aas.say(self.say_4)
self.linkerhand_beweging()
# time.sleep(1)
self.aas.say(self.say_5)
self.all.fadeRGB("FaceLeds", "green", 0.01)
self.tts.say("\\pau=500\\")
self.aas.say(self.say_6)
self.all.fadeRGB("FaceLeds", "white", 0.01)
self.aas.say(self.say_7)
self.mtn.rest()
self.mtn.setStiffnesses(self.hips, 1.0)
def play_sounds(self, soundfiles_att):
'''
Uploads the stimuli files to Sam using a paramiko sftp server.
Sam then plays the files, then deletes them off its main storage.
'''
soundfiles = list(soundfiles_att.split(", "))
# soundfiles = []
# filename = ""
# for i in soundfiles_att:
# if i == ',':
# soundfiles.append(filename)
# filename = ''
# else:
# filename = filename+i
NAO_USERNAME = "nao"
NAO_PASSWORD = "nao"
t = paramiko.Transport((self.ipadress, 22))
t.connect(username=NAO_USERNAME, password=NAO_PASSWORD)
sftp = paramiko.SFTPClient.from_transport(t)
sftp.chdir('/home/nao/tests/')
for soundfile in soundfiles:
# localpath = (
# 'C:\\Users\\Nao\\Documents\\Nao\\Python_scripts\\tmp\\' + soundfile)
# localpath = "./" + soundfile.strip()
remotepath = str('/home/nao/tests/' + soundfile)
try:
sftp.put(soundfile, remotepath)
except:
raise ValueError('Yo cannot find the right stuff')
for i in range(1, 1000):
dir_list = sftp.listdir()
if soundfile in dir_list:
break
else:
time.sleep(0.01)
if i == 999:
raise ValueError('File was not uploaded to nao')
sys.exit()
for soundfile in soundfiles:
# localpath = (
# 'C:\\Users\\Nao\\Documents\\Nao scripts\\Expe_files\\' + soundfile)
localpath = "./tmp/" + soundfile
remotepath = str('/home/nao/tests/' + soundfile)
try:
self.aap.playFile(remotepath)
except RuntimeError:
# raise ValueError(
# 'stupid thing needs to be string check type')
sys.exit(0)
sys.exit(0)
sftp.remove(soundfile)
time.sleep(0.5)
def answer(self, robot_input):
'''
Waits for the response from the subject on which of the sounds was different.
'''
try:
if self.language == 'EN':
self.say_1 = "That is correct."
self.say_2 = "That is incorrect."
self.say_3 = "You did not give an answer."
elif self.language == 'NL':
self.say_1 = "Dat is correct."
self.say_2 = "Dat is niet correct."
self.say_3 = "Je hebt geen antwoord gegeven."
correct_answer = int(robot_input[0])
feedback = int(robot_input[1])
# this function returns the answer given by the participant. As input it requires the correct answer (from matlab) and it has an option for feedback (0 or 1).
start_time = time.time()
# LEDs change colour to indicate Sam is ready for a response
self.all.fadeRGB("FaceLeds", "green", 0.01)
current_running_time = 0
answer_given = 0
# TODO maybe add a warning after 7 seconds.
# TODO add a way to replay the sounds if necessary?
while current_running_time < (start_time+120):
# check the data continously for 7 seconds
try:
head1 = self.mem.getData('RearTactilTouched')
head2 = self.mem.getData('FrontTactilTouched')
head3 = self.mem.getData('MiddleTactilTouched')
head = [head1, head2, head3]
left1 = self.mem.getData('HandLeftRightTouched')
left2 = self.mem.getData('HandLeftBackTouched')
left3 = self.mem.getData('HandLeftLeftTouched')
left = [left1, left2, left3]
right1 = self.mem.getData('HandRightRightTouched')
right2 = self.mem.getData('HandRightBackTouched')
right3 = self.mem.getData('HandRightLeftTouched')
right = [right1, right2, right3]
if any(right):
answer_given = 0
break
elif any(head):
answer_given = 1
break
elif any(left):
answer_given = 2
break
current_running_time = time.time()
except RuntimeError:
sys.exit(0)
if feedback == 1:
self.mtn.setStiffnesses(["HeadYaw", "HeadPitch"], [1.0, 1.0])
if answer_given == correct_answer:
self.head_nod()
elif answer_given != correct_answer:
self.head_shake()
else:
self.tts.say(self.say_3)
self.mtn.setStiffnesses(["HeadYaw", "HeadPitch"], [0.0, 0.0])
self.all.fadeRGB("FaceLeds", "white", 0.1)
return answer_given
except RuntimeError:
sys.exit(0)
# === Custom movements ===
+231
View File
@@ -0,0 +1,231 @@
from naoqi import ALProxy
from Robot import Robot
import paramiko
import time
import sys
import os
import numpy as np
class RobotGender(Robot):
def genderIntro(self):
if self.language == "EN":
self.say_1 = "^start(animations/Stand/Gestures/Explain_2)You are going to hear a voice that sounds either like a boy, or a girl. \
It is your task to determine the gender of the voice. \
You can answer by touching my right hand, \\pau=500\\or left hand. \
Each time you hear a voice, I will tell you which of my hands is for boy, and which hand is for girl. \
^wait(animations/Stand/Gestures/Explain_2)"
self.say_2 = "\\pau=500\\ During the experiment, when my eyes turn green like this,"
self.say_3 = "I am ready for your answer."
# self.say_4 = "One last thing. If at any point you want to stop the experiment, wait for me to stop talking, and then press my right foot. \\pau=500\\ Now I will try to make myself as quite as possible."
self.say_4 = "Now I will try to make myself as quite as possible."
if self.language == "NL":
self.say_1 = "^start(animations/Stand/Gestures/Explain_2)Je gaat een stem horen die zoals een jongen of een meisje klinkt. \
Ik vraag dan aan jou of je de stem van een jongen of een meisje hebt gehoord. \
Je kunt antwoorden door mijn rechterhand, \\pau=500\\of linkerhand aan te raken. \
Elke keer als je een stem hoort, zal ik je vertellen welke hand voor jongen is, en welke hand voor meisje is. \
^wait(animations/Stand/Gestures/Explain_2)"
self.say_2 = "\\pau=500\\ Tijdens het experiment, als mijn ogen zo groen worden,"
self.say_3 = "Mag jij antwoord geven."
self.say_4 = "Nog een ding. Als je het experiment tussendoor wilt stoppen, wacht dan tot ik ben gestopt met praten en raak dan mijn rechtervoet aan. \\pau=500\\ Nou zal ik me nu zo stil mogelijk maken."
self.mtn.wakeUp()
self.aas.say(self.say_1)
self.aas.setBodyLanguageMode = 0
self.pst.goToPosture("Stand", 0.7)
self.aas.say(self.say_2)
self.all.fadeRGB("FaceLeds", "green", 0.01)
self.tts.say("\\pau=150\\")
self.aas.say(self.say_3)
self.all.fadeRGB("FaceLeds", "white", 0.01)
self.aas.say(self.say_4)
self.mtn.rest()
self.mtn.setStiffnesses(self.hips, 1.0)
def play_sounds(self, stimulus, lang):
'''
Uploads the stimuli files to Sam using a paramiko sftp server.
Sam then plays the files, then deletes them off its main storage.
'''
NAO_USERNAME = "nao"
NAO_PASSWORD = "nao"
t = paramiko.Transport((self.ipadress, 22))
t.connect(username=NAO_USERNAME, password=NAO_PASSWORD)
sftp = paramiko.SFTPClient.from_transport(t)
sftp.chdir('/home/nao/tests/')
remotepath = str('/home/nao/tests/' + stimulus)
try:
sftp.put(stimulus, remotepath)
except:
raise ValueError('No file provided for upload.')
for i in range(1, 1000):
dir_list = sftp.listdir()
if stimulus in dir_list:
break
else:
time.sleep(0.01)
if i == 999:
raise ValueError('File was not uploaded to nao')
# localpath = (
# 'C:\\Users\\Nao\\Documents\\Nao scripts\\Expe_files\\' + soundfile)
remotepath = str('/home/nao/tests/' + stimulus)
try:
self.aap.playFile(remotepath)
except RuntimeError:
# raise ValueError(
# 'stupid thing needs to be string check type')
sys.exit(0)
sftp.remove(stimulus)
time.sleep(0.5)
def answer(self):
self.mtn.setStiffnesses(self.hips, 1.0)
self.mtn.setStiffnesses(
["RShoulderPitch", "RShoulderRoll", "RElbowYaw", "RElbowRoll", "RWristYaw", "LShoulderPitch", "LShoulderRoll", "LElbowYaw", "LElbowRoll", "LWristYaw"], 1.0)
OR = ""
if self.language == "EN":
gender = np.array(["Boy?", "Girl?"])
OR = "or"
elif self.language == "NL":
gender = np.array(["Jongen?", "Meisje?"])
OR = "of"
np.random.shuffle(gender)
self.rightHandMotion(gender[0])
self.tts.say(OR)
self.leftHandMove(gender[1])
self.mtn.setStiffnesses(
["RShoulderPitch", "RShoulderRoll", "RElbowYaw", "RElbowRoll", "RWristYaw", "LShoulderPitch", "LShoulderRoll", "LElbowYaw", "LElbowRoll", "LWristYaw"], 0.0)
start_time = time.time()
self.all.fadeRGB("FaceLeds", "green", 0.01)
current_running_time = 0
answer_given = 0
gender_chosen = ""
while current_running_time < (start_time + 120):
try:
left1 = self.mem.getData('HandLeftRightTouched')
left2 = self.mem.getData('HandLeftBackTouched')
left3 = self.mem.getData('HandLeftLeftTouched')
left = [left1, left2, left3]
right1 = self.mem.getData('HandRightRightTouched')
right2 = self.mem.getData('HandRightBackTouched')
right3 = self.mem.getData('HandRightLeftTouched')
right = [right1, right2, right3]
if any(right):
answer_given = 1
gender_chosen = gender[0].split(" ")[-1][:-1]
break
elif any(left):
answer_given = 2
gender_chosen = gender[1].split(" ")[-1][:-1]
break
current_running_time = time.time()
except RuntimeError:
sys.exit(0)
self.all.fadeRGB("FaceLeds", "white", 0.01)
resp = {"answer": answer_given, "gender": gender_chosen}
return resp, gender_chosen
# === Custom movements ===
def rightHandMotion(self, gender):
# Choregraphe bezier export in Python.
names = list()
times = list()
keys = list()
names.append("RElbowRoll")
times.append([1, 1.48, 1.96])
keys.append([[0.90817, [3, -0.333333, 0], [3, 0.16, 0]], [0.909704,
[3, -0.16, 0], [3, 0.16, 0]], [0.865218, [3, -0.16, 0], [3, 0, 0]]])
names.append("RElbowYaw")
times.append([1, 1.48, 1.96])
keys.append([[0.493906, [3, -0.333333, 0], [3, 0.16, 0]], [1.00626,
[3, -0.16, 0], [3, 0.16, 0]], [0.486236, [3, -0.16, 0], [3, 0, 0]]])
names.append("RHand")
times.append([1, 1.48, 1.96])
keys.append([[0.3544, [3, -0.333333, 0], [3, 0.16, 0]], [0.3544,
[3, -0.16, 0], [3, 0.16, 0]], [0.3544, [3, -0.16, 0], [3, 0, 0]]])
names.append("RShoulderPitch")
times.append([1, 1.48, 1.96])
keys.append([[1.21804, [3, -0.333333, 0], [3, 0.16, 0]], [1.05083,
[3, -0.16, 0], [3, 0.16, 0]], [1.23338, [3, -0.16, 0], [3, 0, 0]]])
names.append("RShoulderRoll")
times.append([1, 1.48, 1.96])
keys.append([[-0.0552659, [3, -0.333333, 0], [3, 0.16, 0]], [-0.305308,
[3, -0.16, 0], [3, 0.16, 0]], [0.0229681, [3, -0.16, 0], [3, 0, 0]]])
names.append("RWristYaw")
times.append([1, 1.48, 1.96])
keys.append([[0.23466, [3, -0.333333, 0], [3, 0.16, 0]], [1.41737,
[3, -0.16, 0], [3, 0.16, 0]], [0.0429101, [3, -0.16, 0], [3, 0, 0]]])
try:
# uncomment the following line and modify the IP if you use this script outside Choregraphe.
# motion = ALProxy("ALMotion", IP, 9559)
motion = ALProxy("ALMotion")
motion.moveInit()
w = motion.post.angleInterpolationBezier(names, times, keys)
self.tts.say(gender)
motion.wait(w, 0)
except BaseException, err:
print err
def leftHandMove(self, gender):
# Choregraphe bezier export in Python.
names = list()
times = list()
keys = list()
names.append("LElbowRoll")
times.append([1, 1.48])
keys.append([[-1.03848, [3, -0.333333, 0], [3, 0.16, 0]],
[-1.04921, [3, -0.16, 0], [3, 0, 0]]])
names.append("LElbowYaw")
times.append([1, 1.48])
keys.append([[-1.71505, [3, -0.333333, 0], [3, 0.16, 0]],
[-1.49416, [3, -0.16, 0], [3, 0, 0]]])
names.append("LHand")
times.append([1, 1.48])
keys.append([[0.0296, [3, -0.333333, 0], [3, 0.16, 0]],
[0.0296, [3, -0.16, 0], [3, 0, 0]]])
names.append("LShoulderPitch")
times.append([1, 1.48])
keys.append([[1.20875, [3, -0.333333, 0], [3, 0.16, 0]],
[1.53856, [3, -0.16, 0], [3, 0, 0]]])
names.append("LShoulderRoll")
times.append([1, 1.48])
keys.append([[0.171766, [3, -0.333333, 0], [3, 0.16, 0]],
[-0.220938, [3, -0.16, 0], [3, 0, 0]]])
names.append("LWristYaw")
times.append([1, 1.48])
keys.append([[-0.983336, [3, -0.333333, 0], [3, 0.16, 0]],
[0.96331, [3, -0.16, 0], [3, 0, 0]]])
try:
# uncomment the following line and modify the IP if you use this script outside Choregraphe.
# motion = ALProxy("ALMotion", IP, 9559)
motion = ALProxy("ALMotion")
motion.moveInit()
w = motion.post.angleInterpolationBezier(names, times, keys)
self.tts.say(gender)
motion.wait(w, 0)
except BaseException, err:
print err
View File
Whitespace-only changes.
View File
Whitespace-only changes.
BIN
View File
Binary file not shown.
+194
View File
@@ -0,0 +1,194 @@
import numpy as np
import importlib
import os
import soundfile as sf
import sounddevice as sd
import scipy.signal as sis
from picka_definition import main as pickaDef
from tools.to_noise import noise
from gender.cosgate import cosgate
from tools.load_matrix import loadmat
from scipy.io import savemat
from Robot.Robot import Robot
from naoqi import ALBroker
from tools.exit_condition import ExitExperimentModule
def main(language, game, att, interface):
# TODO Add interface part
# gain_field_colour = np.array([6.3, 74.5, 41.6]) / 100 * .4 + .6
calibration = {}
att = float(att)
if not os.path.exists('./calibration.mat'):
calibration["fishy"] = 0
calibration["gender"] = 0
calibration["emotion"] = 0
calibration["crm"] = 0
else:
mat = loadmat('./calibration.mat')
calibration = mat["calibration"]
options = {}
options["subject_name"] = ""
options["language"] = language
if game == "fishy":
folder = "./fishy"
fx_prefix = "expe"
calibration["fishy"] = att
elif game == "gender":
folder = "./gender"
fx_prefix = "gender"
options["phase"] = "generation"
options["language"] = language
calibration["gender"] = att
elif game == "emotion":
folder = "./emotion"
fx_prefix = "emotion"
calibration["emotion"] = att
elif game == "crm":
folder = "./crm"
fx_prefix = "crm"
calibration["crm"] = att
scripts = []
PICKA = pickaDef()
for i in range(len(PICKA)):
scripts.append(os.path.join(
PICKA["def" + str(i)]["folder"], PICKA["def" + str(i)]["prefix"]))
length_sample = 30
spectrum_max = -np.inf
experiments = {}
# for i in range(len(scripts)):
# script = scripts[i]
# folder, fx_prefix = os.path.split(script)
experiments["scr" + str(i)] = {}
experiments["scr" + str(i)]["folder"] = folder
experiments["scr" + str(i)]["fx_prefix"] = fx_prefix
# os.chdir(folder)
# print os.getcwd()
# try:
package = folder.split("/")[1]
fh_options = importlib.import_module(
"..{}_options".format(fx_prefix), package="{}.{}_options".format(package, fx_prefix))
fh_build = importlib.import_module(
"..{}_build_conditions".format(fx_prefix), package="{}.{}_build_conditions".format(package, fx_prefix))
experiments["scr" + str(i)]["fh_options"] = fh_options
experiments["scr" + str(i)]["fh_build"] = fh_build
options = fh_options.expe_options(options)
_, options = fh_build.expe_build_conditions(options)
if not "sounds_for_calibration" in options:
raise ValueError(
"Options does not contain sounds_for_calibration")
if len(options["sounds_for_calibration"]) == 0:
raise ValueError(
"There are no sounds for calibration. Try preprocessing first.")
print "Checking if RMS of calibration sounds are equal."
x = np.array([])
RMSs = np.zeros(len(options["sounds_for_calibration"]))
previous_fs = []
for k in range(len(options["sounds_for_calibration"])):
y, fs = sf.read(options["sounds_for_calibration"][k])
if previous_fs and previous_fs != fs:
raise ValueError("File {} does not have the same sampling frequency ({} Hz) as the previous one ({} Hz).".format(
options["sounds_for_calibration"][k], fs, previous_fs))
previous_fs = fs
RMSs[k] = np.sqrt(np.mean(y**2))
x = np.hstack((x, y))
mRMS = np.mean(RMSs)
print "RMS: min=%.3f, avg=%.3f, max=%.3f" % (
np.min(RMSs), mRMS, np.max(RMSs))
print "The sampling frequency is %d Hz." % fs
print "Converting to noise..."
print np.size(x)
noisy_x = noise(x, fs)
if len(noisy_x) < fs*length_sample:
noisy_x = np.tile(noisy_x, int(np.ceil(
fs*length_sample/len(noisy_x))))
noisy_x = noisy_x[:np.min(len(noisy_x))]
NOISY_X = 20 * np.log10(np.abs(np.fft.fft(noisy_x)) /
np.sqrt(len(noisy_x)))
w = sis.hann(256)
w = w / np.sum(w)
NOISY_X = np.convolve(NOISY_X, w, mode='same')
f = (np.arange(len(noisy_x)))/(len(noisy_x)) * fs
spectrum_max = np.max(np.array([spectrum_max, int(max(NOISY_X))]))
experiments["scr" + str(i)]["fs"] = fs
experiments["scr" + str(i)]["noise"] = cosgate(noisy_x, fs, 50e-3)
experiments["scr" + str(i)]["noise"] = experiments["scr" +
str(i)]["noise"] * 10.0 ** att/20
# experiments["scr" + str(i)]["gain"] = fh_gain
if interface == "laptop":
sd.play(experiments["scr" + str(i)]["noise"], fs)
elif interface.lower() == "sam":
sam = Robot("sam.local", 9559, language)
sam.aad.setOutputVolume(sam.stimulus_volume)
sf.write("calibration_{}.wav".format(game),
experiments["scr" + str(i)]["noise"], fs)
sam.play_audio("calibration_{}.wav".format(game))
r = raw_input("Save this attenuation value?: ")
if r.lower() == "y":
savemat('./calibration.mat', mdict={"calibration": calibration})
elif r.lower() == 'n':
pass
else:
raise ValueError("That is not a valid option.")
print "done"
# except:
# raise Exception("Error")
if __name__ == "__main__":
import argparse
myBroker = ALBroker("myBroker", "0.0.0.0", 0, "sam.local", 9559)
stop_audio = ExitExperimentModule("stop_audio", myBroker)
parser = argparse.ArgumentParser()
parser.add_argument(
"--language", "-l", help="Language of sound files to calibrate.", choices=["EN", "NL"])
parser.add_argument("--game", "-g", help="Game for calibration",
choices=["fishy", "gender", "emotion", "crm"])
parser.add_argument("--attenuation", "-a",
help="Attenuation to be applied.")
parser.add_argument(
"--interface", "-i", help="Interface that calibration must be perfored for.", choices=["sam", "laptop"])
args = parser.parse_args()
main(args.language, args.game, args.attenuation, args.interface)
View File
Whitespace-only changes.
+236
View File
@@ -0,0 +1,236 @@
import numpy as np
import os
from pick import pick
from parse_corpus import parseCorpus
from scipy.io import savemat
import warnings
from tools.load_matrix import loadmat
CALIBRATE = False
def expe_build_conditions(options):
options["fs"] = 44100
options["gain"] = 0
mat = loadmat('./calibration.mat')
cal = mat["calibration"]
options["attenuation_dB"] = cal["crm"]
# options["attenuation_dB"] = 10 # Calibrated attenuation from fishy
options["target_corpus_language"] = options["language"]
options["target_corpus_path"] = "./stimuli/crm/spk1F-" + \
options["language"].lower()
if options["target_corpus_language"] == "tr_tr":
options["target_corpus_filemask"] = 'cat_*.wav'
else:
options["target_corpus_filemask"] = 'dog_*.wav'
options["target_corpus"] = parseCorpus(options["target_corpus_path"],
options["target_corpus_filemask"])
options["n_colours"] = len(options["target_corpus"]["colours"])
options["n_numbers"] = len(options["target_corpus"]["numbers"])
options["n_call_signs"] = len(options["target_corpus"]["call_signs"])
np.random.shuffle(options["target_corpus"]["colours"])
if options["target_corpus_language"] == "tr_tr":
options["images"] = "girl+cat.jpg"
else:
options["images"] = "woman+dog.jpg"
# Masker options
options["masker_corpus_language"] = options["language"]
options["masker_corpus_path"] = options["target_corpus_path"]
if options["target_corpus_language"] == "tr_tr":
options["masker_corpus_filemask"] = "rabbit_*.wav"
else:
options["masker_corpus_filemask"] = "cat_*.wav"
lst = [
f for f in os.listdir(options["masker_corpus_path"])
if f.startswith(options["masker_corpus_filemask"].split('_')[0])
and f.endswith('.wav')
]
options["masker_corpus"] = lst
options["sounds_for_calibration"] = []
lst = [
f for f in os.listdir(options["target_corpus_path"])
if f.startswith(options["target_corpus_filemask"].split('_')[0])
and f.endswith('.wav')
]
if not CALIBRATE:
for k in range(len(lst)):
options["sounds_for_calibration"].append(
os.path.join(options["target_corpus_path"], lst[k]))
for k in range(len(options["masker_corpus"])):
options["sounds_for_calibration"].append(
os.path.join(options["masker_corpus_path"], lst[k]))
else:
for k in range(10):
options["sounds_for_calibration"].append(
os.path.join(options["target_corpus_path"], lst[k]))
for k in range(10):
options["sounds_for_calibration"].append(
os.path.join(options["masker_corpus_path"], lst[k]))
options["cache_path"] = "./stimuli_store/crm/spk1F-" + \
options["masker_corpus_language"].lower()
if not os.path.exists(options["cache_path"]):
os.makedirs(options["cache_path"])
options["voices"] = {}
i = 1
for dF0 in np.linspace(0, -12, 3):
for dVTL in np.linspace(0, 3.8, 3):
options["voices"]["v" + str(i)] = {}
options["voices"]["v" + str(i)]["dF0"] = dF0
options["voices"]["v" + str(i)]["dVTL"] = dVTL
i += 1
options["n_voices"] = len(options["voices"])
# Check if NH or HI
grp = ""
if "subject_name" in options and options["subject_name"] != "":
grp = options["subject_name"][0:2]
else:
grp = "NH"
if grp == "NH":
options["tmrs"] = np.array([-6, 0, 6, np.inf])
elif grp == "HI" or grp == "CI":
options["tmrs"] = np.array([0, 6, 12, np.inf])
# Strategy on hoe to change the TMR
# - In the 'louder_constant' strategy, the TMR is such that we keep the target level constant for TMRs>0, and the masker level constant for TMRs<0
# - In the 'constant_level' strategy, we keep the overall level constant
options["tmr_strategy"] = 'constant_level'
options["target_delay"] = 750e-3
options["masker_end_delay"] = 250e-3
options["masker_min_chunk_duration"] = 150e-3
options["masker_max_chunk_duration"] = 300e-3
options["masker_chunk_ramp"] = 2e-3
options["masker_ramp"] = 50e-3
options["test"] = {}
options["training"] = {}
options["test"]["n_repeat"] = 7
options["training"]["n_repeat"] = 1
options["training"]["block_size"] = 20
options["test"]["block_size"] = 30
test = {}
for i_repeat in range(options["test"]["n_repeat"]):
for i_tmr in range(len(options["tmrs"])):
if options["tmrs"][i_tmr] == np.inf:
i_voices = np.array([1])
else:
i_voices = np.array([1, 3, 7, 9])
for i_voice in i_voices:
trial = {}
trial["target"] = {}
trial["target"]["colour"], trial["target"][
"colour_index"] = pick(options["target_corpus"]["colours"])
number, trial["target"]["number_index"] = pick(
options["target_corpus"]["numbers"])
trial["target"]["number"] = int(number)
trial["target"]["call_sign"] = options[
"target_corpus_filemask"].split('_')[0]
trial["target"]["sound_file"] = '{}_{}_{}.wav'.format(
trial["target"]["call_sign"], trial["target"]["colour"],
trial["target"]["number"])
trial["image"] = options["images"][0]
trial["voice"] = options["voices"]["v" + str(i_voice)]
trial["voice"]["index"] = i_voice
trial["i_repeat"] = i_repeat
trial["tmr"] = options["tmrs"][i_tmr]
trial["visual_feedback"] = 1
trial["done"] = 0
if 'trials' not in test:
test["trials"] = [trial]
else:
test["trials"].append(trial)
np.random.shuffle(test["trials"])
training = {}
i = 1
for i_repeat in range(options["training"]["n_repeat"]):
for i_voice in range(options["n_voices"]):
trial = {}
trial["target"] = {}
trial["target"]["colour"], trial["target"]["colour_index"] = pick(
options["target_corpus"]["colours"])
number, trial["target"]["number_index"] = pick(
options["target_corpus"]["numbers"])
trial["target"]["number"] = int(number)
trial["target"]["call_sign"] = options[
"target_corpus_filemask"].split('_')[0]
trial["target"]["sound_file"] = '{}_{}_{}.wav'.format(
trial["target"]["call_sign"], trial["target"]["colour"],
trial["target"]["number"])
trial["image"] = options["images"][0]
trial["voice"] = options["voices"]["v" + str(i_voice + 1)]
trial["voice"]["index"] = i_voice
trial["i_repeat"] = i_repeat
if i <= 2:
trial["tmr"] = np.inf
else:
trial["tmr"] = 6
i += 1
trial["visual_feedback"] = 1
trial["done"] = 0
if 'trials' not in training:
training["trials"] = [trial]
else:
training["trials"].append(trial)
training_short = {}
training_short["trials"] = training["trials"][:4]
expe = {}
expe["test"] = test
expe["training"] = training_short
if "res_filename" in options:
savemat(options["res_filename"],
mdict={
"expe": expe,
"options": options
})
else:
warnings.warn("The test file was not saved: no filename provided")
return expe, options
+326
View File
@@ -0,0 +1,326 @@
import os
import sys
from resampy import resample
from scipy.signal import resample_poly
import nnresample
import soundfile as sf
import numpy as np
from pick import pick
from pyworld import pyworld as pw
from gender.cosgate import cosgate
import scipy.io as spio
from scipy import interpolate as spi
from tools.load_matrix import loadmat
np.set_printoptions(threshold=sys.maxsize)
def makeStim(options, trial, is_demo=False):
# trial["target"]["sound_file"] = 'dog_green_8.wav'
print "Reading soundfile '{}' as target...\n".format(
trial["target"]["sound_file"])
x, fs = sf.read(os.path.join(
options["target_corpus_path"], trial["target"]["sound_file"]))
# if fs != options["fs"]:
# x = resample(x, fs, options["fs"], filter='kaiser_fast')
# fs = options["fs"]
x_rms = np.sqrt(np.mean(x**2))
options["reference_rms"] = x_rms
if trial["tmr"] < np.inf:
x = (x / x_rms) * 10 ** (trial["tmr"]/20.0)
else:
x = x / x_rms
options["target_delay"] = 750e-3
options["masker_end_delay"] = 250e-3
target = np.array([])
target = np.append(target, np.zeros(
int(np.round(options["target_delay"] * fs))))
target = np.append(target, x)
target = np.append(target, np.zeros(
int(np.round(options["masker_end_delay"] * fs))))
masker, masker_dict = create_masker(options, trial, len(target))
masker_rms = np.sqrt(np.nanmean(masker**2))
if trial["tmr"] < np.inf:
masker = masker / masker_rms
else:
masker = 0 * masker
z = np.add(target, masker)
z_rms = np.sqrt(np.nanmean(z ** 2))
z = z/z_rms * options["reference_rms"]
info = {}
info["masker"] = masker_dict
return z, fs, info
def create_masker(options, trial, n_samples):
fs = options["fs"]
masker_dict = {}
masker = np.array([])
n_chunk = 1
while len(masker) < n_samples:
sound_file, _ = pick(options["masker_corpus"])
# sound_file = 'cat_pink_6.wav'
masker_dict["stim_" + str(n_chunk)] = {}
masker_dict["stim_" + str(n_chunk)]["soundfile"] = sound_file
y, fs = pyworld_process(os.path.join(
options["masker_corpus_path"], sound_file.strip()), trial["voice"]["dF0"], trial["voice"]["dVTL"], options)
# y = y * np.power(10, -options["attenuation_dB"]/20.0)
y = y * 10.0 ** (options["attenuation_dB"]/20)
chunk_duration = np.random.rand() * (options["masker_max_chunk_duration"] -
options["masker_min_chunk_duration"]) + options["masker_min_chunk_duration"]
chunk_duration = np.round(chunk_duration*fs)
chunk_start = np.random.randint(len(y)-chunk_duration)
chunk_ind = chunk_start + np.array([0, chunk_duration-1])
masker_dict["stim_" + str(n_chunk)]["chunk_indices"] = chunk_ind
chunk = y[int(chunk_ind[0]):int(chunk_ind[1])]
chunk = cosgate(chunk, fs, options["masker_chunk_ramp"])
masker = np.append(masker, chunk)
n_chunk = n_chunk + 1
masker = masker[:n_samples]
masker = cosgate(masker, fs, options["masker_ramp"])
return masker, masker_dict
def pyworld_process(wavIn, dF0, dVTL, options):
# dF0 = 0
# dVTL = 0
_, wavIn_file = os.path.split(wavIn)
wavIn_name, _ = os.path.splitext(wavIn_file)
cache_path = options["cache_path"]
wavOut = make_fname(wavIn, dF0, dVTL, cache_path)
if not os.path.exists(wavOut) or options["force_rebuild_straight_output"]:
if not os.path.exists(cache_path):
os.mkdir(cache_path)
mat = os.path.join(cache_path, wavIn_name + ".pyworld.mat")
f0 = []
fs = 0
sp = []
ap = []
x_rms = 0
if os.path.exists(mat):
load_mat = loadmat(mat)
f0 = load_mat['f0']
fs = load_mat['fs']
freq = load_mat['frequencies']
sp = load_mat['sp']
ap = load_mat['ap']
t = load_mat['temporal_positions']
x_rms = load_mat['x_rms']
else:
x, fs = sf.read(wavIn)
# if fs != options['fs']:
# x = resample(x, fs, options["fs"], filter='kaiser_best')
# fs = options["fs"]
_f0, t = pw.dio(x, fs)
f0, sp, ap = pw.wav2world(x, fs)
freq = np.arange(0, np.size(sp, axis=1),
dtype='float64') / (np.size(sp)) * fs/2
x_rms = np.sqrt(np.mean(x**2))
duration = len(x/fs)
# spio.savemat(mat, mdict={'fs': fs, 'f0': f0,
# 'sp': sp, 'ap': ap,
# 'x_rms': x_rms,
# 'frequencies': freq,
# 'temporal_positions': t,
# 'duration': duration
# })
f0 = f0 * 2.0 ** (dF0/12)
mapp = mapp * 2.0 ** -(dVTL/12)
f0 = f0 * mapp
nfft = (sp.shape[1]-1)*2
f = np.arange(sp.shape[1]) / float(nfft) * float(fs)
t = np.arange(sp.shape[0]) / pw.default_frame_period
sp = Fast2DInterp(t, f, sp, type="cubic")(t, f)
ap = Fast2DInterp(t, f, ap, type="cubic")(t, f)
# sp = sp_ap_creation(sp, t, f, mapp)
# ap = sp_ap_creation(ap, t, f, mapp)
# if f0.flags['C_CONTIGUOUS']:
# f0 = np.ascontiguousarray(f0, dtype=np.float)
# # sp = np.ascontiguousarray(
# # sp, dtype=np.float)
# # ap = np.ascontiguousarray(
# # ap, dtype=np.float)
f0, sp, ap = regularize_arrays(f0, sp, ap)
y_mat = pw.synthesize(f0, sp, ap, fs)
y = np.array(y_mat)
y = y / np.sqrt(np.mean(y ** 2)) * x_rms
my = np.amax(np.absolute(y))
if np.amax(np.absolute(y)) > 1:
# expe_logger.warn("Output was normalised for {}".format(wavOut))
y_magnitude_factor = my/0.98
y = 0.98 * y / np.amax(np.absolute(y))
else:
y_magnitude_factor = 1.0
sf.write(wavOut, y, fs)
else:
y, fs = sf.read(wavOut)
return y, fs
def make_fname(wav, f0, vtl, destPath):
_, namext = os.path.split(wav)
name, ext = os.path.splitext(namext)
fname = "{}_dF0{}_dVTL{}{}".format(name, f0, vtl, ext)
fname = os.path.join(destPath, fname)
return fname
def sp_ap_creation(mat, temp, freq, vtl, type='cubic'):
'''
Interpolates the spectrogram and aperiodicity, respectively
using the same temporal positions, but new freq that takes
into account the ser value (ser = np.power(2, -dVTL/12)).
Ser is usually provided by the defined options in
expe_build_conditions
'''
# x = np.arange(1, mat.shape[1]+1)
# y = np.arange(1, mat.shape[0]+1)
# f = interpolate.interp2d(x, y, mat, kind='cubic')
# f = interpolate.RectBivariateSpline(temp, freq, mat)
if type == 'cubic':
f = spi.RectBivariateSpline(temp, freq, mat)
elif type == 'linear':
f = spi.interp2d(freq, temp, mat, kind='linear')
else:
raise ValueError('Interpolant type unknown: "%s"' % type)
if vtl != 0.0:
interp = f(temp, freq.T/vtl)
else:
interp = f(temp, freq.T/1.0)
return interp
# xs = np.arange(1, spe["spectrogram"].shape[1]+1)
# ys = np.arange(1, spe["spectrogram"].shape[0]+1)
# fis = interp2d(xs, ys, spe["spectrogram"], 'cubic')
# spe["spectrogram"] = fis(spe["temporal_positions"],
# spe["frequencies"]/ser)
def regularize_arrays(*args):
"""
Making sure the arrays passed as arguments are in the right format for pyworld.
"""
out = list()
for x in args:
out.append(np.require(x, requirements='C'))
return tuple(out)
class Fast2DInterp():
"""
Creates an interpolant object based on ``scipy.interpolate.RectBivariateSpline`` but
dealing with out of range values.
The constructor is: ``Fast2DInterp(x, y, z, ofrv=None)`` where ``x`` and ``y``
are 1D arrays and ``z`` is a 2D array. The optional argument ``ofrv`` defines
the value used for out of range inputs. If ``ofrv`` is ``None``, then the
default behaviour of ``RectBivariateSpline`` is kept, i.e. the closest value is
returned.
The default type is ``linear``, which then makes use of ``scipy.interpolate.interp2d``.
With ``cubic``, the ``RectBivariateSpline`` is used.
Note that the class is not so useful in the end when used with ``linear``, but
is useful if you want to use cubic-splines.
"""
def __init__(self, x, y, z, ofrv=None, type='linear'):
self.type = type
if self.type == 'cubic':
self.interpolant = spi.RectBivariateSpline(x, y, z)
elif self.type == 'linear':
self.interpolant = spi.interp2d(y, x, z, kind='linear')
else:
raise ValueError('Interpolant type unknown: "%s"' % type)
self.x_range = (x[0], x[-1])
self.y_range = (y[0], y[-1])
# Out of range value:
self.ofrv = ofrv
def is_in_range(self, w, r):
return np.logical_and(w >= r[0], w <= r[1])
def __call__(self, x, y):
return self.interp(x, y)
def interp_(self, x, y):
if self.type == 'cubic':
return self.interpolant(x, y)
elif self.type == 'linear':
return self.interpolant(y, x)
def interp(self, x, y):
if (np.isscalar(x) or len(x) == 1) and (np.isscalar(y) or len(y) == 1):
if self.ofrv is not None:
if self.is_in_range(x, self.x_range) and self.is_in_range(y, self.y_range):
o = self.interp_(x, y)[0, 0]
else:
o = self.ofrv
else:
o = self.interp_(x, y)[0, 0]
else:
o = self.interp_(x, y)
if self.ofrv is not None:
s = np.logical_and(self.is_in_range(
xx, self.x_range), self.is_in_range(yy, self.y_range))
o[s] = self.ofrv
return o
+18
View File
@@ -0,0 +1,18 @@
import os
def expe_options(options):
options["result_path"] = "./results/" + options["subject_name"]
if not os.path.exists(options["result_path"]):
os.mkdir(options["result_path"])
options["result_prefix"] = "crm_"
options["experiment_label"] = "PICKA :: CRM"
options["force_rebuild_straight_output"] = False
options["experiment_begin"] = 1
return options
+219
View File
@@ -0,0 +1,219 @@
import numpy as np
import soundfile as sf
import time
import datetime
import sys
import os
import cPickle as pickle
from tools.load_matrix import loadmat
from scipy.io import savemat
from Robot.RobotCRM import RobotCRM
from crm_make_stimulus import makeStim
def robot(ip, port, lang, options, phase):
results = {}
sam = RobotCRM(ip, port, lang, options["subject_name"])
try:
saveFromPickle(options)
except IOError:
pass
mat = loadmat(options["res_filename"])
expe = mat["expe"]
options = mat["options"]
if "results" in mat:
results = mat["results"]
track = loadmat(options["res_tracker"])
exp = track["tracker"]
nbreak = 0
starting = 1
simulate = False
done = []
while np.mean(done) != 1:
done = []
for i in range(len(expe[phase]["trials"])):
done.append(expe[phase]["trials"][i]["done"])
nbreak += 1
if nbreak > options[phase]["block_size"]:
nbreak = 0
# TODO: Something to add a break.
try:
i_trial = done.index(0)
except ValueError:
break
track_trial = i_trial + 1
if exp["experiment_begin"]:
trials = {
"current_trial": track_trial,
"total_trials": len(expe[phase]["trials"])
}
with open('./crm/trials.p', 'wb') as f:
pickle.dump(trials, f)
time.sleep(5)
# sam.intro()
exp["experiment_begin"] = 0
savemat(options["res_tracker"], mdict={"tracker": exp})
if starting:
trials = {
"current_trial": track_trial,
"total_trials": len(expe[phase]["trials"])
}
with open('./crm/trials.p', 'wb') as f:
pickle.dump(trials, f)
if phase == "test":
if lang == "EN":
sam.simple_say("Welcome to the testing phase of the game.")
elif lang == "NL":
sam.simple_say(
"Welkom bij de testronde van dit spelletje.")
else:
# sam.crmIntro()
pass
# sam.crmIntro()
sam.game_break()
if phase == "test" and i_trial == np.round(len(done) / 2):
if lang == "EN":
sam.simple_say("You've reached halfway.")
if lang == "NL":
sam.simple_say("")
sam.take_break()
starting = 0
# for i in range(len(expe[phase]["trials"])):
# done.append(expe[phase]["trials"][i]["done"])
# nbreak += 1
# if nbreak > options[phase]["block_size"]:
# nbreak = 0
# # TODO: Something to add a break.
# try:
# i_trial = done.index(0)
# except ValueError:
# break
trial = expe[phase]["trials"][i_trial]
xOut, fs, info = makeStim(options, trial)
# xOut = xOut*np.power(10, options["attenuation_dB"]/20)
xOut = xOut * 10.0**(options["attenuation_dB"] / 20)
m = np.max(np.abs(xOut))
if m > .98:
xOut = xOut / m * .98
print "xOut was rescaled to avoid clipping by a factor %.2f" % (
0.98 / m)
sf.write('stimulus.wav', xOut, fs)
correct_answer = {
"colour": trial["target"]["colour"],
"number": trial["target"]["number"]
}
# === Play stimulus then delete file
sam.aad.setOutputVolume(sam.stimulus_volume)
sam.play_sounds('stimulus.wav', lang)
sam.aad.setOutputVolume(sam.speaking_volume)
# os.remove('stimulus.wav)
# === Get response
response = {}
response["timestamp"] = str(datetime.datetime.now())
if not simulate:
resp, resp_time = sam.answer(correct_answer,
trial["visual_feedback"], track_trial,
len(expe[phase]["trials"]))
else:
resp = {"number": 4, "colour": "pink"}
resp_time = 1.0
response["response_time(ms)"] = round(resp_time * 100, 2)
# resp = correct_answer
response["colour"] = resp["colour"]
response["number"] = resp["number"]
response["correct"] = response["colour"] == correct_answer[
"colour"] and response["number"] == correct_answer["number"]
response["info"] = info
response["trial"] = trial
# === Save results
if not phase in results:
results[phase] = {}
results[phase]["responses"] = np.array([response])
else:
results[phase]["responses"] = np.append(
results[phase]["responses"], response)
expe[phase]["trials"][i_trial]["done"] = 1
a = time.time()
pickle.dump(
expe, open("{}/expe_temp.p".format(options["result_path"]), 'wb'))
pickle.dump(
options,
open("{}/options_temp.p".format(options["result_path"]), 'wb'))
pickle.dump(
results,
open("{}/results_temp.p".format(options["result_path"]), 'wb'))
print "results saved: " + str(time.time() - a)
if phase == "training":
if lang == "EN":
sam.simple_say("That's the end of the training phase.")
elif lang == "NL":
sam.simple_say("Dit is het einde van de oefenronde ")
else:
exp["experiments"]["crm"] = 1
savemat(options["res_tracker"], mdict={"tracker": exp})
if lang == "EN":
sam.simple_say("That's the end of the testing phase. Well done.")
elif lang == "NL":
sam.simple_say("Dit is het einde van de test. Goed gedaan.")
exp_tracker = np.array(
[exp["experiments"][key] for key in exp["experiments"].keys()])
saveFromPickle(options)
if np.mean(exp_tracker) == 1:
sam.ending()
# except:
# saveFromPickle(options)
# savemat(options["res_filename"], mdict={
# "expe": expe, "options": opt, "results": results})
def saveFromPickle(options):
print "-------"
print "Loading results"
print "-------"
try:
expe = pickle.load(
open("{}/expe_temp.p".format(options["result_path"]), 'rb'))
opt = pickle.load(
open("{}/options_temp.p".format(options["result_path"]), 'rb'))
results = pickle.load(
open("{}/results_temp.p".format(options["result_path"]), 'rb'))
os.remove("{}/expe_temp.p".format(options["result_path"]))
os.remove("{}/options_temp.p".format(options["result_path"]))
os.remove("{}/results_temp.p".format(options["result_path"]))
savemat(options["res_filename"],
mdict={
"expe": expe,
"options": opt,
"results": results
})
except Exception as e:
print e
return
+42
View File
@@ -0,0 +1,42 @@
import os
from crm_options import expe_options as crmOptions
from scipy.io import savemat
from crm_robot import robot
from crm_build_conditions import expe_build_conditions as buildConditions
from tools.load_matrix import loadmat
def main(options, subject, phase, lang, p_exists, ip, port):
options = {}
options["subject_name"] = subject
options = crmOptions(options)
options["language"] = lang
res_filename = os.path.join(options["result_path"], '{}{}_{}_robot.mat'.format(
options["result_prefix"], lang.lower(), subject))
options["res_filename"] = res_filename
res_tracker = os.path.join(
options["result_path"], '{}_tracker.mat'.format(subject))
options["res_tracker"] = res_tracker
if not os.path.exists(res_tracker):
track = {}
track["experiment_begin"] = 1
track["experiments"] = {}
track["experiments"]["fishy"] = 0
track["experiments"]["gender"] = 0
track["experiments"]["emotion"] = 0
track["experiments"]["crm"] = 0
savemat(res_tracker, mdict={"tracker": track})
if not os.path.exists(res_filename):
expe, options = buildConditions(options)
else:
mat = loadmat(options["res_filename"])
expe = mat["expe"]
options = mat["options"]
robot(ip, port, lang, options, phase)
+28
View File
@@ -0,0 +1,28 @@
import os
import numpy as np
def parseCorpus(folder, filemask):
lst = [f for f in os.listdir(
folder) if f.startswith(filemask.split('_')[0])]
call_signs = []
colours = []
numbers = []
for i in range(len(lst)):
_, filename = os.path.split(lst[i])
f, _ = os.path.splitext(filename)
parts = f.split('_')
call_signs.append(parts[0])
colours.append(parts[1])
numbers.append(int(parts[2]))
corpus = {}
corpus["call_signs"] = np.unique(call_signs)
corpus["colours"] = np.unique(colours)
corpus["numbers"] = np.unique(numbers)
return corpus
+14
View File
@@ -0,0 +1,14 @@
import numpy as np
def pick(lst):
if len(locals()) < 2:
n = 1
lst = np.array(lst)
# i = np.random.permutation(len(lst))
i = np.random.randint(len(lst))
k = lst[i]
return k, i
+50
View File
@@ -0,0 +1,50 @@
import os
import numpy as np
from crm_options import expe_options as crmOptions
from crm_build_conditions import expe_build_conditions as buildConditions
from crm_make_stimulus import pyworld_process
def preprocess(mode, language, force):
options = {}
options["language"] = language
options["subject_name"] = ""
options = crmOptions(options)
expe, options = buildConditions(options)
options["force_rebuild_pyworld_output"] = force
print "=== Analysing all masker files ==="
for i in range(len(options["masker_corpus"])):
fname = options["masker_corpus"][i]
fname = os.path.join(options["masker_corpus_path"], fname)
print "%02d/%d Analysing '%s' \n" % (i + 1,
len(options["masker_corpus"]), fname)
for j in range(1, len(options["voices"]) + 1):
voice = options["voices"]["v" + str(j)]
pyworld_process(fname, voice["dF0"], voice["dVTL"], options)
if mode == "all":
print "=== Synthesizing for all masker files ==="
trials = expe["training"]["trials"] + expe["test"]["trials"]
k = 1
for i in range(len(trials)):
trial = trials[i]
for j in range(len(options["masker_corpus"])):
fname = options["masker_corpus"][j]
fname = os.path.join(
options["masker_corpus_path"], fname)
print "%04d/%d Synthesizing'%s' for dF0=%.2f st, dVTL=%.2f st\n" % (k, len(trials) * len(
options["masker_corpus"]), fname, trial["voice"]["dF0"], trial["voice"]["dVTL"])
pyworld_process(
fname, trial["voice"]["dF0"], trial["voice"]["dVTL"], options)
k += 1
print "\n"
View File
Whitespace-only changes.
+187
View File
@@ -0,0 +1,187 @@
# --------------------------------------------------------------------------
# Authors:
# ------ MATlAB ------
# Paolo Toffanin <p.toffanin@umcg.nl>, RuG, UMCG, Groningen, NL
# Jacqueline Libert
# Leanne Nagels < leanne.nagels@rug.nl >
# Etienne Gaudrain <etienne.gaudrain@cnrs.fr> - 2017-12-05
# CNRS, CRNL, Lyon, FR | RuG, UMCG, Groningen, NL
# ------ Python ------
# 2020-04-13: Luke Meyer < l.meyer.5@student.rug.nl >
# Copyright MRC-CBSU(UK), CNRS(FR), UMCG(NL) and the author(s).
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY
# without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see < http: // www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
import numpy as np
from scipy import io as sio
import warnings
import os
import re
from tools.load_matrix import loadmat
def expe_build_conditions(options):
'''
Creates the EXPE structure that contains the trials for the PICKA
Emotion experiment.
Note: the emotion names listed in options[test][emotions] must coincide
with the file names of the sound material, as well as with the file
names of the sprite images.
'''
# options["sound_folder"] = "./stimuli/emotion/en"
options["sound_folder"] = "./stimuli/emotion/"
options["sound_filemask"] = ".wav"
mat = loadmat('./calibration.mat')
cal = mat["calibration"]
options["attenuation_dB"] = cal["emotion"]
# Parse the corpus
options = parse_corpus(options)
# Select emotions for test
options["test"]["emotions"] = ['angry', 'sad', 'happy']
options["order_button_emotions"] = np.random.permutation(
options["test"]["emotions"])
# Select emotions for training
options["training"]["emotions"] = ['angry', 'sad', 'happy']
options["order_button_emotions"] = np.random.permutation(
options["training"]["emotions"])
for e in range(len(options["test"]["emotions"])):
if options["test"]["emotions"][e] not in options["test"]["corpus"]:
raise ValueError("Emotion '{}' was not found in the selected corpus...".format(
options["test"]["emotions"][e]))
# Number of repetitions per emotion
options["test"]["n_repeat"] = float("Inf")
# === Create the test trials ===
test = {}
for i_emotion in range(len(options["test"]["emotions"])):
emotion = options["test"]["emotions"][i_emotion]
n = len(options["test"]["corpus"][emotion])
if np.isinf(options["test"]["n_repeat"]):
item_order = np.array(range(0, n))
else:
item_order = []
while len(item_order) < options["test"]["n_repeat"]:
item_order.append(np.random.permutation(
np.min([options["test"]["n_repeat"], n])))
for ir in range(int(np.min([options["test"]["n_repeat"], len(item_order)]))):
trial = options["test"]["corpus"][emotion][item_order[ir]]
trial["emotion"] = emotion
trial["i_repeat"] = ir
trial["done"] = 0
if not "trials" in test:
test["trials"] = [trial]
else:
test["trials"].append(trial)
expe = {}
expe["test"] = {}
expe["test"]["trials"] = np.random.permutation(test["trials"])
# === Create the training trials ===
training = {}
for i_trial in range(len(options["training"]["corpus"])):
trial = options["training"]["corpus"][i_trial]
trial["done"] = 0
if not "trials" in training:
training["trials"] = [trial]
else:
training["trials"].append(trial)
expe["training"] = {}
expe["training"]["trials"] = np.random.permutation(training["trials"])
if "res_filename" in options:
sio.savemat(options["res_filename"], mdict={
'expe': expe, 'options': options})
else:
warnings.warn("The test file was not saved: no filename provided.")
return expe, options
def parse_corpus(options):
options["sounds_for_calibration"] = {}
if not "test" in options:
options["test"] = {}
if not "training" in options:
options["training"] = {}
options["test"]["corpus"] = {}
lst = [f for f in os.listdir(os.path.join(
options["sound_folder"])) if f.endswith(options["sound_filemask"])]
for k in range(len(lst)):
options["sounds_for_calibration"][k] = os.path.join(
options["sound_folder"], lst[k])
_, fname = os.path.split(lst[k])
tokens = re.split("[" + re.escape("_") + "]", fname)
if tokens[0] == "training":
item = {}
item["file"] = lst[k]
item["talker"] = float(tokens[1][1:])
item["emotion"] = tokens[2]
item["sentence"] = float(tokens[3][1:])
item["utterance"] = float(tokens[4][1:].split(".")[0])
if not "corpus" in options["training"]:
options["training"]["corpus"] = [item]
else:
options["training"]["corpus"].append(item)
else:
item = {}
item["file"] = lst[k]
item["talker"] = float(tokens[0][1:])
emotion = tokens[1]
item["sentence"] = float(tokens[2][1:])
item["utterance"] = float(tokens[3][1:].split(".")[0])
if not emotion in options["test"]["corpus"]:
options["test"]["corpus"][emotion] = [item]
else:
options["test"]["corpus"][emotion].append(item)
return options
def explode(sep, string):
rem = string
table = []
while rem:
tokens = re.split("[" + re.escape(sep) + "]", rem)
token = tokens[0]
rem = sep.join(tokens[1:])
table.append(token)
return table
+49
View File
@@ -0,0 +1,49 @@
# --------------------------------------------------------------------------
# Authors:
# ------ MATlAB ------
# Paolo Toffanin <p.toffanin@umcg.nl>, RuG, UMCG, Groningen, NL
# Jacqueline Libert
# Leanne Nagels < leanne.nagels@rug.nl >
# Etienne Gaudrain <etienne.gaudrain@cnrs.fr> - 2017-12-05
# CNRS, CRNL, Lyon, FR | RuG, UMCG, Groningen, NL
# ------ Python ------
# 2020-04-13: Luke Meyer < l.meyer.5@student.rug.nl >
# Copyright MRC-CBSU(UK), CNRS(FR), UMCG(NL) and the author(s).
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY
# without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see < http: // www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
import os
def expe_options(options):
options["result_path"] = "./results/" + options["subject_name"]
if not os.path.exists(options["result_path"]):
os.mkdir(options["result_path"])
# result prefix
options["result_prefix"] = "emo_"
# label
options["experiment_label"] = "PICKA :: Emotion"
# options["subject_age"] = subject["age"]
# options["subject_sex"] = subject["sex"]
options["res_filename"] = os.path.join(options["result_path"], "{}{}_{}_robot.mat".format(
options["result_prefix"], options["language"].lower(), options["subject_name"]))
options["experiment_begin"] = 1
return options
+169
View File
@@ -0,0 +1,169 @@
# --------------------------------------------------------------------------
# Authors:
# ------ MATlAB ------
# Paolo Toffanin <p.toffanin@umcg.nl>, RuG, UMCG, Groningen, NL
# Jacqueline Libert
# Leanne Nagels < leanne.nagels@rug.nl >
# Etienne Gaudrain <etienne.gaudrain@cnrs.fr> - 2017-12-05
# CNRS, CRNL, Lyon, FR | RuG, UMCG, Groningen, NL
# ------ Python ------
# 2020-04-13: Luke Meyer < l.meyer.5@student.rug.nl >
# Copyright MRC-CBSU(UK), CNRS(FR), UMCG(NL) and the author(s).
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY
# without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see < http: // www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
import os
import numpy as np
import soundfile as sf
import datetime
import time
from Robot.RobotEmotion import RobotEmotion
from tools.load_matrix import loadmat
from scipy import io as sio
def robot(ip, port, lang, options, phase):
# -- Start an instance of SAM
sam = RobotEmotion(ip, port, lang)
# -- Set initial volume
# NAO
simulateSubj = False
if options["subject_name"] == "test":
simulateSubj = True
# Create the result dictionary and load the subject's results/options file
results = {}
mat_contents = loadmat(options["res_filename"])
expe = mat_contents['expe']
options = mat_contents['options']
track = loadmat(options["res_tracker"])
exp = track["tracker"]
if not "gain" in options:
options["gain"] = 0
# === Main Loop ===
ladderstep = 1
starting = 1
itrial_session = 0
done = []
# === Main Loop that runs experiment ===
while np.mean(done) != 1:
# Reintialises the done array and reappend for when a task has been completed
done = []
for i in range(len(expe[phase]["trials"])):
done.append(expe[phase]["trials"][i]["done"])
try:
i_trial = done.index(0)
itrial_session = itrial_session + 1
except ValueError:
break
print "Trial {} of {}".format(itrial_session, len(done) + 1)
if exp["experiment_begin"]:
# NAO
sam.intro()
exp["experiment_begin"] = 0
sio.savemat(options["res_tracker"], mdict={"tracker": exp})
if starting:
if phase == "test":
if lang == "EN":
sam.simple_say("Welcome to the testing phase of the game.")
elif lang == "NL":
sam.simple_say(
"Welkom bij de testronde van dit spelletje.")
else:
# NAO
sam.emotionIntro()
pass
sam.game_break()
starting = 0
trial = expe[phase]["trials"][i_trial]
# y, fs = sf.read(os.path.join(options["sound_folder"], trial["file"]))
os.chdir(options["sound_folder"])
x, fs = sf.read(trial["file"])
x = x * 10.0 ** options["attenuation_dB"]/20
sf.write('./gen_stimulus.wav', x, fs)
# NAO
sam.aad.setOutputVolume(sam.stimulus_volume)
sam.play_sounds('gen_stimulus.wav', lang)
sam.aad.setOutputVolume(sam.speaking_volume)
os.remove('./gen_stimulus.wav')
os.chdir('../../')
tic = time.time()
response = {}
response["trial"] = trial
if simulateSubj:
# response["timestamp"] = datetime.datetime.now()
response["response_time(ms)"] = round((time.time() - tic)*100, 2)
response["emotion"] = options[phase]["emotions"][np.random.randint(
len(options[phase]["emotions"]))]
response["correct"] = response["emotion"] == trial["emotion"]
else:
response["timestamp"] = datetime.datetime.now()
response["emotion"] = sam.answer(trial["emotion"], 1)
response["response_time"] = round((time.time() - tic)*100, 2)
response["correct"] = response["emotion"] == trial["emotion"]
print("Clicked button: {}\n".format(response["emotion"]))
print("Response time: {} ms\n".format(
round(response["response_time"] * 1000)))
print("Response correct: {} \n\n".format(response["correct"]))
expe[phase]["trials"][i_trial]["done"] = 1
if not phase in results:
results[phase] = {}
results[phase]["responses"] = [response]
else:
results[phase]["responses"].append(response)
sio.savemat(options["res_filename"], mdict={
"options": options, "expe": expe, "results": results})
if phase == "training":
if lang == "EN":
sam.simple_say("That's the end of the training phase")
elif lang == "NL":
sam.simple_say("Dit is het einde van de oefenronde ")
else:
exp["experiments"]["emotion"] = 1
sio.savemat(options["res_tracker"], mdict={"tracker": exp})
if lang == "EN":
sam.simple_say(
"That's the end of the testing phase, and the end of this game.")
elif lang == "NL":
sam.simple_say(
"Dit is het einde van de test, en het einde van dit spelletje.")
exp_tracker = np.array([exp["experiments"][key]
for key in exp["experiments"].keys()])
if np.mean(exp_tracker) == 1:
sam.ending()
+95
View File
@@ -0,0 +1,95 @@
# --------------------------------------------------------------------------
# Authors:
# ------ MATlAB ------
# Paolo Toffanin <p.toffanin@umcg.nl>, RuG, UMCG, Groningen, NL
# Jacqueline Libert
# Leanne Nagels < leanne.nagels@rug.nl >
# Etienne Gaudrain <etienne.gaudrain@cnrs.fr> - 2017-12-05
# CNRS, CRNL, Lyon, FR | RuG, UMCG, Groningen, NL
# ------ Python ------
# 2020-04-13: Luke Meyer < l.meyer.5@student.rug.nl >
# Copyright MRC-CBSU(UK), CNRS(FR), UMCG(NL) and the author(s).
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY
# without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see < http: // www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
import os
import sys
from scipy.io import savemat
from emotion_options import expe_options as emotion_options
from emotion_build_conditions import expe_build_conditions as build_conditions
from emotion_robot import robot
def main(options, subject, phase, lang, p_exists, ip, port):
options = {}
options["subject_name"] = subject
options["language"] = lang
options = emotion_options(options)
if p_exists is not None:
res_tracker = os.path.join(
options["result_path"], '{}_tracker.mat'.format(subject))
options["res_tracker"] = res_tracker
if not os.path.exists(res_tracker):
track = {}
track["experiment_begin"] = 1
track["experiments"] = {}
track["experiments"]["fishy"] = 0
track["experiments"]["gender"] = 0
track["experiments"]["emotion"] = 0
track["experiments"]["crm"] = 0
savemat(res_tracker, mdict={"tracker": track})
if not p_exists:
build_conditions(options)
else:
res_tracker = os.path.join(
options["result_path"], '{}_tracker.mat'.format(subject))
options["res_tracker"] = res_tracker
if not os.path.exists(res_tracker):
track = {}
track["experiment_begin"] = 1
track["experiments"] = {}
track["experiments"]["fishy"] = 0
track["experiments"]["gender"] = 0
track["experiments"]["emotion"] = 0
track["experiments"]["crm"] = 0
savemat(res_tracker, mdict={"tracker": track})
if not os.path.exists(options["res_filename"]):
msg = "The subject '{}' does not exist. Create it?".format(
options["subject_name"])
print msg
ans = raw_input("(Y/n): ")
if ans.lower() == 'y':
build_conditions(options)
elif ans.lower() == 'n':
sys.exit()
else:
raise "that is not a valid choice"
else:
msg = "Found {}. Use this file?".format(subject)
print msg
ans = raw_input("(Y/n): ")
if ans.lower() == 'n':
sys.exit()
robot(ip, port, lang, options, phase)
View File
Whitespace-only changes.
+327
View File
@@ -0,0 +1,327 @@
# --------------------------------------------------------------------------
# Authors:
# ------ MATlAB ------
# 2010-03-15: Etienne Gaudrain < etienne.gaudrain@mrc-cbu.cam.ac.uk >
# 2011-10-20: Etienne Gaudrain < etienne.gaudrain@mrc-cbu.cam.ac.uk >
# 2013-04-22: Etienne Gaudrain < e.p.c.gaudrain@rug.nl >
# 2017-03-27: Etienne Gaudrain < etienne.gaudrain@cnrs.fr >
# ------ Python ------
# 2020-01-28: Luke Meyer < l.meyer.5@student.rug.nl >
# Copyright MRC-CBSU(UK), CNRS(FR), UMCG(NL) and the author(s).
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY
# without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see < http: // www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
from expe_options import expe_options
from collections import OrderedDict
import warnings
import scipy.io as sio
import cPickle
import random
import numpy as np
import glob
import os
from tools.load_matrix import loadmat
def expe_build_conditions(options):
'''
This function creates the list of conditions that will be tested in the
experiment.
Without argument, it just returns the `expe` structure as well as the
list of `options`.
With an option argument that contains a `res_filename` field, it saves
them in a result file.
Modify the "Build test block" section to change which conditions are to
be stested.
WARNING: Once saved in a result file, the conditions are not modified
anymore at runtime even if the code is modified. This is done on purpose
so that we always know what were the options used for a specific
experimental session.
'''
# If all syllables need to be rebuilt (overwrites cached files)
FORCE_REBUIL_SYLLS = 0
# --- GUI options ---
options["instructions"] = {}
options["instructions"]["training"] = "You are going to hear three triplets of different syllables. \n" +\
"One of the triplets is said with a different voice. \n" +\
"Your task is to click on the button that corresponds to the different voice. \n"
options["instructions"]["test"] = options["instructions"]["training"]
# --- Signal options ---
options["fs"] = 44100
# options["attenuation_dB"] = 27 # General attenuation
mat = loadmat('./calibration.mat')
cal = mat["calibration"]
options["attenuation_dB"] = cal["fishy"] # Calibrated attenuation
options["ear"] = "both" # right, left, or both
# --- Design specifications ---
options["test"] = {}
options["test"]["n_repeat"] = 1 # Number of repetition per condition
options["test"]["step_size_modifier"] = 1/np.sqrt(2)
# When difference <= to this times the step-size, decrease the step size
options["test"]["change_step_size_condition"] = 2
# Change step-size every n trials
options["test"]["change_step_size_n_trials"] = 15
options["test"]["initial_step_size"] = 2 # Semitones
options["test"]["starting_difference"] = 12 # Semitones
options["test"]["down_up"] = np.array([2, 1]) # 2-down, 1-up => 70.7%
options["test"]["terminate_on_n_turns"] = 8
options["test"]["terminate_on_n_trials"] = 100
options["test"]["retry"] = 1 # number of retries if measure failed
options["test"]["threshold_on_last_n_trials"] = 6
options["training"] = {}
options["training"]["n_repeat"] = 1 # Number of repetition per condition
options["training"]["step_size_modifier"] = 1
# When difference <= to this times the step-size, decrease the step size
options["training"]["change_step_size_condition"] = 1
# Change step-size every n trials
options["training"]["change_step_size_n_trials"] = 15
options["training"]["initial_step_size"] = 3 # Semitones
options["training"]["starting_difference"] = 6 # Semitones
options["training"]["down_up"] = np.array([2, 1]) # 2-down, 1-up => 70.7%
options["training"]["terminate_on_n_turns"] = 0
options["training"]["terminate_on_n_trials"] = 6
options["training"]["retry"] = 0 # number of retries if measure failed
options["training"]["threshold_on_last_n_trials"] = 5
# --- Stimuli options ---
ref_f0 = 242.0 # This is the average pitch of the original voice
options["ref_f0"] = ref_f0
options["test"]["voices"] = {}
options["test"]["voices"]["v1"] = {}
options["test"]["voices"]["v1"]["label"] = 'female'
options["test"]["voices"]["v1"]["f0"] = ref_f0
options["test"]["voices"]["v1"]["ser"] = 1.0
options["test"]["voices"]["v2"] = {}
options["test"]["voices"]["v2"]["label"] = 'male'
options["test"]["voices"]["v2"]["f0"] = ref_f0/2.0
options["test"]["voices"]["v2"]["ser"] = 1 * np.power(2, -3.8/12)
options["test"]["voices"]["v3"] = {}
options["test"]["voices"]["v3"]["label"] = 'child'
options["test"]["voices"]["v3"]["f0"] = round(ref_f0*np.power(2, 5.0/12))
options["test"]["voices"]["v3"]["ser"] = 1 * np.power(2, 7.0/12)
options["test"]["voices"]["v4"] = {}
options["test"]["voices"]["v4"]["label"] = 'male-gpr'
options["test"]["voices"]["v4"]["f0"] = ref_f0/2.0
options["test"]["voices"]["v4"]["ser"] = 1.0
options["test"]["voices"]["v5"] = {}
options["test"]["voices"]["v5"]["label"] = 'male-vtl'
options["test"]["voices"]["v5"]["f0"] = options["test"]["voices"]["v1"]["f0"]
options["test"]["voices"]["v5"]["ser"] = 1 * np.power(2, -3.8/12)
options["test"]["voices"]["v6"] = {}
options["test"]["voices"]["v6"]["label"] = 'child-gpr'
options["test"]["voices"]["v6"]["f0"] = round(ref_f0*np.power(2, 5.0/12))
options["test"]["voices"]["v6"]["ser"] = 1.0
options["test"]["voices"]["v7"] = {}
options["test"]["voices"]["v7"]["label"] = 'child-vtl'
options["test"]["voices"]["v7"]["f0"] = options["test"]["voices"]["v1"]["f0"]
options["test"]["voices"]["v7"]["ser"] = 1 * np.power(2, 7.0/12)
options["training"]["voices"] = options["test"]["voices"]
# -- Voice pairing choices
# 1 2 : female -> Male
# 1 4 : Female -> Male GPR
# 1 5 : Female -> Male VTL
# 1 3 : Female -> Child
# 1 6 : Female -> Child GPR
# 1 7 : Female -> Child VTL
options["test"]["voice_pairs"] = np.matrix('1 4; 1 5; 1 6; 1 7')
options["training"]["voice_pairs"] = np.matrix('1 2; 1 3')
if options["language"] == "EN":
options["sound_path"] = './stimuli/fishy/en'
options["sound_path_store"] = './stimuli_store/en'
options["tmp_path"] = './tmp/en'
elif options["language"] == "NL":
options["sound_path"] = './stimuli/fishy/nl'
options["sound_path_store"] = './stimuli_store/nl'
options["tmp_path"] = './tmp/nl'
if not os.path.exists(options["tmp_path"]):
os.mkdir(options["tmp_path"])
if not os.path.exists(options["sound_path_store"]):
os.mkdir(options["sound_path_store"])
syllable_list = []
dir_waves = [f for f in os.listdir(
options["sound_path"]) if f.endswith(".wav")]
for file in dir_waves:
if file.endswith(".wav"):
syllable_list.append(file)
for i in range(len(syllable_list)):
syllable_list[i] = syllable_list[i].replace('.wav', '')
options["syllables"] = np.array(syllable_list)
options["sounds_for_calibration"] = []
for f in range(len(dir_waves)):
options["sounds_for_calibration"].append(
os.path.join(options["sound_path"], dir_waves[f]))
options["n_syll"] = 3
options["inter_syllable_silence"] = 50.0e-3
options["syllable_duration"] = 200.0e-3
options["f0_contour_step_size"] = 1.0/3.0 # semitones
# options["f0_contours"] = np.array([[-1, 0, +1], [+1, 0, -1], np.add([-1.0, 1.0, -1.0], 1.0/3), np.subtract([1, -1, 1], 1.0/3), np.add(
# [-1, -1, 1], 1.0/3), np.subtract([1, 1, -1], 1.0/3), np.subtract([-1, 1, 1], 1.0/3), np.add([1, -1, -1], 1.0/3)])
options["f0_contours"] = np.array([[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [
1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]])
options["inter_triplet_interval"] = 250.0e-3
options["force_rebuild_sylls"] = FORCE_REBUIL_SYLLS
# --- Vocoder options ---
# Base Parameters
p = {}
p["envelope"] = {}
p["envelope"]["method"] = 'low-pass'
p["envelope"]["rectify"] = 'half-wave'
p["envelope"]["order"] = 2
p["synth"] = {}
p["synth"]["carrier"] = 'noise'
p["synth"]["filter_before"] = False
p["synth"]["filter_after"] = True
p["synth"]["f0"] = 1.0
options["vocoder"] = {}
options["vocoder"]['v1'] = {}
options["vocoder"]['v1']["label"] = 'noise'
options["vocoder"]['v1']["description"] = 'Noise-band vocoder, 6 bands from 1250 to 7000, envelope cutoff defined per band.'
options["vocoder"]['v1']["parameters"] = p
options["vocoder"]['v2'] = {}
options["vocoder"]['v2']["label"] = 'sin'
options["vocoder"]['v2']["description"] = 'Sinewave vocoder, 6 bands from 1250 to 7000, envelope cutoff defined per band, not refiltered after modulation.'
options["vocoder"]['v2']["parameters"] = p
options["vocoder"]['v2']["parameters"]["synth"]["carrier"] = 'sin'
options["vocoder"]['v2']["parameters"]["synth"]["filter_after"] = False
options["vocoder"]['v3'] = {}
options["vocoder"]['v3']["label"] = 'lownoise'
options["vocoder"]['v3']["description"] = 'Low-noise-noise-band vocoder, 6 bands from 1250 to 7000, envelope cutoff defined per band.'
options["vocoder"]['v3']["parameters"] = p
options["vocoder"]['v3']["parameters"]["synth"]["carrier"] = 'low-noise'
options["vocoder"]["v4"] = {}
options["vocoder"]['v4']["label"] = 'pshc'
options["vocoder"]['v4']["description"] = 'PSHC vocoder, 6 bands from 1250 to 7000, envelope cutoff defined per band.'
options["vocoder"]['v4']["parameters"] = p
options["vocoder"]['v4']["parameters"]["synth"]["carrier"] = 'pshc'
# === Build test block ===
test = {}
# def update(d1, d2):
# for k, v in d2.items():
# if k in d1 and isinstance(v, dict) and isinstance(d1[k], dict):
# update(d1[k], v)
# else:
# d1[k] = v
m, _ = options["test"]["voice_pairs"].shape
for ir in range(options["test"]["n_repeat"]):
for i_vp in range(m): # iterate for each row in voice_pairs
condition = {}
condition["ref_voice"] = options["test"]["voice_pairs"][i_vp, 0]
condition["dir_voice"] = options["test"]["voice_pairs"][i_vp, 1]
condition["visual_feedback"] = 1.0
condition["sound_feedback"] = 1.0
# Should not be removed
condition["i_repeat"] = ir
condition["done"] = 0
condition["attempts"] = 0
if not "conditions" in test:
test["conditions"] = [condition]
else:
test["conditions"].append(condition)
# items = test["conditions"].items()
test["conditions"] = random.sample(
test["conditions"], len(test["conditions"]))
# === Build training block ===
training = {}
m, _ = options["training"]["voice_pairs"].shape
for ir in range(options["training"]["n_repeat"]):
for i_vp in range(m): # iterate for each row in voice_pairs
condition = {}
condition["ref_voice"] = options["training"]["voice_pairs"][i_vp, 0]
condition["dir_voice"] = options["training"]["voice_pairs"][i_vp, 1]
condition["visual_feedback"] = 1.0
condition["sound_feedback"] = 1.0
# Should not be removed
condition["i_repeat"] = ir
condition["done"] = 0
condition["attempts"] = 0
if not "conditions" in training:
training["conditions"] = [condition]
else:
training["conditions"].append(condition)
# items = test["conditions"].items()
# Randomise the order of the conditions
training["conditions"] = random.sample(
training["conditions"], len(training["conditions"]))
# === Create expe dictionary and save .mat file ===
expe = {}
expe["test"] = test
expe["training"] = training
if "res_filename" in options:
# with open(options["res_filename"], 'w') as f:
# cPickle.dump([options, expe, p], f)
sio.savemat(options["res_filename"], mdict={
'expe': expe, 'options': options, 'p': p})
else:
warnings.warn("The test file was not saved: no filename provided.")
return expe, options
+339
View File
@@ -0,0 +1,339 @@
# --------------------------------------------------------------------------
# Authors:
# ------ MATlAB ------
# 2010-03-16: Etienne Gaudrain <etienne.gaudrain@mrc-cbu.cam.ac.uk>
# 2011-10-20: Etienne Gaudrain <etienne.gaudrain@mrc-cbu.cam.ac.uk>
# 2013-04-22: Etienne Gaudrain <e.p.c.gaudrain@rug.nl>
# 2017-03-27: Etienne Gaudrain <etienne.gaudrain@cnrs.fr>
# ------ Python ------
# 2020-02-10: Luke Meyer < l.meyer.5@student.rug.nl >
# Copyright MRC-CBSU(UK), CNRS(FR), UMCG(NL) and the author(s).
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY
# without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see < http: // www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
from pyworld import pyworld as pw
import numpy as np
import os
import math
import warnings
import logging
from time import clock
from scipy import interpolate
import scipy.io as spio
import soundfile as sf
from resampy import resample
import random
import collections
import matplotlib.pyplot as plt
# from audiotsm import phasevocoder
# from audiotsm.io.wav import WavReader, WavWriter
from tools.load_matrix import loadmat
import sys
# -- Uncomment for when using the MATLAB/Python API ---
# import matlab.engine
# future = matlab.engine.start_matlab(async=True)
# eng = future.result()
# eng.addpath('../Nao-PICKA scripts/Expe_files/lib/STRAIGHTV40_006b')
time_logger = logging.getLogger("time_logger")
expe_logger = logging.getLogger("expe_logger")
def expe_make_stim(options, trial, p):
'''
Generates the stimuli files for a given trial
and how the trial has been specified
'''
xOut_temp = collections.OrderedDict()
f0 = [trial["f0"][0], trial["f0"][1]]
ser = [trial["ser"][0], trial["ser"][1]]
for i in range(len(trial["syllables"])):
sylls = trial["syllables"][i]
x = np.array([])
for j in range(len(sylls)):
tmp = f0[i]
octave = options["f0_contour_step_size"] * \
(trial["f0_contours"][j, i] / 12.0)
sf0 = tmp * np.power(2, octave)
t = clock()
y, fs = straight_process(sylls[j], sf0, ser[i], options, p, trial)
# y = y * np.power(10, -options["attenuation_dB"]/20.0)
y = y * 10 ** options["attenuation_dB"]/20.0
stim_time = clock() - t
time_logger.info(
"Time to generate single stimulus: {}".format(stim_time))
if fs != options["fs"]:
y = resample(y, options["fs"], fs, filter="kaiser_fast")
options["fs"] = fs
d1 = int(round(options["syllable_duration"]*fs) - len(y))
if d1 > 0:
# Adds padding because the syllable signal is too short
npad_L = int(math.floor(d1/20))
npad_R = int(d1-npad_L)
nr = int(math.floor(1e-3 * fs))
y[0:nr] = y[0:nr] * np.linspace(0, 1, num=nr).conj().T
y[len(y)-nr:] = y[len(y)-nr:] * np.linspace(1, 0, num=nr).T
y = np.concatenate(
(np.zeros((npad_L,)), y, np.zeros((npad_R,))))
elif d1 < 0:
# The synthesised signal is too long
y = y[0:len(y)-d1]
nr = int(math.floor(1e-3 * fs)) # 1 ms linear ramp at the end
y[len(y)-nr:] = y[len(y)-nr:] * np.linspace(1, 0, num=nr).T
else:
nr = int(math.floor(1e-3 * fs))
y[0:nr] = y[0:nr] * np.linspace(0, 1, num=nr).conj().T
y[len(y)-nr:] = y[len(y)-nr:] * np.linspace(1, 0, num=nr).T
x = np.concatenate((x, y))
zeros = np.zeros(
(int(math.floor(fs*options["inter_syllable_silence"])),))
if j != len(sylls):
x = np.concatenate((x, zeros))
# TODO come back to coding in the vocoder
# if trial["vocoder"] > 0:
# pass
if options["ear"] == 'right':
x = np.matrix([np.zeros(np.size(x))], x)
elif options["ear"] == 'left':
x = np.matrix([x], [np.zeros(np.size(x))])
elif options["ear"] == 'both':
x = np.tile(x, (2, 1)).T
else:
raise ValueError(
"Options.ear = {} is not implemented.".format(options["ear"]))
if i == 0:
xOut_temp[0] = x
xOut_temp[1] = x
else:
xOut_temp[2] = x
# Create a random permutation array according to the length of xOut_temp
i_order = np.random.permutation(len(xOut_temp))
keys = list(xOut_temp.keys())
keys = [keys[i] for i in i_order]
# Create the ordered dictionary that holds the randomised stimuli in the order given
xOut = collections.OrderedDict()
i = 0
for key in keys:
xOut[i] = xOut_temp[key]
i += 1
i_correct = np.where(i_order == 2)
i_correct = i_correct[0][0]
return xOut, fs, i_correct
def straight_process(syll, t_f0, ser, options, p, trial):
'''
Generates the individual stimuli files
'''
wavIn = os.path.join(options["sound_path"], syll + ".wav")
wavOut = make_fname(
wavIn, t_f0, ser, options["syllable_duration"], options["tmp_path"], trial)
y = []
fs = 0
if not os.path.exists(wavOut) or options["force_rebuild_sylls"]:
# Matlab
# mat = os.path.join(options["sound_path"], syll + '.straight.mat')
# PyWorld
mat = os.path.join(options["sound_path_store"], syll + '.pyworld.mat')
# Intialise varibales so they are accessible in the correct scope
f0 = []
fs = 0
sp = []
ap = []
freq = []
temp_pos = []
x_rms = 0
if os.path.exists(mat):
# Load the data from the .mat file
load_mat = loadmat(mat)
f0 = load_mat['f0']
fs = load_mat['fs']
sp = np.array(load_mat['sp'])
ap = np.array(load_mat['ap'])
# Needed for PyWorld
freq = np.array(load_mat["frequencies"])
temp_pos = np.array(load_mat["temporal_positions"])
x_rms = load_mat['x_rms']
else:
pass
x, fs = sf.read(wavIn)
# --- Using MATLAB scripts
# x = x.tolist()
# mat_x = matlab.double(x)
# mat_fs = matlab.single([fs])
# f0, ap = eng.exstraightsource(mat_x, mat_fs)
# --- Using PyWORLD script
# -- Works for f0 and VTL changes
_f0, t = pw.dio(x, fs)
f0 = pw.stonemask(x, _f0, t, fs)
sp = pw.cheaptrick(x, f0, t, fs)
ap = pw.d4c(x, f0, t, fs)
freq = np.arange(0, np.size(sp, axis=1),
dtype='float64') / (np.size(sp)) * fs/2
temp_pos = t
x_rms = np.sqrt(np.mean(x**2))
duration = len(x/fs)
spio.savemat(mat, mdict={'fs': fs, 'f0': f0,
'sp': sp, 'ap': ap,
'x_rms': x_rms,
'frequencies': freq,
'temporal_positions': t,
'duration': duration
})
mf0_arr = []
for i in f0:
if i != 0:
mf0_arr.append(np.log(i))
mf0 = np.e**(np.mean(np.array(mf0_arr)))
for i in range(len(f0)):
if f0[i] != 0:
f0[i] = f0[i] / mf0 * t_f0
# Only necessary when running the MATLAB code
try:
p["timeAxisMappingTable"] = (
options["syllable_duration"] * 1e3)/len(f0)
except ZeroDivisionError as e:
print "-------- ERROR : " + str(e) + ' ------------'
print "length f0 was 0"
p["timeAxisMappingTable"] = 0
p["frequencyAxisMappingTable"] = ser.item()
# --- Uncomment when using the MATLAB scripts
# mat_f0 = f0.tolist()
# mat_f0 = matlab.double(mat_f0)
# mat_sp = sp.tolist()
# mat_sp = matlab.double(mat_sp)
# mat_ap = ap.tolist()
# mat_ap = matlab.double(mat_ap)
# mat_fs = matlab.single([fs])
# y_mat = eng.exstraightsynth(mat_f0, mat_sp, mat_ap, mat_fs, p)
# --- Uncomment when using PyWORLD script
sp = sp_ap_creation(sp, temp_pos, freq, ser)
ap = sp_ap_creation(ap, temp_pos, freq, ser)
if f0.flags['C_CONTIGUOUS']:
f0 = np.ascontiguousarray(f0, dtype=np.float)
sp = np.ascontiguousarray(
sp, dtype=np.float)
ap = np.ascontiguousarray(
ap, dtype=np.float)
y_mat = pw.synthesize(f0, sp, ap, fs)
y = np.array(y_mat)
y = y / np.sqrt(np.mean(y**2)) * x_rms
if np.amax(np.absolute(y)) > 1:
expe_logger.warn("Output was normalised for {}".format(wavOut))
y = 0.98 * y / np.amax(np.absolute(y))
sf.write(wavOut, y, fs)
y, fs = sf.read(wavOut)
# axes = np.arange(0, len(y))
# ax.plot(axes, y)
# fig.savefig("test1.png")
# plt.show()
else:
y, fs = sf.read(wavOut)
return y, fs
def make_fname(wav, f0, ser, d, destPath, trial):
'''Generates the file name for the new stimulus'''
_, namext = os.path.split(wav)
name, ext = os.path.splitext(namext)
try:
int(math.floor(f0))
except ValueError as e:
print e
# fname = "{}_GPR{}_ser{}_D{}".format(name, math.floor(f0), ser, math.floor(d*1e3))
fname = "%s_GPR%d_ser%.2f_D%d" % (
name, int(math.floor(f0)), ser, int(math.floor(d*1e3)))
fname = os.path.join(destPath, fname + ext)
return fname
def sp_ap_creation(mat, temp, freq, ser):
'''
Interpolates the spectrogram and aperiodicity, respectively
using the same temporal positions, but new freq that takes
into account the ser value (ser = np.power(2, -dVTL/12)).
Ser is usually provided by the defined options in
expe_build_conditions
'''
# x = np.arange(1, mat.shape[1]+1)
# y = np.arange(1, mat.shape[0]+1)
# f = interpolate.interp2d(x, y, mat, kind='cubic')
f = interpolate.RectBivariateSpline(temp, freq, mat)
interp = f(temp, freq.T/ser)
return interp
# xs = np.arange(1, spe["spectrogram"].shape[1]+1)
# ys = np.arange(1, spe["spectrogram"].shape[0]+1)
# fis = interp2d(xs, ys, spe["spectrogram"], 'cubic')
# spe["spectrogram"] = fis(spe["temporal_positions"],
# spe["frequencies"]/ser)
+46
View File
@@ -0,0 +1,46 @@
# --------------------------------------------------------------------------
# Authors:
# ------ MATlAB ------
# 2017-03-29: Etienne Gaudrain <etienne.gaudrain@cnrs.fr>
# ------ Python ------
# 2020-01-27: Luke Meyer < l.meyer.5@student.rug.nl >
# Copyright MRC-CBSU(UK), CNRS(FR), UMCG(NL) and the author(s).
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY
# without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see < http: // www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
import os
def expe_options(options):
'''Defines the basic options'''
options["result_path"] = "./results/" + options["subject_name"]
options["result_prefix"] = 'jnd_'
options["logs_path"] = './logs/fishy'
options["log_file"] = os.path.join(options["result_path"], 'status.txt')
# DELETE Relevant paths, but may not be necessary
options["path"] = {}
options["path"]["straight"] = 'straight'
options["path"]["sqlite"] = 'sqlite'
options["path"]["vocoder"] = 'vocoder'
options["path"]["audio"] = 'audiotsm'
options["experiment_begin"] = 1
return options
+924
View File
@@ -0,0 +1,924 @@
# --------------------------------------------------------------------------
# Authors:
# ------ MATlAB ------
# 2013-02-24: Etienne Gaudrain <e.p.c.gaudrain@rug.nl>
# 2017-03-29: Etienne Gaudrain <etienne.gaudrain@cnrs.fr>
# ------ Python ------
# 2020-01-28: Luke Meyer < l.meyer.5@student.rug.nl >
# Copyright MRC-CBSU(UK), CNRS(FR), UMCG(NL) and the author(s).
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY
# without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see < http: // www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
# ----- System packages
import sys
import os
import warnings
import datetime
import pickle
import random
import time
import logging
from collections import OrderedDict
# ----- Third party packages
import numpy as np
# import matplotlib.pyplot as plt
import soundfile as sf
import scipy.io as sio
# from matplotlib.animation import FuncAnimation
from naoqi import ALBroker
# ----- File imports
from Robot.RobotFishy import RobotFishy
import tools.settings as settings
from tools.exit_condition import ExitExperimentModule
from expe_make_stim import expe_make_stim
from tools.load_matrix import loadmat
# Ignores division and invalid warnings sent to the console
np.seterr(divide='ignore', invalid='ignore')
# Global variables that assit in live tracking the responses in each trial
global PLT_CLOSED
global FIG
global AX1
PLT_CLOSED = True
# --- Create a log file
def expe_robot(ip, port, lang, options, phase, subject):
global PLT_CLOSED
if os.path.exists("{}/thresholds_temp.p".format(options["result_path"])):
print "Checking previous save data"
saveFromPickle(options)
# -- Start an instance of SAM
sam = type('', (), {})()
create_sam = True
if create_sam:
sam = RobotFishy(ip, port, lang, subject)
# -- Set initial volume
# print 'Connected to SAM'
ave_time = np.array([])
# gen_logger = logging.getLogger("gen_logger")
expe_logger = logging.getLogger("expe_logger")
time_logger = logging.getLogger("time_logger")
halfWay = [
"\\vct=110\\You're about halfway. Keep going!\\vct=100\\",
"\\vct=110\\You've reached the halfway point. Great!\\vct=100\\",
"\\vct=110\\Half down, half to go!\\vct=100\\"
]
threeQuarters = [
"\\vct=110\\You're almost done!\\vct=100\\",
"\\vct=110\\Just a few more left!\\vct=100\\",
"\\vct=110\\You're nearing the end!\\vct=100\\"
]
# with open(options["res_filename"], 'r') as f:
# options, expe, p = pickle.load(f)
# -- Load the .mat file
mat_contents = loadmat(options["res_filename"])
expe = mat_contents['expe']
options = mat_contents['options']
try:
results = mat_contents['results']
except KeyError:
# Create a new results dictionary if one is not found or this is a new subject
results = {}
try:
thresholds_dict = mat_contents["thresholds"]
except KeyError:
thresholds_dict = OrderedDict()
p = mat_contents['p']
track = loadmat(options["res_tracker"])
exp = track["tracker"]
starting = 1
# SIMUL = 0 - Run the experiment with a participant
# SIMUL = 1 - Autonomously mimick step process
# SIMUL = 2 - Always give correct answer
# SIMUL = 3 - Always give random answer
SIMUL = 0
DEBUG = 1
PILOT = 3
PRESENT = 1
terminate = 0
beginning_of_session = datetime.datetime.now()
# Intialise the done array to store if a task has been completed
done = []
pilot = 0
# === Main Loop that runs experiment ===
while np.mean(done) != 1:
# while pilot < PILOT:
pilot += 1
# Reintialises the done array and reappend for when a task has been completed
done = []
for i in range(len(expe[phase]["conditions"])):
done.append(expe[phase]["conditions"][i]["done"])
# If this is the beginning of the test, Sam introduces the experiment and what to do
if options["instructions"][
phase] and starting and phase == "training" and exp[
"experiment_begin"]:
try:
sam.intro()
except AttributeError:
pass
exp["experiment_begin"] = 0
sio.savemat(options["res_tracker"], mdict={"tracker": exp})
pass
if starting:
try:
if phase == "test":
sam.simple_say("Welcome to the testing phase of the game.")
pass
else:
sam.fishyIntro()
pass
pass
sam.game_break()
except AttributeError:
pass
starting = 0
# Find the next task that has not yet been completed
try:
i_condition = done.index(0)
# i_condition = 7
except ValueError:
break
expe_logger.info(
"\n=============== Testing condition {} / {} ============\n\n".
format(i_condition + 1, len(expe[phase]["conditions"])))
print "\n=============== Testing condition {} / {} ============\n\n".format(
i_condition + 1, len(expe[phase]["conditions"]))
condition = expe[phase]["conditions"][i_condition]
# if condition["vocoder"] > 0:
# print "{}\n\n".format(options["vocoder"][condition["vocoder"]]["label"])
# --- Prepare unitary vector for this voice direction ---
u_f0 = 12 * np.log2(
options["test"]["voices"]['v' + str(condition["dir_voice"])]["f0"]
/
options["test"]["voices"]['v' + str(condition["ref_voice"])]["f0"])
u_ser = 12 * np.log2(
options["test"]["voices"]['v' + str(condition["dir_voice"])]["ser"]
/ options["test"]["voices"]['v' +
str(condition["ref_voice"])]["ser"])
u = np.array([u_f0, u_ser])
u = u / np.sqrt(np.sum(np.power(u, 2)))
expe_logger.info(
"\n=============== Unitary vector {} ============\n\n".format(
str(u)))
# --- Adaptive procedure ---
difference = options[phase]["starting_difference"]
step_size = options[phase]["initial_step_size"]
response_correct = np.array([])
decision_vector = []
steps = np.array([])
differences = np.array([difference])
beginning_of_run = datetime.datetime.now()
# Set probability of encouragement
prob_encou = 0.1
response_tracker = 0
half_way = 1
three_quarter = 1
while True:
expe_logger.info("========== Trial========\n\n")
# Prepare the trial
trial = condition
# Compute the test voice
new_voice_st = difference * u
trial["f0"] = options["test"]["voices"][
'v' + str(trial["ref_voice"])]["f0"] * np.array(
[1, np.power(2, new_voice_st[0] / 12)])
trial["ser"] = options["test"]["voices"][
'v' + str(condition["ref_voice"])]["ser"] * np.array(
[1, np.power(2, new_voice_st[1] / 12)])
options["f0_contours"] = np.array(options["f0_contours"])
c, _ = options["f0_contours"].shape
ifc = np.random.permutation(c)
trial["f0_contours"] = options["f0_contours"][ifc[0:3], :]
isyll = np.random.permutation(len(options["syllables"]))
trial["syllables"] = []
syll_array = np.array([x.strip() for x in options["syllables"]])
options["syllables"] = syll_array
for _ in range(2):
trial["syllables"].append(
options["syllables"][isyll[0:options["n_syll"]]])
# Prepare the stimulus
if PRESENT == 0:
i_correct = 1
ave_time = np.append(ave_time, 1)
else:
settings.time_taken = time.time()
xOut, fs, i_correct = expe_make_stim(options, trial, p)
filenames = []
# Create the files with the stimuli
for i in range(len(xOut)):
filenames.append('stimulus_{}.wav'.format(i + 1))
# x = xOut[i] * 10 ** -options["attenuation_dB"]/20
sf.write(
filenames[i],
np.concatenate((np.zeros(
(1024 * 3, 2)), xOut[i], np.zeros((1024 * 3, 2)))),
fs)
tme = time.time() - settings.time_taken
time_logger.info(
"Time to generate 3 stimulus files: {}".format(tme))
ave_time = np.append(ave_time, tme)
filenames_combined = '{}, {}, {}'.format(
filenames[0], filenames[1], filenames[2])
# Send the stimuli files to Sam
try:
sam.aad.setOutputVolume(sam.stimulus_volume)
sam.play_sounds(filenames_combined)
sam.aad.setOutputVolume(sam.speaking_volume)
except AttributeError:
pass
# for i in range(len(xOut)):
# os.remove(filenames[i])
pass
# Start time for response time of subject
t = time.time()
# -- Collect the response ---
# Fill the response dictionary
response = {}
response["input"] = [i_correct, 1]
if SIMUL == 1:
i_clicked = i_correct
while differences[-1] < 0.01:
i_clicked = i_correct - 1
break
elif SIMUL == 3:
if difference + np.random.randn(1) > 1:
i_clicked = i_correct
else:
i_clicked = i_correct + 1
else:
try:
i_clicked = sam.answer(response["input"])
except AttributeError:
pass
pass
#
# i_clicked = random.randint(0, 3)
response["response_time"] = time.time() - t
response["timestamp"] = 'Timestamp: {:%Y-%m-%d %H:%M:%S}'.format(
datetime.datetime.now())
response["button_clicked"] = i_clicked
if i_correct == i_clicked:
response["correct"] = True
else:
response["correct"] = False
response_correct = np.append(response_correct, response["correct"])
decision_vector.append(response["correct"])
response["condition"] = condition
response["condition"]["u"] = u
response["trial"] = trial
response["trial"]["v"] = difference * u
expe_logger.info(
'Difference \t\t\t: {:1f} st ({:1f} st GPR, {:1f} st VTL) \n'.
format(difference, difference * u[0], difference * u[1]))
expe_logger.info('Correct button\t\t\t: {}\n'.format(i_correct))
expe_logger.info('Clicked response\t\t\t: {}\n'.format(i_clicked))
expe_logger.info('Response time\t\t\t: {} ms\n'.format(
round(response["response_time"] * 1000)))
expe_logger.info(
'Time since beginning of run\t: {}\n'.format(beginning_of_run))
expe_logger.info('Time since beginning of session\t: {}\n'.format(
beginning_of_session))
# Add response to results structure
n_attempt = expe[phase]["conditions"][i_condition]["attempts"] + 1
attempt_idx = n_attempt - 1
if not phase in results or i_condition <= len(
results[phase]["conditions"]):
att = {}
if not phase in results:
results[phase] = {}
keys = ["differences", "steps", "diff_i_top", "sd"]
att = dict.fromkeys(keys, np.empty([]))
att["threshold"] = 0
att["responses"] = {}
if i_condition == 1:
pass
if not "conditions" in results[phase]:
# results[phase]["conditions"] = np.array([attempt])
results[phase]["conditions"] = {}
if not "c" + str(i_condition) in results[phase]["conditions"]:
results[phase]["conditions"]["c" + str(i_condition)] = {}
# results[phase]["conditions"]["c" + str(i_condition)]["att"] = np.array([att])
results[phase]["conditions"]["c" +
str(i_condition)]["att"] = {
"responses": {},
"differences": [],
"steps": [],
"diff_i_tp": [],
"threshold": 0,
"sd": 0,
"duration": 0,
"exit_reason": ""
}
# else:
# # results[phase]["conditions"] = np.append(
# # results[phase]["conditions"], attempt)
# try:
# # results[phase]["conditions"]["c" + str(i_condition)]["att"] = np.append(
# # results[phase]["conditions"]["c" + str(i_condition)]["att"], att)
# results[phase]["conditions"]["c" +
# str(i_condition)]["att"] = {""}
# except KeyError:
# results[phase]["conditions"]["c" +
# str(i_condition)] = {}
# results[phase]["conditions"]["c" + str(i_condition)]["att"] = np.array([
# att])
# if not results[phase]["conditions"]["c" + str(i_condition)]["att"][attempt_idx]["responses"]:
# results[phase]["conditions"]["c" + str(i_condition)]["att"][attempt_idx]["responses"] = [
# response]
# if not results[phase]["conditions"]["c" + str(i_condition)]["att"]["responses"]:
# results[phase]["conditions"]["c" +
# str(i_condition)]["att"]["responses"] = [response]
# else:
# # results[phase]["conditions"]["c" + str(i_condition)]["att"][attempt_idx]["responses"].append(
# # response)
# results[phase]["conditions"]["c" +
# str(i_condition)]["att"]["responses"].append(response)
results[phase]["conditions"]["c" +
str(i_condition)]["att"]["responses"][
"r" +
str(response_tracker)] = response
response_tracker += 1
# --- Probability for encourangement ---
if phase == "test":
encou_answer = 'correct'
if i_clicked != i_correct:
prob_encou = prob_encou + 0.05
encou_answer = 'wrong'
if np.random.rand() < prob_encou:
try:
resp = sam.encouragement(encou_answer)
except AttributeError:
pass
prob_encou = 0.1
time.sleep(0.5)
# --- Prepare parameters for next trial ---
if len(decision_vector) >= options[phase]["down_up"][0] and all(
v == 1
for v in decision_vector[-1 -
options[phase]["down_up"][1]:]):
# The last n_down responses were correct -> Reduce
# difference by step_size, then update step_size
expe_logger.info(
'-- Where going down by {} st \n'.format(step_size))
difference = difference - step_size
steps = np.append(steps, -step_size)
differences = np.append(differences, difference)
# Update step size.
if difference <= options[phase][
"change_step_size_condition"] * step_size or len(
differences
) % options[phase]["change_step_size_n_trials"] == 0:
expe_logger.info(
'Step size is getting updated; was {} st'.format(
step_size))
step_size = step_size * \
options[phase]["step_size_modifier"]
expe_logger.info(
'step size is now {} st\n'.format(step_size))
# Reset decision vector
decision_vector = []
elif len(decision_vector) >= options[phase]["down_up"][1] and all(
v == 0
for v in decision_vector[-1 -
options[phase]["down_up"][1]:]):
# The last n_up responses were incorrect -> Increase
# difference by step_size. No update of step_size when going up
expe_logger.info('-- Where going up by {}\n'.format(step_size))
difference = difference + step_size
steps = np.append(steps, step_size)
differences = np.append(differences, difference)
decision_vector = []
else:
expe_logger.info('-- Where going neither up or down\n')
steps = np.append(steps, 0)
differences = np.append(differences, difference)
# x = np.abs(np.sign(steps[np.nonzero(steps)]))
# x = x[np.nonzero(np.diff(x))]
nturns = np.sum(np.diff(np.sign(steps[steps != 0])) != 0)
# nturns = np.sum(np.nonzero(np.diff(np.sign(np.nonzero(steps)))))
# --- Check if an exit condition has been reached ---
print nturns
if phase == "test":
if nturns == (options[phase]["terminate_on_n_turns"] /
2) and half_way:
n = random.randint(0, 2)
sam.simple_say(halfWay[n])
half_way = 0
elif nturns == ((3 * options[phase]["terminate_on_n_turns"]) /
4) and three_quarter:
n = random.randint(0, 2)
sam.simple_say(threeQuarters[n])
three_quarter = 0
if phase == "test":
if nturns >= options[phase]["terminate_on_n_turns"]:
expe_logger.info(
'====== END OF RUN due to enough turns =========\n')
print '==== END OF RUN due to enough turns =========\n'
# results[phase]["conditions"]["c" + str(
# i_condition)]["att"][attempt_idx]["exit_reason"] = 'nturns'
results[phase]["conditions"][
"c" +
str(i_condition)]["att"]["exit_reason"] = 'nturns'
expe[phase]["conditions"][i_condition]["done"] = 1
expe[phase]["conditions"][i_condition]["attempts"] += 1
i_nz = np.nonzero(steps)
i_d = np.nonzero(np.diff(np.sign(steps[steps != 0])) != 0)
i_tp = i_nz[0][i_d] + 1
i_tp = np.append(i_tp, len(differences))
i_tp = i_tp[-1 -
options[phase]["threshold_on_last_n_trials"]:]
# results[phase]["conditions"]["c" + str(
# i_condition)]["att"][attempt_idx]["diff_i_tp"] = i_tp
results[phase]["conditions"][
"c" + str(i_condition)]["att"]["diff_i_tp"] = [i_tp]
thr = np.mean(differences[i_tp - 1])
# results[phase]["conditions"]["c" + str(
# i_condition)]["att"][attempt_idx]["threshold"] = thr
results[phase]["conditions"][
"c" + str(i_condition)]["att"]["threshold"] = thr
sd = np.std(differences[i_tp - 1], ddof=1)
# results[phase]["conditions"]["c" + str(
# i_condition)]["att"][attempt_idx]["sd"] = sd
results[phase]["conditions"][
"c" + str(i_condition)]["att"]["sd"] = sd
expe_logger.info(
'Threshold: {} st ({} st GPR, {} st VTL)\n'.format(
thr, thr * u[0], thr * u[1]))
print 'Threshold: {} st ({} st GPR, {} st VTL)\n'.format(
thr, thr * u[0], thr * u[1])
thresholds_dict["Trial_" +
str(i_condition + 1)] = OrderedDict()
f0_1 = condition["f0"][0]
f0_2 = condition["f0"][1]
ser_1 = condition["ser"][0]
ser_2 = condition["ser"][1]
if f0_1 != f0_2 and ser_1 != ser_2:
thresholds_dict["Trial_" +
str(i_condition +
1)]["condition"] = "f0&VTL"
elif ser_1 != ser_2:
thresholds_dict["Trial_" + str(i_condition +
1)]["condition"] = "VTL"
elif f0_1 != f0_2:
thresholds_dict["Trial_" + str(i_condition +
1)]["condition"] = "f0"
thresholds_dict["Trial_" +
str(i_condition + 1)]["threshold"] = {}
thresholds_dict["Trial_" +
str(i_condition +
1)]["threshold"]["threshold"] = thr
thresholds_dict["Trial_" +
str(i_condition +
1)]["threshold"]["f0"] = thr * u[0]
thresholds_dict["Trial_" +
str(i_condition +
1)]["threshold"]["vtl"] = thr * u[1]
# thresholds_dict["Trial_"+str(i_condition)]["threshold"] = 'Threshold: {} st ({} st GPR, {} st VTL)\n'.format(
# thr, thr*u[0], thr*u[1])
break
# elif len(response_correct) >= 20:
elif len(response_correct
) >= options[phase]["terminate_on_n_trials"]:
expe_logger.info(
'====== END OF RUN due to too many trials ======\n')
print '====== END OF RUN due to too many trials ======\n'
# results[phase]["conditions"]["c" + str(
# i_condition)]["att"][attempt_idx]["exit_reason"] = 'ntrials'
results[phase]["conditions"][
"c" +
str(i_condition)]["att"]["exit_reason"] = 'ntrials'
expe[phase]["conditions"][i_condition]["attempts"] += 1
# Should we retry?
if expe[phase]["conditions"][i_condition][
"attempts"] >= options[phase]["retry"] + 1:
# retry = sam.retry()
# retry = 0
# if retry:
# pass
# else:
# # sam.ending()
# pass
expe[phase]["conditions"][i_condition]["done"] = 1
# results[phase]["conditions"]["c" + str(i_condition)]["att"][attempt_idx]["diff_i_tp"] = np.empty([
# ])
results[phase]["conditions"][
"c" + str(i_condition)]["att"]["diff_i_tp"] = np.empty(
[])
# results[phase]["conditions"]["c" + str(
# i_condition)]["att"][attempt_idx]["threshold"] = 0
results[phase]["conditions"][
"c" + str(i_condition)]["att"]["threshold"] = 0
# results[phase]["conditions"]["c" + str(
# i_condition)]["att"][attempt_idx]["sd"] = 0
results[phase]["conditions"][
"c" + str(i_condition)]["att"]["sd"] = 0
break
elif len(response_correct) >= options[phase][
"change_step_size_n_trials"] and all(
v == 0 for v in response_correct[
-1 -
options[phase]["change_step_size_n_trials"]:]):
# All last trials are incorrect
expe_logger.info(
'====== END OF RUN due to too many incorrect answers ======\n'
)
print '====== END OF RUN due to too many incorrect answers ======\n'
# results[phase]["conditions"]["c" + str(
# i_condition)]["att"][attempt_idx]["exit_reason"] = 'nwrong'
results[phase]["conditions"][
"c" +
str(i_condition)]["att"]["exit_reason"] = 'nwrong'
expe[phase]["conditions"][i_condition]["attempts"] += 1
# Try again?
if expe[phase]["conditions"][i_condition][
"attempts"] >= options[phase]["retry"] + 1:
# retry = sam.retry()
# if retry:
# pass
# else:
# sam.ending()
# pass
expe[phase]["conditions"][i_condition]["done"] = 1
break
# results[phase]["conditions"]["c" + str(
# i_condition)]["att"][attempt_idx]["differences"] = differences
# results[phase]["conditions"]["c" + str(
# i_condition)]["att"][attempt_idx]["steps"] = steps
results[phase]["conditions"][
"c" + str(i_condition)]["att"]["differences"] = differences
results[phase]["conditions"][
"c" + str(i_condition)]["att"]["steps"] = steps
else:
if len(response_correct
) >= options[phase]["terminate_on_n_trials"]:
expe_logger.info(
'====== END OF Training RUN due to too many trials ======\n'
)
print '====== END OF Training RUN due to too many trials ======\n'
# results[phase]["conditions"]["c" + str(
# i_condition)]["att"][attempt_idx]["exit_reason"] = 'ntrials'
results[phase]["conditions"][
"c" +
str(i_condition)]["att"]["exit_reason"] = 'ntrials'
expe[phase]["conditions"][i_condition]["attempts"] += 1
# Should we retry?
if expe[phase]["conditions"][i_condition][
"attempts"] >= options[phase]["retry"] + 1:
# retry = sam.retry()
# retry = 0
# if retry:
# pass
# else:
# # sam.ending()
# pass
expe[phase]["conditions"][i_condition]["done"] = 1
# results[phase]["conditions"]["c" + str(i_condition)]["att"][attempt_idx]["diff_i_tp"] = np.empty([
# ])
# results[phase]["conditions"]["c" + str(
# i_condition)]["att"][attempt_idx]["threshold"] = 0
# results[phase]["conditions"]["c" + str(
# i_condition)]["att"][attempt_idx]["sd"] = 0
results[phase]["conditions"][
"c" + str(i_condition)]["att"]["diff_i_tp"] = np.empty(
[])
results[phase]["conditions"][
"c" + str(i_condition)]["att"]["threshold"] = 0
results[phase]["conditions"][
"c" + str(i_condition)]["att"]["sd"] = 0
break
# if DEBUG:
# # Plot the matplotlib graphs if DEBUG is True
# plot_differences(results, differences, response_correct)
# --- Save the response of the current task in .mat file ---
check = 1
# Close the current open plot and set the plot tracker to True so a new figure can be created for the next trial
# plt.close()
PLT_CLOSED = True
delete_last_lines(n=6)
avg_time = np.mean(ave_time)
time_logger.info(
"Average time taken to generate three stimulus files for one trial: {}"
.format(avg_time))
time_logger.info("Average time (min): {}".format(
str(datetime.timedelta(seconds=avg_time))))
tot_time = avg_time * len(ave_time)
time_logger.info("Total time of trial: {}".format(
datetime.timedelta(seconds=tot_time)))
try:
sam.simple_say("Thats the end of this task.")
except AttributeError:
pass
if i_condition == len(done) - 1:
terminate = 1
pickle.dump(
expe, open("{}/expe_temp.p".format(options["result_path"]), 'wb'))
pickle.dump(
options,
open("{}/options_temp.p".format(options["result_path"]), 'wb'))
pickle.dump(
results,
open("{}/results_temp.p".format(options["result_path"]), 'wb'))
pickle.dump(
thresholds_dict,
open("{}/thresholds_temp.p".format(options["result_path"]), 'wb'))
pickle.dump(p, open("{}/p_temp.p".format(options["result_path"]),
'wb'))
# sio.savemat(options["res_filename"], mdict={
# 'expe': expe,
# 'options': options,
# 'results': results,
# 'thresholds': thresholds_dict,
# 'p': p})
if phase == "test":
if np.mean(done) == 1:
break
if not terminate:
try:
sam.take_break()
except AttributeError:
pass
pass
elif phase == "training":
done = [
expe[phase]["conditions"][i]["done"]
for i in range(len(expe[phase]["conditions"]))
]
if np.mean(done) == 1:
break
try:
sam.simple_say(
"When you're ready to continue, touch the top of my head.")
sam.mtn.setStiffnesses(["HeadYaw", "HeadPitch"], [1.0, 1.0])
sam.hoofd_beweging()
sam.mtn.setStiffnesses(["HeadYaw", "HeadPitch"], [0.0, 0.0])
except AttributeError:
pass
# --- End of adaptive loop ---
# --- Save the response of the whole trial in .mat file ---
saveFromPickle(options)
# sio.savemat(options["res_filename"], mdict={
# 'expe': expe, 'options': options, 'results': results, 'thresholds': thresholds_dict, 'p': p}, appendmat=True)
complete = []
for i in expe[phase]["conditions"]:
complete.append(i["done"])
# --- Create the report status for the trial ---
report_status(options["subject_name"], phase, np.sum(complete),
len(complete), options["log_file"])
# TODO Possibly add a game break message
# Once out of the main loop, tell the researcher
sys.stdout.write("==== END OF EXPERIMENT. ====\n")
for k, v in thresholds_dict.iteritems():
for key, value in v.iteritems():
if v[key] == "VTL" or v[key] == "f0":
expe_logger.info(k)
expe_logger.info("Condition: " + v[key])
if phase == "test":
exp["experiments"]["fishy"] = 1
sio.savemat(options["res_tracker"], mdict={"tracker": exp})
try:
sam.simple_say(" and also the end of the testing phase.")
except AttributeError:
pass
else:
try:
sam.simple_say(" and also the end of the training phase")
except AttributeError:
pass
pass
exp_tracker = np.array(
[exp["experiments"][key] for key in exp["experiments"].keys()])
if np.mean(exp_tracker) == 1:
try:
sam.ending()
except AttributeError:
pass
expe_logger.info(
"==== END OF EXPERIMENT ({}). Thank you for your participation".
format(phase))
def report_status(subj, phase, i, n, logFile):
with open(logFile, 'w') as f:
f.write('{} : {} : {}/{}\n'.format(subj, phase, i, n))
f.close()
# def plot_differences(results, differences, response_correct):
# '''
# Creates the matplotlib graphs of the responses.
# ax1 shows the steps of the adaptive loop and ax2 shows something else...
# '''
# global PLT_CLOSED
# global FIG
# global AX1
# if PLT_CLOSED:
# create_fig()
# fig = FIG
# ax1 = AX1
# plt.cla()
# x = np.arange(len(differences)-1)
# y = np.array(differences[:-1])
# ax1.plot(x, y, 'r--')
# ax1.plot(len(differences) +
# np.array([-1, 0]), differences[len(differences)-2:], 'b--')
# ax1.plot(x[np.where(response_correct == 1)],
# y[np.where(response_correct == 1)], 'g--')
# ax1.plot(x[np.where(response_correct == 0)],
# y[np.where(response_correct == 0)], 'y--')
# # ax2.plot([options[phase]["voices"]["v" + str(condition["ref_voice"])]["f0"],
# # options[phase]["voices"]["v" + str(condition["dir_voice"])]["f0"]],
# # [options[phase]["voices"]["v" + str(condition["ref_voice"])]["ser"],
# # options[phase]["voices"]["v" + str(condition["dir_voice"])]["ser"]])
# # for i_resp in range(len(results[phase]["conditions"]["c" + str(i_condition)]["att"][attempt_idx]["responses"])):
# # if results[phase]["conditions"]["c" + str(i_condition)]["att"][attempt_idx]["responses"][i_resp]["correct"]:
# # ax2.plot(results[phase]["conditions"]["c" + str(i_condition)]
# # ["att"][attempt_idx]["responses"][i_resp]["trial"]["f0"][1],
# # results[phase]["conditions"]["c" + str(i_condition)]
# # ["att"][attempt_idx]["responses"][i_resp]["trial"]["ser"][1], 'm-')
# # else:
# # ax2.plot(results[phase]["conditions"]["c" + str(i_condition)]
# # ["att"][attempt_idx]["responses"][i_resp]["trial"]["f0"][1],
# # results[phase]["conditions"]["c" + str(i_condition)]
# # ["att"][attempt_idx]["responses"][i_resp]["trial"]["ser"][1], 'm-')
# # for i_sp in range(len(options[phase]["voices"])):
# # ax2.plot(options[phase]["voices"]["v" + str(i_sp+1)]["f0"],
# # options[phase]["voices"]["v" + str(i_sp+1)]["ser"], 'g:')
# # plt.tight_layout()
# # plt.show()
# # plt.draw()
# fig.canvas.draw()
# plt.pause(0.0001)
# def create_fig():
# '''Creates an instance of a matplotlib figure and sets the global variables accordingly.'''
# global PLT_CLOSED
# global FIG
# global AX1
# if PLT_CLOSED:
# (FIG, AX1) = plt.subplots(1)
# FIG.suptitle("Debug Mode")
# PLT_CLOSED = False
def delete_last_lines(n=1):
CURSOR_UP_ONE = '\x1b[1A'
ERASE_LINE = '\x1b[2K'
for _ in range(n):
sys.stdout.write(CURSOR_UP_ONE)
sys.stdout.write(ERASE_LINE)
def saveFromPickle(options):
print "-------"
print "Loading results"
print "-------"
try:
expe = pickle.load(
open("{}/expe_temp.p".format(options["result_path"]), 'rb'))
opt = pickle.load(
open("{}/options_temp.p".format(options["result_path"]), 'rb'))
results = pickle.load(
open("{}/results_temp.p".format(options["result_path"]), 'rb'))
thresholds_dict = pickle.load(
open("{}/thresholds_temp.p".format(options["result_path"]), 'rb'))
p = pickle.load(
open("{}/p_temp.p".format(options["result_path"]), 'rb'))
sio.savemat(options["res_filename"],
mdict={
"expe": expe,
"options": opt,
"results": results,
"thresholds": thresholds_dict,
"p": p
})
os.remove("{}/expe_temp.p".format(options["result_path"]))
os.remove("{}/options_temp.p".format(options["result_path"]))
os.remove("{}/results_temp.p".format(options["result_path"]))
os.remove("{}/thresholds_temp.p".format(options["result_path"]))
os.remove("{}/p_temp.p".format(options["result_path"]))
except Exception as e:
print e
return
+174
View File
@@ -0,0 +1,174 @@
# --------------------------------------------------------------------------
# Authors:
# ------ MATlAB ------
# 2010-03-16: Etienne Gaudrain <etienne.gaudrain@mrc-cbu.cam.ac.uk>
# 2013-02-24: Etienne Gaudrain <e.p.c.gaudrain@rug.nl>
# 2017-03-29: Etienne Gaudrain <etienne.gaudrain@cnrs.fr>
# ------ Python ------
# 2020-01-28: Luke Meyer < l.meyer.5@student.rug.nl >
# Copyright MRC-CBSU(UK), CNRS(FR), UMCG(NL) and the author(s).
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY
# without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see < http: // www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
import sys
import os
import expe_robot
import ctypes
import time
import logging
import datetime
import expe_build_conditions
import expe_options
import tools.settings as settings
from scipy.io import savemat
from naoqi import ALBroker
from tools.exit_condition import ExitExperimentModule
VERSION = 20202801
expe_exit = None
def setup_logger(name, log_file, level=logging.INFO):
"""To setup as many loggers as you want"""
formatter = logging.Formatter('%(levelname)s:%(message)s')
handler = logging.FileHandler(log_file)
handler.setFormatter(formatter)
logger = logging.getLogger(name)
logger.setLevel(level)
logger.addHandler(handler)
logger.propagate = False
return logger
def main(options, subject, phase, lang, p_exists, ip='127.0.0.1', port=9559):
'''
Runs the experiment.
SUBJECT is a string identifying the subject.
PHASE is either 'training' or 'test'
IP is the ipaddress of Sam when connected to a relevant network
PORT is the port for connection to Sam
'''
options["subject_name"] = subject
options["language"] = lang
options = expe_options.expe_options(options)
# Adds necessary paths. So far not in use.
added_path = []
added_path.append(options["path"]["audio"])
added_path.append(options["path"]["vocoder"])
# Create the results directory in the current directory if it does not already exist
if not os.path.exists(options["result_path"]):
os.mkdir(options["result_path"])
# Create the logs directory in the current directory if it does not already exist
if not os.path.exists(options["logs_path"]):
os.mkdir(options["logs_path"])
# Create the subject's file path
res_filename = os.path.join(
options["result_path"],
"{}{}_{}_robot.mat".format(options["result_prefix"], lang.lower(),
subject))
options["res_filename"] = res_filename
res_tracker = os.path.join(options["result_path"],
'{}_tracker.mat'.format(subject))
options["res_tracker"] = res_tracker
if not os.path.exists(res_tracker):
track = {}
track["experiment_begin"] = 1
track["experiments"] = {}
track["experiments"]["fishy"] = 0
track["experiments"]["gender"] = 0
track["experiments"]["emotion"] = 0
track["experiments"]["crm"] = 0
savemat(res_tracker, mdict={"tracker": track})
# Create various loggers to track different elements
log_filename = os.path.join(
options["logs_path"],
"{}{}_{}_robot.mat".format(options["result_prefix"], lang.lower(),
subject))
options["log_filename"] = log_filename
# tracks participants progress
expe_logger = setup_logger("expe_logger", options["log_filename"])
# tracks general information
gen_logger = setup_logger("gen_logger", "./logs/general.log")
time_logger = setup_logger("time_logger", "./logs/time_check.log")
# gen_logger = setup_logger("gen_logger", gen_logs)
# Check if the subject's file already exists, otherwise create it
if p_exists is None:
if not os.path.exists(res_filename):
msg = "The subject '{}' does not exist. Create it?".format(subject)
print msg
ans = raw_input("(Y/n): ")
if ans.lower() == 'y':
expe_build_conditions.expe_build_conditions(options, lang)
# -- Create new logging file
expe_logger.info(
"====== Beginning new log for subject: {} ======".format(
subject))
expe_logger.info("====== Date of creation: {} \n\n".format(
datetime.datetime.today()))
elif ans.lower() == 'n':
sys.exit()
else:
raise "that is not a valid choice"
else:
msg = "Found {}. Use this file?".format(subject)
print msg
ans = raw_input("(Y/n): ")
expe_logger.info(
"===== Continuing previous created experiment =====")
expe_logger.info("===== Date: {}\n\n".format(
datetime.datetime.today()))
if ans.lower() == 'n':
sys.exit()
elif not p_exists:
expe_build_conditions.expe_build_conditions(options)
# run the robot experiment
gen_logger.info("***** Starting general logging *****\n\n")
time_logger.info("***** Starting time check logging *****\n\n")
# Used when testing the time it takes to generate stimulus files
matlab = True
if matlab:
time_logger.info("=== Using matlab stimulus generation ===\n")
else:
time_logger.info("=== Using PyWorld stimulus generation === \n")
expe_robot.expe_robot(ip, port, lang, options, phase, subject)
if __name__ == "__main__":
options = {}
main(options, "test", "test", "en")
+46
View File
@@ -0,0 +1,46 @@
import os
import soundfile as sf
import pyworld as pw
import numpy as np
import scipy.io as spio
from expe_options import expe_options
from expe_build_conditions import expe_build_conditions
def preprocess(language):
options = {}
options["language"] = language
options["subject_name"] = ''
options = expe_options(options)
_, options = expe_build_conditions(options)
for i in range(len(options["syllables"])):
syll = options["syllables"][i]
print "%02d/%02d - %s\n" % (i, len(options["syllables"]), syll)
wavIn = os.path.join(options["sound_path"], syll + ".wav")
mat = os.path.join(options["sound_path_store"], syll + '.pyworld.mat')
if not os.path.exists(mat):
x, fs = sf.read(wavIn)
_f0, t = pw.dio(x, fs)
f0 = pw.stonemask(x, _f0, t, fs)
sp = pw.cheaptrick(x, f0, t, fs)
ap = pw.d4c(x, f0, t, fs)
freq = np.arange(0, np.size(sp, axis=1),
dtype='float64') / (np.size(sp)) * fs/2
temp_pos = t
x_rms = np.sqrt(np.mean(x**2))
duration = len(x/fs)
spio.savemat(mat, mdict={'fs': fs, 'f0': f0,
'sp': sp, 'ap': ap,
'x_rms': x_rms,
'frequencies': freq,
'temporal_positions': t,
'duration': duration
})
View File
Whitespace-only changes.
+40
View File
@@ -0,0 +1,40 @@
import math
import warnings
import numpy as np
def cosgate(x, fs, d):
if type(d) == 'list':
if len(d) == 1:
d = np.array([d, d])
elif len(d) > 2:
raise ValueError(
"The ramp duration argument can only be of length 1 or 2.")
else:
d = np.array([d])
d = d * fs
# Onset
k = np.array(range(0, int(d[0]-1)))
# if np.size(x, 2) == 1:
# k = k.T
x[[k+1]] = np.multiply(x[[k+1]], 1 -
(1 + np.cos(k * np.pi / (d[0]-1)) / 2))
# Offset
try:
k = np.array(range(0, int(d[1]-1)))
x[[-k]] = np.multiply(x[[-k]], 1 -
(1 + np.cos(k * np.pi / (d[1]-1)) / 2))
except IndexError:
k = np.array(range(0, int(d[0]-1)))
x[[-k]] = np.multiply(x[[-k]], 1 -
(1 + np.cos(k * np.pi / (d[0]-1)) / 2))
# if np.size(x, 2) == 1:
# k = k.T
y = x
return y
+202
View File
@@ -0,0 +1,202 @@
import numpy as np
import os
import wave
import math
from scipy.io import savemat
import warnings
from gender_options import expe_options
from tools.load_matrix import loadmat
def expe_build_conditions(options):
# Build Signal conditions
options["fs"] = 44100
# options["attenuation_dB"] = 7
mat = loadmat('./calibration.mat')
cal = mat["calibration"]
options["attenuation_dB"] = cal["gender"]
# options["attenuation_dB"] = 10 # Calibrated attenuation
options["ear"] = "both"
# Design specifications
options["test"] = {}
options["training"] = {}
options["test"]["n_repeat"] = 1
options["training"]["n_repeat"] = 1
word_list = []
if options["Bert"]:
options["test"]["f0s"] = np.array([0.0, -3.0, -6.0, -9.0, -12.0])
options["test"]["vtls"] = np.array([0, 0.7, 1.6, 2.4, 3.0, 3.6])
else:
options["test"]["f0s"] = np.array([0.0, -6.0, -12.0])
options["test"]["vtls"] = np.array([0, 1.8, 3.6])
options["training"]["f0s"] = np.array([0.0, -12.0])
options["training"]["vtls"] = np.array([0.0, 3.6])
nF0 = len(options["test"]["f0s"])
nVTL = len(options["test"]["vtls"])
if options["phase"] == "generation":
word_list = ["Bus", "Leeg", "Pen", "Vaak"]
elif options["phase"] == "test" or options["phase"] == "training":
if options["language"].lower() == "nl":
word_list = ["Bus", "Leeg", "Pen", "Vaak"]
elif options["language"].lower() == "en":
word_list = ["bike", "hat", "pool", "watch"]
options["test"]["word_list"] = word_list
options["training"]["word_list"] = word_list
nWords = len(word_list)
options["sound_path_local"] = os.path.join(
options["sound_path"], options["language"])
options["tmp_path_local"] = options["tmp_path"]
options["sounds_for_calibration"] = []
lst = [f for f in os.listdir(
options["tmp_path_local"]) if f.endswith(".wav")]
for f in range(len(lst)):
options["sounds_for_calibration"].append(
os.path.join(options["tmp_path_local"], lst[f]))
options["test"]["total_ntrials"] = nWords * nVTL * nF0
# oneSampleFile = os.path.join(options["tmp_path"], "{}_GPR{}_VTL{}.wav".format(word_list[0],
# options["test"]["f0s"][0], options["test"]["vtls"][0]))
# options["training"]["total_ntrials"] = len(
# word_list) * len(options["training"]["f0s"]) * len(options["training"]["vtls"])
options["training"]["total_ntrials"] = 7
# if os.path.exists(oneSampleFile):
# w = wave.open(oneSampleFile, 'r')
# frames = w.getnframes()
# rate = w.getframerate()
# duration = frames/float(rate)
# options["word_duration"] = duration
# else:
# options["word_duration"] = 850e-3
options["lowpass"] = 4000
options["force_rebuild_sylls"] = 0
# Build test block
# options["test"]["faces"] = np.array(["woman_1", "woman_2", "woman_3", "woman_4", "woman_5",
# "woman_6", "woman_7", "man_1", "man_2", "man_3", "man_4",
# "man_5", "man_6", "man_7"])
options["test"]["face_genders"] = ['man', 'woman']
options["test"]["number_faces"] = 7
options["training"]["face_genders"] = options["test"]["face_genders"]
options["training"]["number_faces"] = options["test"]["number_faces"]
# nFaces = len(options["test"]["faces"])
# nRepetitions = math.ceil(options["test"]["total_ntrials"]/nFaces)
# nFemales = sum([True for s in options["test"]
# ["faces"] if s.startswith("woman")])
# nMales = nFaces - nFemales
# indexes = np.tile(range(1, nFemales), int(nRepetitions))
# np.random.shuffle(indexes)
# indexes = np.delete(
# indexes, np.s_[options["test"]["total_ntrials"]/2:], None)
# indexesM = np.tile(range(1+nFemales, nMales+nFemales), int(nRepetitions))
# np.random.shuffle(indexesM)
# indexesM = np.delete(
# indexesM, np.s_[options["test"]["total_ntrials"]/2:], None)
# indexes = [indexes, indexesM]
# np.random.shuffle(indexes)
# np.random.shuffle(options["test"]["faces"])
# options["test"]["faces"] = options["test"]["faces"][indexes]
# TODO test Hands
test = {}
counter = 1
for ir in range(options["test"]["n_repeat"]):
for f0 in range(nF0):
for vtl in range(nVTL):
i_words = np.random.permutation(nWords)
for i_face_gender in range(2):
face_gender = options["test"]["face_genders"][i_face_gender]
i_word_start = i_face_gender * nWords / 2 + 1
for i_word in np.arange(nWords/2) - 1+i_word_start:
trial = {}
trial["f0"] = options["test"]["f0s"][f0]
trial["vtl"] = options["test"]["vtls"][vtl]
trial["word"] = options["test"]["word_list"][i_words[i_word]]
trial["i_repeat"] = ir
trial["done"] = 0
trial["face"] = '{}_{}'.format(
face_gender, np.random.randint(options["test"]["number_faces"]))
trial["face_gender"] = face_gender
if not "trials" in test:
test["trials"] = [trial]
else:
test["trials"].append(trial)
training = {}
nWords = len(options["training"]["word_list"])
for ir in range(options["training"]["n_repeat"]):
for i_v in range(len(options["training"]["f0s"])):
i_f0 = i_v
i_vtl = i_v
i_words = np.random.permutation(nWords)
for i_face_gender in range(2):
face_gender = options["training"]["face_genders"][i_face_gender]
i_word_start = i_face_gender*nWords/2+1
for i_word in np.arange(nWords/2) - 1+i_word_start:
trial = {}
trial["f0"] = options["training"]["f0s"][i_f0]
trial["vtl"] = options["training"]["vtls"][i_vtl]
trial["word"] = options["training"]["word_list"][i_words[i_word]]
trial["i_repeat"] = ir
trial["done"] = 0
trial["face"] = '{}_{}'.format(
face_gender, np.random.randint(options["test"]["number_faces"]))
trial["face_gender"] = face_gender
if not "trials" in training:
training["trials"] = [trial]
else:
training["trials"].append(trial)
# Create expe dictionary and save
expe = {}
if options["phase"] == "generation":
expe["test"] = {}
expe["test"]["trials"] = test["trials"]
else:
expe["test"] = {}
expe["training"] = {}
i_order = np.random.permutation(len(test["trials"]))
expe["test"]["trials"] = []
for i in i_order:
expe["test"]["trials"].append(test["trials"][i])
i_order = np.random.permutation(len(training["trials"]))
expe["training"]["trials"] = []
for i in i_order:
expe["training"]["trials"].append(training["trials"][i])
if "res_filename" in options:
savemat(options["res_filename"], mdict={
"expe": expe, "options": options})
else:
warnings.warn("The test file was not saved: no filename provided")
return expe, options
if __name__ == "__main__":
options = expe_options()
buildConditions(options)
+37
View File
@@ -0,0 +1,37 @@
import os
import numpy as np
from gender_build_conditions import expe_build_conditions as buildConditions
from gender_makeStimuli import makeStimuli
def generateStimuli(options, phase):
if os.path.exists(options["res_filename"]):
os.remove(options["res_filename"])
opt = raw_input("Delete previously processed sound files? (Y/n): ")
if opt.lower() == "y":
# os.remove(os.path.join(options["sound_path"], '*.wav'))
old = [f for f in os.listdir(
options["tmp_path"]) if f.endswith(".wav")]
for o in old:
os.remove(os.path.join(options["tmp_path"], o))
elif opt.lower() == 'n':
return
else:
raise ValueError("That is not a valid option")
expe, options = buildConditions(options)
done = []
while np.mean(done) != 1:
done = []
for i in range(len(expe[phase]["trials"])):
done.append(expe[phase]["trials"][i]["done"])
try:
itrial = done.index(0)
except ValueError:
break
trial = expe[phase]["trials"][itrial]
makeStimuli(options, trial)
expe[phase]["trials"][itrial]["done"] = 1
+285
View File
@@ -0,0 +1,285 @@
# --------------------------------------------------------------------------
# Authors:
# ------ MATlAB ------
# 2010-03-16: Etienne Gaudrain <etienne.gaudrain@mrc-cbu.cam.ac.uk>
# 2011-10-20: Etienne Gaudrain <etienne.gaudrain@mrc-cbu.cam.ac.uk>
# 2013-04-22: Etienne Gaudrain <e.p.c.gaudrain@rug.nl>
# 2017-03-27: Etienne Gaudrain <etienne.gaudrain@cnrs.fr>
# ------ Python ------
# 2020-02-10: Luke Meyer < l.meyer.5@student.rug.nl >
# Copyright MRC-CBSU(UK), CNRS(FR), UMCG(NL) and the author(s).
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY
# without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see < http: // www.gnu.org/licenses/>.
# --------------------------------------------------------------------------
from pyworld import pyworld as pw
import numpy as np
import os
import math
import warnings
import logging
from time import clock
from scipy import interpolate
import scipy.io as spio
from scipy.signal import butter, filtfilt
import soundfile as sf
from playsound import playsound
from resampy import resample
import random
import collections
import matplotlib.pyplot as plt
# from audiotsm import phasevocoder
# from audiotsm.io.wav import WavReader, WavWriter
from tools.load_matrix import loadmat
from gender_removeSilence import removeSilence
import sys
# -- Uncomment for when using the MATLAB/Python API ---
# import matlab.engine
# future = matlab.engine.start_matlab(async=True)
# eng = future.result()
# eng.addpath('../Nao-PICKA scripts/Expe_files/lib/STRAIGHTV40_006b')
time_logger = logging.getLogger("time_logger")
expe_logger = logging.getLogger("expe_logger")
def makeStimuli(options, trial):
'''
Generates the stimuli files for a given trial
and how the trial has been specified
'''
x = np.array([])
t = clock()
y, fs = straight_process(
trial["word"], trial["f0"], trial["vtl"], None, options)
y = y * np.power(10, -options["attenuation_dB"]/20.0)
stim_time = clock() - t
time_logger.info(
"Time to generate single stimulus: {}".format(stim_time))
if fs != options["fs"]:
y = resample(y, options["fs"], fs, filter="kaiser_fast")
options["fs"] = fs
# dl = int(round(options["word_duration"]*fs) - len(y))
# if dl > 0:
# # Adds padding because the syllable signal is too short
# npad_L = int(math.floor(dl/20))
# npad_R = int(dl-npad_L)
# nr = int(math.floor(1e-3 * fs))
# y[0:nr] = y[0:nr] * np.linspace(0, 1, num=nr).conj().T
# y[len(y)-nr:] = y[len(y)-nr:] * np.linspace(1, 0, num=nr).T
# y = np.concatenate(
# (np.zeros((npad_L,)), y, np.zeros((npad_R,))))
# elif dl < 0:
# # The synthesised signal is too long
# y = y[0:len(y)-dl]
# nr = int(math.floor(1e-3 * fs)) # 1 ms linear ramp at the end
# y[len(y)-nr:] = y[len(y)-nr:] * np.linspace(1, 0, num=nr).T
# else:
# nr = int(math.floor(1e-3 * fs))
# y[0:nr] = y[0:nr] * np.linspace(0, 1, num=nr).conj().T
# y[len(y)-nr:] = y[len(y)-nr:] * np.linspace(1, 0, num=nr).T
# x = np.concatenate((x, y))
print "%s -- F0: %5.1f Hz, VTL: %4.2f \n" % (
trial["word"], trial["f0"], trial["vtl"])
if options["lowpass"] != None:
b, a = butter(4, (options["lowpass"] * 2.0)/fs, 'low')
x = filtfilt(b, a, y)
if options["ear"] == 'right':
x = np.matrix([np.zeros(np.size(x))], x)
elif options["ear"] == 'left':
x = np.matrix([x], [np.zeros(np.size(x))])
elif options["ear"] == 'both':
x = np.tile(x, (2, 1)).T
else:
raise ValueError(
"Options.ear = {} is not implemented.".format(options["ear"]))
return x, fs
def straight_process(word, nb_st, vtl, d, options):
'''
Generates the individual stimuli files
'''
wavIn = os.path.join(options["sound_path"], word + ".wav")
wavOut = make_fname(
wavIn, nb_st, vtl, d, options["tmp_path"])
y = []
if not os.path.exists(wavOut) or options["force_rebuild_sylls"]:
mat = os.path.join(options["sound_path_store"], word + '.pyworld.mat')
# Intialise variables so they are accessible in the correct scope
f0 = []
fs = 0
sp = []
ap = []
freq = []
temp_pos = []
x_rms = 0
if os.path.exists(mat):
# Load the data from the .mat file
load_mat = loadmat(mat)
f0 = load_mat['f0']
fs = load_mat['fs']
sp = np.array(load_mat['sp'])
ap = np.array(load_mat['ap'])
# Needed for PyWorld
freq = np.array(load_mat["frequencies"])
temp_pos = np.array(load_mat["temporal_positions"])
x_rms = load_mat['x_rms']
else:
pass
x, fs = sf.read(wavIn)
try:
x = x[:, 0]
except IndexError:
x = x[:]
x = np.ascontiguousarray(x, dtype=np.float)
# --- Using PyWORLD script
_f0, t = pw.dio(x, fs)
f0 = pw.stonemask(x, _f0, t, fs)
sp = pw.cheaptrick(x, f0, t, fs)
ap = pw.d4c(x, f0, t, fs)
freq = np.arange(0, np.size(sp, axis=1),
dtype='float64') / (np.size(sp)) * fs/2
temp_pos = t
duration = len(x/fs)
x_rms = np.sqrt(np.mean(x**2))
spio.savemat(mat, mdict={'fs': fs, 'f0': f0,
'sp': sp, 'ap': ap,
'x_rms': x_rms,
'frequencies': freq,
'temporal_positions': t,
'duration': duration
})
f0[np.where(f0 != 0)] = f0[np.where(f0 != 0)] * \
np.power(2, (nb_st/12))
mapp = 1 * np.power(2, -(vtl/12))
sp = sp_ap_creation(sp, temp_pos, freq, mapp)
ap = sp_ap_creation(ap, temp_pos, freq, mapp)
if f0.flags['C_CONTIGUOUS']:
f0 = np.ascontiguousarray(f0, dtype=np.float)
sp = np.ascontiguousarray(
sp, dtype=np.float)
ap = np.ascontiguousarray(
ap, dtype=np.float)
y_mat = pw.synthesize(f0, sp, ap, fs)
y = np.array(y_mat)
y = y / np.sqrt(np.mean(y**2)) * x_rms
my = np.amax(np.absolute(y))
y_magnitude_factor = 0
if np.amax(np.absolute(y)) > 1:
expe_logger.warn("Output was normalised for {}".format(wavOut))
y_magnitude_factor = my/0.98
y = 0.98 * y / np.amax(np.absolute(y))
else:
y_magnitude_factor = 1.0
# y = removeSilence(y, fs, 50e-3)
sf.write(wavOut, y, fs)
y, fs = sf.read(wavOut)
# axes = np.arange(0, len(y))
# ax.plot(axes, y)
# fig.savefig("test1.png")
# plt.show()
else:
y, fs = sf.read(wavOut)
return y, fs
def make_fname(wav, f0, vtl, d, destPath):
'''Generates the file name for the new stimulus'''
_, namext = os.path.split(wav)
name, ext = os.path.splitext(namext)
try:
int(math.floor(f0))
except ValueError as e:
print e
if d == None:
fname = "%s_GPR%d_VTL%.2f" % (
name, int(math.floor(f0)), vtl)
else:
fname = "%s_GPR%d_VTL%.2f_D%d" % (
name, int(math.floor(f0)), vtl, int(math.floor(d*1e3)))
fname = os.path.join(destPath, fname + ext)
return fname
def sp_ap_creation(mat, temp, freq, vtl):
'''
Interpolates the spectrogram and aperiodicity, respectively
using the same temporal positions, but new freq that takes
into account the ser value (ser = np.power(2, -dVTL/12)).
Ser is usually provided by the defined options in
expe_build_conditions
'''
# x = np.arange(1, mat.shape[1]+1)
# y = np.arange(1, mat.shape[0]+1)
# f = interpolate.interp2d(x, y, mat, kind='cubic')
f = interpolate.RectBivariateSpline(temp, freq, mat)
if vtl != 0.0:
interp = f(temp, freq.T/vtl)
else:
interp = f(temp, freq.T/1.0)
return interp
# xs = np.arange(1, spe["spectrogram"].shape[1]+1)
# ys = np.arange(1, spe["spectrogram"].shape[0]+1)
# fis = interp2d(xs, ys, spe["spectrogram"], 'cubic')
# spe["spectrogram"] = fis(spe["temporal_positions"],
# spe["frequencies"]/ser)
+51
View File
@@ -0,0 +1,51 @@
import os
import warnings
import sys
def expe_options(options):
# options["result_path"] = "./results/gender"
options["result_path"] = "./results/" + options["subject_name"]
options["sound_path"] = "./stimuli/gender/{}".format(
options["language"].lower())
options["sound_path_store"] = "./stimuli_store/gender/{}".format(
options["language"].lower())
if not os.path.exists(options["sound_path_store"]):
os.makedirs(options["sound_path_store"])
if not os.path.exists(options["sound_path"]):
os.makedirs(options["sound_path"])
if not "Bert" in options:
options["Bert"] = False
if options["Bert"]:
options["tmp_path"] = "./stimuli/gender/{}/processed/Bert".format(
options["language"].lower())
else:
options["tmp_path"] = "./stimuli/gender/{}/processed".format(
options["language"].lower())
options["result_prefix"] = "gen_"
if not os.listdir(options["sound_path"]):
raise ValueError("Sound path cannot be empty")
if not os.path.exists(options["tmp_path"]):
os.makedirs(options["tmp_path"])
# if not os.listdir(options["tmp_path"]) and options["phase"] != "generation":
# opt = raw_input(
# "Running experiment without preprocessing sounds? (Y/n)")
# if opt.lower() == "y":
# warnings.warn(
# "This will slow down the experiment substantially. Press ctrl+c to cancel if unhappy")
# elif opt.lower() == "n":
# warnings.warn(
# "Recommended to preprocess stimuli files before running the experiment.")
# sys.exit()
# else:
# raise ValueError("That is not a valid option")
options["experiment_begin"] = 1
return options
+39
View File
@@ -0,0 +1,39 @@
from cosgate import cosgate
from scipy.signal import butter, filtfilt
import numpy as np
import math
def removeSilence(y, fs, sampleDuration=750e-3):
sampleDuration = np.array([sampleDuration, sampleDuration])
d1 = sampleDuration[0]
d2 = sampleDuration[1]
b, a = butter(3, 50*2.0/fs, 'low')
fil = filtfilt(b, a, y)
fil = np.expand_dims(fil, axis=1)
e = np.max(fil, 1)
e = cosgate(e, fs, 20e-3)
c = 2 * np.max([np.array([[e[0:int(math.floor(d1*fs))]],
[e[len(e)-int(math.floor(d2*fs)):]]])])
# FIXME : There is a clicking at the beginning and end of sound. Speak to Etienne
# Onset
i1 = np.min(((e[:-1] < c) & (e[1:] >= c)).nonzero()[0])
# offset
i2 = np.max(((e[:-1] < c) & (e[1:] >= c)).nonzero()[0])
m = math.floor(20e-3 * fs)
i1 = int(np.max([1, i1 - m]))
i2 = int(np.max([len(y), i2 - m]))
y = cosgate(y[i1:i2], fs, 1e-3)
# bounds = np.array([i1, i2])
return y
+218
View File
@@ -0,0 +1,218 @@
import numpy as np
import os
import sys
import re
import random
import datetime
import soundfile as sf
import time
import logging
from playsound import playsound
from scipy.io import savemat
from gender_build_conditions import expe_build_conditions as buildConditions
from gender_makeStimuli import makeStimuli
from Robot.RobotGender import RobotGender
from tools.load_matrix import loadmat
def robot(expe, options, phase, lang, ip, port):
results = {}
gender_resp = {}
gender_resp[phase] = {}
starting = 1
# if phase == "training":
# starting = 1
mat = loadmat(options["res_filename"])
options = mat["options"]
expe = mat["expe"]
try:
results = mat['results']
except KeyError:
# Create a new results dictionary if one is not found or this is a new subject
results = {}
track = loadmat(options["res_tracker"])
exp = track["tracker"]
# --- Start an instance of Sam
sam = type('', (), {})()
create_sam = True
if create_sam:
sam = RobotGender(ip, port, lang)
# --- Set the initial volume
# --- Open loggers
expe_logger = logging.getLogger("expe_logger")
time_logger = logging.getLogger("time_logger")
autoplayer = False
terminate = 0
if options["subject_name"] == 'NHAtest':
os.remove(options["res_filename"])
autoplayer = True
resultsFiles = [os.path.join(options["result_path"], f) for f in os.listdir(
options["result_path"]) if f.endswith(".mat")]
nRep = len(resultsFiles) - sum([bool(re.search(options["subject_name"],
resultsFiles[i])) for i in range(len(resultsFiles))])
nRep = nRep + 1
options["subject_name"] = "NHAtest"
options["res_filename"] = os.path.join(
options["result_path"], "%sen_%s_robot.mat" % (
options["result_prefix"], options["subject_name"]))
# expe, options = buildConditions(options)
# === Main loop ===
# Intialise the done array to store if a task has been completed
done = []
expe_logger.info("##########\n\nStarting Gender experiment\n\n##########")
time_logger.info("##########\n\nStarting Gender experiment\n\n##########")
if starting and exp["experiment_begin"]:
try:
sam.intro()
sam.genderIntro()
except AttributeError:
pass
exp["experiment_begin"] = 0
savemat(options["res_tracker"], mdict={"tracker": exp})
elif starting:
try:
if phase == "test":
if lang == "EN":
sam.simple_say("Welcome to the testing phase of the game.")
elif lang == "NL":
sam.simple_say(
"Welkom bij de testronde van dit spelletje.")
except AttributeError:
pass
pass
starting = 0
try:
sam.game_break()
except AttributeError:
pass
response_tracker = 0
while np.mean(done) != 1:
response = {}
done = [expe[phase]["trials"][i]["done"]
for i in range(len(expe[phase]["trials"]))]
if autoplayer:
starting = 1
try:
itrial = done.index(0)
except ValueError:
break
expe_logger.info("\n=============== Testing trial {} / {} ============\n\n".format(
itrial+1, len(expe[phase]["trials"])))
print "\n=============== Testing condition {} / {} ============\n\n".format(
itrial + 1, len(expe[phase]["trials"]))
trial = expe[phase]["trials"][itrial]
t = time.time()
xOut, fs = makeStimuli(options, trial)
sf.write('stimulus.wav', xOut, fs)
time_logger.info(
"Time to generate sound file: {}".format(time.time() - t))
t = time.time()
# time.sleep(1)
try:
sam.aad.setOutputVolume(sam.stimulus_volume)
sam.play_sounds('stimulus.wav', lang)
sam.aad.setOutputVolume(sam.speaking_volume)
except AttributeError:
pass
# time.sleep(2)
time_logger.info(
"Time to upload and play sound file: {}".format(time.time() - t))
os.remove('stimulus.wav')
try:
resp, chosen_gen = sam.answer()
except AttributeError:
pass
# resp = random.randint(0, 1)
# chosen_gen = ["Boy", "Girl"][np.random.randint(2)]
if autoplayer:
response["response_answer"] = {
"answer": [0, 1][np.random.randint(0, 2)],
"gender": ["Girl", "Boy"][np.random.randint(0, 2)]
}
response["response_time"] = 0
response["timestamp"] = str(datetime.datetime.now())
else:
t = time.time()
response["response_answer"] = resp
response["response_time"] = time.time() - t
response["timestamp"] = str(datetime.datetime.now())
response["trial"] = trial
if not phase in results:
results[phase] = {}
results[phase]["responses"] = {}
# results[phase]["responses"] = []
# else:
# results[phase]["responses"] = np.append(
# results[phase]["responses"], response)
results[phase]["responses"]["r" + str(response_tracker)] = response
response_tracker += 1
expe[phase]["trials"][itrial]["done"] = 1
try:
gender_resp_temp = {}
gender_resp_temp["answer"] = chosen_gen
gender_resp_temp["f0(st)"] = trial["f0"]
gender_resp_temp["VTL(st)"] = trial["vtl"]
gender_resp_temp["face_used"] = trial["face_gender"]
gender_resp[phase]["trial_" + str(itrial + 1)] = gender_resp_temp
except UnboundLocalError:
pass
if gender_resp_temp:
savemat(options["res_filename"], mdict={
"options": options, "expe": expe, "results": results, "gender_response": gender_resp})
else:
savemat(options["res_filename"], mdict={
"options": options, "expe": expe, "results": results})
if itrial == options[phase]["total_ntrials"]:
break
if phase == "training":
try:
if lang == "EN":
sam.simple_say("That's the end of the training phase")
elif lang == "NL":
sam.simple_say("Dit is het einde van de oefenronde ")
except AttributeError:
pass
pass
else:
exp["experiments"]["gender"] = 1
savemat(options["res_tracker"], mdict={"tracker": exp})
exp_tracker = np.array([exp["experiments"][key]
for key in exp["experiments"].keys()])
try:
if lang == "EN":
sam.simple_say(
"That's the end of the testing phase, and the end of this game.")
elif lang == "NL":
sam.simple_say(
"Dit is het einde van de test, en het einde van dit spelletje.")
except AttributeError:
pass
if np.mean(exp_tracker) == 1:
try:
sam.ending()
except AttributeError:
pass
pass
+56
View File
@@ -0,0 +1,56 @@
import os
from gender_options import expe_options as genOptions
from gender_build_conditions import expe_build_conditions as buildConditions
from gender_generateStimuli import generateStimuli
from gender_robot import robot
from tools.load_matrix import loadmat
from scipy.io import savemat
def main(options, subject, phase, language, p_exists=None, ip="127.0.0.1", port=9559):
options["subject_name"] = subject
options["language"] = language
options["phase"] = phase
options["Bert"] = False
options = genOptions(options)
try:
if not os.path.exists(options["result_path"]):
os.makedirs(options["result_path"])
except Exception as e:
print e
res_filename = os.path.join(options["result_path"], "{}{}_{}_robot.mat".format(
options["result_prefix"], language.lower(), subject))
options["res_filename"] = res_filename
res_tracker = os.path.join(
options["result_path"], '{}_tracker.mat'.format(subject))
options["res_tracker"] = res_tracker
if not os.path.exists(res_tracker):
track = {}
track["experiments"] = {}
track["experiment_begin"] = 1
track["experiments"]["fishy"] = 0
track["experiments"]["gender"] = 0
track["experiments"]["emotion"] = 0
track["experiments"]["crm"] = 0
savemat(res_tracker, mdict={"tracker": track})
if options["subject_name"] == "generation":
generateStimuli(options, phase)
else:
if not os.path.exists(res_filename):
expe, options = buildConditions(options)
else:
mat = loadmat(options["res_filename"])
expe = mat["expe"]
options = mat["options"]
robot(expe, options, phase, language, ip, port)
if __name__ == "__main__":
options = {}
options["experiment_begin"] = 1
main(options, "generation", "test", "nl")
Whitespace-only changes.
Binary file not shown.

After

Width:  |  Height:  |  Size: 745 KiB

+121
View File
@@ -0,0 +1,121 @@
import tools.settings as settings
import logging
import os
from fishy.expe_run import main as fishy_main
from gender.gender_run import main as gender_main
# from emotion.emotion_run import main as emotion_main
from crm.crm_run import main as crm_main
from naoqi import ALBroker
from tools.exit_condition import ExitExperimentModule
import tools.settings as settings
import pathlib
VERSION = 20202801
expe_exit = None
def setup_logger(name, log_file, level=logging.INFO):
"""To setup as many loggers as you want"""
formatter = logging.Formatter('%(levelname)s:%(message)s')
handler = logging.FileHandler(log_file)
handler.setFormatter(formatter)
logger = logging.getLogger(name)
logger.setLevel(level)
logger.addHandler(handler)
logger.propagate = False
return logger
def pickaMain(subject,
game,
phase,
lang,
p_exists,
ip='127.0.0.1',
port=9559,
broker=False,
cel_id=None):
global expe_exit
settings.task_id = cel_id
print settings.task_id
if not os.path.exists('./calibration.mat'):
raise "Calibration has not been done for any of the sound files yet. \
Please do this before before continuing with the PICKA experiment."
try:
if not broker:
myBroker = ALBroker("myBroker", "0.0.0.0", 0, str(ip), port)
expe_exit = ExitExperimentModule("expe_exit", myBroker, lang)
pass
else:
gameBroker = ALBroker("gameBroker", "0.0.0.1", 0, str(ip), port)
except RuntimeError as e:
print e
pass
options = {}
p_exists = p_exists == 'true'
if game.lower() == "fishy":
fishy_main(options, subject, phase, lang, p_exists, ip, port)
elif game.lower() == "gender":
gender_main(options, subject, phase, lang, p_exists, ip, port)
elif game.lower() == "emotion":
emotion_main(options, subject, phase, lang, p_exists, ip, port)
elif game.lower() == "crm":
crm_main(options, subject, phase, lang, p_exists, ip, port)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(
description="The main script used to run SAM",
epilog=
"Written by Luke Meyer <l.meyer.5@student.rug.nl>, adapted from MATLAB script by Etienne Gaudrain <etienne.gaudrain@cnrs.fr>\nCopyright 2017 CNRS (FR), UMCG (NL)",
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('-ip',
'--ipadress',
help="The ipadress of SAM.",
default='127.0.0.1')
parser.add_argument('-pp',
'--port',
help="Port that SAM has open for connection.",
default=9559,
type=int)
parser.add_argument('-g',
'--game',
help="The game for the current experiment.",
choices=["gender", "fishy", "emotion", "crm"],
required=True)
parser.add_argument('--version',
help="Displays current version",
action='version',
version='Version = {}'.format(VERSION))
parser.add_argument('-s',
'--subject',
help="Name of the subject perfomring the test.",
required=True)
parser.add_argument('-p',
'--phase',
help="Phase of testing. Test or training",
required=True)
parser.add_argument(
'-l',
'--lang',
help="Language in which experiment should be conducted.",
default="EN",
choices=["EN", "NL"],
required=True)
parser.add_argument(
'-e',
'--file_exists',
help=
"Optional parameter if it is already known that a participant's results file already exists or not."
)
args = parser.parse_args()
pickaMain(args.subject, args.game, args.phase, args.lang, args.file_exists,
args.ipadress, 9559)
+25
View File
@@ -0,0 +1,25 @@
def main():
PICKA = {}
i = 0
PICKA["def" + str(i)] = {}
PICKA["def" + str(i)]["folder"] = "./fishy"
PICKA["def" + str(i)]["prefix"] = "expe"
i += 1
PICKA["def" + str(i)] = {}
PICKA["def" + str(i)]["folder"] = "./gender"
PICKA["def" + str(i)]["prefix"] = "gender"
i += 1
PICKA["def" + str(i)] = {}
PICKA["def" + str(i)]["folder"] = "./emotion"
PICKA["def" + str(i)]["prefix"] = "emotion"
i += 1
PICKA["def" + str(i)] = {}
PICKA["def" + str(i)]["folder"] = "./crm"
PICKA["def" + str(i)]["prefix"] = "crm"
return PICKA
+53
View File
@@ -0,0 +1,53 @@
import sys
from gender.gender_run import main as gender_run
from fishy.preprocess import preprocess as fishy_preprocess
from crm.preprocess_corpus import preprocess as crm_preprocess_corpus
def preprocess(language):
r = raw_input(
"Would you like to preprocess all stimuli? It will take approx. 5 min. (Y/n): ")
if r.lower() == 'y':
pass
elif r.lower() == 'n':
sys.exit()
else:
raise "That is not a valid option."
print "==== Preprocessing for fishy ===="
try:
fishy_preprocess(language)
except:
raise Exception("There was an error with fishy preprocess.")
print "==== Preprocessing for Gender ===="
try:
options = {}
gender_run(options, "generation", "test", language)
except:
raise Exception(
"There was an error preporocessing the gender stimuli.")
print "==== Preprocessing for CRM ===="
try:
crm_preprocess_corpus("all", language, 0)
except:
raise Exception("There was an error preprocessing the CRM corpus.")
print "Preprocessing completed."
print "Calibration must still be performed."
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--language", "-l",
help="Language for preprocessing", required=True)
args = parser.parse_args()
preprocess(args.language)
+658
View File
@@ -0,0 +1,658 @@
from __future__ import division
import cython
import numpy as np
cimport numpy as np
np.import_array()
cdef extern from "world/synthesis.h":
void Synthesis(const double *f0,
int f0_length, const double * const *spectrogram,
const double * const *aperiodicity,
int fft_size, double frame_period,
int fs, int y_length, double *y) except +
cdef extern from "world/cheaptrick.h":
ctypedef struct CheapTrickOption:
double q1
double f0_floor
int fft_size
int GetFFTSizeForCheapTrick(int fs, const CheapTrickOption *option) except +
double GetF0FloorForCheapTrick(int fs, int fft_size) except +
void InitializeCheapTrickOption(int fs, CheapTrickOption *option) except +
void CheapTrick(const double *x, int x_length, int fs, const double *temporal_positions,
const double *f0, int f0_length, const CheapTrickOption *option,
double **spectrogram) except +
cdef extern from "world/dio.h":
ctypedef struct DioOption:
double f0_floor
double f0_ceil
double channels_in_octave
double frame_period
int speed
double allowed_range
void InitializeDioOption(DioOption *option) except +
int GetSamplesForDIO(int fs, int x_length, double frame_period)
void Dio(const double *x, int x_length, int fs, const DioOption *option,
double *temporal_positions, double *f0) except +
cdef extern from "world/harvest.h":
ctypedef struct HarvestOption:
double f0_floor
double f0_ceil
double frame_period
void InitializeHarvestOption(HarvestOption *option)
int GetSamplesForHarvest(int fs, int x_length, double frame_period)
void Harvest(const double *x, int x_length, int fs, const HarvestOption *option,
double *temporal_positions, double *f0) except +
cdef extern from "world/d4c.h":
ctypedef struct D4COption:
double threshold
void InitializeD4COption(D4COption *option) except +
void D4C(const double *x, int x_length, int fs, const double *temporal_positions,
const double *f0, int f0_length, int fft_size, const D4COption *option,
double **aperiodicity) except +
cdef extern from "world/stonemask.h":
void StoneMask(const double *x, int x_length, int fs,
const double *temporal_positions, const double *f0, int f0_length,
double *refined_f0) except +
cdef extern from "world/codec.h":
int GetNumberOfAperiodicities(int fs)
void CodeAperiodicity(const double * const *aperiodicity, int f0_length,
int fs, int fft_size, double **coded_aperiodicity) except +
void DecodeAperiodicity(const double * const *coded_aperiodicity,
int f0_length, int fs, int fft_size, double **aperiodicity) except +
void CodeSpectralEnvelope(const double * const *spectrogram, int f0_length,
int fs, int fft_size, int number_of_dimensions,
double **coded_spectral_envelope) except +
void DecodeSpectralEnvelope(const double * const *coded_spectral_envelope,
int f0_length, int fs, int fft_size, int number_of_dimensions,
double **spectrogram) except +
default_frame_period = 5.0
default_f0_floor = 71.0
default_f0_ceil = 800.0
def dio(np.ndarray[double, ndim=1, mode="c"] x not None, int fs,
f0_floor=default_f0_floor, f0_ceil=default_f0_ceil,
channels_in_octave=2.0, frame_period=default_frame_period,
speed=1, allowed_range=0.1):
"""DIO F0 extraction algorithm.
Parameters
----------
x : ndarray
Input waveform signal.
fs : int
Sample rate of input signal in Hz.
f0_floor : float
Lower F0 limit in Hz.
Default: 71.0
f0_ceil : float
Upper F0 limit in Hz.
Default: 800.0
channels_in_octave : float
Resolution of multiband processing; normally shouldn't be changed.
Default: 2.0
frame_period : float
Period between consecutive frames in milliseconds.
Default: 5.0
speed : int
The F0 estimator may downsample the input signal using this integer factor
(range [1;12]). The algorithm will then operate on a signal at fs/speed Hz
to reduce computational complexity, but high values may negatively impact
accuracy.
Default: 1 (no downsampling)
allowed_range : float
Threshold for voiced/unvoiced decision. Can be any value >= 0, but 0.02 to 0.2
is a reasonable range. Lower values will cause more frames to be considered
unvoiced (in the extreme case of `threshold=0`, almost all frames will be unvoiced).
Default: 0.1
Returns
-------
f0 : ndarray
Estimated F0 contour.
temporal_positions : ndarray
Temporal position of each frame.
"""
cdef int x_length = <int>len(x)
cdef DioOption option
InitializeDioOption(&option)
option.channels_in_octave = channels_in_octave
option.f0_floor = f0_floor
option.f0_ceil = f0_ceil
option.frame_period = frame_period
option.speed = speed
option.allowed_range = allowed_range
f0_length = GetSamplesForDIO(fs, x_length, option.frame_period)
cdef np.ndarray[double, ndim=1, mode="c"] f0 = \
np.zeros(f0_length, dtype=np.dtype('float64'))
cdef np.ndarray[double, ndim=1, mode="c"] temporal_positions = \
np.zeros(f0_length, dtype=np.dtype('float64'))
Dio(&x[0], x_length, fs, &option, &temporal_positions[0], &f0[0])
return f0, temporal_positions
def harvest(np.ndarray[double, ndim=1, mode="c"] x not None, int fs,
f0_floor=default_f0_floor, f0_ceil=default_f0_ceil,
frame_period=default_frame_period):
"""Harvest F0 extraction algorithm.
Parameters
----------
x : ndarray
Input waveform signal.
fs : int
Sample rate of input signal in Hz.
f0_floor : float
Lower F0 limit in Hz.
Default: 71.0
f0_ceil : float
Upper F0 limit in Hz.
Default: 800.0
frame_period : float
Period between consecutive frames in milliseconds.
Default: 5.0
Returns
-------
f0 : ndarray
Estimated F0 contour.
temporal_positions : ndarray
Temporal position of each frame.
"""
cdef int x_length = <int>len(x)
cdef HarvestOption option
InitializeHarvestOption(&option)
option.f0_floor = f0_floor
option.f0_ceil = f0_ceil
option.frame_period = frame_period
f0_length = GetSamplesForHarvest(fs, x_length, option.frame_period)
cdef np.ndarray[double, ndim=1, mode="c"] f0 = \
np.zeros(f0_length, dtype=np.dtype('float64'))
cdef np.ndarray[double, ndim=1, mode="c"] temporal_positions = \
np.zeros(f0_length, dtype=np.dtype('float64'))
Harvest(&x[0], x_length, fs, &option, &temporal_positions[0], &f0[0])
return f0, temporal_positions
def stonemask(np.ndarray[double, ndim=1, mode="c"] x not None,
np.ndarray[double, ndim=1, mode="c"] f0 not None,
np.ndarray[double, ndim=1, mode="c"] temporal_positions not None,
int fs):
"""StoneMask F0 refinement algorithm.
Parameters
----------
x : ndarray
Input waveform signal.
f0 : ndarray
Input F0 contour.
temporal_positions : ndarray
Temporal positions of each frame.
fs : int
Sample rate of input signal in Hz.
Returns
-------
refined_f0 : ndarray
Refined F0 contour.
"""
cdef int x_length = <int>len(x)
cdef int f0_length = <int>len(f0)
cdef np.ndarray[double, ndim=1, mode="c"] refined_f0 = \
np.zeros(f0_length, dtype=np.dtype('float64'))
StoneMask(&x[0], x_length, fs, &temporal_positions[0],
&f0[0], f0_length, &refined_f0[0])
return refined_f0
def get_cheaptrick_fft_size(fs, f0_floor=default_f0_floor):
"""Calculate suitable FFT size for CheapTrick given F0 floor.
Parameters
----------
fs : int
Sample rate of input signal in Hz.
f0_floor : float
Lower F0 limit in Hz. The required FFT size is a direct
consequence of the F0 floor used.
Default: 71.0
Returns
-------
fft_size : int
Resulting FFT size.
"""
cdef CheapTrickOption option
option.f0_floor = f0_floor
cdef int fft_size = GetFFTSizeForCheapTrick(fs, &option)
return fft_size
def get_cheaptrick_f0_floor(fs, fft_size):
"""Calculates actual lower F0 limit for CheapTrick
based on the sampling frequency and FFT size used. Whenever F0 is below
this threshold the spectrum will be analyzed as if the frame is unvoiced
(using kDefaultF0 defined in constantnumbers.h).
Parameters
----------
fs : int
Sample rate of input signal in Hz.
fft_size : int
FFT size used for CheapTrick.
Returns
-------
f0_floor : float
Resulting lower F0 limit in Hz.
"""
cdef double f0_floor = GetF0FloorForCheapTrick(fs, fft_size)
return f0_floor
def cheaptrick(np.ndarray[double, ndim=1, mode="c"] x not None,
np.ndarray[double, ndim=1, mode="c"] f0 not None,
np.ndarray[double, ndim=1, mode="c"] temporal_positions not None,
int fs,
q1=-0.15, f0_floor=default_f0_floor, fft_size=None):
"""CheapTrick harmonic spectral envelope estimation algorithm.
Parameters
----------
x : ndarray
Input waveform signal.
f0 : ndarray
Input F0 contour.
temporal_positions : ndarray
Temporal positions of each frame.
fs : int
Sample rate of input signal in Hz.
q1 : float
Spectral recovery parameter.
Default: -0.15 (this value was tuned and normally does not need adjustment)
f0_floor : float, None
Lower F0 limit in Hz. Not used in case `fft_size` is specified.
Default: 71.0
fft_size : int, None
FFT size to be used. When `None` (default) is used, the FFT size is computed
automatically as a function of the given input sample rate and F0 floor.
When `fft_size` is specified, the given `f0_floor` parameter is ignored.
Default: None
Returns
-------
spectrogram : ndarray
Spectral envelope (squared magnitude).
"""
cdef CheapTrickOption option
InitializeCheapTrickOption(fs, &option)
option.q1 = q1
if fft_size is None:
option.f0_floor = f0_floor # CheapTrickOption.f0_floor is only used in GetFFTSizeForCheapTrick()
option.fft_size = GetFFTSizeForCheapTrick(fs, &option)
else:
option.fft_size = fft_size
# the f0_floor used by CheapTrick() will be re-compute from this given fft_size
cdef int x_length = <int>len(x)
cdef int f0_length = <int>len(f0)
cdef double[:, ::1] spectrogram = np.zeros((f0_length, option.fft_size//2 + 1),
dtype=np.dtype('float64'))
cdef np.intp_t[:] tmp = np.zeros(f0_length, dtype=np.intp)
cdef double **cpp_spectrogram = <double**> (<void*> &tmp[0])
cdef np.intp_t i
for i in range(f0_length):
cpp_spectrogram[i] = &spectrogram[i, 0]
CheapTrick(&x[0], x_length, fs, &temporal_positions[0],
&f0[0], f0_length, &option, cpp_spectrogram)
return np.array(spectrogram, dtype=np.float64)
def d4c(np.ndarray[double, ndim=1, mode="c"] x not None,
np.ndarray[double, ndim=1, mode="c"] f0 not None,
np.ndarray[double, ndim=1, mode="c"] temporal_positions not None,
int fs,
threshold=0.85, fft_size=None):
"""D4C aperiodicity estimation algorithm.
Parameters
----------
x : ndarray
Input waveform signal.
f0 : ndarray
Input F0 contour.
temporal_positions : ndarray
Temporal positions of each frame.
fs : int
Sample rate of input signal in Hz.
q1 : float
Spectral recovery parameter.
Default: -0.15 (this value was tuned and normally does not need adjustment)
threshold : float
Threshold for aperiodicity-based voiced/unvoiced decision, in range 0 to 1.
If a value of 0 is used, voiced frames will be kept voiced. If a value > 0 is
used some voiced frames can be considered unvoiced by setting their aperiodicity
to 1 (thus synthesizing them with white noise). Using `threshold=0` will result
in the behavior of older versions of D4C. The current default of 0.85 is meant
to be used in combination with the Harvest F0 estimator, which was designed to have
a high voiced/unvoiced threshold (i.e. most frames will be considered voiced).
Default: 0.85
fft_size : int, None
FFT size to be used. When `None` (default) is used, the FFT size is computed
automatically as a function of the given input sample rate and the default F0 floor.
When `fft_size` is specified, it should match the FFT size used to compute
the spectral envelope (i.e. `fft_size=2*(sp.shape[1] - 1)`) in order to get the
desired results when resynthesizing.
Default: None
Returns
-------
aperiodicity : ndarray
Aperiodicity (envelope, linear magnitude relative to spectral envelope).
"""
cdef int x_length = <int>len(x)
cdef int f0_length = <int>len(f0)
cdef int fft_size0
if fft_size is None:
fft_size0 = get_cheaptrick_fft_size(fs, default_f0_floor)
else:
fft_size0 = fft_size
cdef D4COption option
InitializeD4COption(&option)
option.threshold = threshold
cdef double[:, ::1] aperiodicity = np.zeros((f0_length, fft_size0//2 + 1),
dtype=np.dtype('float64'))
cdef np.intp_t[:] tmp = np.zeros(f0_length, dtype=np.intp)
cdef double **cpp_aperiodicity = <double**> (<void*> &tmp[0])
cdef np.intp_t i
for i in range(f0_length):
cpp_aperiodicity[i] = &aperiodicity[i, 0]
D4C(&x[0], x_length, fs, &temporal_positions[0],
&f0[0], f0_length, fft_size0, &option,
cpp_aperiodicity)
return np.array(aperiodicity, dtype=np.float64)
def synthesize(np.ndarray[double, ndim=1, mode="c"] f0 not None,
np.ndarray[double, ndim=2, mode="c"] spectrogram not None,
np.ndarray[double, ndim=2, mode="c"] aperiodicity not None,
int fs,
double frame_period=default_frame_period):
"""WORLD synthesis from parametric representation.
Parameters
----------
f0 : ndarray
Input F0 contour.
spectrogram : ndarray
Spectral envelope.
aperiodicity : ndarray
Aperodicity envelope.
fs : int
Sample rate of input signal in Hz.
frame_period : float
Period between consecutive frames in milliseconds.
Default: 5.0
Returns
-------
y : ndarray
Output waveform signal.
"""
if (f0.shape[0] != spectrogram.shape[0] or
f0.shape[0] != aperiodicity.shape[0]):
raise ValueError('Mismatched number of frames between F0 ({:d}), '
'spectrogram ({:d}) and aperiodicty ({:d})'
.format(f0.shape[0], spectrogram.shape[0],
aperiodicity.shape[0]))
if spectrogram.shape[1] != aperiodicity.shape[1]:
raise ValueError('Mismatched dimensionality (spec size) between '
'spectrogram ({:d}) and aperiodicity ({:d})'
.format(spectrogram.shape[1], aperiodicity.shape[1]))
cdef int f0_length = <int>len(f0)
y_length = int(f0_length * frame_period * fs / 1000)
cdef int fft_size = (<int>spectrogram.shape[1] - 1)*2
cdef np.ndarray[double, ndim=1, mode="c"] y = \
np.zeros(y_length, dtype=np.dtype('float64'))
cdef double[:, ::1] spectrogram0 = spectrogram
cdef double[:, ::1] aperiodicity0 = aperiodicity
cdef np.intp_t[:] tmp = np.zeros(f0_length, dtype=np.intp)
cdef np.intp_t[:] tmp2 = np.zeros(f0_length, dtype=np.intp)
cdef double **cpp_spectrogram = <double**> (<void*> &tmp[0])
cdef double **cpp_aperiodicity = <double**> (<void*> &tmp2[0])
cdef np.intp_t i
for i in range(f0_length):
cpp_spectrogram[i] = &spectrogram0[i, 0]
cpp_aperiodicity[i] = &aperiodicity0[i, 0]
Synthesis(&f0[0], f0_length, cpp_spectrogram,
cpp_aperiodicity, fft_size, frame_period, fs, y_length, &y[0])
return y
def get_num_aperiodicities(fs):
"""Calculate the required dimensionality to code D4C aperiodicity.
Parameters
----------
fs : int
Sample rate of input signal in Hz.
Returns
-------
n_aper : int
Required number of coefficients.
"""
cdef int n_aper = GetNumberOfAperiodicities(fs)
return n_aper
def code_aperiodicity(np.ndarray[double, ndim=2, mode="c"] aperiodicity, fs):
"""Reduce dimensionality of D4C aperiodicity.
Parameters
----------
aperiodicity : ndarray
Aperodicity envelope.
fs : int
Sample rate of input signal in Hz.
Returns
-------
coded_aperiodicity : ndarray
Coded aperiodicity envelope.
"""
cdef int ap_length = <int>len(aperiodicity)
cdef int fft_size = (<int>aperiodicity.shape[1] - 1)*2
cdef int n_coded_aper = get_num_aperiodicities(fs)
cdef double[:, ::1] aper = aperiodicity
cdef double[:, ::1] coded_aper = np.zeros((ap_length, n_coded_aper),
dtype=np.dtype('float64'))
cdef np.intp_t[:] tmp1 = np.zeros(ap_length, dtype=np.intp)
cdef np.intp_t[:] tmp2 = np.zeros(ap_length, dtype=np.intp)
cdef double **cpp_aper = <double**> (<void*> &tmp1[0])
cdef double **cpp_coded_aper = <double**> (<void*> &tmp2[0])
cdef np.intp_t i
for i in range(ap_length):
cpp_aper[i] = &aper[i, 0]
cpp_coded_aper[i] = &coded_aper[i, 0]
CodeAperiodicity(cpp_aper, ap_length, fs,
fft_size, cpp_coded_aper)
return np.array(coded_aper, dtype=np.float64)
def decode_aperiodicity(np.ndarray[double, ndim=2, mode="c"] coded_aperiodicity,
fs, fft_size):
"""Restore full dimensionality of coded D4C aperiodicity.
Parameters
----------
coded_aperiodicity : ndarray
Coded aperodicity envelope.
fs : int
Sample rate of input signal in Hz.
fft_size : int
FFT size corresponding to the full dimensional aperiodicity.
Returns
-------
aperiodicity : ndarray
Aperiodicity envelope.
"""
cdef int ap_length = <int>len(coded_aperiodicity)
cdef int n_coded_aper = get_num_aperiodicities(fs)
if n_coded_aper != coded_aperiodicity.shape[1]:
raise ValueError('Invalid aperiodicity code dimensionality '
'(was: {:d}, expected: {:d})'
.format(coded_aperiodicity.shape[1], n_coded_aper))
cdef double[:, ::1] coded_aper = coded_aperiodicity
cdef double[:, ::1] aper = np.zeros((ap_length, fft_size//2 + 1),
dtype=np.dtype('float64'))
cdef np.intp_t[:] tmp1 = np.zeros(ap_length, dtype=np.intp)
cdef np.intp_t[:] tmp2 = np.zeros(ap_length, dtype=np.intp)
cdef double **cpp_coded_aper = <double**> (<void*> &tmp1[0])
cdef double **cpp_aper = <double**> (<void*> &tmp2[0])
cdef np.intp_t i
for i in range(ap_length):
cpp_coded_aper[i] = &coded_aper[i, 0]
cpp_aper[i] = &aper[i, 0]
DecodeAperiodicity(cpp_coded_aper, ap_length, fs, fft_size, cpp_aper)
return np.array(aper, dtype=np.float64)
def code_spectral_envelope(np.ndarray[double, ndim=2, mode="c"] spectrogram, fs,
number_of_dimensions):
"""Reduce dimensionality of spectral envelope.
Parameters
----------
spectrogram : ndarray
Spectral envelope.
fs : int
Sample rate of input signal in Hz.
number_of_dimensions : int
Number of dimentions of coded spectral envelope
Returns
-------
coded_spectral_envelope : ndarray
Coded spectral envelope.
"""
cdef int sp_length = <int>len(spectrogram)
cdef int fft_size = (<int>spectrogram.shape[1] - 1)*2
cdef double[:, ::1] sp = spectrogram
cdef double[:, ::1] coded_sp = np.zeros((sp_length, number_of_dimensions),
dtype=np.dtype('float64'))
cdef np.intp_t[:] tmp1 = np.zeros(sp_length, dtype=np.intp)
cdef np.intp_t[:] tmp2 = np.zeros(sp_length, dtype=np.intp)
cdef double **cpp_sp = <double**> (<void*> &tmp1[0])
cdef double **cpp_coded_sp = <double**> (<void*> &tmp2[0])
cdef np.intp_t i
for i in range(sp_length):
cpp_sp[i] = &sp[i, 0]
cpp_coded_sp[i] = &coded_sp[i, 0]
CodeSpectralEnvelope(cpp_sp, sp_length, fs, fft_size,
number_of_dimensions, cpp_coded_sp)
return np.array(coded_sp, dtype=np.float64)
def decode_spectral_envelope(np.ndarray[double, ndim=2, mode="c"] coded_spectral_envelope,
fs, fft_size):
"""Restore full dimensionality of coded spectral envelope.
Parameters
----------
coded_spectral_envelope : ndarray
Coded spectral envelope.
fs : int
Sample rate of input signal in Hz.
fft_size : int
FFT size corresponding to the full dimensional spectral envelope.
Returns
-------
spectrogram : ndarray
Spectral envelope.
"""
cdef int sp_length = <int>len(coded_spectral_envelope)
cdef int number_of_dimensions = <int>len(coded_spectral_envelope[0])
cdef double[:, ::1] coded_sp = coded_spectral_envelope
cdef double[:, ::1] sp = np.zeros((sp_length, fft_size//2 + 1),
dtype=np.dtype('float64'))
cdef np.intp_t[:] tmp1 = np.zeros(sp_length, dtype=np.intp)
cdef np.intp_t[:] tmp2 = np.zeros(sp_length, dtype=np.intp)
cdef double **cpp_coded_sp = <double**> (<void*> &tmp1[0])
cdef double **cpp_sp = <double**> (<void*> &tmp2[0])
cdef np.intp_t i
for i in range(sp_length):
cpp_coded_sp[i] = &coded_sp[i, 0]
cpp_sp[i] = &sp[i, 0]
DecodeSpectralEnvelope(cpp_coded_sp, sp_length, fs, fft_size,
number_of_dimensions, cpp_sp)
return np.array(sp, dtype=np.float64)
def wav2world(x, fs, fft_size=None, frame_period=default_frame_period):
"""Convenience function to do all WORLD analysis steps in a single call.
In this case only `frame_period` can be configured and other parameters
are fixed to their defaults. Likewise, F0 estimation is fixed to
DIO plus StoneMask refinement.
Parameters
----------
x : ndarray
Input waveform signal.
fs : int
Sample rate of input signal in Hz.
frame_period : float
Period between consecutive frames in milliseconds.
Default: 5.0
fft_size : int
Length of Fast Fourier Transform (in number of samples)
The resulting dimension of `ap` adn `sp` will be `fft_size` // 2 + 1
Returns
-------
f0 : ndarray
F0 contour.
sp : ndarray
Spectral envelope.
ap : ndarray
Aperiodicity.
"""
_f0, t = dio(x, fs, frame_period=frame_period)
f0 = stonemask(x, _f0, t, fs)
sp = cheaptrick(x, f0, t, fs, fft_size=fft_size)
ap = d4c(x, f0, t, fs, fft_size=fft_size)
return f0, sp, ap
Binary file not shown.
BIN
View File
Binary file not shown.
+25
View File
@@ -0,0 +1,25 @@
65 dB calibrated laptop -14 attenuation
24.6, 24.6, 24.6, 24.6, 24.6, 24.6, 27.6, 24.6, 41.0, 41.5, 39.3, 53.6, 58.9, 52.6, 54.1, 51.8, 61.1, 53.6, 52.5, 45.8, 38.4, 40.8, 39.0, 39.3, 40.6, 41.4
unattenuated laptop
24.6, 24.6, 24.6, 24.6, 24.6, 27.6, 60.6, 38.4, 51.9, 55.0, 58.1, 68.4, 69.7, 65.8, 67.6, 68.3, 75.4, 71.3, 65.2, 62.1, 49.8, 54.0, 46.0, 39.6, 40.3, 41.4
65 dB calibrated Sam -16 attenuation
24.6, 24.6, 24.6, 24.6, 24.6, 37.6, 33.6, 32.3, 55.5, 54.0, 63.7, 49.1, 39.6, 38.7, 47.0, 44.6, 49.1, 51.5, 45.8, 38.4, 40.3, 38.4, 38.4, 39.6, 40.3, 41.4
unattenuated Sam
24.6, 24.6, 24.6, 24.6, 30.6, 53.3, 48.4, 48.0, 70.9, 69.1, 78.3, 64.4, 55.2, 54.3, 62.8, 60.2, 64.8, 67.3, 61.1, 51.5, 54.3, 47.5, 40.3, 39.6, 40.6, 41.4
65 dB calibrated DIN Robin laptop -8 attenuation
24.6, 24.6, 24.6, 24.6, 24.6, 27.6, 46.4, 43.4, 41.4, 45.8, 44.5, 53.2, 57.4, 48.7, 42.3, 51.9, 56.8, 57.9, 59.6, 53.8, 42.0, 45.5, 46.4, 40.8, 40.8, 41.4
unattenuated DIN
24.6, 24.6, 24.6, 24.6, 24.6, 38.7, 53.6, 50.6, 49.0, 53.6, 52.0, 60.9, 65.1, 56.8, 50.1, 59.5, 64.7, 65.8, 67.3, 61.5, 48.8, 52.6, 53.6, 44.4, 42.6, 41.4
+11
View File
@@ -0,0 +1,11 @@
This file was created as a result of running /Users/egaudrain/Sounds/Emotions/PICKA/script/prepare_equalized on 04-Dec-2017 17:33:38.
The files have been read from "../original/*.wav", then silence has been removed using remove_silence(x, fs, 75e-3).
They were then normalized and their RMS was calculated. The normalized files were saved in the destination folder
with a quantization of 24 bits per sample to avoid aliasing problems. The reference RMS was calculated as the
smallest RMS amongst the normalized files. They were then all scaled again to have that same RMS, and saved
again with a quantization of 16 bits per sample.
Files have been renamed using /Users/egaudrain/Sounds/Emotions/PICKA/script/rename_files.py applying the following nomenclature:
s[talker]e[emotion number]s[sentence]_{p,t}[utterance]
-> t[talker]_[emotion]_s[sentence]_u[utterance]
+1
View File
@@ -0,0 +1 @@
import to_noise
+55
View File
@@ -0,0 +1,55 @@
import numpy as np
# L = np.array([24.6, 24.6, 24.6, 24.6, 24.6, 24.6, 27.6, 24.6, 41.0, 41.5, 39.3, 53.6, 58.9, 52.6, 54.1, 51.8, 61.1, 53.6, 52.5, 45.8, 38.4, 40.8, 39.0, 39.3, 40.6, 41.4])
# L = np.array([
# 24.6, 24.6, 24.6, 24.6, 24.6, 27.6, 46.4, 43.4, 41.4, 45.8, 44.5, 53.2,
# 57.4, 48.7, 42.3, 51.9, 56.8, 57.9, 59.6, 53.8, 42.0, 45.5, 46.4, 40.8,
# 40.8, 41.4
# ])
# SAM 75 dB, attenuation = -1.0
# L = np.array([
# 35.3, 30.6, 24.6, 24.6, 24.6, 30.6, 35.3, 45.0, 54.2, 64.5, 71.2, 66.9,
# 59.7, 55.9, 60.1, 62.1, 59.0, 63.6, 62.8, 59.1, 49.3, 45.3, 42.9, 40.6,
# 40.6, 40.6, 41.4
# ])
# Surface Pro 75 dB, attenuation = -13
# L = np.array([
# 36.6, 30.6, 24.6, 27.6, 35.3, 55.8, 61.8, 61.1, 59.8, 63.6, 58.4, 61.6,
# 65.6, 61.5, 58.6, 61.1, 63.5, 67.5, 65.4, 61.4, 56.1, 48.6, 44.3, 57.6,
# 50.5, 41.0, 41.4
# ])
#ROBIN 75 dB, attenuation = -0.5
# L = np.array([
# 34.6, 27.6, 24.6, 24.6, 24.6, 32.3, 41.4, 50.9, 58.2, 65.3, 64.4, 64.7,
# 63.5, 60.5, 61.1, 65.7, 66.7, 64.1, 64.3, 60.4, 52.7, 50.7, 48.5, 41.9,
# 39.9, 40.6, 41.4
# ])
# HP Pavillion 75 dB, attenuation = 7.5
# L = np.array([
# 27.6, 24.6, 27.6, 36.0, 56.0, 62.3, 61.8, 61.1, 65.3, 59.8, 64.5, 66.0,
# 62.4, 63.6, 64.2, 60.7, 65.5, 64.0, 60.7, 52.6, 45.8, 43.8, 57.3, 50.1,
# 41.4, 41.4
# ])
#Sam Laptop 65 dB, attenuation = -21
# L = np.array([
# 24.6, 24.6, 24.6, 24.6, 27.6, 24.6, 24.6, 30.6, 30.6, 39.9, 42.2, 54.3,
# 56.4, 59.7, 55.2, 53.5, 57.4, 54.6, 50.2, 41.7, 38.0, 43.6, 41.2, 39.6,
# 40.3, 41.4
# ])
#SAM 65dB, attenuation = -11.8
L = np.array([
24.6, 24.6, 24.6, 24.6, 30.6, 27.6, 35.3, 43.7, 54.0, 62.4, 56.3, 48.7,
45.7, 50.7, 47.7, 46.3, 53.1, 50.4, 47.0, 39.9, 37.6, 38.0, 38.7, 39.6,
40.3, 41.4
])
total_power = np.sum(np.power(10, L / 10))
L_total = 10.0 * np.log10(total_power)
print L_total
+62
View File
@@ -0,0 +1,62 @@
from playsound import playsound
import os
import random
import time
import numpy as np
import soundfile as sf
# from expe_options import expe_options
# from expe_build_conditions import expe_build_conditions
from tqdm import tqdm
from to_noise import noise
def main(source):
'''
Simply plays the stimulus files in the tmp folders generated either by:
PyWorld - source is either "python" or "p";
or Matalb - source is either "matlab" or "m"
'''
folder = ''
if source[0].lower() == "p":
folder = "/home/nao/Documents/Sam_files/Python_scripts/tmp/"
elif source[0].lower() == 'm':
folder = "/home/nao/Documents/Sam_files/Nao-PICKA scripts/Expe_files/tmp/"
elif source[0].lower() == 'e':
folder = "/home/nao/Documents/Sam_files/Python_scripts/stimuli/emotion/"
files = os.listdir(folder)
y = np.array([])
for i in tqdm(range(len(files))):
if files[i].endswith(".wav"):
r = random.randint(0, len(files) - 1)
x, fs = sf.read(os.path.join(folder, str(files[r])))
# x = x * np.power(10, -(options["attenuation_dB"]/20.0))
# sf.write("cal_" + str(i) + ".wav", np.concatenate((np.zeros((1024*3, 2)),
# np.tile(x, (2, 1)).T, np.zeros((1024*3, 2)))), fs)
# sfile = os.path.join(
# "/home/nao/Documents/Sam_files/Python_scripts/", "cal_" + str(i) + ".wav")
# playsound(sfile)
# os.remove("cal_" + str(i) + ".wav")
# time.sleep(0.05)
y = np.append(y, x)
y = noise(y, 44100)
sf.write(
"calibration_emotion.wav",
np.concatenate((np.zeros(
(1024 * 3, 2)), np.tile(y, (2, 1)).T, np.zeros((1024 * 3, 2)))),
fs)
sfile = os.path.join("/home/nao/Documents/Sam_files/Python_scripts",
"calibration_e.wav")
# playsound(sfile)
if __name__ == "__main__":
# options = expe_options()
# expe_build_conditions(options)
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("source", type=str, help="Source for the play files")
args = parser.parse_args()
main(args.source)
+16
View File
@@ -0,0 +1,16 @@
import soundfile as sf
from playsound import playsound
import numpy as np
import sys
from threading import Thread
z, fs = sf.read('./calibration_emotion_cut.wav')
# options.attenuation_dB = 36;
z = z * np.power(10.0, (-21.0 / 20))
sf.write("calibration_e.wav", z, fs)
try:
Thread(target=playsound, args=("calibration_e.wav", )).start()
except KeyboardInterrupt:
sys.exit()
+31
View File
@@ -0,0 +1,31 @@
#!/usr/bin/python
import json
from load_matrix import loadmat
from pymatreader import read_mat
import os
def main(f):
matFile = os.path.join(
"/home/nao/Documents/Backups/Participant results/Sam/", f)
mat = loadmat(matFile)
results = mat["results"]
jsonFile = os.path.join(
"/home/nao/Documents/Backups/Participant results/Sam/", os.path.splitext(f)[0] + ".json")
with open(jsonFile, 'w+') as fl:
fl.write(json.dumps(results, indent=4, sort_keys=True))
fl.close()
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('f', help='.mat file to be created into json')
args = parser.parse_args()
main(args.f)
print '--- Operation Completed ---'
+80
View File
@@ -0,0 +1,80 @@
import sys
import time
import os
from naoqi import ALProxy
from naoqi import ALModule
from celery.task.control import revoke
memory = None
a = 0
class ExitExperimentModule(ALModule):
'''Module that will exit the experiment when one of the foot bumpers is touched'''
def __init__(self, name, broker, language):
ALModule.__init__(self, name)
self.tts = ALProxy("ALTextToSpeech")
self.con = ALProxy("ALConnectionManager")
self.spr = ALProxy("ALSpeechRecognition")
self.all = ALProxy("ALLeds")
answers = ["yes", "no"]
self.spr.setVocabulary(answers, False)
self.broker = broker
self.name = name
self.language = language
global memory
memory = ALProxy("ALMemory")
memory.subscribeToEvent("RightBumperPressed",
name, "onBumperPressed")
def onBumperPressed(self, *_args):
import settings
if self.name == "stop_audio":
aap = ALProxy("ALAudioPlayer")
aap.stopAll()
return
global a
print settings.task_id
memory.unsubscribeToEvent(
"RightBumperPressed", self.name)
if self. language == "EN":
self.tts.say(
"If you're sure you want to exit, \\pau=500\\ press my \\pau=500\\ left foot.")
elif self.language == "NL":
self.tts.say(
"Als je zeker weet dat je wilt stoppen, \\pau=500\\ raak dan mijn linkervoet aan.")
# self.tts.say("Exit?")
memory.subscribeToEvent(
"LeftBumperPressed", self.name, "onLeftBumperPressed")
time.sleep(5)
if a == 1:
revoke(self.task_id, terminate=True)
else:
memory.unsubscribeToEvent(
"LeftBumperPressed", self.name)
if self. language == "EN":
self.tts.say("Ok then. Let's continue.")
elif self.language == "NL":
self.tts.say("Ok, laten we dan verder gaan.")
memory.subscribeToEvent("RightBumperPressed",
"expe_exit", "onBumperPressed")
def onLeftBumperPressed(self, *_args):
global a
a = 1
memory.unsubscribeToEvent(
"LeftBumperPressed", self.name)
self.all.fadeRGB("FaceLeds", "white", 0.05)
if self. language == "EN":
self.tts.say("Goodbye")
elif self.language == "NL":
self.tts.say("Tot ziens")
self.broker.shutdown()
+285
View File
@@ -0,0 +1,285 @@
import os
import sys
import pandas as pd
import numpy as np
from load_matrix import loadmat
def main(game, path, lang, age, des):
os.chdir(path)
if game == "fishy":
export_jnd(lang, age, des)
elif game == "gender":
export_gender(lang, age, des)
elif game == "emotion":
export_emotion(lang, age, des)
elif game == "crm":
export_crm(lang, age, des)
def export_jnd(lang, age, des):
res_path = "./"
output_path = des
export_filename = os.path.join(
output_path, "JND_" + lang + "_" + age + ".csv")
table = pd.DataFrame(columns=["subject", "ref_f0", "dir_f0", "ref_ser", "dir_ser", "ref_voice",
"dir_voice", "threshold", "threshold_f0", "threshold_vtl", "sd", "response_datetime"])
for d in os.listdir(res_path):
if d.startswith("NH" + age):
subject_dir = os.path.join(res_path, d)
f = os.path.join(subject_dir, "jnd_" +
lang.lower() + "_" + d + "_robot.mat")
try:
mat = loadmat(f)
results = mat["results"]
options = mat["options"]
for i in range(0, len(results["test"]["conditions"])):
responses = {}
att = {}
try:
att = results["test"]["conditions"]["c" +
str(i)]["att"]
responses = att["responses"]
resp = responses["r" + str(len(responses)-1)]
except (KeyError, TypeError):
att = results["test"]["conditions"]["c" +
str(i)]["att"][0]
responses = att["responses"]
resp = responses[len(responses)-1]
subject = options["subject_name"]
trial = resp["trial"]
u_f0 = 12 * np.log2(options["test"]["voices"]['v' + str(trial["dir_voice"])]
["f0"] / options["test"]["voices"]['v' + str(trial["ref_voice"])]["f0"])
u_ser = 12 * np.log2(options["test"]["voices"]['v' + str(trial["dir_voice"])]
["ser"] / options["test"]["voices"]['v' + str(trial["ref_voice"])]["ser"])
u = np.array([u_f0, u_ser])
u = u / np.sqrt(np.sum(np.power(u, 2)))
ex = {
"subject": subject,
"ref_f0": options["test"]["voices"]["v" + str(trial["ref_voice"])]["f0"],
"dir_f0": options["test"]["voices"]["v" + str(trial["dir_voice"])]["f0"],
"ref_ser": options["test"]["voices"]["v" + str(trial["ref_voice"])]["ser"],
"dir_ser": options["test"]["voices"]["v" + str(trial["dir_voice"])]["ser"],
"ref_voice": options["test"]["voices"]["v" + str(trial["ref_voice"])]["label"],
"dir_voice": options["test"]["voices"]["v" + str(trial["dir_voice"])]["label"],
"threshold": att["threshold"],
"threshold_f0": att["threshold"] * u[0],
"threshold_vtl": att["threshold"] * u[1],
"sd": att["sd"],
"response_datetime": resp["timestamp"],
}
table = table.append(ex, True)
except (KeyError, IOError) as e:
print e
print "Could not retrieve necessary matrices. \n Skipping participant: " + d
table.to_csv(export_filename)
def export_gender(lang, age, des):
res_path = "./"
output_path = des
export_filename = os.path.join(
output_path, "Gender_" + lang + "_" + age + ".csv")
table = pd.DataFrame(columns=["subject", "df0", "dvtl", "word",
"answer", "gender", "response_datetime", "response_time"])
for d in os.listdir(res_path):
if d.startswith("NH" + age):
subject_dir = os.path.join(res_path, d)
f = os.path.join(subject_dir, "gen_" +
lang.lower() + "_" + d + "_robot.mat")
try:
mat = loadmat(f)
results = mat["results"]
options = mat["options"]
gen_responses = mat["gender_response"]
resp = {}
i = 1
for r in results["test"]["responses"]:
subject = options["subject_name"]
try:
trial = r["trial"]
if "trial " in list(gen_responses["test"].keys())[0]:
gen_trial = gen_responses["test"]["trial " +
str(i)]
elif "trial_" in list(gen_responses["test"].keys())[0]:
gen_trial = gen_responses["test"]["trial_" +
str(i)]
resp = r
resp_ans = r["response_answer"]
except TypeError:
resp = results["test"]["responses"][r]
if "trial " in list(gen_responses["test"].keys())[0]:
gen_trial = gen_responses["test"]["trial " +
str(int(r[1:])+1)]
elif "trial_" in list(gen_responses["test"].keys())[0]:
gen_trial = gen_responses["test"]["trial_" +
str(int(r[1:])+1)]
trial = resp["trial"]
resp_ans = resp["response_answer"]
ex = {
"subject": subject,
"df0": gen_trial["f0(st)"],
"dvtl": gen_trial["VTL(st)"],
"word": trial["word"],
"answer": resp_ans["answer"],
"gender": gen_trial["answer"],
"is_female": 1 if gen_trial["answer"] == "Girl" else 0,
"response_datetime": resp["timestamp"],
"response_time": resp["response_time"],
}
table = table.append(ex, True)
i += 1
except (KeyError, IOError) as e:
print e
print "Could not retrieve necessary matrices. \n Skipping participant: " + d
table.to_csv(export_filename)
def export_emotion(lang, age, des):
res_path = './'
output_path = des
export_filename = os.path.join(
output_path, "Emotion_" + lang + "_" + age + ".csv")
table = pd.DataFrame(columns=[
"subject", "emotion", "file", "utterance", "talker", "sentence", "correct", "response_time"])
for d in os.listdir(res_path):
if d.startswith("NH" + age):
subject_dir = os.path.join(res_path, d)
f = os.path.join(subject_dir, "emo_" +
lang.lower() + "_" + d + "_robot.mat")
try:
mat = loadmat(f)
results = mat["results"]
options = mat["options"]
resp = {}
for r in results["test"]["responses"]:
subject = options["subject_name"]
try:
trial = r["trial"]
resp = r
except TypeError:
resp = results["test"]["responses"][r]
trial = resp["trial"]
ex = {
"subject": subject,
"emotion": trial["emotion"],
"file": trial["file"],
"utterance": trial["utterance"],
"talker": trial["talker"],
"sentence": trial["sentence"],
"correct": resp["correct"],
"response_time": resp["response_time"],
}
table = table.append(ex, True)
except (KeyError, IOError) as e:
print e
print "Could not retrieve necessary matrices. \n Skipping participant: " + d
table.to_csv(export_filename)
def export_crm(lang, age, des):
res_path = './'
output_path = des
export_filename = os.path.join(
output_path, "CRM_" + lang + "_" + age + ".csv")
table = pd.DataFrame(columns=[
"subject", "correct", "colour", "number", "call_sign", "sound_file", "dF0", "dVTL", "tmr", "response_time"])
for d in os.listdir(res_path):
if d.startswith("NH" + age):
subject_dir = os.path.join(res_path, d)
f = os.path.join(subject_dir, "crm_" +
lang.lower() + "_" + d + "_robot.mat")
try:
mat = loadmat(f)
results = mat["results"]
options = mat["options"]
resp = {}
for r in results["test"]["responses"]:
subject = options["subject_name"]
try:
trial = r["trial"]
resp = r
except TypeError:
resp = results["test"]["responses"][r]
trial = resp["trial"]
ex = {
"subject": subject,
"correct": resp["correct"],
"colour": trial["target"]["colour"],
"number": trial["target"]["number"],
"call_sign": trial["target"]["call_sign"],
"sound_file": trial["target"]["sound_file"],
"dF0": trial["voice"]["dF0"],
"dVTL": trial["voice"]["dVTL"],
"tmr": trial["tmr"],
"response_time": resp["response_time"]
}
table = table.append(ex, True)
except (KeyError, IOError) as e:
print e
print "Could not retrieve necessary matrices. Skipping participant: " + d
table.to_csv(export_filename)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="The main script used to run SAM",
epilog="Written by Luke Meyer <l.meyer.5@student.rug.nl>, adapted from MATLAB script by Etienne Gaudrain <etienne.gaudrain@cnrs.fr>\nCopyright 2017 CNRS (FR), UMCG (NL)", formatter_class=argparse.RawDescriptionHelpFormatter)
# parser.add_argument(
# '-f', '--file', help="Path to results file", required=True)
# parser.add_argument(
# '-pp', '--port', help="Port that SAM has open for connection.", default=9559, type=int)
parser.add_argument(
'-g', '--game', help="The game for the current experiment.", choices=["gender", "fishy", "emotion", "crm"], required=True)
# parser.add_argument('--version', help="Displays current version",
# action='version', version='Version = {}'.format(VERSION))
parser.add_argument(
'-p', '--path', help="Path to results folder if not in current directory, INCLUDING ./results. Please use absolute path.", default='./')
parser.add_argument(
'-a', '--age', help="Age group to be exported.", default="A", choices=["A", "K"], required=True)
parser.add_argument(
'-l', '--lang', help="Experiment language to be exported.", default="EN", choices=["EN", "NL"], required=True)
parser.add_argument('-d', '--destination',
help="Path to destination of exported results.", default="./", required=True)
args = parser.parse_args()
# mat = loadmat(args.file)
# options = mat["options"]
# results = mat["results"]
# os.chdir("/home/nao/Documents/Sam_files/Python_scripts")
main(args.game, args.path, args.lang, args.age, args.destination)
+108
View File
@@ -0,0 +1,108 @@
# -*- encoding: UTF-8 -*-
""" Say 'hello, you' each time a human face is detected
"""
import sys
import time
from naoqi import ALProxy
from naoqi import ALBroker
from naoqi import ALModule
from optparse import OptionParser
NAO_IP = "nao.local"
# Global variable to store the HumanGreeter module instance
HumanGreeter = None
memory = None
class HumanGreeterModule(ALModule):
""" A simple module able to react
to facedetection events
"""
def __init__(self, name):
ALModule.__init__(self, name)
# No need for IP and port here because
# we have our Python broker connected to NAOqi broker
# Create a proxy to ALTextToSpeech for later use
self.tts = ALProxy("ALTextToSpeech")
# Subscribe to the FaceDetected event:
global memory
memory = ALProxy("ALMemory")
memory.subscribeToEvent("FaceDetected",
"HumanGreeter",
"onFaceDetected")
def onFaceDetected(self, *_args):
""" This will be called each time a face is
detected.
"""
# Unsubscribe to the event when talking,
# to avoid repetitions
memory.unsubscribeToEvent("FaceDetected",
"HumanGreeter")
self.tts.say("Hello, you")
# Subscribe again to the event
memory.subscribeToEvent("FaceDetected",
"HumanGreeter",
"onFaceDetected")
def main():
""" Main entry point
"""
parser = OptionParser()
parser.add_option("--pip",
help="Parent broker port. The IP address or your robot",
dest="pip")
parser.add_option("--pport",
help="Parent broker port. The port NAOqi is listening to",
dest="pport",
type="int")
parser.set_defaults(
pip=NAO_IP,
pport=9559)
(opts, args_) = parser.parse_args()
pip = opts.pip
pport = opts.pport
# We need this broker to be able to construct
# NAOqi modules and subscribe to other modules
# The broker must stay alive until the program exists
myBroker = ALBroker("myBroker",
"0.0.0.0", # listen to anyone
0, # find a free port and use it
pip, # parent broker IP
pport) # parent broker port
# Warning: HumanGreeter must be a global variable
# The name given to the constructor must be the name of the
# variable
global HumanGreeter
HumanGreeter = HumanGreeterModule("HumanGreeter")
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
print
print "Interrupted by user, shutting down"
myBroker.shutdown()
sys.exit(0)
if __name__ == "__main__":
main()
+17
View File
@@ -0,0 +1,17 @@
import soundfile as sf
def generate(stimulus, attenuation):
x, fs = sf.read("/home/nao/PICKA/Python_scripts/stimuli/emotion/" + stimulus)
x = x * 10.0 ** float(attenuation)/20
sf.write('/home/nao/PICKA/Python_scripts/stimuli/emotion/gen_stimulus.wav', x,fs)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Generates stimulus for emotion PICKA test")
parser.add_argument('-s', '--stimulus', help="Stimulus to be generated")
parser.add_argument('-a', '--attenuation', help="Attenuation to be applied")
args = parser.parse_args()
generate(args.stimulus, args.attenuation)
+47
View File
@@ -0,0 +1,47 @@
import numpy as np
import os
import pickle
global groups
groups = []
groupsPkl = os.path.join('../other/', 'groups.pkl')
def rewritePkl(arr, filePath):
with open(filePath, 'w') as f:
pickle.dump(arr, f)
def readPkl(filePath):
with open(filePath, 'r') as f:
loaded = pickle.load(f)
return loaded
def getPkl():
global groups
if os.path.exists(groupsPkl):
groups = readPkl(groupsPkl)
print groups
else:
for _ in range(10):
groups.append("Sam")
groups.append("Laptop")
np.random.shuffle(groups)
# rewritePkl(groups, groupsPkl)
if __name__ == '__main__':
getPkl()
try:
subject = groups.pop()
print "\nParticipant will be starting with: \n\n\t" + subject + "\n\n"
except IndexError:
os.remove(groupsPkl)
print '-- Regenerating file -- '
getPkl()
rewritePkl(groups, groupsPkl)
+176
View File
@@ -0,0 +1,176 @@
#!/usr/bin/env python3
__author__ = "Ashwin Nanjappa"
# GUI viewer to view JSON data as tree.
# Ubuntu packages needed:
# python3-pyqt5
# Std
import argparse
import collections
import json
import sys
# External
from PyQt5 import QtCore
from PyQt5 import QtGui
from PyQt5 import QtWidgets
class TextToTreeItem:
def __init__(self):
self.text_list = []
self.titem_list = []
def append(self, text_list, titem):
for text in text_list:
self.text_list.append(text)
self.titem_list.append(titem)
# Return model indices that match string
def find(self, find_str):
titem_list = []
for i, s in enumerate(self.text_list):
if find_str in s:
titem_list.append(self.titem_list[i])
return titem_list
class JsonView(QtWidgets.QWidget):
def __init__(self, fpath):
super(JsonView, self).__init__()
self.find_box = None
self.tree_widget = None
self.text_to_titem = TextToTreeItem()
self.find_str = ""
self.found_titem_list = []
self.found_idx = 0
jfile = open(fpath)
jdata = json.load(jfile, object_pairs_hook=collections.OrderedDict)
# Find UI
find_layout = self.make_find_ui()
# Tree
self.tree_widget = QtWidgets.QTreeWidget()
self.tree_widget.setHeaderLabels(["Key", "Value"])
self.tree_widget.header().setSectionResizeMode(QtWidgets.QHeaderView.Stretch)
root_item = QtWidgets.QTreeWidgetItem(["Root"])
self.recurse_jdata(jdata, root_item)
self.tree_widget.addTopLevelItem(root_item)
# Add table to layout
layout = QtWidgets.QHBoxLayout()
layout.addWidget(self.tree_widget)
# Group box
gbox = QtWidgets.QGroupBox(fpath)
gbox.setLayout(layout)
layout2 = QtWidgets.QVBoxLayout()
layout2.addLayout(find_layout)
layout2.addWidget(gbox)
self.setLayout(layout2)
def make_find_ui(self):
# Text box
self.find_box = QtWidgets.QLineEdit()
self.find_box.returnPressed.connect(self.find_button_clicked)
# Find Button
find_button = QtWidgets.QPushButton("Find")
find_button.clicked.connect(self.find_button_clicked)
layout = QtWidgets.QHBoxLayout()
layout.addWidget(self.find_box)
layout.addWidget(find_button)
return layout
def find_button_clicked(self):
find_str = self.find_box.text()
# Very common for use to click Find on empty string
if find_str == "":
return
# New search string
if find_str != self.find_str:
self.find_str = find_str
self.found_titem_list = self.text_to_titem.find(self.find_str)
self.found_idx = 0
else:
item_num = len(self.found_titem_list)
self.found_idx = (self.found_idx + 1) % item_num
self.tree_widget.setCurrentItem(self.found_titem_list[self.found_idx])
def recurse_jdata(self, jdata, tree_widget):
if isinstance(jdata, dict):
for key, val in jdata.items():
self.tree_add_row(key, val, tree_widget)
elif isinstance(jdata, list):
for i, val in enumerate(jdata):
key = str(i)
self.tree_add_row(key, val, tree_widget)
else:
print("This should never be reached!")
def tree_add_row(self, key, val, tree_widget):
text_list = []
if isinstance(val, dict) or isinstance(val, list):
text_list.append(key)
row_item = QtWidgets.QTreeWidgetItem([key])
self.recurse_jdata(val, row_item)
else:
text_list.append(key)
text_list.append(str(val))
row_item = QtWidgets.QTreeWidgetItem([key, str(val)])
tree_widget.addChild(row_item)
self.text_to_titem.append(text_list, row_item)
class JsonViewer(QtWidgets.QMainWindow):
def __init__(self):
super(JsonViewer, self).__init__()
fpath = sys.argv[1]
json_view = JsonView(fpath)
self.setCentralWidget(json_view)
self.setWindowTitle("JSON Viewer")
self.show()
def keyPressEvent(self, e):
if e.key() == QtCore.Qt.Key_Escape:
self.close()
def main():
qt_app = QtWidgets.QApplication(sys.argv)
json_viewer = JsonViewer()
sys.exit(qt_app.exec_())
if "__main__" == __name__:
main()
+53
View File
@@ -0,0 +1,53 @@
import scipy.io as spio
import numpy as np
def loadmat(filename):
'''
this function should be called instead of direct spio.loadmat
as it cures the problem of not properly recovering python dictionaries
from mat files. It calls the function check keys to cure all entries
which are still mat-objects
'''
def _check_keys(d):
'''
checks if entries in dictionary are mat-objects. If yes
todict is called to change them to nested dictionaries
'''
for key in d:
if isinstance(d[key], spio.matlab.mio5_params.mat_struct):
d[key] = _todict(d[key])
return d
def _todict(matobj):
'''
A recursive function which constructs from matobjects nested dictionaries
'''
d = {}
for strg in matobj._fieldnames:
elem = matobj.__dict__[strg]
if isinstance(elem, spio.matlab.mio5_params.mat_struct):
d[strg] = _todict(elem)
elif isinstance(elem, np.ndarray):
d[strg] = _tolist(elem)
else:
d[strg] = elem
return d
def _tolist(ndarray):
'''
A recursive function which constructs lists from cellarrays
(which are loaded as numpy ndarrays), recursing into the elements
if they contain matobjects.
'''
elem_list = []
for sub_elem in ndarray:
if isinstance(sub_elem, spio.matlab.mio5_params.mat_struct):
elem_list.append(_todict(sub_elem))
elif isinstance(sub_elem, np.ndarray):
elem_list.append(_tolist(sub_elem))
else:
elem_list.append(sub_elem)
return elem_list
data = spio.loadmat(filename, struct_as_record=False, squeeze_me=True)
return _check_keys(data)
+65
View File
@@ -0,0 +1,65 @@
import scipy.io as spio
import os
import soundfile as sf
import numpy as np
from pyworld import pyworld as pw
from expe_options import expe_options
from expe_build_conditions import expe_build_conditions
from tqdm import tqdm
global f0_arr
f0_arr = np.array([])
def pyworld_process(syll, lang):
'''
Generates the individual stimuli files
'''
global f0_arr
fs = 0
wavIn = os.path.join(
'./stimuli/'+lang.lower(), str(syll) + '.wav')
mat = os.path.join("./stimuli_store/"+lang.lower(), syll + '.pyworld.mat')
# Intialise varibales so they are accessible in the correct scope
if not os.path.exists(mat):
x, fs = sf.read(wavIn)
# --- Using PyWORLD script
_f0, t = pw.dio(x, fs)
f0 = pw.stonemask(x, _f0, t, fs)
sp = pw.cheaptrick(x, f0, t, fs)
ap = pw.d4c(x, f0, t, fs)
freq = np.arange(0, np.size(sp, axis=1),
dtype='float64') / (np.size(sp)) * fs/2
x_rms = np.sqrt(np.mean(x**2))
duration = len(x/fs)
spio.savemat(mat, mdict={'fs': fs, 'f0': f0,
'sp': sp, 'ap': ap,
'x_rms': x_rms,
'frequencies': freq,
'temporal_positions': t,
'duration': duration
})
f0_arr = np.append(f0_arr, f0)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("language", help="Language of files to test")
args = parser.parse_args()
lang = args.language
options = expe_options()
expe_build_conditions(options, lang)
new_files = os.path.join(
'./stimuli/'+lang.lower(), '*')
for f in tqdm(os.listdir('./stimuli/'+lang.lower())):
syll = os.path.splitext(f)[0]
pyworld_process(syll, lang)
print "Avg f0 for all files: " + str(np.mean(f0_arr))
+28
View File
@@ -0,0 +1,28 @@
from expe_build_conditions import expe_build_conditions
from expe_options import expe_options
import os
import soundfile as sf
import numpy as np
from naoqi import ALProxy
from tqdm import tqdm
import random
# aap = ALProxy("ALAudioPlayer", "", 9559)
options = expe_options()
expe_build_conditions(options)
files = os.listdir(options["tmp_path"] + "2")
y = np.array([])
for i in tqdm(range(len(files))):
r = random.randint(0, len(files)-1)
x, fs = sf.read(os.path.join(options["tmp_path"] + "2", str(files[r])))
x = x * np.power(10, -(options["attenuation_dB"]/20.0))
y = np.append(y, x)
sf.write("calibration.wav", np.concatenate(
(np.zeros((1024*3, 2)), np.tile(y, (2, 1)).T, np.zeros((1024*3, 2)))), fs)
# aap.ALAudioPlayer.play()
+231
View File
@@ -0,0 +1,231 @@
import csv
import json
import os
import datetime
import ffmpeg
import re
import subprocess
import time
import multiprocessing
from contextlib import contextmanager
from functools import partial
stream_segments = []
def getGame(angle, game, s, iface, f, subject, upper):
if upper:
game = game.upper()
else:
game = game.capitalize()
try:
if angle in s[iface][game].keys():
for seg, time in s[iface][game][angle]["times"].items():
stream_segments.append(create_streams(
f, time, subject, iface, game, angle, seg))
except KeyError:
pass
def extract_durations(fpath):
timestamps = {}
with open(fpath) as csvfie:
reader = csv.reader(csvfie)
for n, row in enumerate(reader):
if not n:
continue
subject, _, iface, angle, segment, game, start, end, duration = row
if subject not in timestamps:
timestamps[subject] = {}
if iface not in timestamps[subject]:
timestamps[subject][iface] = {}
if game not in timestamps[subject][iface]:
timestamps[subject][iface][game] = {}
if angle not in timestamps[subject][iface][game]:
timestamps[subject][iface][game][angle] = {}
if "times" not in timestamps[subject][iface][game][angle]:
timestamps[subject][iface][game][angle]["times"] = {}
if segment not in timestamps[subject][iface][game][angle]["times"]:
timestamps[subject][iface][game][angle]["times"][segment] = {}
if start not in timestamps[subject][iface][game][angle]["times"][segment]:
timestamps[subject][iface][game][angle]["times"][segment]["start"] = start
if end not in timestamps[subject][iface][game][angle]["times"][segment]:
timestamps[subject][iface][game][angle]["times"][segment]["end"] = end
if duration not in timestamps[subject][iface][game][angle]["times"][segment]:
timestamps[subject][iface][game][angle]["times"][segment]["duration"] = duration
os.chdir("/Volumes/LaCie/Videos to analyse/Separate videos/to split/")
cwd = os.getcwd()
files = os.listdir(cwd)
subject = ''
for f in files:
s = None
for subject in timestamps:
# with poolcontext as pool:
stream = ""
# o = subprocess.check_output(
# ["ffprobe", "-hide_banner", f], stderr=subprocess.STDOUT)
# mediaprobe_re = re.compile(
# r"Duration:\s+(?P<dur>(?:(?:\d:?)+[.]?\d*)|N/A)(?:.+start:\s+(?P<start>\d+[.]\d+))?.+bitrate:\s+(?P<bitrate>(?:\d+\s*..[/]s)|N/A)")
# probe = mediaprobe_re.findall(o.decode("utf-8"))
# duration = datetime.datetime.strptime(probe[0][0], "%H:%M:%S.%f")
# d_hour, d_min, d_sec = duration.hour, duration.minute, duration.second
if subject in f:
if not s:
for k, v in timestamps.items():
if k in f:
subject = k
s = timestamps[k]
break
if "lap" in f.lower():
if "front" in f.lower():
getGame("front", "crm", s, "lap", f, subject, True)
getGame("front", "emotion", s,
"lap", f, subject, False)
getGame("front", "jnd", s, "lap", f, subject, True)
getGame("front", "gender", s,
"lap", f, subject, False)
# a = 'front'
# game = "jnd"
# if a in s[iface][game.upper()].keys():
# for seg, time in s[iface][game.upper()][a]["times"].items():
# stream_segments.append(create_streams(
# f, time, subject, iface, game, a, seg))
# game = "gender"
# if a in s[iface][game.capitalize()].keys():
# for seg, time in s[iface][game.capitalize()][a]["times"].items():
# stream_segments.append(create_streams(
# f, time, subject, iface, game, a, seg))
if "side" in f.lower():
getGame("side", "crm", s, "lap", f, subject, True)
getGame("side", "emotion", s,
"lap", f, subject, False)
getGame("side", "jnd", s, "lap", f, subject, True)
getGame("side", "gender", s,
"lap", f, subject, False)
# a = 'side'
# game = "jnd"
# if a in s[iface][game.upper()].keys():
# for seg, time in s[iface][game.upper()][a]["times"].items():
# stream_segments.append(create_streams(
# f, time, subject, iface, game, a, seg))
# game = "gender"
# if a in s[iface][game.capitalize()].keys():
# for seg, time in s[iface][game.capitalize()][a]["times"].items():
# stream_segments.append(create_streams(
# f, time, subject, iface, game, a, seg))
elif "sam" in f.lower():
if "front" in f.lower():
getGame("front", "crm", s, "sam", f, subject, True)
getGame("front", "emotion", s, "sam", f, subject, False)
getGame("front", "jnd", s, "sam", f, subject, True)
getGame("front", "gender", s, "sam", f, subject, False)
# a = 'front'
# game = "jnd"
# if a in s[iface][game.upper()].keys():
# for seg, time in s[iface][game.upper()][a]["times"].items():
# stream_segments.append(create_streams(
# f, time, subject, iface, game, a, seg))
# game = "gender"
# if a in s[iface][game.capitalize()].keys():
# for seg, time in s[iface][game.capitalize()][a]["times"].items():
# stream_segments.append(create_streams(
# f, time, subject, iface, game, a, seg))
# try:
# game = "PICKA"
# for seg, time in s[iface][game][a]["times"].items():
# stream_segments.append(create_streams(
# f, time, subject, iface, game, a, seg))
# except KeyError:
# pass
if "side" in f.lower():
getGame("side", "crm", s, "sam", f, subject, True)
getGame("side", "emotion", s,
"sam", f, subject, False)
getGame("side", "jnd", s, "sam", f, subject, True)
getGame("side", "gender", s,
"sam", f, subject, False)
# a = 'side'
# game = "jnd"
# if a in s[iface][game.upper()].keys():
# for seg, time in s[iface][game.upper()][a]["times"].items():
# stream_segments.append(create_streams(
# f, time, subject, iface, game, a, seg))
# game = "gender"
# if a in s[iface][game.capitalize()].keys():
# for seg, time in s[iface][game.capitalize()][a]["times"].items():
# stream_segments.append(create_streams(
# f, time, subject, iface, game, a, seg))
# try:
# game = "PICKA"
# for seg, time in s[iface][game][a]["times"].items():
# stream_segments.append(create_streams(
# f, time, subject, iface, game, a, seg))
# except KeyError:
# pass
return stream_segments
@contextmanager
def poolcontext(*args, **kwargs):
pool = multiprocessing.Pool(*args, **kwargs)
yield pool
pool.terminate()
def run_ffmpeg(stream_segment, dirpath):
save_path = "/Volumes/LaCie/Videos to analyse/Separate videos/split/" + \
dirpath + "/extracted/"
stream = stream_segment[0]
fname = save_path + stream_segment[1] + ".mp4"
if not os.path.exists(fname):
stream = ffmpeg.output(stream, fname, **{"async": 1})
# stream = ffmpeg.overwrite_output(stream)
print(stream)
ffmpeg.run(stream)
def create_fname(subject, iface, game, angle, segment):
return "{}-{}-{}-{}-{}".format(subject, iface, angle, game, segment)
def create_streams(filename, times, subject, iface, game, angle, segment):
s = ffmpeg.input(filename, ss=times["start"], to=times["end"])
f = create_fname(subject, iface.capitalize(), game, angle, segment)
return s, f
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
"-t", "--tstamps", default="/Users/lukemeyer/Desktop/RUG/PhD/Results/Experiment_1/Video Coding/timestamps2.csv")
parser.add_argument("-d", "--dirpath", required=True)
args = parser.parse_args()
stream_segments = extract_durations(args.tstamps)
with poolcontext() as pool:
for x in pool.imap(partial(run_ffmpeg, dirpath=args.dirpath), stream_segments, chunksize=1):
time.sleep(1)
# print(json.dumps(timestamps, sort_keys=True, indent=4))
+12
View File
@@ -0,0 +1,12 @@
time_taken = 0
experiment_begin = 1
expe_exit = None
task_id = None
def init():
global time_taken
global experiment_begin
global expe_exit
global task_id
+39
View File
@@ -0,0 +1,39 @@
Subject,Experiment,Interface,Angle,Segment,Game,Start,End,Duration,,
NHA030,1,lap,side,train,JND,,,01:25,,
NHA030,1,lap,side,trial-1,JND,,,06:10,,
NHA030,1,lap,side,trial-2,JND,,,04:14,,
NHA030,1,lap,side,trial-3,JND,,,05:47,,
NHA030,1,lap,side,trial-4,JND,,,06:44,,
NHA030,1,lap,side,train,Gender,,,00:40,,
NHA030,1,lap,side,test,Gender,,,03:06,,
NHA030,1,lap,front,train,JND,00:00:10,00:01:35,01:25,,
NHA030,1,lap,front,trial-1,JND,00:01:57,00:08:07,06:10,,
NHA030,1,lap,front,trial-2,JND,00:08:08,00:12:22,04:14,,
NHA030,1,lap,front,trial-3,JND,00:13:04,00:18:51,05:47,,
NHA030,1,lap,front,trial-4,JND,00:18:51,00:25:35,06:44,,
NHA030,1,lap,front,train,Gender,00:27:03,00:27:43,00:40,,
NHA030,1,lap,front,test,Gender,00:28:10,00:31:16,03:06,,
NHA030,1,sam,side,intro,JND,,,0,,
NHA030,1,sam,side,train,JND,,,0,,
NHA030,1,sam,side,trial-1,JND,,,0,,
NHA030,1,sam,side,break-1,JND,,,0,,
NHA030,1,sam,side,trial-2,JND,,,0,,
NHA030,1,sam,side,break-2,JND,,,0,,
NHA030,1,sam,side,trial-3,JND,,,0,,
NHA030,1,sam,side,break-3,JND,,,0,,
NHA030,1,sam,side,trial-4,JND,,,0,,
NHA030,1,sam,side,intro,Gender,,,0,,
NHA030,1,sam,side,train,Gender,,,0,,
NHA030,1,sam,side,test,Gender,,,0,,
NHA030,1,sam,front,intro,JND,00:02:14,00:03:37,01:23,,
NHA030,1,sam,front,train,JND,00:03:37,00:06:10,02:33,,
NHA030,1,sam,front,trial-1,JND,00:07:22,00:16:00,08:38,,
NHA030,1,sam,front,break-1,JND,00:16:00,00:16:18,00:18,,
NHA030,1,sam,front,trial-2,JND,00:16:18,00:22:15,05:57,,
NHA030,1,sam,front,break-2,JND,00:22:15,00:22:24,00:09,,
NHA030,1,sam,front,trial-3,JND,00:22:24,00:28:09,05:45,,
NHA030,1,sam,front,break-3,JND,00:28:09,00:28:17,00:08,,
NHA030,1,sam,front,trial-4,JND,00:28:17,00:34:06,05:49,,
NHA030,1,sam,front,intro,Gender,00:36:08,00:36:48,00:40,,
NHA030,1,sam,front,train,Gender,00:36:48,00:38:08,01:20,,
NHA030,1,sam,front,test,Gender,00:38:45,00:44:46,06:01,,
1 Subject Experiment Interface Angle Segment Game Start End Duration
2 NHA030 1 lap side train JND 01:25
3 NHA030 1 lap side trial-1 JND 06:10
4 NHA030 1 lap side trial-2 JND 04:14
5 NHA030 1 lap side trial-3 JND 05:47
6 NHA030 1 lap side trial-4 JND 06:44
7 NHA030 1 lap side train Gender 00:40
8 NHA030 1 lap side test Gender 03:06
9 NHA030 1 lap front train JND 00:00:10 00:01:35 01:25
10 NHA030 1 lap front trial-1 JND 00:01:57 00:08:07 06:10
11 NHA030 1 lap front trial-2 JND 00:08:08 00:12:22 04:14
12 NHA030 1 lap front trial-3 JND 00:13:04 00:18:51 05:47
13 NHA030 1 lap front trial-4 JND 00:18:51 00:25:35 06:44
14 NHA030 1 lap front train Gender 00:27:03 00:27:43 00:40
15 NHA030 1 lap front test Gender 00:28:10 00:31:16 03:06
16 NHA030 1 sam side intro JND 0
17 NHA030 1 sam side train JND 0
18 NHA030 1 sam side trial-1 JND 0
19 NHA030 1 sam side break-1 JND 0
20 NHA030 1 sam side trial-2 JND 0
21 NHA030 1 sam side break-2 JND 0
22 NHA030 1 sam side trial-3 JND 0
23 NHA030 1 sam side break-3 JND 0
24 NHA030 1 sam side trial-4 JND 0
25 NHA030 1 sam side intro Gender 0
26 NHA030 1 sam side train Gender 0
27 NHA030 1 sam side test Gender 0
28 NHA030 1 sam front intro JND 00:02:14 00:03:37 01:23
29 NHA030 1 sam front train JND 00:03:37 00:06:10 02:33
30 NHA030 1 sam front trial-1 JND 00:07:22 00:16:00 08:38
31 NHA030 1 sam front break-1 JND 00:16:00 00:16:18 00:18
32 NHA030 1 sam front trial-2 JND 00:16:18 00:22:15 05:57
33 NHA030 1 sam front break-2 JND 00:22:15 00:22:24 00:09
34 NHA030 1 sam front trial-3 JND 00:22:24 00:28:09 05:45
35 NHA030 1 sam front break-3 JND 00:28:09 00:28:17 00:08
36 NHA030 1 sam front trial-4 JND 00:28:17 00:34:06 05:49
37 NHA030 1 sam front intro Gender 00:36:08 00:36:48 00:40
38 NHA030 1 sam front train Gender 00:36:48 00:38:08 01:20
39 NHA030 1 sam front test Gender 00:38:45 00:44:46 06:01
+420
View File
@@ -0,0 +1,420 @@
Subject,Experiment,Interface,Angle,Segment,Game,Start,End,Duration,,
NHA026,1,lap,side,train,JND,00:00:00,00:00:53,00:53,,
NHA026,1,lap,side,trial-1,JND,00:01:05,00:06:03,04:58,,
NHA026,1,lap,side,trial-2,JND,00:06:03,00:11:53,05:50,,
NHA026,1,lap,side,trial-3,JND,00:11:53,00:16:20,04:27,,
NHA026,1,lap,side,trial-4,JND,00:16:20,00:20:40,04:20,,
NHA026,1,lap,side,train,Gender,00:21:51,00:22:37,00:46,,
NHA026,1,lap,side,test,Gender,00:23:00,00:25:50,02:50,,
NHA026,1,lap,front,train,JND,00:00:00,00:01:03,01:03,,
NHA026,1,lap,front,trial-1,JND,00:01:15,00:06:13,04:58,,
NHA026,1,lap,front,trial-2,JND,00:06:13,00:12:03,05:50,,
NHA026,1,lap,front,trial-3,JND,00:12:03,00:16:30,04:27,,
NHA026,1,lap,front,trial-4,JND,00:16:30,00:20:50,04:20,,
NHA026,1,lap,front,train,Gender,00:22:01,00:22:47,00:46,,
NHA026,1,lap,front,test,Gender,00:23:10,00:26:00,02:50,,
NHA026,1,sam,side,intro,JND,00:00:57,00:02:16,01:19,,
NHA026,1,sam,side,train,JND,00:02:16,00:04:21,02:05,,
NHA026,1,sam,side,trial-1,JND,00:05:38,00:13:19,07:41,,
NHA026,1,sam,side,break-1,JND,00:13:19,00:13:30,00:11,,
NHA026,1,sam,side,trial-2,JND,00:13:30,00:23:37,10:07,,
NHA026,1,sam,side,break-2,JND,00:23:37,00:23:52,00:15,,
NHA026,1,sam,side,trial-3,JND,00:23:52,00:29:15,05:23,,
NHA026,1,sam,side,break-3,JND,00:29:15,00:29:37,00:22,,
NHA026,1,sam,side,trial-4,JND,00:29:37,00:37:10,07:33,,
NHA026,1,sam,side,intro,Gender,00:39:10,00:40:01,00:51,,
NHA026,1,sam,side,train,Gender,00:40:01,00:41:18,01:17,,
NHA026,1,sam,side,test,Gender,00:41:43,00:49:14,07:31,,
NHA026,1,sam,front,intro,JND,00:01:06,00:02:27,01:21,,
NHA026,1,sam,front,train,JND,00:02:27,00:04:32,02:05,,
NHA026,1,sam,front,trial-1,JND,00:05:49,00:13:30,07:41,,
NHA026,1,sam,front,break-1,JND,00:13:30,00:13:41,00:11,,
NHA026,1,sam,front,trial-2,JND,00:13:41,00:23:48,10:07,,
NHA026,1,sam,front,break-2,JND,00:23:48,00:24:04,00:16,,
NHA026,1,sam,front,trial-3,JND,00:24:04,00:29:26,05:22,,
NHA026,1,sam,front,break-3,JND,00:29:26,00:29:48,00:22,,
NHA026,1,sam,front,trial-4,JND,00:29:48,00:37:21,07:33,,
NHA026,1,sam,front,intro,Gender,00:39:21,00:40:12,00:51,,
NHA026,1,sam,front,train,Gender,00:41:29,00:41:54,00:25,,
NHA026,1,sam,front,test,Gender,00:49:54,00:49:25,-00:29,,
NHA027,1,lap,side,train,JND,00:00:42,00:01:41,00:59,,
NHA027,1,lap,side,trial-1,JND,00:02:02,00:08:23,06:21,,
NHA027,1,lap,side,trial-2,JND,00:08:23,00:12:46,04:23,,
NHA027,1,lap,side,trial-3,JND,00:15:03,00:19:04,04:01,,
NHA027,1,lap,side,trial-4,JND,00:23:44,00:27:49,04:05,,
NHA027,1,lap,side,train,Gender,00:28:49,00:29:30,00:41,,
NHA027,1,lap,side,test,Gender,00:29:45,00:33:10,03:25,,
NHA027,1,lap,front,train,JND,00:00:45,00:01:44,00:59,,
NHA027,1,lap,front,trial-1,JND,00:02:05,00:08:26,06:21,,
NHA027,1,lap,front,trial-2,JND,00:08:26,00:12:49,04:23,,
NHA027,1,lap,front,trial-3,JND,00:15:06,00:19:07,04:01,,
NHA027,1,lap,front,trial-4,JND,00:23:47,00:27:52,04:05,,
NHA027,1,lap,front,train,Gender,00:28:52,00:29:33,00:41,,
NHA027,1,lap,front,test,Gender,00:29:48,00:33:13,03:25,,
NHA027,1,sam,side,intro,JND,00:00:00,00:01:49,01:49,,
NHA027,1,sam,side,train,JND,00:01:49,00:03:04,01:15,,
NHA027,1,sam,side,trial-1,JND,00:03:24,00:11:02,07:38,,
NHA027,1,sam,side,break-1,JND,00:11:02,00:12:22,01:20,,
NHA027,1,sam,side,trial-2,JND,00:12:22,00:17:32,05:10,,
NHA027,1,sam,side,break-2,JND,00:17:32,00:18:19,00:47,,
NHA027,1,sam,side,trial-3,JND,00:18:19,00:23:37,05:18,,
NHA027,1,sam,side,break-3,JND,00:23:37,00:23:50,00:13,,
NHA027,1,sam,side,trial-4,JND,00:23:50,00:31:26,07:36,,
NHA027,1,sam,side,intro,Gender,00:33:18,00:34:03,00:45,,
NHA027,1,sam,side,train,Gender,00:34:03,00:35:20,01:17,,
NHA027,1,sam,side,test,Gender,00:35:52,00:42:17,06:25,,
NHA027,1,sam,front,intro,JND,00:00:00,00:01:43,01:43,,
NHA027,1,sam,front,train,JND,00:01:43,00:02:58,01:15,,
NHA027,1,sam,front,trial-1,JND,00:03:16,00:10:56,07:40,,
NHA027,1,sam,front,break-1,JND,00:10:56,00:12:16,01:20,,
NHA027,1,sam,front,trial-2,JND,00:12:16,00:17:26,05:10,,
NHA027,1,sam,front,break-2,JND,00:17:26,00:18:13,00:47,,
NHA027,1,sam,front,trial-3,JND,00:18:13,00:23:31,05:18,,
NHA027,1,sam,front,break-3,JND,00:23:31,00:23:44,00:13,,
NHA027,1,sam,front,trial-4,JND,00:23:44,00:31:20,07:36,,
NHA027,1,sam,front,intro,Gender,00:33:12,00:33:57,00:45,,
NHA027,1,sam,front,train,Gender,00:33:57,00:35:14,01:17,,
NHA027,1,sam,front,test,Gender,00:35:46,00:42:11,06:25,,
NHA029,1,lap,side,train,JND,00:00:38,00:01:45,01:12,,
NHA029,1,lap,side,trial-1,JND,00:02:49,00:08:11,05:07,,
NHA029,1,lap,side,trial-2,JND,00:08:11,00:12:31,04:21,,
NHA029,1,lap,side,trial-3,JND,00:12:31,00:17:49,05:18,,
NHA029,1,lap,side,trial-4,JND,00:17:49,00:22:23,04:34,,
NHA029,1,lap,side,train,Gender,00:23:49,00:24:32,00:39,,
NHA029,1,lap,side,test,Gender,00:24:59,00:28:38,03:34,,
NHA029,1,lap,front,train,JND,00:00:30,00:01:42,01:12,,
NHA029,1,lap,front,trial-1,JND,00:02:53,00:08:00,05:07,,
NHA029,1,lap,front,trial-2,JND,00:08:00,00:12:21,04:21,,
NHA029,1,lap,front,trial-3,JND,00:12:21,00:17:39,05:18,,
NHA029,1,lap,front,trial-4,JND,00:17:39,00:22:13,04:34,,
NHA029,1,lap,front,train,Gender,00:23:44,00:24:23,00:39,,
NHA029,1,lap,front,test,Gender,00:24:59,00:28:33,03:34,,
NHA029,1,sam,side,intro,JND,00:00:00,00:01:01,01:01,,
NHA029,1,sam,side,train,JND,00:01:01,00:03:08,02:07,,
NHA029,1,sam,side,trial-1,JND,00:04:03,00:10:53,06:50,,
NHA029,1,sam,side,break-1,JND,00:10:53,00:11:58,01:05,,
NHA029,1,sam,side,trial-2,JND,00:11:58,00:17:04,05:06,,
NHA029,1,sam,side,break-2,JND,00:17:04,00:17:14,00:10,,
NHA029,1,sam,side,trial-3,JND,00:17:14,00:24:24,07:10,,
NHA029,1,sam,side,break-3,JND,00:24:24,00:24:32,00:08,,
NHA029,1,sam,side,trial-4,JND,00:24:32,00:29:52,05:20,,
NHA029,1,sam,side,intro,Gender,00:32:02,00:32:39,00:37,,
NHA029,1,sam,side,train,Gender,00:32:39,00:34:03,01:24,,
NHA029,1,sam,side,test,Gender,00:34:30,00:40:54,06:24,,
NHA029,1,sam,front,intro,JND,00:00:00,00:01:05,01:05,,
NHA029,1,sam,front,train,JND,00:01:05,00:03:12,02:07,,
NHA029,1,sam,front,trial-1,JND,00:04:10,00:10:55,06:45,,
NHA029,1,sam,front,break-1,JND,00:10:55,00:12:00,01:05,,
NHA029,1,sam,front,trial-2,JND,00:12:00,00:17:03,05:03,,
NHA029,1,sam,front,break-2,JND,00:17:03,00:17:16,00:13,,
NHA029,1,sam,front,trial-3,JND,00:17:16,00:24:26,07:10,,
NHA029,1,sam,front,break-3,JND,00:24:26,00:24:35,00:09,,
NHA029,1,sam,front,trial-4,JND,00:24:35,00:29:56,05:21,,
NHA029,1,sam,front,intro,Gender,00:32:02,00:32:42,00:40,,
NHA029,1,sam,front,train,Gender,00:32:42,00:34:04,01:22,,
NHA029,1,sam,front,test,Gender,00:34:31,00:40:57,06:26,,
NHA030,1,lap,side,train,JND,,,01:25,,
NHA030,1,lap,side,trial-1,JND,,,06:10,,
NHA030,1,lap,side,trial-2,JND,,,04:14,,
NHA030,1,lap,side,trial-3,JND,,,05:47,,
NHA030,1,lap,side,trial-4,JND,,,06:44,,
NHA030,1,lap,side,train,Gender,,,00:40,,
NHA030,1,lap,side,test,Gender,,,03:06,,
NHA030,1,lap,front,train,JND,00:00:10,00:01:35,01:25,,
NHA030,1,lap,front,trial-1,JND,00:01:57,00:08:07,06:10,,
NHA030,1,lap,front,trial-2,JND,00:08:08,00:12:22,04:14,,
NHA030,1,lap,front,trial-3,JND,00:13:04,00:18:51,05:47,,
NHA030,1,lap,front,trial-4,JND,00:18:51,00:25:35,06:44,,
NHA030,1,lap,front,train,Gender,00:27:03,00:27:43,00:40,,
NHA030,1,lap,front,test,Gender,00:28:10,00:31:16,03:06,,
NHA030,1,sam,side,intro,JND,,,0,,
NHA030,1,sam,side,train,JND,,,0,,
NHA030,1,sam,side,trial-1,JND,,,0,,
NHA030,1,sam,side,break-1,JND,,,0,,
NHA030,1,sam,side,trial-2,JND,,,0,,
NHA030,1,sam,side,break-2,JND,,,0,,
NHA030,1,sam,side,trial-3,JND,,,0,,
NHA030,1,sam,side,break-3,JND,,,0,,
NHA030,1,sam,side,trial-4,JND,,,0,,
NHA030,1,sam,side,intro,Gender,,,0,,
NHA030,1,sam,side,train,Gender,,,0,,
NHA030,1,sam,side,test,Gender,,,0,,
NHA030,1,sam,front,intro,JND,00:02:14,00:03:37,01:23,,
NHA030,1,sam,front,train,JND,00:03:37,00:06:10,02:33,,
NHA030,1,sam,front,trial-1,JND,00:07:22,00:16:00,08:38,,
NHA030,1,sam,front,break-1,JND,00:16:00,00:16:18,00:18,,
NHA030,1,sam,front,trial-2,JND,00:16:18,00:22:15,05:57,,
NHA030,1,sam,front,break-2,JND,00:22:15,00:22:24,00:09,,
NHA030,1,sam,front,trial-3,JND,00:22:24,00:28:09,05:45,,
NHA030,1,sam,front,break-3,JND,00:28:09,00:28:17,00:08,,
NHA030,1,sam,front,trial-4,JND,00:28:17,00:34:06,05:49,,
NHA030,1,sam,front,intro,Gender,00:36:08,00:36:48,00:40,,
NHA030,1,sam,front,train,Gender,00:36:48,00:38:08,01:20,,
NHA030,1,sam,front,test,Gender,00:38:45,00:44:46,06:01,,
NHA033,1,lap,side,train,JND,,,01:04,,
NHA033,1,lap,side,trial-1,JND,,,04:20,,
NHA033,1,lap,side,trial-2,JND,,,06:56,,
NHA033,1,lap,side,trial-3,JND,,,04:47,,
NHA033,1,lap,side,trial-4,JND,,,07:17,,
NHA033,1,lap,side,train,Gender,,,00:35,,
NHA033,1,lap,side,test,Gender,,,03:43,,
NHA033,1,lap,front,train,JND,00:00:13,00:01:17,01:04,,
NHA033,1,lap,front,trial-1,JND,00:01:53,00:06:13,04:20,,
NHA033,1,lap,front,trial-2,JND,00:06:13,00:13:09,06:56,,
NHA033,1,lap,front,trial-3,JND,00:13:09,00:17:56,04:47,,
NHA033,1,lap,front,trial-4,JND,00:17:56,00:25:13,07:17,,
NHA033,1,lap,front,train,Gender,00:26:57,00:27:32,00:35,,
NHA033,1,lap,front,test,Gender,00:28:13,00:31:56,03:43,,
NHA033,1,sam,side,intro,JND,,,0,,
NHA033,1,sam,side,train,JND,,,0,,
NHA033,1,sam,side,trial-1,JND,,,0,,
NHA033,1,sam,side,break-1,JND,,,0,,
NHA033,1,sam,side,trial-2,JND,,,0,,
NHA033,1,sam,side,break-2,JND,,,0,,
NHA033,1,sam,side,trial-3,JND,,,0,,
NHA033,1,sam,side,break-3,JND,,,0,,
NHA033,1,sam,side,trial-4,JND,,,0,,
NHA033,1,sam,side,intro,Gender,,,0,,
NHA033,1,sam,side,train,Gender,,,0,,
NHA033,1,sam,side,test,Gender,,,0,,
NHA033,1,sam,front,intro,JND,00:00:00,00:01:09,01:09,,
NHA033,1,sam,front,train,JND,00:01:09,00:03:40,02:31,,
NHA033,1,sam,front,trial-1,JND,00:06:40,00:15:49,09:09,,
NHA033,1,sam,front,break-1,JND,00:15:49,00:15:59,00:10,,
NHA033,1,sam,front,trial-2,JND,00:15:59,00:20:47,04:48,,
NHA033,1,sam,front,break-2,JND,00:20:47,00:21:52,01:05,,
NHA033,1,sam,front,trial-3,JND,00:21:52,00:29:33,07:41,,
NHA033,1,sam,front,break-3,JND,00:29:33,00:30:50,01:17,,
NHA033,1,sam,front,trial-4,JND,00:30:50,00:37:57,07:07,,
NHA033,1,sam,front,intro,Gender,00:40:16,00:40:55,00:39,,
NHA033,1,sam,front,train,Gender,00:40:55,00:42:18,01:23,,
NHA033,1,sam,front,test,Gender,00:42:59,00:49:36,06:37,,
NHA034,1,lap,side,train,JND,,,00:58,,
NHA034,1,lap,side,trial-1,JND,,,03:37,,
NHA034,1,lap,side,trial-2,JND,,,04:53,,
NHA034,1,lap,side,trial-3,JND,,,04:17,,
NHA034,1,lap,side,trial-4,JND,,,05:35,,
NHA034,1,lap,side,train,Gender,,,00:40,,
NHA034,1,lap,side,test,Gender,,,03:04,,
NHA034,1,lap,front,train,JND,00:00:07,00:01:05,00:58,,
NHA034,1,lap,front,trial-1,JND,00:01:22,00:04:59,03:37,,
NHA034,1,lap,front,trial-2,JND,00:04:59,00:09:52,04:53,,
NHA034,1,lap,front,trial-3,JND,00:09:52,00:14:09,04:17,,
NHA034,1,lap,front,trial-4,JND,00:14:09,00:19:44,05:35,,
NHA034,1,lap,front,train,Gender,00:21:12,00:21:52,00:40,,
NHA034,1,lap,front,test,Gender,00:22:12,00:25:16,03:04,,
NHA034,1,sam,side,intro,JND,00:01:38,00:02:44,01:06,,
NHA034,1,sam,side,train,JND,00:02:44,00:05:16,02:32,,
NHA034,1,sam,side,trial-1,JND,00:07:25,00:14:36,07:11,,
NHA034,1,sam,side,break-1,JND,00:14:36,00:14:46,00:10,,
NHA034,1,sam,side,trial-2,JND,00:14:46,00:22:14,07:28,,
NHA034,1,sam,side,break-2,JND,00:22:14,00:22:23,00:09,,
NHA034,1,sam,side,trial-3,JND,00:22:23,00:30:01,07:38,,
NHA034,1,sam,side,break-3,JND,00:30:01,00:30:30,00:29,,
NHA034,1,sam,side,trial-4,JND,00:30:30,00:38:02,07:32,,
NHA034,1,sam,side,intro,Gender,00:39:41,00:40:20,00:39,,
NHA034,1,sam,side,train,Gender,00:40:20,00:41:37,01:17,,
NHA034,1,sam,side,test,Gender,00:42:37,00:50:31,07:54,,
NHA034,1_2,sam,side,end,PICKA,00:50:31,00:50:49,00:18,,
NHA034,1,sam,front,intro,JND,,,0,,
NHA034,1,sam,front,train,JND,,,0,,
NHA034,1,sam,front,trial-1,JND,,,0,,
NHA034,1,sam,front,break-1,JND,,,0,,
NHA034,1,sam,front,trial-2,JND,,,0,,
NHA034,1,sam,front,break-2,JND,,,0,,
NHA034,1,sam,front,trial-3,JND,,,0,,
NHA034,1,sam,front,break-3,JND,,,0,,
NHA034,1,sam,front,trial-4,JND,,,0,,
NHA034,1,sam,front,intro,Gender,,,0,,
NHA034,1,sam,front,train,Gender,,,0,,
NHA034,1,sam,front,test,Gender,,,0,,
NHA035,1,lap,side,train,JND,,,00:23,,
NHA035,1,lap,side,trial-1,JND,,,04:05,,
NHA035,1,lap,side,trial-2,JND,,,04:32,,
NHA035,1,lap,side,trial-3,JND,,,03:19,,
NHA035,1,lap,side,trial-4,JND,,,16:27,,
NHA035,1,lap,side,train,Gender,,,00:41,,
NHA035,1,lap,side,test,Gender,,,02:55,,
NHA035,1,lap,front,train,JND,00:00:09,00:00:32,00:23,,
NHA035,1,lap,front,trial-1,JND,00:01:10,00:05:15,04:05,,
NHA035,1,lap,front,trial-2,JND,00:05:15,00:09:47,04:32,,
NHA035,1,lap,front,trial-3,JND,00:09:47,00:13:06,03:19,,
NHA035,1,lap,front,trial-4,JND,00:13:06,00:29:33,16:27,,
NHA035,1,lap,front,train,Gender,00:21:06,00:21:47,00:41,,
NHA035,1,lap,front,test,Gender,00:22:17,00:25:12,02:55,,
NHA035,1,sam,side,train,JND,00:00:20,00:02:20,02:00,,
NHA035,1,sam,side,trial-1,JND,00:04:01,00:10:16,06:15,,
NHA035,1,sam,side,break-1,JND,00:10:16,00:10:26,00:10,,
NHA035,1,sam,side,trial-2,JND,00:10:26,00:15:39,05:13,,
NHA035,1,sam,side,break-2,JND,00:15:39,00:16:37,00:58,,
NHA035,1,sam,side,trial-3,JND,00:16:37,00:26:12,09:35,,
NHA035,1,sam,side,break-3,JND,00:26:12,00:26:21,00:09,,
NHA035,1,sam,side,trial-4,JND,00:26:21,00:33:18,06:57,,
NHA035,1,sam,side,intro,Gender,00:35:17,00:35:57,00:40,,
NHA035,1,sam,side,train,Gender,00:35:57,00:37:20,01:23,,
NHA035,1,sam,side,test,Gender,00:37:48,00:43:59,06:11,,
NHA035,1,sam,front,intro,JND,,,0,,
NHA035,1,sam,front,train,JND,,,0,,
NHA035,1,sam,front,trial-1,JND,,,0,,
NHA035,1,sam,front,break-1,JND,,,0,,
NHA035,1,sam,front,trial-2,JND,,,0,,
NHA035,1,sam,front,break-2,JND,,,0,,
NHA035,1,sam,front,trial-3,JND,,,0,,
NHA035,1,sam,front,break-3,JND,,,0,,
NHA035,1,sam,front,trial-4,JND,,,0,,
NHA035,1,sam,front,intro,Gender,,,0,,
NHA035,1,sam,front,train,Gender,,,0,,
NHA035,1,sam,front,test,Gender,,,0,,
NHA036,1,lap,side,train,JND,,,01:01,,
NHA036,1,lap,side,trial-1,JND,,,07:22,,
NHA036,1,lap,side,trial-2,JND,,,04:40,,
NHA036,1,lap,side,trial-3,JND,,,05:43,,
NHA036,1,lap,side,trial-4,JND,,,04:09,,
NHA036,1,lap,side,train,Gender,,,00:44,,
NHA036,1,lap,side,test,Gender,,,03:55,,
NHA036,1,lap,front,train,JND,00:00:07,00:01:08,01:01,,
NHA036,1,lap,front,trial-1,JND,00:01:25,00:08:47,07:22,,
NHA036,1,lap,front,trial-2,JND,00:08:59,00:13:39,04:40,,
NHA036,1,lap,front,trial-3,JND,00:13:39,00:19:22,05:43,,
NHA036,1,lap,front,trial-4,JND,00:19:22,00:23:31,04:09,,
NHA036,1,lap,front,train,Gender,00:25:05,00:25:49,00:44,,
NHA036,1,lap,front,test,Gender,00:26:43,00:30:38,03:55,,
NHA036,1,sam,side,intro,JND,00:01:54,00:03:06,01:12,,
NHA036,1,sam,side,train,JND,00:03:06,00:05:15,02:09,,
NHA036,1,sam,side,trial-1,JND,00:05:47,00:14:04,08:17,,
NHA036,1,sam,side,break-1,JND,00:14:04,00:15:01,00:57,,
NHA036,1,sam,side,trial-2,JND,00:15:01,00:23:22,08:21,,
NHA036,1,sam,side,break-2,JND,00:23:22,00:23:50,00:28,,
NHA036,1,sam,side,trial-3,JND,00:23:50,00:31:09,07:19,,
NHA036,1,sam,side,break-3,JND,00:31:09,00:32:16,01:07,,
NHA036,1,sam,side,trial-4,JND,00:32:16,00:37:40,05:24,,
NHA036,1,sam,side,intro,Gender,00:42:18,00:42:54,00:36,,
NHA036,1,sam,side,train,Gender,00:42:54,00:44:16,01:22,,
NHA036,1,sam,side,test,Gender,00:45:00,00:53:15,08:15,,
NHA036,1_2,sam,side,end,PICKA,00:53:15,00:53:32,00:17,,
NHA036,1,sam,front,intro,JND,,,0,,
NHA036,1,sam,front,train,JND,,,0,,
NHA036,1,sam,front,trial-1,JND,,,0,,
NHA036,1,sam,front,break-1,JND,,,0,,
NHA036,1,sam,front,trial-2,JND,,,0,,
NHA036,1,sam,front,break-2,JND,,,0,,
NHA036,1,sam,front,trial-3,JND,,,0,,
NHA036,1,sam,front,break-3,JND,,,0,,
NHA036,1,sam,front,trial-4,JND,,,0,,
NHA036,1,sam,front,intro,Gender,,,0,,
NHA036,1,sam,front,train,Gender,,,0,,
NHA036,1,sam,front,test,Gender,00:42:59,00:49:36,06:37,,
NHA038,1,lap,side,train,JND,,,01:18,,
NHA038,1,lap,side,trial-1,JND,,,05:20,,
NHA038,1,lap,side,trial-2,JND,,,06:33,,
NHA038,1,lap,side,trial-3,JND,,,05:43,,
NHA038,1,lap,side,trial-4,JND,,,05:34,,
NHA038,1,lap,side,train,Gender,,,00:46,,
NHA038,1,lap,side,test,Gender,,,03:45,,
NHA038,1,lap,front,train,JND,00:01:38,00:02:56,01:18,,
NHA038,1,lap,front,trial-1,JND,00:04:06,00:09:26,05:20,,
NHA038,1,lap,front,trial-2,JND,00:09:42,00:16:15,06:33,,
NHA038,1,lap,front,trial-3,JND,00:16:38,00:22:21,05:43,,
NHA038,1,lap,front,trial-4,JND,00:22:30,00:28:04,05:34,,
NHA038,1,lap,front,train,Gender,00:30:03,00:30:49,00:46,,
NHA038,1,lap,front,test,Gender,00:31:34,00:35:19,03:45,,
NHA038,1,sam,side,intro,JND,00:00:30,00:01:45,01:15,,
NHA038,1,sam,side,train,JND,00:01:45,00:04:12,02:27,,
NHA038,1,sam,side,trial-1,JND,00:07:32,00:13:32,06:00,,
NHA038,1,sam,side,break-1,JND,00:13:32,00:13:49,00:17,,
NHA038,1,sam,side,trial-2,JND,00:13:49,00:20:49,07:00,,
NHA038,1,sam,side,break-2,JND,00:20:49,00:20:57,00:08,,
NHA038,1,sam,side,trial-3,JND,00:20:57,00:31:35,10:38,,
NHA038,1,sam,side,break-3,JND,00:31:35,00:31:44,00:09,,
NHA038,1,sam,side,trial-4,JND,00:31:44,00:38:19,06:35,,
NHA038,1,sam,side,intro,Gender,00:41:42,00:42:22,00:40,,
NHA038,1,sam,side,train,Gender,00:42:22,00:43:43,01:21,,
NHA038,1,sam,side,test,Gender,00:45:08,00:51:39,06:31,,
NHA038,1,sam,front,intro,JND,00:00:36,00:01:51,01:15,,
NHA038,1,sam,front,train,JND,00:01:51,00:04:19,02:28,,
NHA038,1,sam,front,trial-1,JND,00:07:38,00:13:38,06:00,,
NHA038,1,sam,front,break-1,JND,00:13:38,00:13:56,00:18,,
NHA038,1,sam,front,trial-2,JND,00:13:56,00:20:56,07:00,,
NHA038,1,sam,front,break-2,JND,00:20:56,00:21:05,00:09,,
NHA038,1,sam,front,trial-3,JND,00:21:05,00:31:42,10:37,,
NHA038,1,sam,front,break-3,JND,00:31:42,00:31:50,00:08,,
NHA038,1,sam,front,trial-4,JND,00:31:50,00:38:26,06:36,,
NHA038,1,sam,front,intro,Gender,00:41:49,00:42:29,00:40,,
NHA038,1,sam,front,train,Gender,00:42:29,00:43:49,01:20,,
NHA038,1,sam,front,test,Gender,00:45:15,00:51:46,06:31,,
NHA039,1,lap,side,train,JND,,,00:57,,
NHA039,1,lap,side,trial-1,JND,,,03:31,,
NHA039,1,lap,side,trial-2,JND,,,04:54,,
NHA039,1,lap,side,trial-3,JND,,,04:31,,
NHA039,1,lap,side,trial-4,JND,,,03:55,,
NHA039,1,lap,side,train,Gender,,,00:40,,
NHA039,1,lap,side,test,Gender,,,03:03,,
NHA039,1,lap,front,train,JND,00:00:13,00:01:10,00:57,,
NHA039,1,lap,front,trial-1,JND,00:01:29,00:05:00,03:31,,
NHA039,1,lap,front,trial-2,JND,00:05:00,00:09:54,04:54,,
NHA039,1,lap,front,trial-3,JND,00:09:54,00:14:25,04:31,,
NHA039,1,lap,front,trial-4,JND,00:14:25,00:18:20,03:55,,
NHA039,1,lap,front,train,Gender,00:19:30,00:20:10,00:40,,
NHA039,1,lap,front,test,Gender,00:20:34,00:23:37,03:03,,
NHA039,1,sam,side,intro,JND,00:00:00,00:01:10,01:10,,
NHA039,1,sam,side,train,JND,00:01:10,00:03:16,02:06,,
NHA039,1,sam,side,trial-1,JND,00:03:59,00:12:34,08:35,,
NHA039,1,sam,side,break-1,JND,00:12:34,00:12:50,00:16,,
NHA039,1,sam,side,trial-2,JND,00:12:50,00:17:14,04:24,,
NHA039,1,sam,side,break-2,JND,00:17:14,00:17:23,00:09,,
NHA039,1,sam,side,trial-3,JND,00:17:23,00:24:23,07:00,,
NHA039,1,sam,side,break-3,JND,00:24:23,00:24:31,00:08,,
NHA039,1,sam,side,trial-4,JND,00:24:31,00:29:03,04:32,,
NHA039,1,sam,side,intro,Gender,00:30:50,00:31:29,00:39,,
NHA039,1,sam,side,train,Gender,00:31:29,00:32:48,01:19,,
NHA039,1,sam,side,test,Gender,00:33:31,00:39:02,05:31,,
NHA039,1,sam,front,intro,JND,00:00:10,00:01:20,01:10,,
NHA039,1,sam,front,train,JND,00:01:20,00:03:26,02:06,,
NHA039,1,sam,front,trial-1,JND,00:04:08,00:12:43,08:35,,
NHA039,1,sam,front,break-1,JND,00:12:43,00:12:59,00:16,,
NHA039,1,sam,front,trial-2,JND,00:12:59,00:17:23,04:24,,
NHA039,1,sam,front,break-2,JND,00:17:23,00:17:32,00:09,,
NHA039,1,sam,front,trial-3,JND,00:17:32,00:24:31,06:59,,
NHA039,1,sam,front,break-3,JND,00:24:31,00:24:40,00:09,,
NHA039,1,sam,front,trial-4,JND,00:24:40,00:29:12,04:32,,
NHA039,1,sam,front,intro,Gender,00:30:59,00:31:39,00:40,,
NHA039,1,sam,front,train,Gender,00:31:39,00:32:57,01:18,,
NHA039,1,sam,front,test,Gender,00:33:40,00:39:13,05:33,,
NHA041,1,lap,side,train,JND,00:00:23,00:01:19,0,,
NHA041,1,lap,side,trial-1,JND,00:01:50,00:07:13,0,,
NHA041,1,lap,side,trial-2,JND,00:07:13,00:12:36,0,,
NHA041,1,lap,side,trial-3,JND,00:12:36,00:18:15,0,,
NHA041,1,lap,side,trial-4,JND,00:18:15,00:23:55,0,,
NHA041,1,lap,side,train,Gender,00:26:52,00:27:39,00:45,,
NHA041,1,lap,side,test,Gender,00:28:00,00:31:54,03:55,,
NHA041,1,lap,front,train,JND,,,0,,
NHA041,1,lap,front,trial-1,JND,,,0,,
NHA041,1,lap,front,trial-2,JND,,,0,,
NHA041,1,lap,front,trial-3,JND,,,0,,
NHA041,1,lap,front,trial-4,JND,,,0,,
NHA041,1,lap,front,train,Gender,00:00:43,00:01:28,00:45,,
NHA041,1,lap,front,test,Gender,00:01:49,00:05:44,03:55,,
NHA041,1,sam,side,intro,JND,,,0,,
NHA041,1,sam,side,train,JND,,,0,,
NHA041,1,sam,side,trial-1,JND,,,0,,
NHA041,1,sam,side,break-1,JND,,,0,,
NHA041,1,sam,side,trial-2,JND,,,0,,
NHA041,1,sam,side,break-2,JND,,,0,,
NHA041,1,sam,side,trial-3,JND,,,0,,
NHA041,1,sam,side,break-3,JND,,,0,,
NHA041,1,sam,side,trial-4,JND,,,0,,
NHA041,1,sam,side,intro,Gender,,,0,,
NHA041,1,sam,side,train,Gender,,,0,,
NHA041,1,sam,side,test,Gender,,,0,,
NHA041,1,sam,front,intro,JND,00:00:00,00:00:59,00:59,,
NHA041,1,sam,front,train,JND,00:00:59,00:03:20,02:21,,
NHA041,1,sam,front,trial-1,JND,00:08:04,00:16:59,08:55,,
NHA041,1,sam,front,break-1,JND,00:16:59,00:18:03,01:04,,
NHA041,1,sam,front,trial-2,JND,00:18:03,00:24:09,06:06,,
NHA041,1,sam,front,break-2,JND,00:24:09,00:25:07,00:58,,
NHA041,1,sam,front,trial-3,JND,00:25:07,00:29:58,04:51,,
NHA041,1,sam,front,break-3,JND,00:29:58,00:31:04,01:06,,
NHA041,1,sam,front,trial-4,JND,00:31:04,00:37:20,06:16,,
NHA041,1,sam,front,intro,Gender,00:39:14,00:39:53,00:39,,
NHA041,1,sam,front,train,Gender,00:39:53,00:41:17,01:24,,
NHA041,1,sam,front,test,Gender,00:41:56,00:48:33,06:37,,
1 Subject Experiment Interface Angle Segment Game Start End Duration
2 NHA026 1 lap side train JND 00:00:00 00:00:53 00:53
3 NHA026 1 lap side trial-1 JND 00:01:05 00:06:03 04:58
4 NHA026 1 lap side trial-2 JND 00:06:03 00:11:53 05:50
5 NHA026 1 lap side trial-3 JND 00:11:53 00:16:20 04:27
6 NHA026 1 lap side trial-4 JND 00:16:20 00:20:40 04:20
7 NHA026 1 lap side train Gender 00:21:51 00:22:37 00:46
8 NHA026 1 lap side test Gender 00:23:00 00:25:50 02:50
9 NHA026 1 lap front train JND 00:00:00 00:01:03 01:03
10 NHA026 1 lap front trial-1 JND 00:01:15 00:06:13 04:58
11 NHA026 1 lap front trial-2 JND 00:06:13 00:12:03 05:50
12 NHA026 1 lap front trial-3 JND 00:12:03 00:16:30 04:27
13 NHA026 1 lap front trial-4 JND 00:16:30 00:20:50 04:20
14 NHA026 1 lap front train Gender 00:22:01 00:22:47 00:46
15 NHA026 1 lap front test Gender 00:23:10 00:26:00 02:50
16 NHA026 1 sam side intro JND 00:00:57 00:02:16 01:19
17 NHA026 1 sam side train JND 00:02:16 00:04:21 02:05
18 NHA026 1 sam side trial-1 JND 00:05:38 00:13:19 07:41
19 NHA026 1 sam side break-1 JND 00:13:19 00:13:30 00:11
20 NHA026 1 sam side trial-2 JND 00:13:30 00:23:37 10:07
21 NHA026 1 sam side break-2 JND 00:23:37 00:23:52 00:15
22 NHA026 1 sam side trial-3 JND 00:23:52 00:29:15 05:23
23 NHA026 1 sam side break-3 JND 00:29:15 00:29:37 00:22
24 NHA026 1 sam side trial-4 JND 00:29:37 00:37:10 07:33
25 NHA026 1 sam side intro Gender 00:39:10 00:40:01 00:51
26 NHA026 1 sam side train Gender 00:40:01 00:41:18 01:17
27 NHA026 1 sam side test Gender 00:41:43 00:49:14 07:31
28 NHA026 1 sam front intro JND 00:01:06 00:02:27 01:21
29 NHA026 1 sam front train JND 00:02:27 00:04:32 02:05
30 NHA026 1 sam front trial-1 JND 00:05:49 00:13:30 07:41
31 NHA026 1 sam front break-1 JND 00:13:30 00:13:41 00:11
32 NHA026 1 sam front trial-2 JND 00:13:41 00:23:48 10:07
33 NHA026 1 sam front break-2 JND 00:23:48 00:24:04 00:16
34 NHA026 1 sam front trial-3 JND 00:24:04 00:29:26 05:22
35 NHA026 1 sam front break-3 JND 00:29:26 00:29:48 00:22
36 NHA026 1 sam front trial-4 JND 00:29:48 00:37:21 07:33
37 NHA026 1 sam front intro Gender 00:39:21 00:40:12 00:51
38 NHA026 1 sam front train Gender 00:41:29 00:41:54 00:25
39 NHA026 1 sam front test Gender 00:49:54 00:49:25 -00:29
40 NHA027 1 lap side train JND 00:00:42 00:01:41 00:59
41 NHA027 1 lap side trial-1 JND 00:02:02 00:08:23 06:21
42 NHA027 1 lap side trial-2 JND 00:08:23 00:12:46 04:23
43 NHA027 1 lap side trial-3 JND 00:15:03 00:19:04 04:01
44 NHA027 1 lap side trial-4 JND 00:23:44 00:27:49 04:05
45 NHA027 1 lap side train Gender 00:28:49 00:29:30 00:41
46 NHA027 1 lap side test Gender 00:29:45 00:33:10 03:25
47 NHA027 1 lap front train JND 00:00:45 00:01:44 00:59
48 NHA027 1 lap front trial-1 JND 00:02:05 00:08:26 06:21
49 NHA027 1 lap front trial-2 JND 00:08:26 00:12:49 04:23
50 NHA027 1 lap front trial-3 JND 00:15:06 00:19:07 04:01
51 NHA027 1 lap front trial-4 JND 00:23:47 00:27:52 04:05
52 NHA027 1 lap front train Gender 00:28:52 00:29:33 00:41
53 NHA027 1 lap front test Gender 00:29:48 00:33:13 03:25
54 NHA027 1 sam side intro JND 00:00:00 00:01:49 01:49
55 NHA027 1 sam side train JND 00:01:49 00:03:04 01:15
56 NHA027 1 sam side trial-1 JND 00:03:24 00:11:02 07:38
57 NHA027 1 sam side break-1 JND 00:11:02 00:12:22 01:20
58 NHA027 1 sam side trial-2 JND 00:12:22 00:17:32 05:10
59 NHA027 1 sam side break-2 JND 00:17:32 00:18:19 00:47
60 NHA027 1 sam side trial-3 JND 00:18:19 00:23:37 05:18
61 NHA027 1 sam side break-3 JND 00:23:37 00:23:50 00:13
62 NHA027 1 sam side trial-4 JND 00:23:50 00:31:26 07:36
63 NHA027 1 sam side intro Gender 00:33:18 00:34:03 00:45
64 NHA027 1 sam side train Gender 00:34:03 00:35:20 01:17
65 NHA027 1 sam side test Gender 00:35:52 00:42:17 06:25
66 NHA027 1 sam front intro JND 00:00:00 00:01:43 01:43
67 NHA027 1 sam front train JND 00:01:43 00:02:58 01:15
68 NHA027 1 sam front trial-1 JND 00:03:16 00:10:56 07:40
69 NHA027 1 sam front break-1 JND 00:10:56 00:12:16 01:20
70 NHA027 1 sam front trial-2 JND 00:12:16 00:17:26 05:10
71 NHA027 1 sam front break-2 JND 00:17:26 00:18:13 00:47
72 NHA027 1 sam front trial-3 JND 00:18:13 00:23:31 05:18
73 NHA027 1 sam front break-3 JND 00:23:31 00:23:44 00:13
74 NHA027 1 sam front trial-4 JND 00:23:44 00:31:20 07:36
75 NHA027 1 sam front intro Gender 00:33:12 00:33:57 00:45
76 NHA027 1 sam front train Gender 00:33:57 00:35:14 01:17
77 NHA027 1 sam front test Gender 00:35:46 00:42:11 06:25
78 NHA029 1 lap side train JND 00:00:38 00:01:45 01:12
79 NHA029 1 lap side trial-1 JND 00:02:49 00:08:11 05:07
80 NHA029 1 lap side trial-2 JND 00:08:11 00:12:31 04:21
81 NHA029 1 lap side trial-3 JND 00:12:31 00:17:49 05:18
82 NHA029 1 lap side trial-4 JND 00:17:49 00:22:23 04:34
83 NHA029 1 lap side train Gender 00:23:49 00:24:32 00:39
84 NHA029 1 lap side test Gender 00:24:59 00:28:38 03:34
85 NHA029 1 lap front train JND 00:00:30 00:01:42 01:12
86 NHA029 1 lap front trial-1 JND 00:02:53 00:08:00 05:07
87 NHA029 1 lap front trial-2 JND 00:08:00 00:12:21 04:21
88 NHA029 1 lap front trial-3 JND 00:12:21 00:17:39 05:18
89 NHA029 1 lap front trial-4 JND 00:17:39 00:22:13 04:34
90 NHA029 1 lap front train Gender 00:23:44 00:24:23 00:39
91 NHA029 1 lap front test Gender 00:24:59 00:28:33 03:34
92 NHA029 1 sam side intro JND 00:00:00 00:01:01 01:01
93 NHA029 1 sam side train JND 00:01:01 00:03:08 02:07
94 NHA029 1 sam side trial-1 JND 00:04:03 00:10:53 06:50
95 NHA029 1 sam side break-1 JND 00:10:53 00:11:58 01:05
96 NHA029 1 sam side trial-2 JND 00:11:58 00:17:04 05:06
97 NHA029 1 sam side break-2 JND 00:17:04 00:17:14 00:10
98 NHA029 1 sam side trial-3 JND 00:17:14 00:24:24 07:10
99 NHA029 1 sam side break-3 JND 00:24:24 00:24:32 00:08
100 NHA029 1 sam side trial-4 JND 00:24:32 00:29:52 05:20
101 NHA029 1 sam side intro Gender 00:32:02 00:32:39 00:37
102 NHA029 1 sam side train Gender 00:32:39 00:34:03 01:24
103 NHA029 1 sam side test Gender 00:34:30 00:40:54 06:24
104 NHA029 1 sam front intro JND 00:00:00 00:01:05 01:05
105 NHA029 1 sam front train JND 00:01:05 00:03:12 02:07
106 NHA029 1 sam front trial-1 JND 00:04:10 00:10:55 06:45
107 NHA029 1 sam front break-1 JND 00:10:55 00:12:00 01:05
108 NHA029 1 sam front trial-2 JND 00:12:00 00:17:03 05:03
109 NHA029 1 sam front break-2 JND 00:17:03 00:17:16 00:13
110 NHA029 1 sam front trial-3 JND 00:17:16 00:24:26 07:10
111 NHA029 1 sam front break-3 JND 00:24:26 00:24:35 00:09
112 NHA029 1 sam front trial-4 JND 00:24:35 00:29:56 05:21
113 NHA029 1 sam front intro Gender 00:32:02 00:32:42 00:40
114 NHA029 1 sam front train Gender 00:32:42 00:34:04 01:22
115 NHA029 1 sam front test Gender 00:34:31 00:40:57 06:26
116 NHA030 1 lap side train JND 01:25
117 NHA030 1 lap side trial-1 JND 06:10
118 NHA030 1 lap side trial-2 JND 04:14
119 NHA030 1 lap side trial-3 JND 05:47
120 NHA030 1 lap side trial-4 JND 06:44
121 NHA030 1 lap side train Gender 00:40
122 NHA030 1 lap side test Gender 03:06
123 NHA030 1 lap front train JND 00:00:10 00:01:35 01:25
124 NHA030 1 lap front trial-1 JND 00:01:57 00:08:07 06:10
125 NHA030 1 lap front trial-2 JND 00:08:08 00:12:22 04:14
126 NHA030 1 lap front trial-3 JND 00:13:04 00:18:51 05:47
127 NHA030 1 lap front trial-4 JND 00:18:51 00:25:35 06:44
128 NHA030 1 lap front train Gender 00:27:03 00:27:43 00:40
129 NHA030 1 lap front test Gender 00:28:10 00:31:16 03:06
130 NHA030 1 sam side intro JND 0
131 NHA030 1 sam side train JND 0
132 NHA030 1 sam side trial-1 JND 0
133 NHA030 1 sam side break-1 JND 0
134 NHA030 1 sam side trial-2 JND 0
135 NHA030 1 sam side break-2 JND 0
136 NHA030 1 sam side trial-3 JND 0
137 NHA030 1 sam side break-3 JND 0
138 NHA030 1 sam side trial-4 JND 0
139 NHA030 1 sam side intro Gender 0
140 NHA030 1 sam side train Gender 0
141 NHA030 1 sam side test Gender 0
142 NHA030 1 sam front intro JND 00:02:14 00:03:37 01:23
143 NHA030 1 sam front train JND 00:03:37 00:06:10 02:33
144 NHA030 1 sam front trial-1 JND 00:07:22 00:16:00 08:38
145 NHA030 1 sam front break-1 JND 00:16:00 00:16:18 00:18
146 NHA030 1 sam front trial-2 JND 00:16:18 00:22:15 05:57
147 NHA030 1 sam front break-2 JND 00:22:15 00:22:24 00:09
148 NHA030 1 sam front trial-3 JND 00:22:24 00:28:09 05:45
149 NHA030 1 sam front break-3 JND 00:28:09 00:28:17 00:08
150 NHA030 1 sam front trial-4 JND 00:28:17 00:34:06 05:49
151 NHA030 1 sam front intro Gender 00:36:08 00:36:48 00:40
152 NHA030 1 sam front train Gender 00:36:48 00:38:08 01:20
153 NHA030 1 sam front test Gender 00:38:45 00:44:46 06:01
154 NHA033 1 lap side train JND 01:04
155 NHA033 1 lap side trial-1 JND 04:20
156 NHA033 1 lap side trial-2 JND 06:56
157 NHA033 1 lap side trial-3 JND 04:47
158 NHA033 1 lap side trial-4 JND 07:17
159 NHA033 1 lap side train Gender 00:35
160 NHA033 1 lap side test Gender 03:43
161 NHA033 1 lap front train JND 00:00:13 00:01:17 01:04
162 NHA033 1 lap front trial-1 JND 00:01:53 00:06:13 04:20
163 NHA033 1 lap front trial-2 JND 00:06:13 00:13:09 06:56
164 NHA033 1 lap front trial-3 JND 00:13:09 00:17:56 04:47
165 NHA033 1 lap front trial-4 JND 00:17:56 00:25:13 07:17
166 NHA033 1 lap front train Gender 00:26:57 00:27:32 00:35
167 NHA033 1 lap front test Gender 00:28:13 00:31:56 03:43
168 NHA033 1 sam side intro JND 0
169 NHA033 1 sam side train JND 0
170 NHA033 1 sam side trial-1 JND 0
171 NHA033 1 sam side break-1 JND 0
172 NHA033 1 sam side trial-2 JND 0
173 NHA033 1 sam side break-2 JND 0
174 NHA033 1 sam side trial-3 JND 0
175 NHA033 1 sam side break-3 JND 0
176 NHA033 1 sam side trial-4 JND 0
177 NHA033 1 sam side intro Gender 0
178 NHA033 1 sam side train Gender 0
179 NHA033 1 sam side test Gender 0
180 NHA033 1 sam front intro JND 00:00:00 00:01:09 01:09
181 NHA033 1 sam front train JND 00:01:09 00:03:40 02:31
182 NHA033 1 sam front trial-1 JND 00:06:40 00:15:49 09:09
183 NHA033 1 sam front break-1 JND 00:15:49 00:15:59 00:10
184 NHA033 1 sam front trial-2 JND 00:15:59 00:20:47 04:48
185 NHA033 1 sam front break-2 JND 00:20:47 00:21:52 01:05
186 NHA033 1 sam front trial-3 JND 00:21:52 00:29:33 07:41
187 NHA033 1 sam front break-3 JND 00:29:33 00:30:50 01:17
188 NHA033 1 sam front trial-4 JND 00:30:50 00:37:57 07:07
189 NHA033 1 sam front intro Gender 00:40:16 00:40:55 00:39
190 NHA033 1 sam front train Gender 00:40:55 00:42:18 01:23
191 NHA033 1 sam front test Gender 00:42:59 00:49:36 06:37
192 NHA034 1 lap side train JND 00:58
193 NHA034 1 lap side trial-1 JND 03:37
194 NHA034 1 lap side trial-2 JND 04:53
195 NHA034 1 lap side trial-3 JND 04:17
196 NHA034 1 lap side trial-4 JND 05:35
197 NHA034 1 lap side train Gender 00:40
198 NHA034 1 lap side test Gender 03:04
199 NHA034 1 lap front train JND 00:00:07 00:01:05 00:58
200 NHA034 1 lap front trial-1 JND 00:01:22 00:04:59 03:37
201 NHA034 1 lap front trial-2 JND 00:04:59 00:09:52 04:53
202 NHA034 1 lap front trial-3 JND 00:09:52 00:14:09 04:17
203 NHA034 1 lap front trial-4 JND 00:14:09 00:19:44 05:35
204 NHA034 1 lap front train Gender 00:21:12 00:21:52 00:40
205 NHA034 1 lap front test Gender 00:22:12 00:25:16 03:04
206 NHA034 1 sam side intro JND 00:01:38 00:02:44 01:06
207 NHA034 1 sam side train JND 00:02:44 00:05:16 02:32
208 NHA034 1 sam side trial-1 JND 00:07:25 00:14:36 07:11
209 NHA034 1 sam side break-1 JND 00:14:36 00:14:46 00:10
210 NHA034 1 sam side trial-2 JND 00:14:46 00:22:14 07:28
211 NHA034 1 sam side break-2 JND 00:22:14 00:22:23 00:09
212 NHA034 1 sam side trial-3 JND 00:22:23 00:30:01 07:38
213 NHA034 1 sam side break-3 JND 00:30:01 00:30:30 00:29
214 NHA034 1 sam side trial-4 JND 00:30:30 00:38:02 07:32
215 NHA034 1 sam side intro Gender 00:39:41 00:40:20 00:39
216 NHA034 1 sam side train Gender 00:40:20 00:41:37 01:17
217 NHA034 1 sam side test Gender 00:42:37 00:50:31 07:54
218 NHA034 1_2 sam side end PICKA 00:50:31 00:50:49 00:18
219 NHA034 1 sam front intro JND 0
220 NHA034 1 sam front train JND 0
221 NHA034 1 sam front trial-1 JND 0
222 NHA034 1 sam front break-1 JND 0
223 NHA034 1 sam front trial-2 JND 0
224 NHA034 1 sam front break-2 JND 0
225 NHA034 1 sam front trial-3 JND 0
226 NHA034 1 sam front break-3 JND 0
227 NHA034 1 sam front trial-4 JND 0
228 NHA034 1 sam front intro Gender 0
229 NHA034 1 sam front train Gender 0
230 NHA034 1 sam front test Gender 0
231 NHA035 1 lap side train JND 00:23
232 NHA035 1 lap side trial-1 JND 04:05
233 NHA035 1 lap side trial-2 JND 04:32
234 NHA035 1 lap side trial-3 JND 03:19
235 NHA035 1 lap side trial-4 JND 16:27
236 NHA035 1 lap side train Gender 00:41
237 NHA035 1 lap side test Gender 02:55
238 NHA035 1 lap front train JND 00:00:09 00:00:32 00:23
239 NHA035 1 lap front trial-1 JND 00:01:10 00:05:15 04:05
240 NHA035 1 lap front trial-2 JND 00:05:15 00:09:47 04:32
241 NHA035 1 lap front trial-3 JND 00:09:47 00:13:06 03:19
242 NHA035 1 lap front trial-4 JND 00:13:06 00:29:33 16:27
243 NHA035 1 lap front train Gender 00:21:06 00:21:47 00:41
244 NHA035 1 lap front test Gender 00:22:17 00:25:12 02:55
245 NHA035 1 sam side train JND 00:00:20 00:02:20 02:00
246 NHA035 1 sam side trial-1 JND 00:04:01 00:10:16 06:15
247 NHA035 1 sam side break-1 JND 00:10:16 00:10:26 00:10
248 NHA035 1 sam side trial-2 JND 00:10:26 00:15:39 05:13
249 NHA035 1 sam side break-2 JND 00:15:39 00:16:37 00:58
250 NHA035 1 sam side trial-3 JND 00:16:37 00:26:12 09:35
251 NHA035 1 sam side break-3 JND 00:26:12 00:26:21 00:09
252 NHA035 1 sam side trial-4 JND 00:26:21 00:33:18 06:57
253 NHA035 1 sam side intro Gender 00:35:17 00:35:57 00:40
254 NHA035 1 sam side train Gender 00:35:57 00:37:20 01:23
255 NHA035 1 sam side test Gender 00:37:48 00:43:59 06:11
256 NHA035 1 sam front intro JND 0
257 NHA035 1 sam front train JND 0
258 NHA035 1 sam front trial-1 JND 0
259 NHA035 1 sam front break-1 JND 0
260 NHA035 1 sam front trial-2 JND 0
261 NHA035 1 sam front break-2 JND 0
262 NHA035 1 sam front trial-3 JND 0
263 NHA035 1 sam front break-3 JND 0
264 NHA035 1 sam front trial-4 JND 0
265 NHA035 1 sam front intro Gender 0
266 NHA035 1 sam front train Gender 0
267 NHA035 1 sam front test Gender 0
268 NHA036 1 lap side train JND 01:01
269 NHA036 1 lap side trial-1 JND 07:22
270 NHA036 1 lap side trial-2 JND 04:40
271 NHA036 1 lap side trial-3 JND 05:43
272 NHA036 1 lap side trial-4 JND 04:09
273 NHA036 1 lap side train Gender 00:44
274 NHA036 1 lap side test Gender 03:55
275 NHA036 1 lap front train JND 00:00:07 00:01:08 01:01
276 NHA036 1 lap front trial-1 JND 00:01:25 00:08:47 07:22
277 NHA036 1 lap front trial-2 JND 00:08:59 00:13:39 04:40
278 NHA036 1 lap front trial-3 JND 00:13:39 00:19:22 05:43
279 NHA036 1 lap front trial-4 JND 00:19:22 00:23:31 04:09
280 NHA036 1 lap front train Gender 00:25:05 00:25:49 00:44
281 NHA036 1 lap front test Gender 00:26:43 00:30:38 03:55
282 NHA036 1 sam side intro JND 00:01:54 00:03:06 01:12
283 NHA036 1 sam side train JND 00:03:06 00:05:15 02:09
284 NHA036 1 sam side trial-1 JND 00:05:47 00:14:04 08:17
285 NHA036 1 sam side break-1 JND 00:14:04 00:15:01 00:57
286 NHA036 1 sam side trial-2 JND 00:15:01 00:23:22 08:21
287 NHA036 1 sam side break-2 JND 00:23:22 00:23:50 00:28
288 NHA036 1 sam side trial-3 JND 00:23:50 00:31:09 07:19
289 NHA036 1 sam side break-3 JND 00:31:09 00:32:16 01:07
290 NHA036 1 sam side trial-4 JND 00:32:16 00:37:40 05:24
291 NHA036 1 sam side intro Gender 00:42:18 00:42:54 00:36
292 NHA036 1 sam side train Gender 00:42:54 00:44:16 01:22
293 NHA036 1 sam side test Gender 00:45:00 00:53:15 08:15
294 NHA036 1_2 sam side end PICKA 00:53:15 00:53:32 00:17
295 NHA036 1 sam front intro JND 0
296 NHA036 1 sam front train JND 0
297 NHA036 1 sam front trial-1 JND 0
298 NHA036 1 sam front break-1 JND 0
299 NHA036 1 sam front trial-2 JND 0
300 NHA036 1 sam front break-2 JND 0
301 NHA036 1 sam front trial-3 JND 0
302 NHA036 1 sam front break-3 JND 0
303 NHA036 1 sam front trial-4 JND 0
304 NHA036 1 sam front intro Gender 0
305 NHA036 1 sam front train Gender 0
306 NHA036 1 sam front test Gender 00:42:59 00:49:36 06:37
307 NHA038 1 lap side train JND 01:18
308 NHA038 1 lap side trial-1 JND 05:20
309 NHA038 1 lap side trial-2 JND 06:33
310 NHA038 1 lap side trial-3 JND 05:43
311 NHA038 1 lap side trial-4 JND 05:34
312 NHA038 1 lap side train Gender 00:46
313 NHA038 1 lap side test Gender 03:45
314 NHA038 1 lap front train JND 00:01:38 00:02:56 01:18
315 NHA038 1 lap front trial-1 JND 00:04:06 00:09:26 05:20
316 NHA038 1 lap front trial-2 JND 00:09:42 00:16:15 06:33
317 NHA038 1 lap front trial-3 JND 00:16:38 00:22:21 05:43
318 NHA038 1 lap front trial-4 JND 00:22:30 00:28:04 05:34
319 NHA038 1 lap front train Gender 00:30:03 00:30:49 00:46
320 NHA038 1 lap front test Gender 00:31:34 00:35:19 03:45
321 NHA038 1 sam side intro JND 00:00:30 00:01:45 01:15
322 NHA038 1 sam side train JND 00:01:45 00:04:12 02:27
323 NHA038 1 sam side trial-1 JND 00:07:32 00:13:32 06:00
324 NHA038 1 sam side break-1 JND 00:13:32 00:13:49 00:17
325 NHA038 1 sam side trial-2 JND 00:13:49 00:20:49 07:00
326 NHA038 1 sam side break-2 JND 00:20:49 00:20:57 00:08
327 NHA038 1 sam side trial-3 JND 00:20:57 00:31:35 10:38
328 NHA038 1 sam side break-3 JND 00:31:35 00:31:44 00:09
329 NHA038 1 sam side trial-4 JND 00:31:44 00:38:19 06:35
330 NHA038 1 sam side intro Gender 00:41:42 00:42:22 00:40
331 NHA038 1 sam side train Gender 00:42:22 00:43:43 01:21
332 NHA038 1 sam side test Gender 00:45:08 00:51:39 06:31
333 NHA038 1 sam front intro JND 00:00:36 00:01:51 01:15
334 NHA038 1 sam front train JND 00:01:51 00:04:19 02:28
335 NHA038 1 sam front trial-1 JND 00:07:38 00:13:38 06:00
336 NHA038 1 sam front break-1 JND 00:13:38 00:13:56 00:18
337 NHA038 1 sam front trial-2 JND 00:13:56 00:20:56 07:00
338 NHA038 1 sam front break-2 JND 00:20:56 00:21:05 00:09
339 NHA038 1 sam front trial-3 JND 00:21:05 00:31:42 10:37
340 NHA038 1 sam front break-3 JND 00:31:42 00:31:50 00:08
341 NHA038 1 sam front trial-4 JND 00:31:50 00:38:26 06:36
342 NHA038 1 sam front intro Gender 00:41:49 00:42:29 00:40
343 NHA038 1 sam front train Gender 00:42:29 00:43:49 01:20
344 NHA038 1 sam front test Gender 00:45:15 00:51:46 06:31
345 NHA039 1 lap side train JND 00:57
346 NHA039 1 lap side trial-1 JND 03:31
347 NHA039 1 lap side trial-2 JND 04:54
348 NHA039 1 lap side trial-3 JND 04:31
349 NHA039 1 lap side trial-4 JND 03:55
350 NHA039 1 lap side train Gender 00:40
351 NHA039 1 lap side test Gender 03:03
352 NHA039 1 lap front train JND 00:00:13 00:01:10 00:57
353 NHA039 1 lap front trial-1 JND 00:01:29 00:05:00 03:31
354 NHA039 1 lap front trial-2 JND 00:05:00 00:09:54 04:54
355 NHA039 1 lap front trial-3 JND 00:09:54 00:14:25 04:31
356 NHA039 1 lap front trial-4 JND 00:14:25 00:18:20 03:55
357 NHA039 1 lap front train Gender 00:19:30 00:20:10 00:40
358 NHA039 1 lap front test Gender 00:20:34 00:23:37 03:03
359 NHA039 1 sam side intro JND 00:00:00 00:01:10 01:10
360 NHA039 1 sam side train JND 00:01:10 00:03:16 02:06
361 NHA039 1 sam side trial-1 JND 00:03:59 00:12:34 08:35
362 NHA039 1 sam side break-1 JND 00:12:34 00:12:50 00:16
363 NHA039 1 sam side trial-2 JND 00:12:50 00:17:14 04:24
364 NHA039 1 sam side break-2 JND 00:17:14 00:17:23 00:09
365 NHA039 1 sam side trial-3 JND 00:17:23 00:24:23 07:00
366 NHA039 1 sam side break-3 JND 00:24:23 00:24:31 00:08
367 NHA039 1 sam side trial-4 JND 00:24:31 00:29:03 04:32
368 NHA039 1 sam side intro Gender 00:30:50 00:31:29 00:39
369 NHA039 1 sam side train Gender 00:31:29 00:32:48 01:19
370 NHA039 1 sam side test Gender 00:33:31 00:39:02 05:31
371 NHA039 1 sam front intro JND 00:00:10 00:01:20 01:10
372 NHA039 1 sam front train JND 00:01:20 00:03:26 02:06
373 NHA039 1 sam front trial-1 JND 00:04:08 00:12:43 08:35
374 NHA039 1 sam front break-1 JND 00:12:43 00:12:59 00:16
375 NHA039 1 sam front trial-2 JND 00:12:59 00:17:23 04:24
376 NHA039 1 sam front break-2 JND 00:17:23 00:17:32 00:09
377 NHA039 1 sam front trial-3 JND 00:17:32 00:24:31 06:59
378 NHA039 1 sam front break-3 JND 00:24:31 00:24:40 00:09
379 NHA039 1 sam front trial-4 JND 00:24:40 00:29:12 04:32
380 NHA039 1 sam front intro Gender 00:30:59 00:31:39 00:40
381 NHA039 1 sam front train Gender 00:31:39 00:32:57 01:18
382 NHA039 1 sam front test Gender 00:33:40 00:39:13 05:33
383 NHA041 1 lap side train JND 00:00:23 00:01:19 0
384 NHA041 1 lap side trial-1 JND 00:01:50 00:07:13 0
385 NHA041 1 lap side trial-2 JND 00:07:13 00:12:36 0
386 NHA041 1 lap side trial-3 JND 00:12:36 00:18:15 0
387 NHA041 1 lap side trial-4 JND 00:18:15 00:23:55 0
388 NHA041 1 lap side train Gender 00:26:52 00:27:39 00:45
389 NHA041 1 lap side test Gender 00:28:00 00:31:54 03:55
390 NHA041 1 lap front train JND 0
391 NHA041 1 lap front trial-1 JND 0
392 NHA041 1 lap front trial-2 JND 0
393 NHA041 1 lap front trial-3 JND 0
394 NHA041 1 lap front trial-4 JND 0
395 NHA041 1 lap front train Gender 00:00:43 00:01:28 00:45
396 NHA041 1 lap front test Gender 00:01:49 00:05:44 03:55
397 NHA041 1 sam side intro JND 0
398 NHA041 1 sam side train JND 0
399 NHA041 1 sam side trial-1 JND 0
400 NHA041 1 sam side break-1 JND 0
401 NHA041 1 sam side trial-2 JND 0
402 NHA041 1 sam side break-2 JND 0
403 NHA041 1 sam side trial-3 JND 0
404 NHA041 1 sam side break-3 JND 0
405 NHA041 1 sam side trial-4 JND 0
406 NHA041 1 sam side intro Gender 0
407 NHA041 1 sam side train Gender 0
408 NHA041 1 sam side test Gender 0
409 NHA041 1 sam front intro JND 00:00:00 00:00:59 00:59
410 NHA041 1 sam front train JND 00:00:59 00:03:20 02:21
411 NHA041 1 sam front trial-1 JND 00:08:04 00:16:59 08:55
412 NHA041 1 sam front break-1 JND 00:16:59 00:18:03 01:04
413 NHA041 1 sam front trial-2 JND 00:18:03 00:24:09 06:06
414 NHA041 1 sam front break-2 JND 00:24:09 00:25:07 00:58
415 NHA041 1 sam front trial-3 JND 00:25:07 00:29:58 04:51
416 NHA041 1 sam front break-3 JND 00:29:58 00:31:04 01:06
417 NHA041 1 sam front trial-4 JND 00:31:04 00:37:20 06:16
418 NHA041 1 sam front intro Gender 00:39:14 00:39:53 00:39
419 NHA041 1 sam front train Gender 00:39:53 00:41:17 01:24
420 NHA041 1 sam front test Gender 00:41:56 00:48:33 06:37
+23
View File
@@ -0,0 +1,23 @@
import numpy as np
from scipy.fftpack import fft
def noise(x, fs, do_am=False, smooth=False):
X = fft(x)
n = len(X)
if n % 2 == 0:
p = np.random.rand((n-2)/2)
p = np.hstack((0, p, 0, -p))
else:
p = np.random.rand((n-1)/2)
p = np.hstack((0, p, -p))
if not smooth:
Y = np.abs(X) * np.exp(1j*2*np.pi*p)
y = np.real(np.fft.ifft(Y))
y = y * np.sqrt(np.mean(x**2)) / np.sqrt(np.mean(y**2))
return y
+25
View File
@@ -0,0 +1,25 @@
from numpy import sort
from playsound import playsound
import paramiko
import os
from naoqi import ALProxy
pth = "/home/nao/Documents/Pure tones/"
files = os.listdir(pth)
# for f, file_as_num in enumerate(sorted(int(os.path.splitext(file)[0][:-2]) for file in files)):
# print(file_as_num)
# playsound(os.path.join(pth,str(file_as_num) + "Hz.wav"))
# raw_input("Continue?")
aap = ALProxy("ALAudioPlayer", "sam.local", 9559)
aad = ALProxy("ALAudioDevice", "sam.local",9559)
aad.setOutputVolume(10)
sam_pth = "/home/nao/volume_test/"
for f, file_as_num in enumerate(sorted(int(os.path.splitext(file)[0][:-2]) for file in files)):
print(file_as_num)
aap.playFile(sam_pth + str(file_as_num) + "Hz.wav")
raw_input("Continue?")
View File
Whitespace-only changes.
+193
View File
@@ -0,0 +1,193 @@
from flask import Flask, render_template, request, url_for, redirect, jsonify
from celery import Celery
from naoqi import ALBroker
import subprocess
import os
import sys
import pickle
import time
from multiprocessing import Pool
if True:
sys.path.append("../")
from tools.exit_condition import ExitExperimentModule
import tools.settings as settings
app = Flask(__name__)
_pool = None
# app.config['CELERY_BROKER_URL'] = 'redis://localhost:6379/0'
# app.config['CELERY_RESULT_BACKEND'] = 'redis://localhost:6379/0'
# website_url = "picka-exp.xyx:5000"
# app.config["SERVER_NAME"] = website_url
# celery = Celery(app.name, broker=app.config["CELERY_BROKER_URL"])
# celery.conf.update(app.config)
expe_exit = None
global language
IP_ADDRESS = "169.254.165.5"
# IP_ADDRESS = "sam.local"
# @celery.task(bind=True)
# def runPickaExp(self, subject, game, phase, lang, p_exists, ip):
def runPickaExp(subject, game, phase, lang, p_exists, ip):
sys.path.append(os.getcwd())
from picka import pickaMain
#
# This might take several minutes to complete
# @celery.task(bind=True)
# def runPickaExp(self, subject, game, phase, lang, p_exists, ip):
print("Started picka!!")
if os.getcwd() != '/home/nao/Documents/Sam_files/Python_scripts':
os.chdir('../')
pickaMain(subject, game, phase, lang, p_exists, ip, broker=True)
# main(subject, game, phase, lang, p_exists,
# ip, broker=True, cel_id=self.request.id)
print "End of running process."
@app.route('/')
def hello():
return render_template("main.html")
@app.route("/run_picka", methods=["GET", "POST"])
def runPicka():
global language
error = 0
p_exists = request.form.get("p_exists")
game = request.form.get("game")
subject = request.form.get("participant").strip()
phase = request.form.get("phase").strip().lower()
lang = request.form.get("lang").strip()
language = lang
ip = IP_ADDRESS
p_exists = int(p_exists == 'true')
port = "9559"
try:
if p_exists != None:
# runPickaExp.delay(subject, game, phase, lang, p_exists, ip)
try:
# runPickaExp(subject, game, phase, lang, p_exists, ip)
begin = _pool.apply_async(
runPickaExp, [subject, game, phase, lang, p_exists, ip])
except:
raise Exception()
return jsonify({'game': game})
except RuntimeError as e:
error = 1
print e
print "There was an error."
return jsonify({'game': game, "error": error})
# cmd = "/usr/bin/python picka.py -s {} -g {} -p {} -l {} -e {}".format(
# subject, game, phase, lang, p_exists)
# print cmd
# subprocess.call(cmd, shell=True)
@app.route('/check_participant', methods=['GET', 'POST'])
def check_participant():
if os.getcwd() != "/home/nao/Documents/Sam_files/Python_scripts/www":
os.chdir("./www")
game = request.form.get("game")
subject = request.form.get("participant").strip()
phase = request.form.get("phase").strip().lower()
lang = request.form.get("lang").strip()
if game == "fishy":
participant = os.path.join(
"../results/" + subject,
"jnd_{}_{}_robot.mat".format(lang.lower(), subject))
else:
participant = os.path.join(
"../results/" + subject,
"{}_{}_{}_robot.mat".format(game[:3], lang.lower(), subject))
# subprocess.call(cmd, shell=True)
p_exists = 0
if os.path.exists(participant):
p_exists = 1
# os.chdir("www/")
# return redirect(url_for('checkParticipant', participant=participant))
return jsonify({
'p_exists': p_exists,
"game": game,
"subject": subject,
"phase": phase,
"lang": lang
})
@app.route('/no-interaction')
def noInt():
return render_template('no-int.html')
@app.route('/no-interaction-diagram')
def noIntDiagram():
return render_template('no-int-w-diagram.html')
@app.route('/crm-game')
def runCRM():
global language
while not os.path.exists('../crm/trials.p'):
time.sleep(0.01)
if os.path.isfile('../crm/trials.p'):
try:
with open('../crm/trials.p', 'rb') as f:
data = pickle.load(f)
except EOFError as e:
print e
os.remove('../crm/trials.p')
language = 'en'
return render_template("crm-game.html",
lang=language,
current_trial=int(data["current_trial"]),
total_trials=int(data["total_trials"]))
@app.route('/crm_answer', methods=["GET", "POST"])
def save_answer():
colour = request.form.get("colour")
number = request.form.get("number")
answer = {"colour": colour, "number": number}
pickle.dump(answer, open('../crm/answer.p', 'wb'))
while not os.path.exists('../crm/trials.p'):
time.sleep(0.01)
if os.path.isfile('../crm/trials.p'):
try:
with open('../crm/trials.p', 'rb') as f:
data = pickle.load(f)
except EOFError as e:
print e
os.remove('../crm/trials.p')
resp = {"answer": answer, "trials": data}
# return redirect(url_for('runCRM'))
return jsonify(resp)
if __name__ == "__main__":
# runPickaExp("NHA927", "crm", "training", "EN", 0, IP_ADDRESS)
global expe_exit
settings.init()
_pool = Pool(processes=4)
try:
# myBroker = ALBroker("myBroker", "0.0.0.0", 0, IP_ADDRESS, 9559)
# expe_exit = ExitExperimentModule("expe_exit", myBroker, "EN")
app.run(host="0.0.0.0", debug=True)
except SystemError as e:
print e
_pool.close()
_pool.join()
os._exit(1)
+5
View File
@@ -0,0 +1,5 @@
#!/bin/bash
echo "test"
celery -A app.celery worker --loglevel=debug
+11416
View File
File diff suppressed because it is too large. Load diff
+1953
View File
File diff suppressed because it is too large. Load diff
+252
View File
@@ -0,0 +1,252 @@
.game_img {
width: 200px;
}
.main_img {
display: block;
margin-left: auto;
margin-right: auto;
width: 50%;
}
.fullwidth-div {
position: absolute;
width: 100%;
height: 100%;
left: 0;
margin: 0;
}
button.game-btn {
background-color: #6AD9D9;
background-repeat: no-repeat;
border: #6AD9D9;
cursor: pointer;
overflow: hidden;
outline: none;
box-shadow: 10px 10px 5px;
border-radius: 10px;
height: 100%;
width: 100%;
}
.create-participant:hover {
background-color: #F6454F !important;
border: #F6454F;
}
.create-participant:active {
color: black !important;
background-color: #FFD503 !important;
border: #FFD503 !important;
}
.create-participant:focus {
background-color: #6AD9D9 !important;
}
.main-logos {
background-color: #ECDFCD;
margin-bottom: 10%;
}
#main_logos {
padding-top: 1%;
}
/* .game-logos {
margin-left: 2%;
} */
#no-interaction {
font-size: 5em;
color: red;
background: #ECDFCD;
border-radius: 30px;
padding: 0.5% 5%;
text-align: center;
}
#no-interaction-diagram {
font-size: 5em;
color: red;
background: #ECDFCD;
border-radius: 30px;
padding: 0.5% 5%;
text-align: center;
}
.no-interaction {
margin-top: 20%;
text-align: center;
}
.no-interaction-diagram {
margin-top: 5%;
text-align: center;
}
label,
input {
display: block;
}
input.text {
margin-bottom: 12px;
width: 95%;
padding: .4em;
}
fieldset {
padding: 0;
border: 0;
}
h1 {
font-size: 1.2em;
margin: .6em 0;
}
div#users-contain {
width: 350px;
margin: 20px 0;
}
div#dialog-form {
height: 290px !important;
}
div#users-contain table {
margin: 1em 0;
border-collapse: collapse;
width: 100%;
}
div#users-contain table td,
div#users-contain table th {
border: 1px solid #eee;
padding: .6em 10px;
text-align: left;
}
.ui-dialog .ui-state-error {
padding: .3em;
}
.validateTips {
border: 1px solid transparent;
padding: 0.3em;
}
#crm-grid {
text-align: center;
color: white;
width: 100%;
margin: 0 auto;
}
#crm-grid>tbody>tr>td {
height: 5em;
width: 2em;
}
#crm-parent {
padding: 1% 10% 10% 10%;
}
.crm-holder {
background: rgb(44, 44, 44);
margin-top: 5%;
padding: 3% 4% 4% 10%;
width: 100%;
border-radius: 2em;
}
.crm-button {
width: 100%;
height: 100%;
border: none;
color: white;
}
.crm-button:hover {
background-color: grey;
}
.crm-cell {
border: 1px solid black;
}
.crm-blue {
background-color: blue;
}
.crm-black {
background-color: black;
}
.crm-white {
background-color: white;
color: black;
}
.crm-red {
background-color: red;
}
.crm-pink {
background-color: pink;
color: black;
}
.crm-green {
background-color: green;
}
.crm-name {
font-weight: bold;
}
#myProgress {
width: 100%;
background-color: grey;
margin-left: -3.5%;
}
.ui-progressbar-value {
margin: 0 !important;
background-color: green;
}
#sam-diagram {
text-align: center;
height: 40em;
width: auto;
}
@media only screen and (max-width: 1365px) {
#sam-diagram {
height: 30em;
margin-top: 1%;
}
#no-interaction-diagram {
font-size: 2em;
border-radius: 15px;
padding: 0.5% 5%;
text-align: center;
}
.no-interaction-diagram {
margin-top: 2%;
}
#woman_holding_dog {
width: 15%;
}
#woman_holding_dog img {
width: 120%;
position: relative;
top: 25%;
}
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 110 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 210 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 745 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 481 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 833 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 163 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

+13
View File
@@ -0,0 +1,13 @@
/*! jQuery UI - v1.12.1 - 2016-09-14
* http://jqueryui.com
* Includes: widget.js, position.js, data.js, disable-selection.js, effect.js, effects/effect-blind.js, effects/effect-bounce.js, effects/effect-clip.js, effects/effect-drop.js, effects/effect-explode.js, effects/effect-fade.js, effects/effect-fold.js, effects/effect-highlight.js, effects/effect-puff.js, effects/effect-pulsate.js, effects/effect-scale.js, effects/effect-shake.js, effects/effect-size.js, effects/effect-slide.js, effects/effect-transfer.js, focusable.js, form-reset-mixin.js, jquery-1-7.js, keycode.js, labels.js, scroll-parent.js, tabbable.js, unique-id.js, widgets/accordion.js, widgets/autocomplete.js, widgets/button.js, widgets/checkboxradio.js, widgets/controlgroup.js, widgets/datepicker.js, widgets/dialog.js, widgets/draggable.js, widgets/droppable.js, widgets/menu.js, widgets/mouse.js, widgets/progressbar.js, widgets/resizable.js, widgets/selectable.js, widgets/selectmenu.js, widgets/slider.js, widgets/sortable.js, widgets/spinner.js, widgets/tabs.js, widgets/tooltip.js
* Copyright jQuery Foundation and other contributors; Licensed MIT */
(function(t){"function"==typeof define&&define.amd?define(["jquery"],t):t(jQuery)})(function(t){function e(t){for(var e=t.css("visibility");"inherit"===e;)t=t.parent(),e=t.css("visibility");return"hidden"!==e}function i(t){for(var e,i;t.length&&t[0]!==document;){if(e=t.css("position"),("absolute"===e||"relative"===e||"fixed"===e)&&(i=parseInt(t.css("zIndex"),10),!isNaN(i)&&0!==i))return i;t=t.parent()}return 0}function s(){this._curInst=null,this._keyEvent=!1,this._disabledInputs=[],this._datepickerShowing=!1,this._inDialog=!1,this._mainDivId="ui-datepicker-div",this._inlineClass="ui-datepicker-inline",this._appendClass="ui-datepicker-append",this._triggerClass="ui-datepicker-trigger",this._dialogClass="ui-datepicker-dialog",this._disableClass="ui-datepicker-disabled",this._unselectableClass="ui-datepicker-unselectable",this._currentClass="ui-datepicker-current-day",this._dayOverClass="ui-datepicker-days-cell-over",this.regional=[],this.regional[""]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],weekHeader:"Wk",dateFormat:"mm/dd/yy",firstDay:0,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},this._defaults={showOn:"focus",showAnim:"fadeIn",showOptions:{},defaultDate:null,appendText:"",buttonText:"...",buttonImage:"",buttonImageOnly:!1,hideIfNoPrevNext:!1,navigationAsDateFormat:!1,gotoCurrent:!1,changeMonth:!1,changeYear:!1,yearRange:"c-10:c+10",showOtherMonths:!1,selectOtherMonths:!1,showWeek:!1,calculateWeek:this.iso8601Week,shortYearCutoff:"+10",minDate:null,maxDate:null,duration:"fast",beforeShowDay:null,beforeShow:null,onSelect:null,onChangeMonthYear:null,onClose:null,numberOfMonths:1,showCurrentAtPos:0,stepMonths:1,stepBigMonths:12,altField:"",altFormat:"",constrainInput:!0,showButtonPanel:!1,autoSize:!1,disabled:!1},t.extend(this._defaults,this.regional[""]),this.regional.en=t.extend(!0,{},this.regional[""]),this.regional["en-US"]=t.extend(!0,{},this.regional.en),this.dpDiv=n(t("<div id='"+this._mainDivId+"' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>"))}function n(e){var i="button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";return e.on("mouseout",i,function(){t(this).removeClass("ui-state-hover"),-1!==this.className.indexOf("ui-datepicker-prev")&&t(this).removeClass("ui-datepicker-prev-hover"),-1!==this.className.indexOf("ui-datepicker-next")&&t(this).removeClass("ui-datepicker-next-hover")}).on("mouseover",i,o)}function o(){t.datepicker._isDisabledDatepicker(m.inline?m.dpDiv.parent()[0]:m.input[0])||(t(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"),t(this).addClass("ui-state-hover"),-1!==this.className.indexOf("ui-datepicker-prev")&&t(this).addClass("ui-datepicker-prev-hover"),-1!==this.className.indexOf("ui-datepicker-next")&&t(this).addClass("ui-datepicker-next-hover"))}function a(e,i){t.extend(e,i);for(var s in i)null==i[s]&&(e[s]=i[s]);return e}function r(t){return function(){var e=this.element.val();t.apply(this,arguments),this._refresh(),e!==this.element.val()&&this._trigger("change")}}t.ui=t.ui||{},t.ui.version="1.12.1";var h=0,l=Array.prototype.slice;t.cleanData=function(e){return function(i){var s,n,o;for(o=0;null!=(n=i[o]);o++)try{s=t._data(n,"events"),s&&s.remove&&t(n).triggerHandler("remove")}catch(a){}e(i)}}(t.cleanData),t.widget=function(e,i,s){var n,o,a,r={},h=e.split(".")[0];e=e.split(".")[1];var l=h+"-"+e;return s||(s=i,i=t.Widget),t.isArray(s)&&(s=t.extend.apply(null,[{}].concat(s))),t.expr[":"][l.toLowerCase()]=function(e){return!!t.data(e,l)},t[h]=t[h]||{},n=t[h][e],o=t[h][e]=function(t,e){return this._createWidget?(arguments.length&&this._createWidget(t,e),void 0):new o(t,e)},t.extend(o,n,{version:s.version,_proto:t.extend({},s),_childConstructors:[]}),a=new i,a.options=t.widget.extend({},a.options),t.each(s,function(e,s){return t.isFunction(s)?(r[e]=function(){function t(){return i.prototype[e].apply(this,arguments)}function n(t){return i.prototype[e].apply(this,t)}return function(){var e,i=this._super,o=this._superApply;return this._super=t,this._superApply=n,e=s.apply(this,arguments),this._super=i,this._superApply=o,e}}(),void 0):(r[e]=s,void 0)}),o.prototype=t.widget.extend(a,{widgetEventPrefix:n?a.widgetEventPrefix||e:e},r,{constructor:o,namespace:h,widgetName:e,widgetFullName:l}),n?(t.each(n._childConstructors,function(e,i){var s=i.prototype;t.widget(s.namespace+"."+s.widgetName,o,i._proto)}),delete n._childConstructors):i._childConstructors.push(o),t.widget.bridge(e,o),o},t.widget.extend=function(e){for(var i,s,n=l.call(arguments,1),o=0,a=n.length;a>Line truncated
}}(t.fn.show),hide:function(t){return function(s){if(i(s))return t.apply(this,arguments);var n=e.apply(this,arguments);return n.mode="hide",this.effect.call(this,n)}}(t.fn.hide),toggle:function(t){return function(s){if(i(s)||"boolean"==typeof s)return t.apply(this,arguments);var n=e.apply(this,arguments);return n.mode="toggle",this.effect.call(this,n)}}(t.fn.toggle),cssUnit:function(e){var i=this.css(e),s=[];return t.each(["em","px","%","pt"],function(t,e){i.indexOf(e)>0&&(s=[parseFloat(i),e])}),s},cssClip:function(t){return t?this.css("clip","rect("+t.top+"px "+t.right+"px "+t.bottom+"px "+t.left+"px)"):s(this.css("clip"),this)},transfer:function(e,i){var s=t(this),n=t(e.to),o="fixed"===n.css("position"),a=t("body"),r=o?a.scrollTop():0,h=o?a.scrollLeft():0,l=n.offset(),c={top:l.top-r,left:l.left-h,height:n.innerHeight(),width:n.innerWidth()},u=s.offset(),d=t("<div class='ui-effects-transfer'></div>").appendTo("body").addClass(e.className).css({top:u.top-r,left:u.left-h,height:s.innerHeight(),width:s.innerWidth(),position:o?"fixed":"absolute"}).animate(c,e.duration,e.easing,function(){d.remove(),t.isFunction(i)&&i()})}}),t.fx.step.clip=function(e){e.clipInit||(e.start=t(e.elem).cssClip(),"string"==typeof e.end&&(e.end=s(e.end,e.elem)),e.clipInit=!0),t(e.elem).cssClip({top:e.pos*(e.end.top-e.start.top)+e.start.top,right:e.pos*(e.end.right-e.start.right)+e.start.right,bottom:e.pos*(e.end.bottom-e.start.bottom)+e.start.bottom,left:e.pos*(e.end.left-e.start.left)+e.start.left})}}(),function(){var e={};t.each(["Quad","Cubic","Quart","Quint","Expo"],function(t,i){e[i]=function(e){return Math.pow(e,t+2)}}),t.extend(e,{Sine:function(t){return 1-Math.cos(t*Math.PI/2)},Circ:function(t){return 1-Math.sqrt(1-t*t)},Elastic:function(t){return 0===t||1===t?t:-Math.pow(2,8*(t-1))*Math.sin((80*(t-1)-7.5)*Math.PI/15)},Back:function(t){return t*t*(3*t-2)},Bounce:function(t){for(var e,i=4;((e=Math.pow(2,--i))-1)/11>t;);return 1/Math.pow(4,3-i)-7.5625*Math.pow((3*e-2)/22-t,2)}}),t.each(e,function(e,i){t.easing["easeIn"+e]=i,t.easing["easeOut"+e]=function(t){return 1-i(1-t)},t.easing["easeInOut"+e]=function(t){return.5>t?i(2*t)/2:1-i(-2*t+2)/2}})}();var f=t.effects;t.effects.define("blind","hide",function(e,i){var s={up:["bottom","top"],vertical:["bottom","top"],down:["top","bottom"],left:["right","left"],horizontal:["right","left"],right:["left","right"]},n=t(this),o=e.direction||"up",a=n.cssClip(),r={clip:t.extend({},a)},h=t.effects.createPlaceholder(n);r.clip[s[o][0]]=r.clip[s[o][1]],"show"===e.mode&&(n.cssClip(r.clip),h&&h.css(t.effects.clipToBox(r)),r.clip=a),h&&h.animate(t.effects.clipToBox(r),e.duration,e.easing),n.animate(r,{queue:!1,duration:e.duration,easing:e.easing,complete:i})}),t.effects.define("bounce",function(e,i){var s,n,o,a=t(this),r=e.mode,h="hide"===r,l="show"===r,c=e.direction||"up",u=e.distance,d=e.times||5,p=2*d+(l||h?1:0),f=e.duration/p,g=e.easing,m="up"===c||"down"===c?"top":"left",_="up"===c||"left"===c,v=0,b=a.queue().length;for(t.effects.createPlaceholder(a),o=a.css(m),u||(u=a["top"===m?"outerHeight":"outerWidth"]()/3),l&&(n={opacity:1},n[m]=o,a.css("opacity",0).css(m,_?2*-u:2*u).animate(n,f,g)),h&&(u/=Math.pow(2,d-1)),n={},n[m]=o;d>v;v++)s={},s[m]=(_?"-=":"+=")+u,a.animate(s,f,g).animate(n,f,g),u=h?2*u:u/2;h&&(s={opacity:0},s[m]=(_?"-=":"+=")+u,a.animate(s,f,g)),a.queue(i),t.effects.unshift(a,b,p+1)}),t.effects.define("clip","hide",function(e,i){var s,n={},o=t(this),a=e.direction||"vertical",r="both"===a,h=r||"horizontal"===a,l=r||"vertical"===a;s=o.cssClip(),n.clip={top:l?(s.bottom-s.top)/2:s.top,right:h?(s.right-s.left)/2:s.right,bottom:l?(s.bottom-s.top)/2:s.bottom,left:h?(s.right-s.left)/2:s.left},t.effects.createPlaceholder(o),"show"===e.mode&&(o.cssClip(n.clip),n.clip=s),o.animate(n,{queue:!1,duration:e.duration,easing:e.easing,complete:i})}),t.effects.define("drop","hide",function(e,i){var s,n=t(this),o=e.mode,a="show"===o,r=e.direction||"left",h="up"===r||"down"===r?"top":"left",l="up"===r||"left"===r?"-=":"+=",c="+="===l?"-=":"+=",u={opacity:0};t.effects.createPlaceholder(n),s=e.distance||n["top"===h?"outerHeight":"outerWidth"](!0)/2,u[h]=l+s,a&&(n.css(u),u[h]=c+s,u.opacity=1),n.animate(u,{queue:!1,duration:e.duration,easing:e.easing,complete:i})}),t.effects.define("explode","hide",function(e,i){function s(){b.push(this),b.length===u*d&&n()}function n(){p.css({visibility:"visible"}),t(b).remove(),i()}var o,a,r,h,l,c,u=e.pieces?Math.round(Math.sqrt(e.pieces)):3,d=u,p=t(this),f=e.mode,g="show"===f,m=p.show().css("visibility","hidden").offset(),_=Math.ceil(p.outerWidth()/d),v=Math.ceil(p.outerHeight()/u),b=[];for(o=0;u>o;o++)for(h=m.top+o*v,c=o-(u-1)/2,a=0;d>a;a++)r=m.left+a*_,l=a-(d-1)/2,p.clone().appendTo("body").wrap("<div></div>").css({position:"absolute",visibility:"visible",left:-a*_,top:-o*v}).parent().addClass("ui-effects-explode").css({position:"absolute",overflow:"hidden",width:_,height:v,left:r+(g?l*_:0),top:h+(g?c*v:0),opacity:g?0:1}).animate({left:r+(g?0:l*_),top:h+(g?0:c*v),opacLine truncated
this.isMultiLine=o||!a&&this._isContentEditable(this.element),this.valueMethod=this.element[o||a?"val":"text"],this.isNewMenu=!0,this._addClass("ui-autocomplete-input"),this.element.attr("autocomplete","off"),this._on(this.element,{keydown:function(n){if(this.element.prop("readOnly"))return e=!0,s=!0,i=!0,void 0;e=!1,s=!1,i=!1;var o=t.ui.keyCode;switch(n.keyCode){case o.PAGE_UP:e=!0,this._move("previousPage",n);break;case o.PAGE_DOWN:e=!0,this._move("nextPage",n);break;case o.UP:e=!0,this._keyEvent("previous",n);break;case o.DOWN:e=!0,this._keyEvent("next",n);break;case o.ENTER:this.menu.active&&(e=!0,n.preventDefault(),this.menu.select(n));break;case o.TAB:this.menu.active&&this.menu.select(n);break;case o.ESCAPE:this.menu.element.is(":visible")&&(this.isMultiLine||this._value(this.term),this.close(n),n.preventDefault());break;default:i=!0,this._searchTimeout(n)}},keypress:function(s){if(e)return e=!1,(!this.isMultiLine||this.menu.element.is(":visible"))&&s.preventDefault(),void 0;if(!i){var n=t.ui.keyCode;switch(s.keyCode){case n.PAGE_UP:this._move("previousPage",s);break;case n.PAGE_DOWN:this._move("nextPage",s);break;case n.UP:this._keyEvent("previous",s);break;case n.DOWN:this._keyEvent("next",s)}}},input:function(t){return s?(s=!1,t.preventDefault(),void 0):(this._searchTimeout(t),void 0)},focus:function(){this.selectedItem=null,this.previous=this._value()},blur:function(t){return this.cancelBlur?(delete this.cancelBlur,void 0):(clearTimeout(this.searching),this.close(t),this._change(t),void 0)}}),this._initSource(),this.menu=t("<ul>").appendTo(this._appendTo()).menu({role:null}).hide().menu("instance"),this._addClass(this.menu.element,"ui-autocomplete","ui-front"),this._on(this.menu.element,{mousedown:function(e){e.preventDefault(),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur,this.element[0]!==t.ui.safeActiveElement(this.document[0])&&this.element.trigger("focus")})},menufocus:function(e,i){var s,n;return this.isNewMenu&&(this.isNewMenu=!1,e.originalEvent&&/^mouse/.test(e.originalEvent.type))?(this.menu.blur(),this.document.one("mousemove",function(){t(e.target).trigger(e.originalEvent)}),void 0):(n=i.item.data("ui-autocomplete-item"),!1!==this._trigger("focus",e,{item:n})&&e.originalEvent&&/^key/.test(e.originalEvent.type)&&this._value(n.value),s=i.item.attr("aria-label")||n.value,s&&t.trim(s).length&&(this.liveRegion.children().hide(),t("<div>").text(s).appendTo(this.liveRegion)),void 0)},menuselect:function(e,i){var s=i.item.data("ui-autocomplete-item"),n=this.previous;this.element[0]!==t.ui.safeActiveElement(this.document[0])&&(this.element.trigger("focus"),this.previous=n,this._delay(function(){this.previous=n,this.selectedItem=s})),!1!==this._trigger("select",e,{item:s})&&this._value(s.value),this.term=this._value(),this.close(e),this.selectedItem=s}}),this.liveRegion=t("<div>",{role:"status","aria-live":"assertive","aria-relevant":"additions"}).appendTo(this.document[0].body),this._addClass(this.liveRegion,null,"ui-helper-hidden-accessible"),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_destroy:function(){clearTimeout(this.searching),this.element.removeAttr("autocomplete"),this.menu.element.remove(),this.liveRegion.remove()},_setOption:function(t,e){this._super(t,e),"source"===t&&this._initSource(),"appendTo"===t&&this.menu.element.appendTo(this._appendTo()),"disabled"===t&&e&&this.xhr&&this.xhr.abort()},_isEventTargetInWidget:function(e){var i=this.menu.element[0];return e.target===this.element[0]||e.target===i||t.contains(i,e.target)},_closeOnClickOutside:function(t){this._isEventTargetInWidget(t)||this.close()},_appendTo:function(){var e=this.options.appendTo;return e&&(e=e.jquery||e.nodeType?t(e):this.document.find(e).eq(0)),e&&e[0]||(e=this.element.closest(".ui-front, dialog")),e.length||(e=this.document[0].body),e},_initSource:function(){var e,i,s=this;t.isArray(this.options.source)?(e=this.options.source,this.source=function(i,s){s(t.ui.autocomplete.filter(e,i.term))}):"string"==typeof this.options.source?(i=this.options.source,this.source=function(e,n){s.xhr&&s.xhr.abort(),s.xhr=t.ajax({url:i,data:e,dataType:"json",success:function(t){n(t)},error:function(){n([])}})}):this.source=this.options.source},_searchTimeout:function(t){clearTimeout(this.searching),this.searching=this._delay(function(){var e=this.term===this._value(),i=this.menu.element.is(":visible"),s=t.altKey||t.ctrlKey||t.metaKey||t.shiftKey;(!e||e&&!i&&!s)&&(this.selectedItem=null,this.search(null,t))},this.options.delay)},search:function(t,e){return t=null!=t?t:this._value(),this.term=this._value(),t.length<this.options.minLength?this.close(e):this._trigger("search",e)!==!1?this._search(t):void 0},_search:function(t){this.pending++,this._addClass("ui-autocomplete-loading"),this.cancelSearch=!1,this.source({term:t},this._response())},_response:function(){var e=++this.requestIndex;return t.proxy(function(t){e===this.requestIndex&&this.__response(t),this.pendinLine truncated
}},_updateDatepicker:function(e){this.maxRows=4,m=e,e.dpDiv.empty().append(this._generateHTML(e)),this._attachHandlers(e);var i,s=this._getNumberOfMonths(e),n=s[1],a=17,r=e.dpDiv.find("."+this._dayOverClass+" a");r.length>0&&o.apply(r.get(0)),e.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width(""),n>1&&e.dpDiv.addClass("ui-datepicker-multi-"+n).css("width",a*n+"em"),e.dpDiv[(1!==s[0]||1!==s[1]?"add":"remove")+"Class"]("ui-datepicker-multi"),e.dpDiv[(this._get(e,"isRTL")?"add":"remove")+"Class"]("ui-datepicker-rtl"),e===t.datepicker._curInst&&t.datepicker._datepickerShowing&&t.datepicker._shouldFocusInput(e)&&e.input.trigger("focus"),e.yearshtml&&(i=e.yearshtml,setTimeout(function(){i===e.yearshtml&&e.yearshtml&&e.dpDiv.find("select.ui-datepicker-year:first").replaceWith(e.yearshtml),i=e.yearshtml=null},0))},_shouldFocusInput:function(t){return t.input&&t.input.is(":visible")&&!t.input.is(":disabled")&&!t.input.is(":focus")},_checkOffset:function(e,i,s){var n=e.dpDiv.outerWidth(),o=e.dpDiv.outerHeight(),a=e.input?e.input.outerWidth():0,r=e.input?e.input.outerHeight():0,h=document.documentElement.clientWidth+(s?0:t(document).scrollLeft()),l=document.documentElement.clientHeight+(s?0:t(document).scrollTop());return i.left-=this._get(e,"isRTL")?n-a:0,i.left-=s&&i.left===e.input.offset().left?t(document).scrollLeft():0,i.top-=s&&i.top===e.input.offset().top+r?t(document).scrollTop():0,i.left-=Math.min(i.left,i.left+n>h&&h>n?Math.abs(i.left+n-h):0),i.top-=Math.min(i.top,i.top+o>l&&l>o?Math.abs(o+r):0),i},_findPos:function(e){for(var i,s=this._getInst(e),n=this._get(s,"isRTL");e&&("hidden"===e.type||1!==e.nodeType||t.expr.filters.hidden(e));)e=e[n?"previousSibling":"nextSibling"];return i=t(e).offset(),[i.left,i.top]},_hideDatepicker:function(e){var i,s,n,o,a=this._curInst;!a||e&&a!==t.data(e,"datepicker")||this._datepickerShowing&&(i=this._get(a,"showAnim"),s=this._get(a,"duration"),n=function(){t.datepicker._tidyDialog(a)},t.effects&&(t.effects.effect[i]||t.effects[i])?a.dpDiv.hide(i,t.datepicker._get(a,"showOptions"),s,n):a.dpDiv["slideDown"===i?"slideUp":"fadeIn"===i?"fadeOut":"hide"](i?s:null,n),i||n(),this._datepickerShowing=!1,o=this._get(a,"onClose"),o&&o.apply(a.input?a.input[0]:null,[a.input?a.input.val():"",a]),this._lastInput=null,this._inDialog&&(this._dialogInput.css({position:"absolute",left:"0",top:"-100px"}),t.blockUI&&(t.unblockUI(),t("body").append(this.dpDiv))),this._inDialog=!1)},_tidyDialog:function(t){t.dpDiv.removeClass(this._dialogClass).off(".ui-datepicker-calendar")},_checkExternalClick:function(e){if(t.datepicker._curInst){var i=t(e.target),s=t.datepicker._getInst(i[0]);(i[0].id!==t.datepicker._mainDivId&&0===i.parents("#"+t.datepicker._mainDivId).length&&!i.hasClass(t.datepicker.markerClassName)&&!i.closest("."+t.datepicker._triggerClass).length&&t.datepicker._datepickerShowing&&(!t.datepicker._inDialog||!t.blockUI)||i.hasClass(t.datepicker.markerClassName)&&t.datepicker._curInst!==s)&&t.datepicker._hideDatepicker()}},_adjustDate:function(e,i,s){var n=t(e),o=this._getInst(n[0]);this._isDisabledDatepicker(n[0])||(this._adjustInstDate(o,i+("M"===s?this._get(o,"showCurrentAtPos"):0),s),this._updateDatepicker(o))},_gotoToday:function(e){var i,s=t(e),n=this._getInst(s[0]);this._get(n,"gotoCurrent")&&n.currentDay?(n.selectedDay=n.currentDay,n.drawMonth=n.selectedMonth=n.currentMonth,n.drawYear=n.selectedYear=n.currentYear):(i=new Date,n.selectedDay=i.getDate(),n.drawMonth=n.selectedMonth=i.getMonth(),n.drawYear=n.selectedYear=i.getFullYear()),this._notifyChange(n),this._adjustDate(s)},_selectMonthYear:function(e,i,s){var n=t(e),o=this._getInst(n[0]);o["selected"+("M"===s?"Month":"Year")]=o["draw"+("M"===s?"Month":"Year")]=parseInt(i.options[i.selectedIndex].value,10),this._notifyChange(o),this._adjustDate(n)},_selectDay:function(e,i,s,n){var o,a=t(e);t(n).hasClass(this._unselectableClass)||this._isDisabledDatepicker(a[0])||(o=this._getInst(a[0]),o.selectedDay=o.currentDay=t("a",n).html(),o.selectedMonth=o.currentMonth=i,o.selectedYear=o.currentYear=s,this._selectDate(e,this._formatDate(o,o.currentDay,o.currentMonth,o.currentYear)))},_clearDate:function(e){var i=t(e);this._selectDate(i,"")},_selectDate:function(e,i){var s,n=t(e),o=this._getInst(n[0]);i=null!=i?i:this._formatDate(o),o.input&&o.input.val(i),this._updateAlternate(o),s=this._get(o,"onSelect"),s?s.apply(o.input?o.input[0]:null,[i,o]):o.input&&o.input.trigger("change"),o.inline?this._updateDatepicker(o):(this._hideDatepicker(),this._lastInput=o.input[0],"object"!=typeof o.input[0]&&o.input.trigger("focus"),this._lastInput=null)},_updateAlternate:function(e){var i,s,n,o=this._get(e,"altField");o&&(i=this._get(e,"altFormat")||this._get(e,"dateFormat"),s=this._getDate(e),n=this.formatDate(i,s,this._getFormatConfig(e)),t(o).val(n))},noWeekends:function(t){var e=t.getDay();return[e>0&&6>e,""]},iso8601Week:function(t){var e,i=new Date(t.getTime());return i.setDate(i.getDate()+4-(i.getDay()||7))Line truncated
},_cacheMargins:function(){this.margins={left:parseInt(this.element.css("marginLeft"),10)||0,top:parseInt(this.element.css("marginTop"),10)||0,right:parseInt(this.element.css("marginRight"),10)||0,bottom:parseInt(this.element.css("marginBottom"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var e,i,s,n=this.options,o=this.document[0];return this.relativeContainer=null,n.containment?"window"===n.containment?(this.containment=[t(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,t(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,t(window).scrollLeft()+t(window).width()-this.helperProportions.width-this.margins.left,t(window).scrollTop()+(t(window).height()||o.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top],void 0):"document"===n.containment?(this.containment=[0,0,t(o).width()-this.helperProportions.width-this.margins.left,(t(o).height()||o.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top],void 0):n.containment.constructor===Array?(this.containment=n.containment,void 0):("parent"===n.containment&&(n.containment=this.helper[0].parentNode),i=t(n.containment),s=i[0],s&&(e=/(scroll|auto)/.test(i.css("overflow")),this.containment=[(parseInt(i.css("borderLeftWidth"),10)||0)+(parseInt(i.css("paddingLeft"),10)||0),(parseInt(i.css("borderTopWidth"),10)||0)+(parseInt(i.css("paddingTop"),10)||0),(e?Math.max(s.scrollWidth,s.offsetWidth):s.offsetWidth)-(parseInt(i.css("borderRightWidth"),10)||0)-(parseInt(i.css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(e?Math.max(s.scrollHeight,s.offsetHeight):s.offsetHeight)-(parseInt(i.css("borderBottomWidth"),10)||0)-(parseInt(i.css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom],this.relativeContainer=i),void 0):(this.containment=null,void 0)},_convertPositionTo:function(t,e){e||(e=this.position);var i="absolute"===t?1:-1,s=this._isRootNode(this.scrollParent[0]);return{top:e.top+this.offset.relative.top*i+this.offset.parent.top*i-("fixed"===this.cssPosition?-this.offset.scroll.top:s?0:this.offset.scroll.top)*i,left:e.left+this.offset.relative.left*i+this.offset.parent.left*i-("fixed"===this.cssPosition?-this.offset.scroll.left:s?0:this.offset.scroll.left)*i}},_generatePosition:function(t,e){var i,s,n,o,a=this.options,r=this._isRootNode(this.scrollParent[0]),h=t.pageX,l=t.pageY;return r&&this.offset.scroll||(this.offset.scroll={top:this.scrollParent.scrollTop(),left:this.scrollParent.scrollLeft()}),e&&(this.containment&&(this.relativeContainer?(s=this.relativeContainer.offset(),i=[this.containment[0]+s.left,this.containment[1]+s.top,this.containment[2]+s.left,this.containment[3]+s.top]):i=this.containment,t.pageX-this.offset.click.left<i[0]&&(h=i[0]+this.offset.click.left),t.pageY-this.offset.click.top<i[1]&&(l=i[1]+this.offset.click.top),t.pageX-this.offset.click.left>i[2]&&(h=i[2]+this.offset.click.left),t.pageY-this.offset.click.top>i[3]&&(l=i[3]+this.offset.click.top)),a.grid&&(n=a.grid[1]?this.originalPageY+Math.round((l-this.originalPageY)/a.grid[1])*a.grid[1]:this.originalPageY,l=i?n-this.offset.click.top>=i[1]||n-this.offset.click.top>i[3]?n:n-this.offset.click.top>=i[1]?n-a.grid[1]:n+a.grid[1]:n,o=a.grid[0]?this.originalPageX+Math.round((h-this.originalPageX)/a.grid[0])*a.grid[0]:this.originalPageX,h=i?o-this.offset.click.left>=i[0]||o-this.offset.click.left>i[2]?o:o-this.offset.click.left>=i[0]?o-a.grid[0]:o+a.grid[0]:o),"y"===a.axis&&(h=this.originalPageX),"x"===a.axis&&(l=this.originalPageY)),{top:l-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.offset.scroll.top:r?0:this.offset.scroll.top),left:h-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.offset.scroll.left:r?0:this.offset.scroll.left)}},_clear:function(){this._removeClass(this.helper,"ui-draggable-dragging"),this.helper[0]===this.element[0]||this.cancelHelperRemoval||this.helper.remove(),this.helper=null,this.cancelHelperRemoval=!1,this.destroyOnClear&&this.destroy()},_trigger:function(e,i,s){return s=s||this._uiHash(),t.ui.plugin.call(this,e,[i,s,this],!0),/^(drag|start|stop)/.test(e)&&(this.positionAbs=this._convertPositionTo("absolute"),s.offset=this.positionAbs),t.Widget.prototype._trigger.call(this,e,i,s)},plugins:{},_uiHash:function(){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}}),t.ui.plugin.add("draggable","connectToSortable",{start:function(e,i,s){var n=t.extend({},i,{item:s.element});s.sortables=[],t(s.options.connectToSortable).each(function(){var i=t(this).sortable("instance");i&&!i.options.disabled&&(s.sortables.push(i),i.refreshPositions(),i._trigger("activate",e,n))})},stop:function(e,i,s){var n=t.extend({},i,{item:s.eleLine truncated
},disable:t.noop,enable:t.noop,close:function(e){var i=this;this._isOpen&&this._trigger("beforeClose",e)!==!1&&(this._isOpen=!1,this._focusedElement=null,this._destroyOverlay(),this._untrackInstance(),this.opener.filter(":focusable").trigger("focus").length||t.ui.safeBlur(t.ui.safeActiveElement(this.document[0])),this._hide(this.uiDialog,this.options.hide,function(){i._trigger("close",e)}))},isOpen:function(){return this._isOpen},moveToTop:function(){this._moveToTop()},_moveToTop:function(e,i){var s=!1,n=this.uiDialog.siblings(".ui-front:visible").map(function(){return+t(this).css("z-index")}).get(),o=Math.max.apply(null,n);return o>=+this.uiDialog.css("z-index")&&(this.uiDialog.css("z-index",o+1),s=!0),s&&!i&&this._trigger("focus",e),s},open:function(){var e=this;return this._isOpen?(this._moveToTop()&&this._focusTabbable(),void 0):(this._isOpen=!0,this.opener=t(t.ui.safeActiveElement(this.document[0])),this._size(),this._position(),this._createOverlay(),this._moveToTop(null,!0),this.overlay&&this.overlay.css("z-index",this.uiDialog.css("z-index")-1),this._show(this.uiDialog,this.options.show,function(){e._focusTabbable(),e._trigger("focus")}),this._makeFocusTarget(),this._trigger("open"),void 0)},_focusTabbable:function(){var t=this._focusedElement;t||(t=this.element.find("[autofocus]")),t.length||(t=this.element.find(":tabbable")),t.length||(t=this.uiDialogButtonPane.find(":tabbable")),t.length||(t=this.uiDialogTitlebarClose.filter(":tabbable")),t.length||(t=this.uiDialog),t.eq(0).trigger("focus")},_keepFocus:function(e){function i(){var e=t.ui.safeActiveElement(this.document[0]),i=this.uiDialog[0]===e||t.contains(this.uiDialog[0],e);i||this._focusTabbable()}e.preventDefault(),i.call(this),this._delay(i)},_createWrapper:function(){this.uiDialog=t("<div>").hide().attr({tabIndex:-1,role:"dialog"}).appendTo(this._appendTo()),this._addClass(this.uiDialog,"ui-dialog","ui-widget ui-widget-content ui-front"),this._on(this.uiDialog,{keydown:function(e){if(this.options.closeOnEscape&&!e.isDefaultPrevented()&&e.keyCode&&e.keyCode===t.ui.keyCode.ESCAPE)return e.preventDefault(),this.close(e),void 0;if(e.keyCode===t.ui.keyCode.TAB&&!e.isDefaultPrevented()){var i=this.uiDialog.find(":tabbable"),s=i.filter(":first"),n=i.filter(":last");e.target!==n[0]&&e.target!==this.uiDialog[0]||e.shiftKey?e.target!==s[0]&&e.target!==this.uiDialog[0]||!e.shiftKey||(this._delay(function(){n.trigger("focus")}),e.preventDefault()):(this._delay(function(){s.trigger("focus")}),e.preventDefault())}},mousedown:function(t){this._moveToTop(t)&&this._focusTabbable()}}),this.element.find("[aria-describedby]").length||this.uiDialog.attr({"aria-describedby":this.element.uniqueId().attr("id")})},_createTitlebar:function(){var e;this.uiDialogTitlebar=t("<div>"),this._addClass(this.uiDialogTitlebar,"ui-dialog-titlebar","ui-widget-header ui-helper-clearfix"),this._on(this.uiDialogTitlebar,{mousedown:function(e){t(e.target).closest(".ui-dialog-titlebar-close")||this.uiDialog.trigger("focus")}}),this.uiDialogTitlebarClose=t("<button type='button'></button>").button({label:t("<a>").text(this.options.closeText).html(),icon:"ui-icon-closethick",showLabel:!1}).appendTo(this.uiDialogTitlebar),this._addClass(this.uiDialogTitlebarClose,"ui-dialog-titlebar-close"),this._on(this.uiDialogTitlebarClose,{click:function(t){t.preventDefault(),this.close(t)}}),e=t("<span>").uniqueId().prependTo(this.uiDialogTitlebar),this._addClass(e,"ui-dialog-title"),this._title(e),this.uiDialogTitlebar.prependTo(this.uiDialog),this.uiDialog.attr({"aria-labelledby":e.attr("id")})},_title:function(t){this.options.title?t.text(this.options.title):t.html("&#160;")},_createButtonPane:function(){this.uiDialogButtonPane=t("<div>"),this._addClass(this.uiDialogButtonPane,"ui-dialog-buttonpane","ui-widget-content ui-helper-clearfix"),this.uiButtonSet=t("<div>").appendTo(this.uiDialogButtonPane),this._addClass(this.uiButtonSet,"ui-dialog-buttonset"),this._createButtons()},_createButtons:function(){var e=this,i=this.options.buttons;return this.uiDialogButtonPane.remove(),this.uiButtonSet.empty(),t.isEmptyObject(i)||t.isArray(i)&&!i.length?(this._removeClass(this.uiDialog,"ui-dialog-buttons"),void 0):(t.each(i,function(i,s){var n,o;s=t.isFunction(s)?{click:s,text:i}:s,s=t.extend({type:"button"},s),n=s.click,o={icon:s.icon,iconPosition:s.iconPosition,showLabel:s.showLabel,icons:s.icons,text:s.text},delete s.click,delete s.icon,delete s.iconPosition,delete s.showLabel,delete s.icons,"boolean"==typeof s.text&&delete s.text,t("<button></button>",s).button(o).appendTo(e.uiButtonSet).on("click",function(){n.apply(e.element[0],arguments)})}),this._addClass(this.uiDialog,"ui-dialog-buttons"),this.uiDialogButtonPane.appendTo(this.uiDialog),void 0)},_makeDraggable:function(){function e(t){return{position:t.position,offset:t.offset}}var i=this,s=this.options;this.uiDialog.draggable({cancel:".ui-dialog-content, .ui-dialog-titlebar-close",handle:".ui-dialog-titlebar",containment:"document",start:functionLine truncated
},_refresh:function(){this._createRange(),this._createHandles(),this._setupEvents(),this._refreshValue()},_createHandles:function(){var e,i,s=this.options,n=this.element.find(".ui-slider-handle"),o="<span tabindex='0'></span>",a=[];for(i=s.values&&s.values.length||1,n.length>i&&(n.slice(i).remove(),n=n.slice(0,i)),e=n.length;i>e;e++)a.push(o);this.handles=n.add(t(a.join("")).appendTo(this.element)),this._addClass(this.handles,"ui-slider-handle","ui-state-default"),this.handle=this.handles.eq(0),this.handles.each(function(e){t(this).data("ui-slider-handle-index",e).attr("tabIndex",0)})},_createRange:function(){var e=this.options;e.range?(e.range===!0&&(e.values?e.values.length&&2!==e.values.length?e.values=[e.values[0],e.values[0]]:t.isArray(e.values)&&(e.values=e.values.slice(0)):e.values=[this._valueMin(),this._valueMin()]),this.range&&this.range.length?(this._removeClass(this.range,"ui-slider-range-min ui-slider-range-max"),this.range.css({left:"",bottom:""})):(this.range=t("<div>").appendTo(this.element),this._addClass(this.range,"ui-slider-range")),("min"===e.range||"max"===e.range)&&this._addClass(this.range,"ui-slider-range-"+e.range)):(this.range&&this.range.remove(),this.range=null)},_setupEvents:function(){this._off(this.handles),this._on(this.handles,this._handleEvents),this._hoverable(this.handles),this._focusable(this.handles)},_destroy:function(){this.handles.remove(),this.range&&this.range.remove(),this._mouseDestroy()},_mouseCapture:function(e){var i,s,n,o,a,r,h,l,c=this,u=this.options;return u.disabled?!1:(this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()},this.elementOffset=this.element.offset(),i={x:e.pageX,y:e.pageY},s=this._normValueFromMouse(i),n=this._valueMax()-this._valueMin()+1,this.handles.each(function(e){var i=Math.abs(s-c.values(e));(n>i||n===i&&(e===c._lastChangedValue||c.values(e)===u.min))&&(n=i,o=t(this),a=e)}),r=this._start(e,a),r===!1?!1:(this._mouseSliding=!0,this._handleIndex=a,this._addClass(o,null,"ui-state-active"),o.trigger("focus"),h=o.offset(),l=!t(e.target).parents().addBack().is(".ui-slider-handle"),this._clickOffset=l?{left:0,top:0}:{left:e.pageX-h.left-o.width()/2,top:e.pageY-h.top-o.height()/2-(parseInt(o.css("borderTopWidth"),10)||0)-(parseInt(o.css("borderBottomWidth"),10)||0)+(parseInt(o.css("marginTop"),10)||0)},this.handles.hasClass("ui-state-hover")||this._slide(e,a,s),this._animateOff=!0,!0))},_mouseStart:function(){return!0},_mouseDrag:function(t){var e={x:t.pageX,y:t.pageY},i=this._normValueFromMouse(e);return this._slide(t,this._handleIndex,i),!1},_mouseStop:function(t){return this._removeClass(this.handles,null,"ui-state-active"),this._mouseSliding=!1,this._stop(t,this._handleIndex),this._change(t,this._handleIndex),this._handleIndex=null,this._clickOffset=null,this._animateOff=!1,!1},_detectOrientation:function(){this.orientation="vertical"===this.options.orientation?"vertical":"horizontal"},_normValueFromMouse:function(t){var e,i,s,n,o;return"horizontal"===this.orientation?(e=this.elementSize.width,i=t.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)):(e=this.elementSize.height,i=t.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)),s=i/e,s>1&&(s=1),0>s&&(s=0),"vertical"===this.orientation&&(s=1-s),n=this._valueMax()-this._valueMin(),o=this._valueMin()+s*n,this._trimAlignValue(o)},_uiHash:function(t,e,i){var s={handle:this.handles[t],handleIndex:t,value:void 0!==e?e:this.value()};return this._hasMultipleValues()&&(s.value=void 0!==e?e:this.values(t),s.values=i||this.values()),s},_hasMultipleValues:function(){return this.options.values&&this.options.values.length},_start:function(t,e){return this._trigger("start",t,this._uiHash(e))},_slide:function(t,e,i){var s,n,o=this.value(),a=this.values();this._hasMultipleValues()&&(n=this.values(e?0:1),o=this.values(e),2===this.options.values.length&&this.options.range===!0&&(i=0===e?Math.min(n,i):Math.max(n,i)),a[e]=i),i!==o&&(s=this._trigger("slide",t,this._uiHash(e,i,a)),s!==!1&&(this._hasMultipleValues()?this.values(e,i):this.value(i)))},_stop:function(t,e){this._trigger("stop",t,this._uiHash(e))},_change:function(t,e){this._keySliding||this._mouseSliding||(this._lastChangedValue=e,this._trigger("change",t,this._uiHash(e)))},value:function(t){return arguments.length?(this.options.value=this._trimAlignValue(t),this._refreshValue(),this._change(null,0),void 0):this._value()},values:function(e,i){var s,n,o;if(arguments.length>1)return this.options.values[e]=this._trimAlignValue(i),this._refreshValue(),this._change(null,e),void 0;if(!arguments.length)return this._values();if(!t.isArray(arguments[0]))return this._hasMultipleValues()?this._values(e):this.value();for(s=this.options.values,n=arguments[0],o=0;s.length>o;o+=1)s[o]=this._trimAlignValue(n[o]),this._change(null,o);this._refreshValue()},_setOption:function(e,i){var s,n=0;switch("range"===e&&this.options.range===!0&&("min"===i?(this.options.value=this._values(0),this.options.valuLine truncated
this._delay(function(){n===this.counter&&this.refreshPositions(!s)})},_clear:function(t,e){function i(t,e,i){return function(s){i._trigger(t,s,e._uiHash(e))}}this.reverting=!1;var s,n=[];if(!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem),this._noFinalSort=null,this.helper[0]===this.currentItem[0]){for(s in this._storedCSS)("auto"===this._storedCSS[s]||"static"===this._storedCSS[s])&&(this._storedCSS[s]="");this.currentItem.css(this._storedCSS),this._removeClass(this.currentItem,"ui-sortable-helper")}else this.currentItem.show();for(this.fromOutside&&!e&&n.push(function(t){this._trigger("receive",t,this._uiHash(this.fromOutside))}),!this.fromOutside&&this.domPosition.prev===this.currentItem.prev().not(".ui-sortable-helper")[0]&&this.domPosition.parent===this.currentItem.parent()[0]||e||n.push(function(t){this._trigger("update",t,this._uiHash())}),this!==this.currentContainer&&(e||(n.push(function(t){this._trigger("remove",t,this._uiHash())}),n.push(function(t){return function(e){t._trigger("receive",e,this._uiHash(this))}}.call(this,this.currentContainer)),n.push(function(t){return function(e){t._trigger("update",e,this._uiHash(this))}}.call(this,this.currentContainer)))),s=this.containers.length-1;s>=0;s--)e||n.push(i("deactivate",this,this.containers[s])),this.containers[s].containerCache.over&&(n.push(i("out",this,this.containers[s])),this.containers[s].containerCache.over=0);if(this.storedCursor&&(this.document.find("body").css("cursor",this.storedCursor),this.storedStylesheet.remove()),this._storedOpacity&&this.helper.css("opacity",this._storedOpacity),this._storedZIndex&&this.helper.css("zIndex","auto"===this._storedZIndex?"":this._storedZIndex),this.dragging=!1,e||this._trigger("beforeStop",t,this._uiHash()),this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.cancelHelperRemoval||(this.helper[0]!==this.currentItem[0]&&this.helper.remove(),this.helper=null),!e){for(s=0;n.length>s;s++)n[s].call(this,t);this._trigger("stop",t,this._uiHash())}return this.fromOutside=!1,!this.cancelHelperRemoval},_trigger:function(){t.Widget.prototype._trigger.apply(this,arguments)===!1&&this.cancel()},_uiHash:function(e){var i=e||this;return{helper:i.helper,placeholder:i.placeholder||t([]),position:i.position,originalPosition:i.originalPosition,offset:i.positionAbs,item:i.currentItem,sender:e?e.element:null}}}),t.widget("ui.spinner",{version:"1.12.1",defaultElement:"<input>",widgetEventPrefix:"spin",options:{classes:{"ui-spinner":"ui-corner-all","ui-spinner-down":"ui-corner-br","ui-spinner-up":"ui-corner-tr"},culture:null,icons:{down:"ui-icon-triangle-1-s",up:"ui-icon-triangle-1-n"},incremental:!0,max:null,min:null,numberFormat:null,page:10,step:1,change:null,spin:null,start:null,stop:null},_create:function(){this._setOption("max",this.options.max),this._setOption("min",this.options.min),this._setOption("step",this.options.step),""!==this.value()&&this._value(this.element.val(),!0),this._draw(),this._on(this._events),this._refresh(),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_getCreateOptions:function(){var e=this._super(),i=this.element;return t.each(["min","max","step"],function(t,s){var n=i.attr(s);null!=n&&n.length&&(e[s]=n)}),e},_events:{keydown:function(t){this._start(t)&&this._keydown(t)&&t.preventDefault()},keyup:"_stop",focus:function(){this.previous=this.element.val()},blur:function(t){return this.cancelBlur?(delete this.cancelBlur,void 0):(this._stop(),this._refresh(),this.previous!==this.element.val()&&this._trigger("change",t),void 0)},mousewheel:function(t,e){if(e){if(!this.spinning&&!this._start(t))return!1;this._spin((e>0?1:-1)*this.options.step,t),clearTimeout(this.mousewheelTimer),this.mousewheelTimer=this._delay(function(){this.spinning&&this._stop(t)},100),t.preventDefault()}},"mousedown .ui-spinner-button":function(e){function i(){var e=this.element[0]===t.ui.safeActiveElement(this.document[0]);e||(this.element.trigger("focus"),this.previous=s,this._delay(function(){this.previous=s}))}var s;s=this.element[0]===t.ui.safeActiveElement(this.document[0])?this.previous:this.element.val(),e.preventDefault(),i.call(this),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur,i.call(this)}),this._start(e)!==!1&&this._repeat(null,t(e.currentTarget).hasClass("ui-spinner-up")?1:-1,e)},"mouseup .ui-spinner-button":"_stop","mouseenter .ui-spinner-button":function(e){return t(e.currentTarget).hasClass("ui-state-active")?this._start(e)===!1?!1:(this._repeat(null,t(e.currentTarget).hasClass("ui-spinner-up")?1:-1,e),void 0):void 0},"mouseleave .ui-spinner-button":"_stop"},_enhance:function(){this.uiSpinner=this.element.attr("autocomplete","off").wrap("<span>").parent().append("<a></a><a></a>")},_draw:function(){this._enhance(),this._addClass(this.uiSpinner,"ui-spinner","ui-widget ui-widget-content"),this._addClass("ui-spinner-input"),this.element.attr("role","spinbutton"),this.buttons=this.uiSpinnLine truncated
+2
View File
@@ -0,0 +1,2 @@
/*! jQuery v3.4.1 | (c) JS Foundation and other contributors | jquery.org/license */
!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(C,e){"use strict";var t=[],E=C.document,r=Object.getPrototypeOf,s=t.slice,g=t.concat,u=t.push,i=t.indexOf,n={},o=n.toString,v=n.hasOwnProperty,a=v.toString,l=a.call(Object),y={},m=function(e){return"function"==typeof e&&"number"!=typeof e.nodeType},x=function(e){return null!=e&&e===e.window},c={type:!0,src:!0,nonce:!0,noModule:!0};function b(e,t,n){var r,i,o=(n=n||E).createElement("script");if(o.text=e,t)for(r in c)(i=t[r]||t.getAttribute&&t.getAttribute(r))&&o.setAttribute(r,i);n.head.appendChild(o).parentNode.removeChild(o)}function w(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?n[o.call(e)]||"object":typeof e}var f="3.4.1",k=function(e,t){return new k.fn.init(e,t)},p=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;function d(e){var t=!!e&&"length"in e&&e.length,n=w(e);return!m(e)&&!x(e)&&("array"===n||0===t||"number"==typeof t&&0<t&&t-1 in e)}k.fn=k.prototype={jquery:f,constructor:k,length:0,toArray:function(){return s.call(this)},get:function(e){return null==e?s.call(this):e<0?this[e+this.length]:this[e]},pushStack:function(e){var t=k.merge(this.constructor(),e);return t.prevObject=this,t},each:function(e){return k.each(this,e)},map:function(n){return this.pushStack(k.map(this,function(e,t){return n.call(e,t,e)}))},slice:function(){return this.pushStack(s.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(e<0?t:0);return this.pushStack(0<=n&&n<t?[this[n]]:[])},end:function(){return this.prevObject||this.constructor()},push:u,sort:t.sort,splice:t.splice},k.extend=k.fn.extend=function(){var e,t,n,r,i,o,a=arguments[0]||{},s=1,u=arguments.length,l=!1;for("boolean"==typeof a&&(l=a,a=arguments[s]||{},s++),"object"==typeof a||m(a)||(a={}),s===u&&(a=this,s--);s<u;s++)if(null!=(e=arguments[s]))for(t in e)r=e[t],"__proto__"!==t&&a!==r&&(l&&r&&(k.isPlainObject(r)||(i=Array.isArray(r)))?(n=a[t],o=i&&!Array.isArray(n)?[]:i||k.isPlainObject(n)?n:{},i=!1,a[t]=k.extend(l,o,r)):void 0!==r&&(a[t]=r));return a},k.extend({expando:"jQuery"+(f+Math.random()).replace(/\D/g,""),isReady:!0,error:function(e){throw new Error(e)},noop:function(){},isPlainObject:function(e){var t,n;return!(!e||"[object Object]"!==o.call(e))&&(!(t=r(e))||"function"==typeof(n=v.call(t,"constructor")&&t.constructor)&&a.call(n)===l)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},globalEval:function(e,t){b(e,{nonce:t&&t.nonce})},each:function(e,t){var n,r=0;if(d(e)){for(n=e.length;r<n;r++)if(!1===t.call(e[r],r,e[r]))break}else for(r in e)if(!1===t.call(e[r],r,e[r]))break;return e},trim:function(e){return null==e?"":(e+"").replace(p,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(d(Object(e))?k.merge(n,"string"==typeof e?[e]:e):u.call(n,e)),n},inArray:function(e,t,n){return null==t?-1:i.call(t,e,n)},merge:function(e,t){for(var n=+t.length,r=0,i=e.length;r<n;r++)e[i++]=t[r];return e.length=i,e},grep:function(e,t,n){for(var r=[],i=0,o=e.length,a=!n;i<o;i++)!t(e[i],i)!==a&&r.push(e[i]);return r},map:function(e,t,n){var r,i,o=0,a=[];if(d(e))for(r=e.length;o<r;o++)null!=(i=t(e[o],o,n))&&a.push(i);else for(o in e)null!=(i=t(e[o],o,n))&&a.push(i);return g.apply([],a)},guid:1,support:y}),"function"==typeof Symbol&&(k.fn[Symbol.iterator]=t[Symbol.iterator]),k.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(e,t){n["[object "+t+"]"]=t.toLowerCase()});var h=function(n){var e,d,b,o,i,h,f,g,w,u,l,T,C,a,E,v,s,c,y,k="sizzle"+1*new Date,m=n.document,S=0,r=0,p=ue(),x=ue(),N=ue(),A=ue(),D=function(e,t){return e===t&&(l=!0),0},j={}.hasOwnProperty,t=[],q=t.pop,L=t.push,H=t.push,O=t.slice,P=function(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1},R="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",I="(?:\\\\.|[\\w-]|[^\0-\\xa0])+",W="\\["+M+"*("+I+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+I+"))|)"+M+"*\\]",$=":("+I+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+W+")*)|.*)\\)|)",F=new RegExp(M+"+","g"),B=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),_=new RegExp("^"+M+"*,"+M+"*"),z=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),U=new RegExp(M+"|>"),X=new RegExp($),V=new RegExp("^"+I+"$"),G={ID:new RegExp("^#("+I+")"),CLASS:new RegExp("^\\.("+I+")"),TAG:new RegExp("^("+I+"|[*])"),ATTR:new RegExp("^"+W),PSEUDO:new RegExp("^"+$),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+R+")$","i"),needsContext:new RegExp("^"+Line truncated
+98
View File
@@ -0,0 +1,98 @@
{% extends 'layout.html' %}
{% block content %}
<div id="crm-parent" class="container-fluid">
<div class="container-fluid crm-holder">
<div id="myProgress">
<div id="progressBar"></div>
</div>
<div id="trial_count" style="text-align: center; margin-bottom: 2%;">
<span style="color: white; font-size: 2em;">
<span id="current_trial">{{ current_trial }}</span>/<span
id="total_trials">{{ total_trials }}</span></span>
</div>
<div class="row">
<div id="woman_holding_dog"><img src="{{url_for('static', filename='images/woman+dog.jpg')}}" alt=""></div>
<div class="col-md">
<table id="crm-grid">
<tr>
<td class="crm-name" style="color: green">
{% if lang == 'nl' %}Groen{% elif lang == 'en' %}Green{% endif %}</th>
{% for i in range(1,10) %}
{% if i != 7 %}
<td class="crm-cell crm-green"><button onclick="submitAnswer('green', {{ i }})"
class="crm-button crm-green">{{ i }}</button></td>
{% endif %}
{% endfor %}
<td class="crm-name" style="color: green">
{% if lang == 'nl' %}Groen{% elif lang == 'en' %}Green{% endif %}</td>
</tr>
<tr>
<td class="crm-name" style="color: blue">
{% if lang == 'nl' %}Blauw{% elif lang == 'en' %}Blue{% endif %}</td>
{% for i in range(1,10) %}
{% if i != 7 %}
<td class="crm-cell crm-blue"><button onclick="submitAnswer('blue', {{ i }})"
class="crm-button crm-blue">{{i}}</button></td>
{%endif%}
{%endfor%}
<td class="crm-name" style="color: blue">
{% if lang == 'nl' %}Blauw{% elif lang == 'en' %}Blue{% endif %}</td>
</tr>
<tr>
<td class="crm-name" style="color: red">
{% if lang == 'nl' %}Rood{% elif lang == 'en' %}Red{% endif %}</th>
{% for i in range(1,10) %}
{% if i != 7 %}
<td class="crm-cell crm-red"><button onclick="submitAnswer('red', {{ i }})"
class="crm-button crm-red">{{ i }}</button></td>
{% endif %}
{% endfor %}
<td class="crm-name" style="color: red">
{% if lang == 'nl' %}Rood{% elif lang == 'en' %}Red{% endif %}</td>
</tr>
<tr>
<td class="crm-name" style="color: pink">
{% if lang == 'nl' %}Rose{% elif lang == 'en' %}pink{% endif %}</th>
{% for i in range(1,10) %}
{% if i != 7 %}
<td class="crm-cell crm-pink"><button onclick="submitAnswer('pink', {{ i }})"
class="crm-button crm-pink">{{ i }}</button></td>
{% endif %}
{% endfor %}
<td class="crm-name" style="color: pink">
{% if lang == 'nl' %}Rose{% elif lang == 'en' %}pink{% endif %}</td>
</tr>
<tr>
<td class="crm-name" style="color: white">
{% if lang == 'nl' %}Wit{% elif lang == 'en' %}White{% endif %}</th>
{% for i in range(1,10) %}
{% if i != 7 %}
<td class="crm-cell crm-white"><button onclick="submitAnswer('white', {{ i }})"
class="crm-button crm-white">{{i}}</button></td>
{% endif %}
{% endfor %}
<td class="crm-name" style="color: white">
{% if lang == 'nl' %}Wit{% elif lang == 'en' %}White{% endif %}</td>
</tr>
<tr>
<td class="crm-name" style="color: grey">
{% if lang == 'nl' %}Zwart{% elif lang == 'en' %}Black{% endif %}</th>
{% for i in range(1,10) %}
{% if i != 7 %}
<td class="crm-cell crm-black"><button onclick="submitAnswer('black', {{ i }})"
class="crm-button crm-black">{{ i }}</button></td>
{% endif %}
{% endfor %}
<td class="crm-name" style="color: grey">
{% if lang == 'nl' %}Zwart{% elif lang == 'en' %}Black{% endif %}</td>
</tr>
</table>
</div>
</div>
</div>
</div>
{% endblock %}
+279
View File
@@ -0,0 +1,279 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="{{url_for('static', filename='css/bootstrap.min.css')}}">
<link rel="stylesheet" href="{{url_for('static', filename='css/styles.css')}}">
<link rel="stylesheet" href="{{url_for('static', filename='css/jquery-ui.min.css')}}">
<script type="text/javascript" src="{{url_for('static', filename='js/jquery.min.js')}}"></script>
<!-- <script src="https://code.jquery.com/jquery-1.12.4.js"></script> -->
<script src="{{url_for('static', filename='js/jquery-ui.min.js')}}"></script>
<title>{% block title %}{% endblock %}</title>
</head>
<script type="text/javascript">
function submitAnswer(colour, number) {
console.log(colour)
console.log(number)
var jqXHR = $.ajax({
type: "POST",
url: "/crm_answer",
async: true,
data: {
colour: colour,
number: number
},
success: function (response) {
if (response.trials.current_trial > response.trials.total_trials) {
response.trials.current_trial = response.trials.total_trials;
};
$('#current_trial').text(response.trials.current_trial)
$('#total_trials').text(response.trials.total_trials)
// if (response.trials.current_trial == 4) {
// var timer = 10;
// setTimeout(checkBreak, 1000);
// console.log("Running break")
// function checkBreak() {
// var b = window.confirm("You can now take a break.")
// if (b == true) {
// return
// } else {
// return
// }
// timer--;
// if (timer >= 0) setTimeout(checkBreak, 1000);
// }
// };
$(function () {
$('#progressBar').progressbar({
value: (response.trials.current_trial / response.trials
.total_trials) * 100
})
})
},
error: function (error) {
console.log(error)
}
});
};
$(function () {
var dialog, form,
participant = $("#p_id"),
phase = $("#phase"),
language = $("#lang"),
game = ""
parent = this
allFields = $([]).add(participant).add(phase).add(language),
tips = $(".validateTips");
function updateTips(t) {
tips
.text(t)
.addClass("ui-state-highlight");
setTimeout(function () {
tips.removeClass("ui-state-highlight", 1500);
}, 500);
}
function getGame(target) {
parent.game = target.dataset.game
}
function checkPID(o, n, max) {
x = o.val().substring(0, 3)
if (o.val().length > max) {
o.addClass("ui-state-error");
updateTips("Length of " + n + "must be " +
max + " characters long.");
return false;
} else if (o.val() != "") {
switch (o.val().startsWith(x)) {
case x == "NHA":
return true;
case x == "NHK":
return true;
case x == "CIA":
return true;
case x == "CIK":
return true;
case x == "":
o.addClass("ui-state-error");
updateTips("Participant ID must start either with NHA, NHK, CIA, or CIK. ");
default:
o.addClass("ui-state-error");
updateTips("Participant ID must start either with NHA, NHK, CIA, or CIK. ");
}
} else {
return false;
}
}
function checkPhase(o) {
x = o.val().toLowerCase();
switch (x) {
case "training":
return true;
case "test":
return true;
default:
o.addClass("ui-state-error");
updateTips("Phase must be either 'training' or 'test'.");
return false;
}
}
function addparticipant() {
var valid = true;
allFields.removeClass("ui-state-error");
valid = valid &&
checkPID(participant, "ID", 6);
valid = valid && checkPhase(phase);
// valid = valid &&
// checkLanguage(language);
if (valid) {
$.ajax({
type: "POST",
url: "/check_participant",
async: true,
data: {
game: parent.game,
phase: phase.val(),
participant: participant.val(),
lang: lang.value
},
success: function (response) {
// window.location.href = "/no-interaction"
// console.log("success")
console.log(response)
var p_exists
if (response.p_exists) {
var c = confirm("This participant already exists. Use their file?")
if (c == true) {
p_exists = true;
} else {
window.location.href = "/";
}
} else {
var c = confirm("The participant doesn't exist. Create new file?");
if (c == true) {
p_exists = false
} else {
window.location.href = "/";
}
};
$.ajax({
type: "POST",
url: "/run_picka",
async: true,
data: {
p_exists: p_exists,
game: response.game,
phase: response.phase,
participant: response.subject,
lang: response.lang
},
success: function (response) {
if (response.game == "crm") {
if (response.error) {
alert(
"There was an error connecting to Sam. Please try again."
)
} else {
window.location.href = "/crm-game"
}
} else if (response.game == "emotion") {
if (response.error) {
alert(
"There was an error connecting to Sam. Please try again."
)
} else {
window.location.href = "/no-interaction-diagram"
}
} else {
if (response.error) {
alert(
"There was an error connecting to Sam. Please try again."
)
} else {
window.location.href = "/no-interaction"
}
}
}
})
},
// error: function (error) {
// console.log(error)
// }
});
dialog.dialog("close");
}
return valid;
}
dialog = $("#dialog-form").dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
buttons: {
"Create participant": addparticipant,
Cancel: function () {
dialog.dialog("close");
}
},
close: function () {
form[0].reset();
allFields.removeClass("ui-state-error");
}
});
form = dialog.find("form").on("submit", function (event) {
event.preventDefault();
addparticipant();
});
$(".create-participant").button().on("click", function (resp) {
game = getGame(resp.target);
dialog.data('game', game).dialog("open");
});
});
var i = 0;
$(document).ready(function () {
$('#progressBar').progressbar({
value: (parseInt($('#current_trial').text()) / parseInt($('#total_trials').text())) * 100
})
})
</script>
<body style="background-color: #54B77E;">
{% block content %}
{% endblock %}
</body>
</html>
+88
View File
@@ -0,0 +1,88 @@
{% extends 'layout.html' %}
{% block content %}
{% if p_exists %}
<script>
alert("Test")
</script>
{% endif %}
<div id="dialog-form" title="Create new Participant">
<p class="validateTips">All form fields are required.</p>
<form>
<fieldset>
<label for="p_id">Participant ID</label>
<input type="text" name="p_id" id="p_id" placeholder="NHA000"
onkeyup="this.value = this.value.toUpperCase();" class="text ui-widget-content ui-corner-all">
<label for="phase">Phase</label>
<input type="text" name="phase" id="phase" placeholder="Training"
class="text ui-widget-content ui-corner-all">
<label for="lang">Language</label>
<select name="lang" id="lang">
<option value="EN">English</option>
<option value="NL">Nederlands</option>
</select>
<!-- <input type="text" name="lang" id="lang" value="EN" class="text ui-widget-content ui-corner-all"> -->
<!-- Allow form submission with keyboard without duplicating the dialog button -->
<input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>
</div>
<div class="container-fluid main-logos">
<div class="container">
<div id="main_logos" class="row">
<div class="col-lg">
<img class="main_img" src="{{url_for('static', filename='images/PICKA.png')}}" alt="">
</div>
<div class="col-lg" style="padding-top: 2%;">
<img class="main_img" src="{{url_for('static', filename='images/rug.png')}}" alt="" style="width: 90%;">
</div>
<div class="col-lg" style="padding-top: 2.5%;">
<img class="main_img" src="{{url_for('static', filename='images/umcg.png')}}" alt="">
</div>
</div>
</div>
</div>
<!-- <p>Subject: <input id="subject" type="text"></p>
<p>Phase: <input id="phase" type="text"></p>
<p>Language: <input id="lang" type="text"></p> -->
<div class="container-fluid game-logos">
<div class="container">
<div class="row">
<div class="col-lg-3">
<button id="game" class="game-btn create-participant">
<img class="game_img" data-game="fishy" src="{{url_for('static', filename='images/fishy.png')}}"
alt="">
</button>
</div>
<div class="col-lg-3">
<button class="game-btn create-participant">
<img class="game_img" data-game="gender" src="{{url_for('static', filename='images/woman.png')}}"
alt="" style="width:85%;">
</button>
</div>
<div class="col-lg-3">
<button class="game-btn create-participant">
<img data-game="emotion" class="game_img" src="{{url_for('static', filename='images/happy.png')}}"
alt="">
</button>
</div>
<div class="col-lg-3">
<button class="game-btn create-participant">
<img data-game="crm" class="game_img" src="{{url_for('static', filename='images/dog.png')}}" alt=""
style="width:85%;">
</button>
</div>
</div>
</div>
</div>
{% endblock %}
</html>
+16
View File
@@ -0,0 +1,16 @@
{% extends 'layout.html' %}
{% block content %}
{% if p_exists %}
<script>
alert("Testing")
</script>
{% endif %}
<div><button class="ui-button ui-corner-all ui-widget"><a href="/">Back</a></button></div>
<div class="container-fluid no-interaction-diagram">
<span id="no-interaction">Please watch Sam</span>
</div>
<div class="container-fluid">
<img src="{{url_for('static', filename='images/sam_emotion_diagram.png')}}" alt="">
</div>
{% endblock %}
Loaded 100 of 103 files, more files were not shown because too many files have changed in this diff. Show more