├── .gitignore
├── config_files
├── example.config
└── example2.config
├── example.config
├── read_calib.py
├── validatecop.py
├── COPparamsFs.py
├── read_datfile.py
├── wiicop.svg
├── README.md
├── GetCOPparams.py
├── WiiCopFunctions.py
├── hyperellipsoid.py
├── wiicop.py
├── wiicop_v1.py
└── LICENSE
/.gitignore:
--------------------------------------------------------------------------------
1 | # ignore the __pycache__ directory
2 | /__pycache__/*
3 | # any test files
4 | test*.py
5 |
--------------------------------------------------------------------------------
/config_files/example.config:
--------------------------------------------------------------------------------
1 | # Example config file
2 | [study info]
3 | study_name = June's study
4 | study_dir = /home/kevin/studydir
5 |
6 | [factors]
7 | # acq_time is compulsory and can have an integer value(s) for acquisition time in seconds or 'inf'
8 | # 'inf' means stop acquisition manually
9 | acq_time = 3
10 | side = right,left
11 | trials = trial1,trial2,trial3
12 |
13 |
14 |
--------------------------------------------------------------------------------
/config_files/example2.config:
--------------------------------------------------------------------------------
1 | # Example config file
2 | [study info]
3 | study_name = researcher's study
4 | study_dir = /home/researchers/studydir
5 |
6 | [factors]
7 | # acq_time is compulsory and can have an integer value(s) for acquisition time in seconds of 'inf'
8 | # for manual stopping of the acquisition
9 | side = right,left
10 | trials = trial1,trial2,trial3
11 | acq_time = 100
12 |
13 |
--------------------------------------------------------------------------------
/example.config:
--------------------------------------------------------------------------------
1 | # Example config for study
2 | [study info]
3 | study_name = example study
4 | study_dir = /home/researchers/Documents/wiistudies/example/
5 |
6 | [factors]
7 | # acq_time is compulsory and can have an integer value(s) for acquisition time in seconds of 'inf'
8 | # for manual stopping of the acquisition
9 | group = year1,year4
10 | trials = trial1,trial2,trial3
11 | acq_time = 40
12 |
13 |
--------------------------------------------------------------------------------
/read_calib.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # to read calibration data and store it as a readable text file
3 | import tkinter.filedialog as tk_fd
4 | import pickle
5 | import numpy as np
6 | import sys
7 |
8 |
9 | dfile = tk_fd.askopenfilename(title = 'Get pickled data file',filetypes=[('Data files', '*.dat'), ('All files','*')])
10 | if not dfile:
11 | print('No file chosen')
12 | sys.exit(0)
13 | with open(dfile,'rb') as fptr:
14 | dc = pickle.load(fptr, fix_imports=False)
15 | print(dc)
16 |
--------------------------------------------------------------------------------
/validatecop.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # to test cop parameters
3 |
4 | from hyperellipsoid import hyperellipsoid
5 | import numpy as np
6 | import math
7 | import COPparamsFs as cp
8 | import matplotlib.pyplot as plt
9 |
10 | def pol2cart(rho, phi):
11 | x = rho * np.cos(phi)
12 | y = rho * np.sin(phi)
13 | return(x, y)
14 |
15 | test_hyp = False
16 |
17 |
18 | if test_hyp:
19 | # test hyperellipsoid
20 | cnt = 0
21 | trls = 1000
22 | for ia in range(0,trls):
23 | # create test data
24 | coords = np.random.normal(0,1,(100,2))
25 | area, axes, angles, center, rot = hyperellipsoid(coords, show=False)
26 | # get new data point
27 | x = np.random.normal(0,1,1)
28 | y = np.random.normal(0,1,1)
29 | # test if in ellipse centred at (0,0) and whose axes are aligned to x & y axes
30 | if x**2/axes[0]**2 + y**2/axes[1]**2 <= 1:
31 | cnt += 1
32 | print(cnt/trls)
33 |
34 | # test path length
35 | nsamp = 2
36 | # create data with known path length - length = 1 at each section
37 | # create uniform random angles
38 | angs = np.random.rand(nsamp) * 2 * math.pi
39 | uvecs = np.transpose(np.array(pol2cart(1,angs)))
40 | lgths = np.linalg.norm(uvecs, axis=1)
41 | # lghts should all = 1...
42 | print(lgths)
43 | # get cumulative sum
44 | tstdat = np.cumsum(uvecs, axis = 0)
45 | # plt.plot(tstdat[:,0],tstdat[:,1],'ro-')
46 | # plt.axes().set_aspect('equal')
47 | # plt.show()
48 | out = cp.pathl(tstdat)
49 | print(out)
50 |
--------------------------------------------------------------------------------
/COPparamsFs.py:
--------------------------------------------------------------------------------
1 | # file to store functions that calculate COP parameters
2 | # All functions need to input a cop data file, being a numpy array with 3
3 | # columns: x-data, y-data, time (seconds)
4 |
5 | # IMPORTS
6 | import numpy as np
7 | from scipy import signal
8 | from scipy.interpolate import interp1d
9 | # Assumes hyperellipsoid.py is in same directory. Written by 'Marcos Duarte.
10 | # https://github.com/demotu/BMC'
11 | from hyperellipsoid import hyperellipsoid
12 |
13 | def to_sing(arr):
14 | # converts array to an nd array with one singleton dimension
15 | arr = np.reshape(arr,(arr.size,-1))
16 | return arr
17 |
18 | def nsamp(cop_dat):
19 | # get number of samples
20 | return cop_dat.shape[0]
21 |
22 | def samp_rate(cop_dat):
23 | # get sample rate
24 | bg = cop_dat[0,-1]
25 | lst = cop_dat[-1,-1]
26 | tme = lst - bg
27 | nsmp = cop_dat.shape[0] - 1
28 | return nsmp/tme
29 |
30 | def PI95(cop_dat):
31 | # get area of 95% prediction ellipse
32 | area, axes, angles, center, R = hyperellipsoid(cop_dat[:,(0,1)], units='mm', show=False)
33 | return area
34 |
35 | def resamp(cop_dat):
36 | # resample data to even sample points using same average sample rate
37 | # resample data
38 | t = np.linspace(cop_dat[0,2], cop_dat[-1,2], num=nsamp(cop_dat), endpoint=True)
39 | f_cor = interp1d(cop_dat[:,2], cop_dat[:,0], kind='linear')
40 | cor = f_cor(t)
41 | f_sag = interp1d(cop_dat[:,2], cop_dat[:,1], kind='linear')
42 | sag = f_sag(t)
43 | # convert all to nd arrays
44 | cor = to_sing(cor)
45 | sag = to_sing(sag)
46 | t = to_sing(t)
47 | return np.concatenate((cor,sag,t),axis=1)
48 |
49 | def bfilt(cop_dat, cutoff, order):
50 | # Butterworth filter
51 | b,a = signal.butter(order, cutoff)
52 | # filter coronal
53 | cor_lp = signal.filtfilt(b, a, cop_dat[:,0])
54 | # filter sagittal
55 | sag_lp = signal.filtfilt(b, a, cop_dat[:,1])
56 | return np.concatenate((to_sing(cor_lp),to_sing(sag_lp),to_sing(cop_dat[:,2])),axis=1)
57 |
58 | def pathl(cop_dat):
59 | # to calculate COP path length
60 | delt = np.diff(cop_dat[:,(0,1)], axis = 0)
61 | sqs = np.square(delt)
62 | sum_s = np.add(sqs[:,0],sqs[:,1])
63 | lgths = np.sqrt(sum_s)
64 | return np.sum(lgths)
65 |
--------------------------------------------------------------------------------
/read_datfile.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # to read a pickled file into memory
3 | import tkinter.filedialog as tk_fd
4 | import pickle
5 | import numpy as np
6 | import sys
7 | import matplotlib.pyplot as plt
8 | from scipy import signal
9 | from scipy.interpolate import interp1d
10 | import math
11 |
12 | doplots = True
13 | savecsv = False
14 |
15 | dfile = tk_fd.askopenfilename(title = 'Get pickled data file',filetypes=[('Data files', '*.dat'), ('All files','*')])
16 | if not dfile:
17 | print('No file chosen')
18 | sys.exit(0)
19 | with open(dfile,'rb') as fptr:
20 | dc = pickle.load(fptr, fix_imports=False)
21 | # convert time data into seconds
22 | #t_dat = dc['timedat'].astype(int)
23 | t_dat = dc['timedat']
24 | # print(t_dat)
25 | # print(t_dat[:,1]/1000000)
26 | t_dat = t_dat[:,0] + t_dat[:,1]/1000000
27 | # reshape t_dat so that it is an nd array with one singleton dimension
28 | t_dat = np.reshape(t_dat,(t_dat.size,-1))
29 | # subtract the first time value from all
30 | t_dat = np.subtract(t_dat,t_dat[0])
31 | # add time data to cop data
32 | bb_dat = np.concatenate((dc['cop'],t_dat), axis=1)
33 | n_samp = bb_dat.shape[0]
34 | # add raw sensor data
35 | bb_dat = np.concatenate((bb_dat,dc['rawsens']), axis=1)
36 | # save each numpy array as a CSV file...
37 | if savecsv:
38 | fname = tk_fd.asksaveasfilename(title='Choose file name to save BB data', filetypes=[('CSV files', '.csv'), ('all files', '.*')])
39 | if fname:
40 | np.savetxt(fname,bb_dat, delimiter=',', header='copX,copY,time,TopR,BotR,TopL,BotL', comments='')
41 | # plot statokinesiogram - coronal plane using time as x-axis
42 | if doplots:
43 |
44 | # resample data
45 | t = np.linspace(bb_dat[0,2], bb_dat[-1,2], num=n_samp, endpoint=True)
46 | f_cor = interp1d(bb_dat[:,2], bb_dat[:,0], kind='linear')
47 | cor = f_cor(t)
48 | f_sag = interp1d(bb_dat[:,2], bb_dat[:,1], kind='linear')
49 | sag = f_sag(t)
50 |
51 | # Butterworth filter
52 | order = 4
53 | # -3dB cutoff freq proportion of Nyquist freq (half sampling freq)
54 | cutoff = 2/3
55 | b,a = signal.butter(order, cutoff)
56 | # filter coronal
57 | cor_lp = signal.filtfilt(b, a, cor)
58 | print(len(cor))
59 | print(len(cor_lp))
60 | # filter sagittal
61 | sag_lp = signal.filtfilt(b, a, sag)
62 |
63 | # plot coronal
64 | fg, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
65 | # resampled or raw
66 | ax1.plot(bb_dat[:,2],bb_dat[:,0],'bo-')
67 | # ax1.plot(t,cor,'bo-')
68 | ax1.set_xlabel('time (secs)')
69 | ax1.set_ylabel('coronal plane')
70 | ax1.grid()
71 | # filtered
72 | ax2.plot(t,cor_lp,'bo-')
73 | ax2.set_xlabel('time (secs)')
74 | ax2.grid()
75 | plt.show()
76 |
77 | # plot sagittal
78 | fg, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
79 | # resampled or raw
80 | ax1.plot(bb_dat[:,2],bb_dat[:,1],'bo-')
81 | # ax1.plot(t,sag,'bo-')
82 | ax1.set_xlabel('time (secs)')
83 | ax1.set_ylabel('coronal plane')
84 | ax1.grid()
85 | # filtered
86 | ax2.plot(t,sag_lp,'bo-')
87 | ax2.set_xlabel('time (secs)')
88 | ax2.grid()
89 | plt.show()
90 |
--------------------------------------------------------------------------------
/wiicop.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
116 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # wiicop.py
2 |
3 | Python 3 software for obtaining centre of pressure (cop) data from the Nintendo Wii board. Works on linux computers only. Also obtains subject code and experiment factors such as group (case/control), acquisition time etc. This is used by students and researchers at the British School of Osteopathy, London [website](http://www.bso.ac.uk/).
4 |
5 | #UPDATE
6 |
7 | New version of `wiicop.py` increases the sample rate (on a Intel Pentium P6200 dual core 2.13GHz) of 10Hz to around 65Hz. It also saves the data in a CSV file instead of a python data file. The CSV file has three columns: cop x value (coronal plane), cop y value (sagittal plane), and time (seconds). It also updates the cop screen display to 20Hz. This makes it achieve the sample rate standards recommended by Scoppa et al (Scoppa, F.; Capra, R.; Gallamini, M. & Shiffer, R. Clinical stabilometry standardization: basic definitions-acquisition interval-sampling frequency Gait & posture, Elsevier, 2013, 37, 290-292). This means that `GetCOPparams.py` will need ammending to work with the new data files.
8 |
9 | #HOW TO USE
10 | 1. Follow all the install instructions below
11 |
12 | 2. Via a terminal, cd to the wiicp.py directory and run wiicop.py:
13 | `./wiicop.py`
14 |
15 | 3. You then calibrate the board for that session. Apply calibration weights, as accurately as possible, to the centre of the board. You can configure which weights to use by editing the top of 'wiicop.py'. The weight options are defined in a dictionary `pd.Series`, numbered from 0. Choose also the units.
16 |
17 | `# Pandas series to define calibration weights`
18 |
19 | `calib_wgts = pd.Series({0:5,1:9,2:16.5})`
20 |
21 | `# calibration units ('Kgs' or 'lbs')`
22 |
23 | `calib_units = 'Kgs'`
24 |
25 | The calibration will check that all the sensors are obtaining 95% of readings that are greater than zero. If insufficiently heavy calibration weights are used, or the surface is uneven, one of the sensors will be floating in the air and not taking readings. The program will terminate if that is the case. The program fits a linear model to the data from each sensor and saves the details in the session directory.
26 |
27 | 4. If set up correctly, it should ask via the command line to choose a study. Then you create a name for the session. A name will be suggested but check one hasn't already got the same name (i.e. if you've done another session the same morning)
28 |
29 | 5. You will then be able to choose study factors for the study. E.g. 'before' or 'after', 'treatment' or 'control' etc.
30 |
31 | 6. A window will then pop up displaying the centre of pressure as a green dot. To start recording data, press the spacebar. If you have configured it to do a timed acquisition, it will stop after the time is up. Otherwise you can stop the acquisition by pressing the spacebar again.
32 |
33 | 7. You will be asked if you want to get another aquisition. If you choose no, the session will terminate.
34 |
35 | 8. You can use `GetCOPparams.py` to read the COP and the calibration data. Currently it calculates area of 95% prediction ellipse (thanks to Marcos Duarte for `hyperellipsoid.py`. https://github.com/demotu/BMC), path length and path velocity.
36 |
37 |
38 |
39 | #INSTALL INSTRUCTIONS
40 |
41 |
42 | 1. Go to [here](https://github.com/dvdhrm/xwiimote) to download the zip file containing the xwiimote software and unzip it in a suitable directory. Or clone using git.
43 |
44 | 2. Go to [here](https://github.com/dvdhrm/xwiimote-bindings) to download the zip file containing the xwiimote bindings and unzip it another directory. Or clone using git.
45 |
46 | 3. Install the following dependencies (ubuntu based distributions) via:
47 |
48 | `sudo apt-get install libudev-dev libncurses5-dev libncursesw5-dev automake autoconf autogen libtool swig python3-dev python3-tk python3-pip`
49 |
50 | 4. Install python modules:
51 |
52 | `sudo pip3 install pyudev pandas matplotlib scipy`
53 |
54 | 5. Compile and install xwiimote library.
55 | Change (cd) to xwiimote directory (xwiimote-master), then run:
56 |
57 | `sudo ./autogen.sh`
58 |
59 | `sudo ./configure`
60 |
61 | `sudo make`
62 |
63 | `sudo make install`
64 |
65 |
66 | 6. Create the xwiimote configure file in /etc/ld.so.comf.d:
67 |
68 | `cd /etc/ld.so.conf.d`
69 |
70 | `sudo nano xwiimote.conf`
71 |
72 | And add the following line to this file:
73 |
74 | `/usr/local/lib`
75 |
76 | and save: Ctrl O, Ctrl X. Next, reload library cache using the following:
77 |
78 | `sudo ldconfig`
79 |
80 | 7. Test xwiimote libraries are installed and can connect Wiiboard by connecting Wiiboard via Bluetooth and running:
81 |
82 | `sudo xwiishow`
83 |
84 | and follow instructions.
85 |
86 | 8. Compile and install xwiimote python bindings. Change (cd) to xwiimote-bindings directory and run following:
87 |
88 | `sudo ./autogen.sh`
89 |
90 | `sudo ./configure PYTHON=/usr/bin/python3`
91 |
92 | `sudo make`
93 |
94 | `sudo make install`
95 |
96 |
97 | 9. Add user to input group to allow user (‘usersname’) to run xwiimote software:
98 |
99 | `sudo usermod -a -G input usersname`
100 |
101 | then log out and log back in again
102 |
103 | 10. Create a directory to put the wiiboard software into, e.g. ~/Wiiboard. Copy wiicop.py and WiiCopFunctions.py into this directory. Then add this directory to your python path by adding this line to your ~/.bashrc file:
104 |
105 | `export PYTHONPATH="$PYTHONPATH:/home/yourusername/path/to/wiicopdir"`
106 |
107 | 11. In same directory create a directory called config_files to put study configuration files for each study. These need to be amended – see below.
108 |
109 | 12. Make sure the python file 'wiicop.py' is executable.
110 |
111 | Either: Right click on it, select 'Properties', select 'Permissions' tab and tick the 'Allow executing file as program' tickbox.
112 |
113 | Or: In a terminal, cd to directory of wiicop.py and run:
114 |
115 | `chmod +x wiicop.py`
116 |
117 | 12. Create a study directory and a sub directory for each study. Amend config file for each study to point to the right directory
118 |
119 |
120 | #NOTES:
121 | In Linux Mint 18 Cinnamon edition the default bluetooth (Blueberry) tool doesn't seem to work. Uninstalling it and installing Blueman seems to work:
122 |
123 | sudo apt-get remove --purge blueberry
124 | sudo apt-get install blueman
125 |
126 | Then reboot
127 |
128 |
129 |
130 |
131 |
132 |
--------------------------------------------------------------------------------
/GetCOPparams.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # software to convert raw centre of pressure (COP) data into various COP based measures of balance
3 |
4 | # IMPORTS
5 | # ~~~~~~~
6 | import tkinter.filedialog as tk_fd
7 | import sys
8 | import os
9 | import re
10 | import pickle
11 | import numpy as np
12 | import pandas as pd
13 | import configparser
14 | import matplotlib.pyplot as plt
15 | import matplotlib
16 | import COPparamsFs as cp
17 | # %matplotlib inline
18 | #import pdb; pdb.set_trace()
19 |
20 |
21 | # INITIALISE
22 | # set regular expression to find calibration file
23 | cal_re = "calib.*dat"
24 | # set regular expression to find cop data file
25 | cop_re = "subj.*.dat"
26 | # specify list of cop parameters
27 | cop_params = ['pred_ellipse','path_length','velocity']
28 | # string that signifies subject code
29 | sbjstr = 'subj'
30 | # Display stabilogram flag
31 | disps_f = False
32 | # Save stabilogram flag
33 | saves_f = True
34 | # name of image directory
35 | imdir = "stabilograms"
36 | # Balance board dimensions width and length in mm (Leach, J.M., Mancini, M., Peterka, R.J., Hayes,
37 | # T.L. and Horak, F.B., 2014. Validating and calibrating the Nintendo Wii
38 | # balance board to derive reliable center of pressure measures. Sensors,
39 | # 14(10), pp.18244-18267.)
40 | BB_Y = 238
41 | BB_X = 433
42 | # filter parameters...
43 | # cutoff frequency as proportion of Nyquist
44 | cutoff = 2/3
45 | # order of Butterworth filter
46 | order = 4
47 |
48 | # set up if plots flagged
49 | if disps_f or saves_f:
50 | matplotlib.rcParams['toolbar'] = 'None'
51 | # create empty list to store stuff to plot
52 | plt_lst = []
53 | # create figure and axis
54 | fig,ax = plt.subplots(1)
55 | fig.canvas.set_window_title('Stabilogram')
56 |
57 | # setup regular expression objects
58 | cal_re_o = re.compile(cal_re)
59 | cop_re_o = re.compile(cop_re)
60 |
61 | # create empty pandas dataframes to store calibration and cop data
62 | cal_df=pd.DataFrame(columns=['session','sensor','slope','slope.se','r.coef','p-val'])
63 | # change to $XDG_RUNTIME_DIR/gvfs where samba mounts its shares
64 | # gvfs_pth = os.environ['XDG_RUNTIME_DIR']+'/gvfs/'
65 | # os.chdir(os.path.dirname(gvfs_pth))
66 | # Get user to choose config file
67 | config_file = tk_fd.askopenfilename(title = 'Get config file for study',filetypes=[('Data files', '*.config'), ('All files','*')])
68 | # move to directory above config file
69 | os.chdir(os.path.dirname(config_file))
70 | os.chdir("..")
71 | # read selected config file
72 | config = configparser.ConfigParser()
73 | config.read(config_file)
74 | # get info list of factors
75 | fct_lst = config.options('factors')
76 | cop_df=pd.DataFrame(columns=['session','subj'] + fct_lst + cop_params)
77 |
78 |
79 | # SEARCH THROUGH CHOSEN DIRECTORY STRUCTURE
80 | # for data and calibration files
81 | seshd = tk_fd.askdirectory(title = 'Open study directory containing sessions')
82 | if not seshd:
83 | sys.exit()
84 | for root, dirs, files in os.walk(seshd):
85 | # for each directory
86 | if len(files) > 0:
87 |
88 | # look for calibration file using reg expression
89 | c_lst = list(filter(cal_re_o.match,files))
90 | if c_lst:
91 | # if list c_lst is not empty..
92 | # should contain only one calibration file
93 | assert len(c_lst)==1, "more than one calibration file in directory: {}".format(root)
94 | # open calibration file
95 | c_pth = os.path.join(root,c_lst[0])
96 | with open(c_pth,'rb') as fptr:
97 | tmp = pickle.load(fptr, fix_imports=False)
98 |
99 | # Store 1 row of calibration data...
100 | cal_dat = tmp['details']
101 | nxt_cal = len(cal_df.index)
102 | s_ind = 0
103 | for sns in cal_dat.keys():
104 | # for each sensor..
105 | # create empty row
106 | cal_df.loc[nxt_cal+s_ind] = None
107 | cal_df.ix[nxt_cal+s_ind,'session'] = os.path.basename(root)
108 | cal_df.ix[nxt_cal+s_ind,'sensor'] = sns
109 | cal_df.ix[nxt_cal+s_ind,'slope'] = cal_dat[sns]['m']
110 | cal_df.ix[nxt_cal+s_ind,'slope.se'] = cal_dat[sns]['se']
111 | cal_df.ix[nxt_cal+s_ind,'r.coef'] = cal_dat[sns]['r']
112 | cal_df.ix[nxt_cal+s_ind,'p-val'] = cal_dat[sns]['p']
113 | s_ind+=1
114 |
115 | # look for cop data file using reg expression
116 | d_lst = list(filter(cop_re_o.match,files))
117 | if d_lst:
118 | for fi in d_lst:
119 | # for each data file..
120 |
121 | # store row of study metadata...
122 | nxt_cop = len(cop_df.index)
123 | # create empty row
124 | cop_df.loc[nxt_cop] = None
125 | # strip extension
126 | prts = fi.split('.')
127 | # save levels as list
128 | lev_lst = prts[0].split('_')
129 | # get subject code
130 | tmp = [s for s in lev_lst if sbjstr in s]
131 | scode = tmp[0].strip(sbjstr)
132 | # convert to int then back to string with 3 leading zeros
133 | scode = int(scode)
134 | scode = str(scode).zfill(3)
135 | cop_df.ix[nxt_cop,'subj'] = scode
136 | # get session
137 | cop_df.ix[nxt_cop,'session'] = os.path.basename(root)
138 | # read study metadata into df
139 | for fct_i in fct_lst:
140 | for lev in lev_lst:
141 | if lev in config['factors'][fct_i]:
142 | cop_df.ix[nxt_cop,fct_i] = lev
143 |
144 |
145 | # read COP data
146 | d_pth = os.path.join(root,fi)
147 | with open(d_pth,'rb') as fptr:
148 | pkl = pickle.load(fptr)
149 | # convert time data into seconds
150 | t_dat = pkl['timedat']
151 | t_dat = t_dat[:,0] + t_dat[:,1]/1000000
152 | # reshape t_dat so that it is an nd array with one singleton dimension
153 | t_dat = np.reshape(t_dat,(t_dat.size,-1))
154 | # add time data to cop data
155 | cop_dat = np.concatenate((pkl['cop'],t_dat), axis=1)
156 |
157 | # Preprocess COP data
158 | # resample to even sample points
159 | cop_dat_r = cp.resamp(cop_dat)
160 | # low pass filtering
161 | cop_dat_f = cp.bfilt(cop_dat_r, cutoff, order)
162 | # # TEST ***
163 | # # plot coronal
164 | # fg, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
165 | # # resampled or raw
166 | # ax1.plot(cop_dat[:,2],cop_dat[:,0],'bo-')
167 | # # ax1.plot(t,cor,'bo-')
168 | # ax1.set_xlabel('time (secs)')
169 | # ax1.set_ylabel('coronal plane')
170 | # ax1.set_title('Raw data')
171 | # ax1.grid()
172 | # # resampled and filtered
173 | # ax2.plot(cop_dat_f[:,2],cop_dat_f[:,0],'bo-')
174 | # ax2.set_xlabel('time (secs)')
175 | # ax2.set_title('Resampled and filtered')
176 | # ax2.grid()
177 | # mng = plt.get_current_fig_manager()
178 | # mng.resize(*mng.window.maxsize())
179 | # plt.show()
180 | # # ***
181 |
182 | # Get COP parameters...
183 | # 95% Prediction interval
184 | cop_df.ix[nxt_cop,'pred_ellipse'] = cp.PI95(cop_dat_f)
185 | # path length
186 | pl = cp.pathl(cop_dat)
187 | cop_df.ix[nxt_cop,'path_length'] = pl
188 | # velocity
189 | import pdb; pdb.set_trace()
190 | cop_df.ix[nxt_cop,'velocity'] = pl/int(cop_df.ix[nxt_cop,'acq_time'])
191 |
192 | # store data for plotting if flagged
193 | if disps_f or saves_f:
194 | # create a dictionary of relevant study factors
195 | std_fct = {}
196 | std_fct['subj'] = scode
197 | for fct_i in fct_lst:
198 | for lev in lev_lst:
199 | if lev in config['factors'][fct_i]:
200 | std_fct[fct_i] = lev
201 | plt_lst.append([[cop_dat, std_fct]])
202 |
203 | # Plot stabilograms (see Scoppa2013) if flagged
204 | if disps_f or saves_f:
205 | if saves_f:
206 | # create image directory if it doesn't exist in current working directory
207 | imdirpth = os.path.join(os.getcwd(),imdir)
208 | if not(os.path.isdir(imdirpth)):
209 | os.mkdir(imdirpth)
210 | ax.axis([-BB_X/2, BB_X/2, -BB_Y/2, BB_Y/2])
211 | ax.grid()
212 | plot1 = True
213 | plt.ion()
214 | for ia in plt_lst:
215 | if plot1:
216 | line_h, = ax.plot(ia[0][0][:,0], ia[0][0][:,1],'b-')
217 | plot1 = False
218 | else:
219 | line_h.set_xdata(ia[0][0][:,0])
220 | line_h.set_ydata(ia[0][0][:,1])
221 | plt.title('Subject: '+ia[0][1]['subj'])
222 | # get factors string
223 | fct_str = ""
224 | for ib in fct_lst:
225 | fct_str = fct_str + ib + ": " + ia[0][1][ib] + ", "
226 | fct_str = fct_str.rstrip(", ")
227 | txt_h = plt.text(-200,100,fct_str, fontsize=14)
228 | if disps_f:
229 | plt.show()
230 | plt.pause(0.5)
231 | if saves_f:
232 | # create file name
233 | im_file = ".png"
234 | for ib in fct_lst:
235 | im_file = ia[0][1][ib] + im_file
236 | im_file = "subj" + ia[0][1]['subj'] + "_" + im_file
237 | plt.savefig(os.path.join(os.getcwd(),imdir,im_file))
238 | txt_h.remove()
239 |
240 |
241 | # create results directory if it doesn't exist
242 | res_dir = os.path.join(seshd,'results')
243 | if not(os.path.isdir(res_dir)):
244 | os.mkdir(res_dir)
245 | # write calibration results
246 | calib_file = os.path.join(res_dir,'calib_results.csv')
247 | cal_df.to_csv(calib_file)
248 | # write study results
249 | study_file = os.path.join(res_dir,'study_results.csv')
250 | cop_df.to_csv(study_file)
251 |
--------------------------------------------------------------------------------
/WiiCopFunctions.py:
--------------------------------------------------------------------------------
1 | # file to store functions for use by Wiicop.py
2 |
3 | import pyudev
4 | import xwiimote
5 | import errno
6 | import select
7 | import sys
8 | import os
9 | import numpy as np
10 | import tkinter as tk
11 | import tkinter.font as font
12 | import string
13 |
14 | # function to test if string is a valid subject code
15 | def validcode(testnm):
16 | valid_chars='{}{}'.format(string.ascii_letters,string.digits)
17 | valid = True
18 | for c in testnm:
19 | if c not in valid_chars:
20 | valid = False
21 | break
22 | return valid
23 |
24 | # function to obtain acquisition info: subject code, study factor levels, acquisition time
25 | def get_acq_info(s_config):
26 | # function to obtain acquisition info: subject code, study factor levels, acquisition time
27 | # input: s_config: config object for study
28 | # output: a dictionary with 2 compulsory keys: 'subject_code' and 'acq_time' and other keys being
29 | # the names of factors and they're associated chosen levels.
30 | # get subject code
31 | s_c = input('Enter subject code: ')
32 | while not validcode(s_c):
33 | print('\nOnly letters and numbers for subject codes\n')
34 | s_c = input('Enter subject code: ')
35 | fact_choices = {'subject_code':s_c}
36 | # get names of factors as a list
37 | fct_names = []
38 | for factor in s_config['factors']:
39 | fct_names.append(factor)
40 | # check if 'acq_time' is in list of factors
41 | if not 'acq_time' in fct_names:
42 | raise ValueError('Message from get_acq_info: There is no acq_time factor in the config file~~')
43 | # get factor levels
44 | for factor in s_config['factors']:
45 | levs = s_config['factors'][factor].split(',')
46 | if len(levs)==1:
47 | fact_choices.update({factor:levs[0]})
48 | continue
49 | tit_str = 'Choose level for {}'.format(factor)
50 | chc = txtmenu(tit_str,levs)
51 | fact_choices.update({factor:levs[chc]})
52 | return fact_choices
53 |
54 | # returns device object for balance board
55 | def connectBB():
56 | # returns sys path for balance board using evdev module
57 | context = pyudev.Context()
58 | # get list of devices matching devtype = 'balanceboard'
59 | devices = pyudev.Enumerator(context)
60 | tst = devices.match_attribute('devtype', 'balanceboard')
61 | # create empty list to store balance board info
62 | bboards = []
63 | # populate list
64 | for dfg in tst:
65 | bboards.append(dfg)
66 | # test how many bboards are connected - should be only one
67 | if len(bboards) == 0:
68 | print('No Wii balance boards found')
69 | return None
70 | if len(bboards) > 1:
71 | print('More than one Wii balance boards found: exiting')
72 | return None
73 | print('\nBalance board found!\n')
74 | # return the first in the list
75 | bb = bboards[0]
76 | return bb
77 |
78 | # function to get data from BB and process it function 'func'
79 | def procBBdata(bb, func, *args):
80 | # function to get data from BB and process it function 'func'
81 | # returns sens_dat that is an NX4 numpy array of raw sensor readings
82 | # each row a single data acquisition
83 | n_s = 4
84 | bbdev = xwiimote.iface(bb.sys_path)
85 | p = select.poll()
86 | p.register(bbdev.get_fd(), select.POLLIN)
87 | # open bb device
88 | bbdev.open(xwiimote.IFACE_BALANCE_BOARD)
89 | # create xwiimote event structure
90 | revt = xwiimote.event()
91 | # create numpy array to store data from board
92 | tmp_dat = np.empty((1,n_s))
93 | # creat another to accumulate all data
94 | sens_dat = np.empty((0,n_s))
95 | go_flg = True
96 | try:
97 | while go_flg:
98 | # waits here until event occurs
99 | polls = p.poll()
100 | for fd, evt in polls:
101 | try:
102 | bbdev.dispatch(revt)
103 | # revt.get_abs() takes an integer argument:
104 | # 0 - top right when power button pointing towards you
105 | # 1 - bottom right
106 | # 2 - top left
107 | # 3 - bottom left
108 | for i_s in range(n_s):
109 | tmp_dat[0,i_s] = revt.get_abs(i_s)[0]
110 | # function that does something with sens_dat. Functions
111 | # called by procBBdata must have parameters:
112 | # go_flg, tmp_dat, sens_dat
113 | go_flg, sens_dat = func(go_flg, tmp_dat, sens_dat, *args)
114 | except IOError as e:
115 | # do nothing if resource unavailable
116 | if e.errno != errno.EAGAIN:
117 | print(e)
118 | p.unregister(bbdev.get_fd())
119 | except KeyboardInterrupt:
120 | pass
121 | # cleaning
122 | bbdev.close(xwiimote.IFACE_BALANCE_BOARD)
123 | p.unregister(bbdev.get_fd())
124 | return sens_dat
125 |
126 | # function to calculate COP
127 | def calcCOP(indat,cal_mod,BB_X, BB_Y):
128 | # inputs: 'indat' a 1 X N_S numpy array of sensor measurements
129 | # 'cal_mod': a 2 X N_S numpy array, 1st row are scale values, 2nd row are offsets
130 | # BB_X, BB_Y - size of balance boad in mm
131 | cal_dat = indat * cal_mod[0,:]
132 | cal_dat += cal_mod[1,:]
133 | cal_dat = cal_dat.flatten()
134 | cop_x = BB_X/2*(cal_dat[0]+cal_dat[1]- (cal_dat[2]+cal_dat[3])) / (cal_dat[0]+cal_dat[1]+cal_dat[2]+cal_dat[3])
135 | cop_y = BB_Y/2*(cal_dat[0]+cal_dat[2]- (cal_dat[1]+cal_dat[3])) / (cal_dat[0]+cal_dat[1]+cal_dat[2]+cal_dat[3])
136 | return np.array([cop_x, cop_y])
137 |
138 | # function to get n_samp samples from the wii board
139 | def getnsamp(go_flg, tmp_dat, sens_dat, n_samp):
140 | # function to get n_samp samples from the wii board
141 | # functions called by procBBdata must have parameters:
142 | # go_flg, tmp_dat, sens_dat
143 | # if number of obtained samples less than n_samp..
144 | if sens_dat.shape[0] < n_samp:
145 | # get sensor data row
146 | sens_dat = np.vstack((sens_dat,tmp_dat))
147 | else:
148 | # flag end of data acquisition
149 | go_flg = False
150 | return go_flg, sens_dat
151 |
152 | # funtion to get choice from a list
153 | def txtmenu(tit_str,opt_lst):
154 | # funtion to get choice from a list
155 | print('\n'+tit_str+':')
156 | print('~'*len(tit_str))
157 | v_chs = set(range(1,len(opt_lst)+1))
158 | for i_opts in range(len(opt_lst)):
159 | print(" "+str(i_opts+1)+") "+opt_lst[i_opts])
160 | inp = input("? ")
161 | inp_invalid = True
162 | while inp_invalid:
163 | try:
164 | ans = int(inp)
165 | if ans not in v_chs:
166 | raise Exception('not valid choice, try again')
167 | inp_invalid = False
168 | except ValueError:
169 | print("Input should be a number, try again")
170 | inp = input("? ")
171 | except Exception as err:
172 | print(err)
173 | inp = input("? ")
174 |
175 | return ans-1
176 |
177 | # function that returns a list of directories
178 | def listdirs(strt_dir):
179 | # function that returns a list of directories
180 | dir_lst = []
181 | for entry in os.scandir(strt_dir):
182 | if entry.is_dir():
183 | dir_lst.append(entry.name)
184 | return dir_lst
185 |
186 | # function to take list of previous session names and a default name for new
187 | # session and return users choice of new session name
188 | def get_sessionname(prev_lst,def_name):
189 | # function to take list of previous session names and a default name for new
190 | # session and return users choice of new session name
191 | # INITIALISE parameters
192 | # background colour
193 | bcol = 'linen'
194 | # font size
195 | f_sz = 11
196 | # base height (px)
197 | b_hgt = 182
198 | # height of listbox in lines
199 | lst_hgt = max(1,len(prev_lst))
200 | # window size
201 | w_hgt = round(b_hgt + f_sz*4/3*lst_hgt)
202 | # window title
203 | wnd_tit = 'Name new session'
204 | # FUNCTION definitions
205 | # function to read entry box when ok button clicked and exit
206 | def click_ok():
207 | s_name = ent.get()
208 | usr_chose.set(True)
209 | root.destroy()
210 | # function to read entry box when return pressed and exit
211 | def name_ent(event):
212 | s_name = ent.get()
213 | usr_chose.set(True)
214 | root.destroy()
215 | # function to read double-clicked line in listbox and write into entrybox
216 | def old2new(event):
217 | # get selected item from list
218 | sel_item = prev_lst[lbox.curselection()[0]]
219 | # write it to entry box
220 | s_name.set(sel_item)
221 | def val_entry():
222 | return False
223 | # CREATE window
224 | # create root
225 | root = tk.Tk()
226 | # flag to indicate choice has been made (i.e. window not closed). Must use
227 | # tkinter varables as can't use python global vars. These must be created after 'root = Tk()'
228 | usr_chose = tk.BooleanVar()
229 | usr_chose.set(False)
230 | # set title of dialogue
231 | root.title(wnd_tit)
232 | # set height of window
233 | root.geometry('260x{}'.format(w_hgt))
234 | # set font size for widgets
235 | customFont = font.Font(size=f_sz)
236 | # create listbox
237 | lbox = tk.Listbox(root, height=lst_hgt, font=customFont, bg=bcol)
238 | # populate listbox
239 | cnt = 1
240 | for i_lst in prev_lst:
241 | lbox.insert(cnt,i_lst)
242 | cnt += 1
243 | # bind listbox to return keypress to call old2new
244 | lbox.bind("",old2new)
245 | # bind listbox to double click to call old2new
246 | lbox.bind("",old2new)
247 | # label for listbox
248 | lbox_lab = tk.Label(root, text = 'Previous sessions', font=customFont)
249 | # create string var for entry box with default name
250 | s_name = tk.StringVar()
251 | s_name.set(def_name)
252 | # Entry box to get name of session
253 | # TO DO validate entry here
254 | ent = tk.Entry(root, font=customFont, textvariable=s_name, bg=bcol)
255 | # set focus to entry box
256 | ent.focus_set()
257 | # bind entry box widget to return keypress
258 | ent.bind("",name_ent)
259 | # label for entry box
260 | ebox_lab = tk.Label(root, text = 'New session', font=customFont)
261 | # ok button to record entry
262 | butt = tk.Button(root, font=customFont, text = 'OK', command=click_ok)
263 | # assemble widgets
264 | lbox_lab.pack(pady=(5,0))
265 | lbox.pack(padx=(15))
266 | ebox_lab.pack(pady=(25,0))
267 | ent.pack(padx=(15))
268 | butt.pack(pady=(20,0))
269 | root.mainloop()
270 | # if user doesn't close window return what's in entry box
271 | if usr_chose.get():
272 | return(s_name.get())
273 | else:
274 | return(None)
275 |
--------------------------------------------------------------------------------
/hyperellipsoid.py:
--------------------------------------------------------------------------------
1 | """Prediction hyperellipsoid for multivariate data."""
2 |
3 | from __future__ import division, print_function
4 | import numpy as np
5 |
6 | __author__ = 'Marcos Duarte, https://github.com/demotu/BMC'
7 | __version__ = "1.0.3"
8 | __license__ = "MIT"
9 |
10 |
11 | def hyperellipsoid(P, y=None, z=None, pvalue=.95, units=None, show=True, ax=None):
12 | """
13 | Prediction hyperellipsoid for multivariate data.
14 |
15 | The hyperellipsoid is a prediction interval for a sample of a multivariate
16 | random variable and is such that there is pvalue*100% of probability that a
17 | new observation will be contained inside the hyperellipsoid [1]_.
18 | The hyperellipsoid is also a tolerance region such that the average or
19 | expected value of the proportion of the population contained in this region
20 | is exactly pvalue*100% (called Type 2 tolerance region by Chew (1966) [1]_).
21 |
22 | The directions and lengths of the semi-axes are found, respectively, as the
23 | eigenvectors and eigenvalues of the covariance matrix of the data using
24 | the concept of principal components analysis (PCA) [2]_ or singular value
25 | decomposition (SVD) [3]_ and the length of the semi-axes are adjusted to
26 | account for the necessary prediction probability.
27 |
28 | The volume of the hyperellipsoid is calculated with the same equation for
29 | the volume of a n-dimensional ball [4]_ with the radius replaced by the
30 | semi-axes of the hyperellipsoid.
31 |
32 | This function calculates the prediction hyperellipsoid for the data,
33 | which is considered a (finite) sample of a multivariate random variable
34 | with normal distribution (i.e., the F distribution is used and not
35 | the approximation by the chi-square distribution).
36 |
37 | Parameters
38 | ----------
39 | P : 1-D or 2-D array_like
40 | For a 1-D array, P is the abscissa values of the [x,y] or [x,y,z] data.
41 | For a 2-D array, P is the joined values of the multivariate data.
42 | The shape of the 2-D array should be (n, p) where n is the number of
43 | observations (rows) and p the number of dimensions (columns).
44 | y : 1-D array_like, optional (default = None)
45 | Ordinate values of the [x, y] or [x, y, z] data.
46 | z : 1-D array_like, optional (default = None)
47 | Ordinate values of the [x, y] or [x, y, z] data.
48 | pvalue : float, optional (default = .95)
49 | Desired prediction probability of the hyperellipsoid.
50 | units : str, optional (default = None)
51 | Units of the input data.
52 | show : bool, optional (default = True)
53 | True (1) plots data in a matplotlib figure, False (0) to not plot.
54 | Only the results for p=2 (ellipse) or p=3 (ellipsoid) will be plotted.
55 | ax : a matplotlib.axes.Axes instance (default = None)
56 |
57 | Returns
58 | -------
59 | hypervolume : float
60 | Hypervolume (e.g., area of the ellipse or volume of the ellipsoid).
61 | axes : 1-D array
62 | Lengths of the semi-axes hyperellipsoid (largest first).
63 | angles : 1-D array
64 | Angles of the semi-axes hyperellipsoid (only for 2D or 3D data).
65 | For the ellipsoid (3D data), the angles are the Euler angles
66 | calculated in the XYZ sequence.
67 | center : 1-D array
68 | Centroid of the hyperellipsoid.
69 | rotation : 2-D array
70 | Rotation matrix for hyperellipsoid semi-axes (only for 2D or 3D data).
71 |
72 | References
73 | ----------
74 | .. [1] http://www.jstor.org/stable/2282774
75 | .. [2] http://en.wikipedia.org/wiki/Principal_component_analysis
76 | .. [3] http://en.wikipedia.org/wiki/Singular_value_decomposition
77 | .. [4] http://en.wikipedia.org/wiki/Volume_of_an_n-ball
78 |
79 | Examples
80 | --------
81 | >>> from hyperellipsoid import hyperellipsoid
82 | >>> y = np.cumsum(np.random.randn(3000)) / 50
83 | >>> x = np.cumsum(np.random.randn(3000)) / 100
84 | >>> area, axes, angles, center, R = hyperellipsoid(x, y, units='cm')
85 | >>> print('Area =', area)
86 | >>> print('Semi-axes =', axes)
87 | >>> print('Angles =', angles)
88 | >>> print('Center =', center)
89 | >>> print('Rotation matrix =\n', R)
90 |
91 | >>> P = np.random.randn(1000, 3)
92 | >>> P[:, 2] = P[:, 2] + P[:, 1]*.5
93 | >>> P[:, 1] = P[:, 1] + P[:, 0]*.5
94 | >>> volume, axes, angles, center, R = hyperellipsoid(P, units='cm')
95 | """
96 |
97 | from scipy.stats import f as F
98 | from scipy.special import gamma
99 |
100 | P = np.array(P, ndmin=2, dtype=float)
101 | if P.shape[0] == 1:
102 | P = P.T
103 | if y is not None:
104 | y = np.array(y, copy=False, ndmin=2, dtype=float)
105 | if y.shape[0] == 1:
106 | y = y.T
107 | P = np.concatenate((P, y), axis=1)
108 | if z is not None:
109 | z = np.array(z, copy=False, ndmin=2, dtype=float)
110 | if z.shape[0] == 1:
111 | z = z.T
112 | P = np.concatenate((P, z), axis=1)
113 | # covariance matrix
114 | cov = np.cov(P, rowvar=0)
115 | # singular value decomposition
116 | U, s, Vt = np.linalg.svd(cov)
117 | p, n = s.size, P.shape[0]
118 | # F percent point function
119 | fppf = F.ppf(pvalue, p, n-p)*(n-1)*p*(n+1)/n/(n-p)
120 | # semi-axes (largest first)
121 | saxes = np.sqrt(s*fppf)
122 | hypervolume = np.pi**(p/2)/gamma(p/2+1)*np.prod(saxes)
123 | # rotation matrix
124 | if p == 2 or p == 3:
125 | R = Vt
126 | if s.size == 2:
127 | angles = np.array([np.rad2deg(np.arctan2(R[1, 0], R[0, 0])),
128 | 90-np.rad2deg(np.arctan2(R[1, 0], -R[0, 0]))])
129 | else:
130 | angles = rotXYZ(R, unit='deg')
131 | # centroid of the hyperellipsoid
132 | center = np.mean(P, axis=0)
133 | else:
134 | R, angles = None, None
135 |
136 | if show and (p == 2 or p == 3):
137 | _plot(P, hypervolume, saxes, center, R, pvalue, units, ax)
138 |
139 | return hypervolume, saxes, angles, center, R
140 |
141 |
142 | def _plot(P, hypervolume, saxes, center, R, pvalue, units, ax):
143 | """Plot results of the hyperellipsoid function, see its help."""
144 |
145 | try:
146 | import matplotlib.pyplot as plt
147 | except ImportError:
148 | print('matplotlib is not available.')
149 | else:
150 | # code based on https://github.com/minillinim/ellipsoid:
151 | # parametric equations
152 | u = np.linspace(0, 2*np.pi, 100)
153 | if saxes.size == 2:
154 | x = saxes[0]*np.cos(u)
155 | y = saxes[1]*np.sin(u)
156 | # rotate data
157 | for i in range(len(x)):
158 | [x[i], y[i]] = np.dot([x[i], y[i]], R) + center
159 | else:
160 | v = np.linspace(0, np.pi, 100)
161 | x = saxes[0]*np.outer(np.cos(u), np.sin(v))
162 | y = saxes[1]*np.outer(np.sin(u), np.sin(v))
163 | z = saxes[2]*np.outer(np.ones_like(u), np.cos(v))
164 | # rotate data
165 | for i in range(len(x)):
166 | for j in range(len(x)):
167 | [x[i,j],y[i,j],z[i,j]] = np.dot([x[i,j],y[i,j],z[i,j]], R) + center
168 |
169 | if saxes.size == 2:
170 | if ax is None:
171 | fig, ax = plt.subplots(1, 1, figsize=(5, 5))
172 | # plot raw data
173 | ax.plot(P[:, 0], P[:, 1], '.-', color=[0, 0, 1, .5])
174 | # plot ellipse
175 | ax.plot(x, y, color=[0, 1, 0, 1], linewidth=2)
176 | # plot axes
177 | for i in range(saxes.size):
178 | # rotate axes
179 | a = np.dot(np.diag(saxes)[i], R).reshape(2, 1)
180 | # points for the axes extremities
181 | a = np.dot(a, np.array([-1, 1], ndmin=2))+center.reshape(2, 1)
182 | ax.plot(a[0], a[1], color=[1, 0, 0, .6], linewidth=2)
183 | ax.text(a[0, 1], a[1, 1], '%d' % (i + 1),
184 | fontsize=20, color='r')
185 | plt.axis('equal')
186 | plt.grid()
187 | title = r'Prediction ellipse (p=%4.2f): Area=' % pvalue
188 | if units is not None:
189 | units2 = ' [%s]' % units
190 | units = units + r'$^2$'
191 | title = title + r'%.2f %s' % (hypervolume, units)
192 | else:
193 | units2 = ''
194 | title = title + r'%.2f' % hypervolume
195 | else:
196 | from mpl_toolkits.mplot3d import Axes3D
197 | if ax is None:
198 | fig = plt.figure(figsize=(7, 7))
199 | ax = fig.add_axes([0, 0, 1, 1], projection='3d')
200 | ax.view_init(20, 30)
201 | # plot raw data
202 | ax.plot(P[:, 0], P[:, 1], P[:, 2], '.-', color=[0, 0, 1, .4])
203 | # plot ellipsoid
204 | ax.plot_surface(x, y, z, rstride=5, cstride=5, color=[0, 1, 0, .1],
205 | linewidth=1, edgecolor=[.1, .9, .1, .4])
206 | # ax.plot_wireframe(x, y, z, color=[0, 1, 0, .5], linewidth=1)
207 | # rstride=3, cstride=3, edgecolor=[0, 1, 0, .5])
208 | # plot axes
209 | for i in range(saxes.size):
210 | # rotate axes
211 | a = np.dot(np.diag(saxes)[i], R).reshape(3, 1)
212 | # points for the axes extremities
213 | a = np.dot(a, np.array([-1, 1], ndmin=2))+center.reshape(3, 1)
214 | ax.plot(a[0], a[1], a[2], color=[1, 0, 0, .6], linewidth=2)
215 | ax.text(a[0, 1], a[1, 1], a[2, 1], '%d' % (i+1),
216 | fontsize=20, color='r')
217 | lims = [np.min([P.min(), x.min(), y.min(), z.min()]),
218 | np.max([P.max(), x.max(), y.max(), z.max()])]
219 | ax.set_xlim(lims)
220 | ax.set_ylim(lims)
221 | ax.set_zlim(lims)
222 | title = r'Prediction ellipsoid (p=%4.2f): Volume=' % pvalue
223 | if units is not None:
224 | units2 = ' [%s]' % units
225 | units = units + r'$^3$'
226 | title = title + r'%.2f %s' % (hypervolume, units)
227 | else:
228 | units2 = ''
229 | title = title + r'%.2f' % hypervolume
230 | ax.set_zlabel('Z' + units2, fontsize=18)
231 |
232 | ax.set_xlabel('X' + units2, fontsize=18)
233 | ax.set_ylabel('Y' + units2, fontsize=18)
234 | plt.title(title)
235 | plt.show()
236 |
237 | return ax
238 |
239 |
240 | def rotXYZ(R, unit='deg'):
241 | """ Compute Euler angles from matrix R using XYZ sequence."""
242 |
243 | angles = np.zeros(3)
244 | angles[0] = np.arctan2(R[2, 1], R[2, 2])
245 | angles[1] = np.arctan2(-R[2, 0], np.sqrt(R[0, 0]**2 + R[1, 0]**2))
246 | angles[2] = np.arctan2(R[1, 0], R[0, 0])
247 |
248 | if unit[:3].lower() == 'deg': # convert from rad to degree
249 | angles = np.rad2deg(angles)
250 |
251 | return angles
252 |
--------------------------------------------------------------------------------
/wiicop.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # to test speed of wii board data acquisition
3 |
4 | import os
5 | import sys
6 | from subprocess import run
7 | import time
8 | import threading
9 | from queue import Queue
10 | import errno
11 | import numpy as np
12 | import pandas as pd
13 | import pickle
14 | from scipy import stats
15 | import pyudev
16 | import xwiimote
17 | import select
18 | import configparser
19 | from WiiCopFunctions import connectBB, calcCOP, procBBdata, txtmenu,\
20 | get_sessionname, listdirs, get_acq_info, getnsamp, validcode
21 | from datetime import datetime
22 | import matplotlib as mpl
23 | import matplotlib.pyplot as plt
24 | from matplotlib.animation import FuncAnimation
25 |
26 | # user defined options
27 | # ~~~~~~~~~~~~~~~~~~~~
28 | # sample size for calibration
29 | smp_size = 50
30 | # outlier z-score threshold defined here
31 | out_thresh = 3
32 | # percentage zeros %age max limit defined here
33 | maxpcnt = 5
34 | # Pandas series to define calibration weights
35 | # calib_wgts = pd.Series({0:5,1:10,2:18})
36 | calib_wgts = pd.Series({0:8,1:12,2:16})
37 | # calibration units ('Kgs' or 'lbs')
38 | # calib_units = 'lbs'
39 | calib_units = 'Kgs'
40 | # set the time interval for FuncAnimation (milliseconds)
41 | anim_interval = 50
42 |
43 | # constants
44 | # ~~~~~~~~~
45 | # dictionary for enumeration of sensors
46 | SENS_DCT = {0:'Top right',1:'Bottom right',2:'Top left',3:'Bottom left'}
47 | # number of sensors
48 | N_S = 4
49 | # lbs to kgs conversion factor
50 | LBS2KGS = 0.453592
51 | # Balance board dimensions width and length in mm (Leach, J.M., Mancini, M., Peterka, R.J., Hayes,
52 | # T.L. and Horak, F.B., 2014. Validating and calibrating the Nintendo Wii
53 | # balance board to derive reliable center of pressure measures. Sensors,
54 | # 14(10), pp.18244-18267.)
55 | BB_Y = 238
56 | BB_X = 433
57 |
58 |
59 | # FUNCTION DEFINITIONS
60 | def aqc_name(acq_info):
61 | # This is returns a string for labelling acquisition and for file name
62 | tmp = acq_info.copy()
63 | afn = 'subj'
64 | afn = afn+tmp.pop('subject_code')
65 | acqt = tmp.pop('acq_time')
66 | for iks in tmp.values():
67 | afn = afn+'_'+iks
68 | if acqt!='inf':
69 | afn = afn+'_t'+acqt
70 | else:
71 | afn = afn+'_tmanual'
72 | return afn
73 |
74 |
75 | # CLASS DEFINITIONS
76 | # create a class based on threading.thread
77 | class wii_thread(threading.Thread):
78 | def __init__ (self,bb,cal_mod,BB_X,BB_Y):
79 | threading.Thread.__init__(self)
80 | self.runflag = True
81 | self.storeflag = False
82 | self.n_s = 4
83 | self.bbdev = xwiimote.iface(bb.sys_path)
84 | self.p = select.poll()
85 | self.p.register(self.bbdev.get_fd(), select.POLLIN)
86 | # open bb device
87 | self.bbdev.open(xwiimote.IFACE_BALANCE_BOARD)
88 | # create xwiimote event structure
89 | self.revt = xwiimote.event()
90 | # create numpy array to store data from board
91 | self.tmp_dat = np.empty((1,self.n_s))
92 | self.cop = np.empty((1,2))
93 | self.cop_dat = np.empty((0,2))
94 | self.cal_mod = cal_mod
95 | self.BB_X = BB_X
96 | self.BB_Y = BB_Y
97 |
98 | def run(self):
99 | lock.acquire()
100 | runflag = self.runflag
101 | lock.release()
102 | while runflag:
103 | polls = self.p.poll()
104 | try:
105 | self.bbdev.dispatch(self.revt)
106 | tdat = self.revt.get_time()
107 | for i_s in range(self.n_s):
108 | self.tmp_dat[0,i_s] = self.revt.get_abs(i_s)[0]
109 | self.cop = calcCOP(self.tmp_dat,self.cal_mod,self.BB_X,self.BB_Y)
110 | lock.acquire()
111 | storeflag = self.storeflag
112 | lock.release()
113 | if storeflag:
114 | wii_q.put(np.concatenate((self.cop,np.array(tdat))))
115 | except IOError as e:
116 | # do nothing if resource unavailable
117 | if e.errno != errno.EAGAIN:
118 | print(e)
119 | self.p.unregister(self.bbdev.get_fd())
120 | lock.acquire()
121 | runflag = self.runflag
122 | lock.release()
123 | # close down BB interface
124 | self.bbdev.close(xwiimote.IFACE_BALANCE_BOARD)
125 | self.p.unregister(self.bbdev.get_fd())
126 |
127 |
128 | class plot_cop:
129 | 'object to implement plotting cop data in animation loop'
130 |
131 | def __init__(self,aqc_info,BB_X,BB_Y):
132 | self.acq_info = aqc_info
133 | # Initial instructions
134 | self.text_start = 'Press Spacebar to start recording'
135 | self.text_stop = 'Press Spacebar to stop recording'
136 | # remove toolbar
137 | mpl.rcParams['toolbar'] = 'None'
138 | # Create new figure and an axes which fills it...
139 | # set figure width in inches
140 | fig_width = 12
141 | # set fig ratio based on size of bboard rectange whose corners are sensors
142 | self.fig = plt.figure(figsize=(fig_width, fig_width*BB_Y/BB_X))
143 | self.fig.canvas.set_window_title(aqc_name(self.acq_info))
144 | # frameon determines whether background of frame will be drawn
145 | ax = self.fig.add_axes([0, 0, 1, 1], frameon=False)
146 | ax.set_xlim(-BB_X/2, BB_X/2), ax.set_xticks([])
147 | ax.set_ylim(-BB_Y/2, BB_Y/2), ax.set_yticks([])
148 | # create a scatter object at initial position 0,0
149 | self.scat = ax.scatter(0, 0, s=200, lw=0.5, facecolors='green')
150 | # create text box
151 | self.text_h = ax.text(0.02, 0.98, self.text_start, verticalalignment='top',horizontalalignment='left',
152 | transform=ax.transAxes, fontsize=12, bbox=dict(facecolor='white'), gid = 'notrec')
153 | # create timer object
154 | if self.acq_info['acq_time'] != 'inf':
155 | acq_time_ms = int(self.acq_info['acq_time'])*1000
156 | self.acq_timer = self.fig.canvas.new_timer(interval=acq_time_ms)
157 | self.acq_timer.add_callback(self.t_event)
158 | # attach keypress event handler to figure canvas
159 | self.fig.canvas.mpl_connect('key_press_event', self.onkeypress)
160 |
161 | def animate(self,cop_i):
162 | # plot COP
163 | lock.acquire()
164 | cop = thd.cop
165 | lock.release()
166 | self.scat.set_offsets(cop)
167 |
168 | # Keypress event handler
169 | def onkeypress(self,evt):
170 | if evt.key==' ':
171 | # spacebar pressed
172 | if self.text_h.get_gid()=='notrec':
173 | # start recording data...
174 | # change colour of dot
175 | self.scat.set_facecolors('red')
176 | plt.draw()
177 | # set gid to recording to flag recording state
178 | self.text_h.set_gid('rec')
179 | if self.acq_info['acq_time'] != 'inf':
180 | # timed acquisition - start timer
181 | self.acq_timer.start()
182 | self.text_h.set_text('Timed acquisition')
183 | else:
184 | # manual acq
185 | # change instructions
186 | self.text_h.set_text(self.text_stop)
187 | # set thread to store data in queue
188 | lock.acquire()
189 | thd.storeflag = True
190 | lock.release()
191 |
192 | elif self.text_h.get_gid()=='rec':
193 | # stop recording
194 | if self.acq_info['acq_time'] != 'inf':
195 | # timed acq - do nothing
196 | pass
197 | else:
198 | # recording data, manual acq
199 | lock.acquire()
200 | thd.storeflag = False
201 | thd.runflag = False
202 | lock.release()
203 | plt.close()
204 | else:
205 | print('error in onkeypress - unrecognised text_h gid')
206 |
207 | # callback function for timer
208 | def t_event(self):
209 | # stop thread queuing data and stop it running
210 | lock.acquire()
211 | thd.storeflag = False
212 | thd.runflag = False
213 | lock.release()
214 | self.acq_timer.remove_callback(self.t_event)
215 | plt.close()
216 |
217 |
218 | # ~~~~~~~~~~~~~~~
219 | # MAIN ROUTINE
220 | # ~~~~~~~~~~~~~~~
221 |
222 | # to suppress the annoying warning
223 | import warnings
224 | warnings.filterwarnings('ignore')
225 | # clear terminal
226 | run('clear')
227 |
228 | # connect to balance board and exit if none connected
229 | bb = connectBB()
230 | if bb==None:
231 | time.sleep(5)
232 | print('Exiting')
233 | sys.exit()
234 |
235 | # SELECT STUDY
236 | # ~~~~~~~~~~~~
237 | # select study and read config file
238 | # get directories
239 | script_dir = os.path.dirname(os.path.realpath(__file__))
240 | config_dir = os.path.join(script_dir,'config_files')
241 |
242 | # Get list of config files in config_dir
243 | config_files_t = os.listdir(config_dir)
244 | config_files = [x for x in config_files_t if '.config' in x]
245 |
246 | # use config parser to read each config file for names of study
247 | s_names = list()
248 | config_tmp = configparser.ConfigParser()
249 | for i_f in config_files:
250 | cf = os.path.join(config_dir,i_f)
251 | config_tmp.read(cf)
252 | s_names.append(config_tmp['study info']['study_name'])
253 |
254 | # user interface to get user selection
255 | del(config_tmp)
256 | chc = txtmenu('Select study',s_names)
257 |
258 | # read selected config file
259 | config = configparser.ConfigParser()
260 | config.read(os.path.join(config_dir,config_files[chc]))
261 |
262 |
263 | # SETUP SESSION
264 | # ~~~~~~~~~~~~~
265 | # get path of study directory
266 | std_dir = config['study info']['study_dir']
267 |
268 | # get path of session directory...
269 | # read all names of all sessions in study directory
270 | prev_sesh = listdirs(std_dir)
271 |
272 | # default name for session
273 | tmnow = datetime.now()
274 | def_name = tmnow.strftime("%b_%d_%Y_%p")
275 | s_dir_nm = get_sessionname(prev_sesh,def_name)
276 |
277 | # check if session dir already exists
278 | if s_dir_nm in prev_sesh:
279 | print('Session already exists. Start again and choose another name')
280 | time.sleep(5)
281 | sys.exit()
282 |
283 | # session path
284 | sesh_path = os.path.join(std_dir,s_dir_nm)
285 | # create directory
286 | os.mkdir(sesh_path,mode=0o775)
287 |
288 |
289 | # CALIBRATE BOARD
290 | # ~~~~~~~~~~~~~~~
291 | # preallocate array for mean of sensor readings for each calibration weight
292 | n_calib = len(calib_wgts)
293 | sens_mean = np.empty([N_S,n_calib])
294 | print('\n\nStarting calibration sequence...\nApply weights as close as possible to the centre...\n')
295 | for i_ws in range(n_calib):
296 | print('Apply',str(calib_wgts[i_ws]),calib_units,'to balance board\n')
297 | input_str = input('Press return when ready...\n\n')
298 | # read data
299 | sens_dat = procBBdata(bb, getnsamp, smp_size)
300 | # print(sens_dat)
301 | # for each sensor...
302 | for i_s in range(N_S):
303 | sens_dat1 = sens_dat[:,i_s]
304 | # print out percentage of readings == 0
305 | prctzero = sum(sens_dat1==0)/smp_size*100
306 | if prctzero > 0:
307 | print('Warning: percentage zeros for {0} sensor = {1:.2f}%'.format(SENS_DCT[i_s],prctzero))
308 | # detect if all values are for sensor are zero
309 | if prctzero > maxpcnt:
310 | print('Error: percentage zeros for {0} sensor exceeds maximum ({1:.2f}%).'.format(SENS_DCT[i_s],prctzero))
311 | print('Use heavier weight or move board to another location.')
312 | print('Exiting')
313 | time.sleep(5)
314 | sys.exit()
315 | else:
316 | # get zscores for sensor
317 | zscrs = stats.zscore(sens_dat1)
318 | # replace those outside threshold with nans
319 | sens_dat1[np.absolute(zscrs) > out_thresh] = np.nan
320 | # get mean excluding nans.
321 | sens_mean[i_s,i_ws] = np.nanmean(sens_dat1)
322 |
323 | # For each sensor get a linear model to calibrate data...
324 | # create dictionary to store results to file and array for model parameters
325 | # 'm'-slopes,'c'-intercepts, 'p'-p-values, 'r'- r values, 'se' -standard errors
326 | # cal_mod row zero = slopes, row 1 = intercepts. Each col represents a sensor
327 | # Calibration weights are divided by number of sensors
328 | cal_mod = np.empty([2,N_S])
329 | cal_dat = dict()
330 | dc = dict()
331 | for i_s in range(N_S):
332 | cal_m, cal_c, cal_r, cal_p, cal_se = stats.linregress(sens_mean[i_s,:],calib_wgts.values/N_S)
333 |
334 | # store results to dictionary
335 | dc.update({'m':cal_m})
336 | dc.update({'c':cal_c})
337 | dc.update({'r':cal_r})
338 | dc.update({'p':cal_p})
339 | dc.update({'se':cal_se})
340 |
341 | # store model parameters to an array
342 | cal_mod[0,i_s] = cal_m
343 | cal_mod[1,i_s] = cal_c
344 | cal_dat.update({SENS_DCT[i_s]:dc})
345 |
346 | # save calibration data in session directory
347 | calib_dat = {'model':cal_mod, 'details':cal_dat}
348 | cfn = os.path.join(sesh_path,'calibration_dat')
349 | with open(cfn,'wb') as fptr:
350 | pickle.dump(calib_dat,fptr)
351 | print('Remove calibration weights from balance board\n\n')
352 |
353 | # #TEST overide calibration
354 | # cal_mod = np.array([[0.01776906,0.01645395,0.02366412,0.02252513],[ 0.39208467,-0.7261971,-0.05245845,-3.55288195]])
355 |
356 | # GET SERIES OF ACQUISITIONS
357 | loop_flag = True
358 |
359 | # set up objects for data acquisition
360 | lock = threading.Lock()
361 | wii_q = Queue(maxsize=0)
362 |
363 |
364 | while loop_flag:
365 |
366 | # Get acquisition info
367 | # {'group': 'case', 'acq_time': 'inf', 'subject_code': '121', 'epoch': 'before'}
368 | acq_info = get_acq_info(config)
369 |
370 | # create plot_cop instance
371 | pltcop_obj = plot_cop(acq_info,BB_X,BB_Y)
372 | thd = wii_thread(bb,cal_mod,BB_X,BB_Y)
373 |
374 | # Start thread
375 | thd.start()
376 |
377 | # PLOT ANIMATION - interval can't be too small or it gives an attribute error
378 | animation = FuncAnimation(pltcop_obj.fig, pltcop_obj.animate,interval=anim_interval)
379 | plt.show()
380 |
381 | thd.join()
382 |
383 | # get data from queue and write to file
384 | acq_data = np.empty((0,4))
385 | while not(wii_q.empty()):
386 | acq_data = np.vstack((acq_data,wii_q.get()))
387 | # convert 3rd (secs) & 4th (microsecs) col to 1 col of secs
388 | acq_data[:,2] = acq_data[:,2] + acq_data[:,3]/1000000
389 | # convert to pandas dataframe
390 | acq_dat_df = pd.DataFrame(data=acq_data[:,(0,1,2)],columns=('copx','copy','time'))
391 | # subtract the time of the first reading from the others - start a time=o
392 | acq_dat_df['time'] = acq_dat_df['time'] - acq_dat_df.ix[0,'time']
393 | # write to file...
394 | # get save file name...
395 | sfn = aqc_name(acq_info)+'.csv'
396 | sfn = os.path.join(sesh_path,sfn)
397 | print(sfn)
398 | acq_dat_df.to_csv(sfn,index=False)
399 |
400 | # ask user if they wish to do another acquisition
401 | chc = input('Get another acquisition? (y/n)\n')
402 | if chc in ['y','Y']:
403 | pass
404 | # clear terminal
405 | #run('clear')
406 | else:
407 | loop_flag = False
408 | # clear terminal
409 | # run('clear')
410 |
411 | # END OF ACQUISITION LOOP
412 |
--------------------------------------------------------------------------------
/wiicop_v1.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # To test a single loop of the acquisition series loop. No timer functionality to begin with
3 |
4 | import pyudev
5 | import xwiimote
6 | import errno
7 | import select
8 | import sys
9 | import os
10 | import time
11 | from subprocess import run
12 | import numpy as np
13 | from scipy import stats
14 | import pandas as pd
15 | import pickle
16 | import configparser
17 | from WiiCopFunctions import *
18 | # from WiiCopFunctions import (get_sessionname, txtmenu, listdirs,
19 | # get_acq_info, connectBB, calcCOP, procBBdata, getnsamp, validcode)
20 | from datetime import datetime
21 | import matplotlib as mpl
22 | import matplotlib.pyplot as plt
23 | from matplotlib.animation import FuncAnimation
24 |
25 | # user defined options
26 | # ~~~~~~~~~~~~~~~~~~~~
27 | # sample size for calibration
28 | smp_size = 50
29 | # outlier z-score threshold defined here
30 | out_thresh = 3
31 | # percentage zeros %age max limit defined here
32 | maxpcnt = 5
33 | # Pandas series to define calibration weights
34 | # calib_wgts = pd.Series({0:5,1:10,2:18})
35 | calib_wgts = pd.Series({0:5,1:9,2:16.5})
36 | # calibration units ('Kgs' or 'lbs')
37 | # calib_units = 'lbs'
38 | calib_units = 'Kgs'
39 | # set the time interval for FuncAnimation (milliseconds)
40 | anim_interval = 100
41 |
42 | # constants
43 | # ~~~~~~~~~
44 | # dictionary for enumeration of sensors
45 | SENS_DCT = {0:'Top right',1:'Bottom right',2:'Top left',3:'Bottom left'}
46 | # number of sensors
47 | N_S = 4
48 | # lbs to kgs conversion factor
49 | LBS2KGS = 0.453592
50 | # Balance board dimensions width and length in mm (Leach, J.M., Mancini, M., Peterka, R.J., Hayes,
51 | # T.L. and Horak, F.B., 2014. Validating and calibrating the Nintendo Wii
52 | # balance board to derive reliable center of pressure measures. Sensors,
53 | # 14(10), pp.18244-18267.)
54 | BB_Y = 238
55 | BB_X = 433
56 |
57 | # define acquisition object
58 | class acq_object:
59 | 'object to implement plotting data in animation loop, storage and saving data'
60 |
61 | # This function initializes the necessary variables to calculate the COP (center of pressure)
62 | # aqc_info: dictionary of acquisition specific info
63 | # sesh_path: path to session directory
64 | # bb: a pyudev device object for balance board
65 | # cal_mod: calibration model
66 | def __init__(self,aqc_info,sesh_path,bb,cal_mod):
67 |
68 | # create numpy array to store data initially from board
69 | self.tmp_dat = np.empty((1,N_S))
70 | self.sens_dat = np.empty((0,N_S))
71 | self.time_dat = np.empty((0,2))
72 | self.cop_dat = np.empty((0,2))
73 |
74 | # store session path
75 | self.sesh_path = sesh_path
76 |
77 | # create var to store start and end time
78 | save_start = 0
79 | save_end = 0
80 |
81 | # set save data to file and array flag
82 | self.savedatf = False
83 | self.storedat = False
84 |
85 | # input acquisition info
86 | self.acq_info = aqc_info
87 |
88 | #initializing wii and poll objects
89 | self.p_obj = select.poll()
90 | self.bbdev = xwiimote.iface(bb.sys_path)
91 |
92 | # register bbdev to pollong object
93 | self.p_obj.register(self.bbdev.get_fd(), select.POLLIN)
94 | # open bb device
95 | self.bbdev.open(xwiimote.IFACE_BALANCE_BOARD)
96 |
97 | # event structure
98 | self.revt = xwiimote.event()
99 | # calibration model
100 | self.cal_mod = cal_mod
101 |
102 |
103 | def animate(self,cop_i):
104 | polls = self.p_obj.poll()
105 | for fd, evt in polls:
106 | try:
107 | self.bbdev.dispatch(self.revt)
108 |
109 | # read each sensor
110 | for i_s in range(N_S):
111 | # get the 'x' data from the Absolute Motion Payload for each sensor
112 | self.tmp_dat[0,i_s] = self.revt.get_abs(i_s)[0]
113 |
114 | # get COP (center of pressure)
115 | cop_p = calcCOP(self.tmp_dat,self.cal_mod,BB_X,BB_Y)
116 |
117 | # plot COP
118 | scat.set_offsets(cop_p)
119 |
120 | if self.storedat:
121 |
122 | # save data in arrays...
123 | self.cop_dat = np.vstack((self.cop_dat,cop_p))
124 | self.time_dat = np.vstack((self.time_dat,np.array(self.revt.get_time())))
125 | self.sens_dat = np.vstack((self.sens_dat,self.tmp_dat))
126 |
127 | except IOError as e:
128 |
129 | # if resource unavailable do nothing
130 | if e.errno != errno.EAGAIN:
131 | print(e)
132 |
133 | # This is called to put data in dictionary & save as a pickled binary file
134 | def save_bbdat(self):
135 |
136 | bbdat = {'rawsens':self.sens_dat,'timedat':self.time_dat,'cop':self.cop_dat}
137 | # get save file name...
138 | sfn = self.aqc_name()+'.dat'
139 | sfn = os.path.join(self.sesh_path,sfn)
140 | with open(sfn,'wb') as fptr:
141 | pickle.dump(bbdat,fptr)
142 |
143 | # This is returns a string for labelling acquisition and for file name
144 | def aqc_name(self):
145 |
146 | tmp = self.acq_info.copy()
147 | afn = 'subj'
148 | afn = afn+tmp.pop('subject_code')
149 | acqt = tmp.pop('acq_time')
150 | for iks in tmp.values():
151 | afn = afn+'_'+iks
152 | if acqt!='inf':
153 | afn = afn+'_'+acqt
154 | return afn
155 |
156 | # This closes the device
157 | def shutdown(self):
158 |
159 | self.bbdev.close(xwiimote.IFACE_BALANCE_BOARD)
160 | self.p_obj.unregister(self.bbdev.get_fd())
161 |
162 |
163 | # ~~~~~~~~~~~~~~~
164 | # MAIN ROUTINE
165 | # ~~~~~~~~~~~~~~~
166 |
167 | # to suppress the annoying warning
168 | import warnings
169 | warnings.filterwarnings('ignore')
170 | # clear terminal
171 | run('clear')
172 |
173 | # connect to balance board and exit if none connected
174 | bb = connectBB()
175 | if bb==None:
176 | time.sleep(5)
177 | print('Exiting')
178 | sys.exit()
179 |
180 |
181 | # SELECT STUDY
182 | # ~~~~~~~~~~~~
183 | # select study and read config file
184 | # get directories
185 | script_dir = os.path.dirname(os.path.realpath(__file__))
186 | config_dir = os.path.join(script_dir,'config_files')
187 |
188 | # Get list of config files in config_dir
189 | config_files_t = os.listdir(config_dir)
190 | config_files = [x for x in config_files_t if '.config' in x]
191 |
192 | # use config parser to read each config file for names of study
193 | s_names = list()
194 | config_tmp = configparser.ConfigParser()
195 | for i_f in config_files:
196 | cf = os.path.join(config_dir,i_f)
197 | config_tmp.read(cf)
198 | s_names.append(config_tmp['study info']['study_name'])
199 |
200 | # user interface to get user selection
201 | del(config_tmp)
202 | chc = txtmenu('Select study',s_names)
203 |
204 | # read selected config file
205 | config = configparser.ConfigParser()
206 | config.read(os.path.join(config_dir,config_files[chc]))
207 |
208 |
209 | # SETUP SESSION
210 | # ~~~~~~~~~~~~~
211 | # get path of study directory
212 | std_dir = config['study info']['study_dir']
213 |
214 | # get path of session directory...
215 | # read all names of all sessions in study directory
216 | prev_sesh = listdirs(std_dir)
217 |
218 | # default name for session
219 | tmnow = datetime.now()
220 | def_name = tmnow.strftime("%b_%d_%Y_%p")
221 | s_dir_nm = get_sessionname(prev_sesh,def_name)
222 |
223 | # check if session dir already exists
224 | if s_dir_nm in prev_sesh:
225 | print('Session already exists. Start again and choose another name')
226 | time.sleep(5)
227 | sys.exit()
228 |
229 | # session path
230 | sesh_path = os.path.join(std_dir,s_dir_nm)
231 | # create directory
232 | os.mkdir(sesh_path,mode=0o775)
233 |
234 |
235 | # CALIBRATE BOARD
236 | # ~~~~~~~~~~~~~~~
237 | # preallocate array for mean of sensor readings for each calibration weight
238 | n_calib = len(calib_wgts)
239 | sens_mean = np.empty([N_S,n_calib])
240 | print('\n\nStarting calibration sequence...\nApply weights as close as possible to the centre...\n')
241 | for i_ws in range(n_calib):
242 | print('Apply',str(calib_wgts[i_ws]),calib_units,'to balance board\n')
243 | input_str = input('Press return when ready...\n\n')
244 | # read data
245 | sens_dat = procBBdata(bb, getnsamp, smp_size)
246 | # print(sens_dat)
247 | # for each sensor...
248 | for i_s in range(N_S):
249 | sens_dat1 = sens_dat[:,i_s]
250 | # print out percentage of readings == 0
251 | prctzero = sum(sens_dat1==0)/smp_size*100
252 | if prctzero > 0:
253 | print('Warning: percentage zeros for {0} sensor = {1:.2f}%'.format(SENS_DCT[i_s],prctzero))
254 | # detect if all values are for sensor are zero
255 | if prctzero > maxpcnt:
256 | print('Error: percentage zeros for {0} sensor exceeds maximum ({1:.2f}%).'.format(SENS_DCT[i_s],prctzero))
257 | print('Use heavier weight or move board to another location.')
258 | print('Exiting')
259 | time.sleep(5)
260 | sys.exit()
261 | else:
262 | # get zscores for sensor
263 | zscrs = stats.zscore(sens_dat1)
264 | # replace those outside threshold with nans
265 | sens_dat1[np.absolute(zscrs) > out_thresh] = np.nan
266 | # get mean excluding nans.
267 | sens_mean[i_s,i_ws] = np.nanmean(sens_dat1)
268 |
269 | # For each sensor get a linear model to calibrate data...
270 | # create dictionary to store results to file and array for model parameters
271 | # 'm'-slopes,'c'-intercepts, 'p'-p-values, 'r'- r values, 'se' -standard errors
272 | # cal_mod row zero = slopes, row 1 = intercepts. Each col represents a sensor
273 | # Calibration weights are divided by number of sensors
274 | cal_mod = np.empty([2,N_S])
275 | cal_dat = dict()
276 | dc = dict()
277 | for i_s in range(N_S):
278 | cal_m, cal_c, cal_r, cal_p, cal_se = stats.linregress(sens_mean[i_s,:],calib_wgts.values/N_S)
279 |
280 | # store results to dictionary
281 | dc.update({'m':cal_m})
282 | dc.update({'c':cal_c})
283 | dc.update({'r':cal_r})
284 | dc.update({'p':cal_p})
285 | dc.update({'se':cal_se})
286 |
287 | # store model parameters to an array
288 | cal_mod[0,i_s] = cal_m
289 | cal_mod[1,i_s] = cal_c
290 | cal_dat.update({SENS_DCT[i_s]:dc})
291 |
292 | # save calibration data in session directory
293 | calib_dat = {'model':cal_mod, 'details':cal_dat}
294 | cfn = os.path.join(sesh_path,'calibration_dat')
295 | with open(cfn,'wb') as fptr:
296 | pickle.dump(calib_dat,fptr)
297 | print('Remove calibration weights from balance board\n\n')
298 |
299 | ##TEST overide calibration
300 | #cal_mod = np.array([[0.01776906,0.01645395,0.02366412,0.02252513],[ 0.39208467,-0.7261971,-0.05245845,-3.55288195]])
301 |
302 |
303 | # GET SERIES OF ACQUISITIONS
304 | loop_flag = True
305 |
306 | while loop_flag:
307 |
308 | # Get acquisition info
309 | # {'group': 'case', 'acq_time': 'inf', 'subject_code': '121', 'epoch': 'before'}
310 | acq_info = get_acq_info(config)
311 |
312 | # get acquisition time in milliseconds if timed
313 | if acq_info['acq_time'] != 'inf':
314 | acq_time_ms = int(acq_info['acq_time'])*1000
315 |
316 | # create acq_object instance
317 | acqobj = acq_object(acq_info,sesh_path,bb,cal_mod)
318 |
319 | # CREATE WINDOW
320 | # Initial instructions
321 | text_start = 'Press Spacebar to start recording'
322 | text_stop = 'Press Spacebar to stop recording'
323 |
324 | # remove toolbar
325 | mpl.rcParams['toolbar'] = 'None'
326 |
327 | # Create new figure and an axes which fills it...
328 | # set figure width in inches
329 | fig_width = 12
330 |
331 | # set fig ratio based on size of bboard rectange whose corners are sensors
332 | fig = plt.figure(figsize=(fig_width, fig_width*BB_Y/BB_X))
333 | fig.canvas.set_window_title(acqobj.aqc_name())
334 |
335 | # frameon determines whether background of frame will be drawn
336 | ax = fig.add_axes([0, 0, 1, 1], frameon=False)
337 | ax.set_xlim(-BB_X/2, BB_X/2), ax.set_xticks([])
338 | ax.set_ylim(-BB_Y/2, BB_Y/2), ax.set_yticks([])
339 |
340 | # create a scatter object at initial position 0,0
341 | cop_x = 0
342 | cop_y = 0
343 | scat = ax.scatter(cop_x, cop_x, s=200, lw=0.5, facecolors='green')
344 |
345 | # create text box
346 | text_h = ax.text(0.02, 0.98, text_start, verticalalignment='top',horizontalalignment='left',
347 | transform=ax.transAxes, fontsize=12, bbox=dict(facecolor='white'), gid = 'notrec')
348 |
349 | # DEFINING KEYPRESS EVENT HANDLER
350 | def onkeypress(evt):
351 | if evt.key==' ':
352 |
353 | # spacebar pressed
354 | if text_h.get_gid()=='notrec':
355 | # not recording data...
356 | # change colour of dot
357 | scat.set_facecolors('red')
358 | plt.draw()
359 | # set gid to recording to flag recording state
360 | text_h.set_gid('rec')
361 | if acq_info['acq_time'] != 'inf':
362 | # timed acquisition - start timer
363 | acq_timer.start()
364 | text_h.set_text('Timed acquisition')
365 | # set acquisition object to store data in array
366 | acqobj.storedat = True
367 | else:
368 | # manual acq
369 | # change instructions
370 | text_h.set_text(text_stop)
371 | # set acquisition object to store data in array
372 | acqobj.storedat = True
373 |
374 | elif text_h.get_gid()=='rec':
375 |
376 | if acq_info['acq_time'] != 'inf':
377 | # timed acq - do nothing
378 | pass
379 | else:
380 | # recording data, manual acq
381 | acqobj.storedat = False
382 | acqobj.savedatf = True
383 | plt.close()
384 | else:
385 | print('error in onkeypress - unrecognised text_h gid')
386 |
387 | def t_event():
388 | # callback function for timer
389 | acqobj.storedat = False
390 | acqobj.savedatf = True
391 | acq_timer.remove_callback(t_event)
392 | plt.close()
393 |
394 | # create timer object
395 | if acq_info['acq_time'] != 'inf':
396 | acq_timer = fig.canvas.new_timer(interval=acq_time_ms)
397 | acq_timer.add_callback(t_event)
398 |
399 | # attach keypress event handler to figure canvas
400 | cid = fig.canvas.mpl_connect('key_press_event', onkeypress)
401 |
402 | # PLOT ANIMATION - interval can't be too small or it gives an attribute error
403 | animation = FuncAnimation(fig, acqobj.animate, interval=anim_interval)
404 | plt.show()
405 |
406 | # save data if flag = True
407 | print(acqobj.savedatf)
408 | if acqobj.savedatf:
409 | acqobj.save_bbdat()
410 | print('\nSession {}:'.format(s_dir_nm))
411 | print(' Data has been saved in file {}\n'.format(acqobj.aqc_name()+'.dat'))
412 | else:
413 | print('\nNo data has been saved in this acquisition\n')
414 |
415 | # shutdown devices
416 | acqobj.shutdown()
417 |
418 | # ask user if they wish to do another acquisition
419 | chc = input('Get another acquisition? (y/n)\n')
420 | if chc in ['y','Y']:
421 | pass
422 | # clear terminal
423 | #run('clear')
424 | else:
425 | loop_flag = False
426 | # clear terminal
427 | # run('clear')
428 |
429 | # END OF ACQUISITION LOOP
430 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------