├── .gitignore ├── LICENSE ├── MANIFEST.in ├── README.md ├── setup.cfg ├── setup.py └── tobii_research_addons ├── ScreenBasedCalibrationValidation.py ├── __init__.py └── vectormath.py /.gitignore: -------------------------------------------------------------------------------- 1 | **/__pycache__/ 2 | *.py[cod] 3 | env* -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include LICENSE 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # prosdk-addons-python - Calibration validation 2 | 3 | ## What is it 4 | Add-ons for the Tobii Pro SDK. 5 | 6 | ![alt text](https://www.tobiipro.com/imagevault/publishedmedia/6rkt3jb83qlottsfh1ts/Tobii-Pro-SDK-with-VR-3_1-banner.jpg) 7 | 8 | 9 | The Tobii Pro SDK is available at: https://www.tobiipro.com/product-listing/tobii-pro-sdk/
10 | Documentation to the API: http://developer.tobiipro.com/python.html 11 | Getting started: http://developer.tobiipro.com/python/python-getting-started.html 12 | 13 | Do not hesitate to contribute to this project and create issues if you find something that might be wrong or could be improved. 14 | 15 | ## Installation 16 | 17 | * Download or clone this folder. 18 | * Navigate to the cloned or downloaded and unpacked folder. 19 | * Install by using pip. 20 | ``` 21 | pip install . 22 | ``` 23 | 24 | The Tobii Pro SDK Python package will be installed automatically by pip. 25 | 26 | ## Features 27 | 28 | ### Calibration Validation 29 | 30 | The package contains functionality for validating calibrations by calculating various statistics for different 31 | stimuli points. Note: There are no functionality for actually presenting the stimuli points on screen. 32 | 33 | #### Example 34 | Before starting a calibration validation, some setup with the desired tracker is needed. 35 | 36 | ```python 37 | import time 38 | import tobii_research as tr 39 | from tobii_research_addons import ScreenBasedCalibrationValidation, Point2 40 | 41 | eyetracker_address = 'Replace the address of the desired tracker' 42 | eyetracker = tr.EyeTracker(eyetracker_address) 43 | ``` 44 | 45 | Now it is possible to create a calibration validation object with the eye tracker object previously created. 46 | More information about this class and its methods can be found in the [ScreenBasedCalibrationValidation](./source/ScreenBasedCalibrationValidation.py) definition. 47 | 48 | ```python 49 | sample_count = 30 50 | timeout_ms = 1000 51 | 52 | calib = ScreenBasedCalibrationValidation(eyetracker, sample_count, timeout_ms) 53 | ``` 54 | 55 | The next step is to enter validation mode. Note that this action will cause the tracker to start collecting gaze data. 56 | 57 | ```python 58 | calib.enter_validation_mode() 59 | ``` 60 | 61 | List the points that are to be used during the validation. 62 | 63 | ```python 64 | points_to_collect = [ 65 | Point2(0.1, 0.1), 66 | Point2(0.1, 0.9), 67 | Point2(0.5, 0.5), 68 | Point2(0.9, 0.1), 69 | Point2(0.9, 0.9)] 70 | ``` 71 | 72 | When collecting data a point should be presented on the screen in the appropriate position. 73 | 74 | ```python 75 | for point in points_to_collect: 76 | # Visualize point on screen 77 | # ... 78 | calib.start_collecting_data(point) 79 | while calib.is_collecting_data: 80 | time.sleep(0.5) 81 | ``` 82 | 83 | Next, just call the compute method to obtain the calibration validation result object. 84 | 85 | ```python 86 | calibration_result = calib.compute() 87 | ``` 88 | 89 | Now the calibration validation result should be available for inspection. 90 | 91 | More information about the calibration validation result can be found in the [CalibrationValidationResult](./source/ScreenBasedCalibrationValidation.py) class. 92 | 93 | If the result is satisfactory then the only thing left to do is to leave validation mode. 94 | This action will clear all the data collected in the current validation session and stop the gaze data collection 95 | from the tracker. 96 | 97 | ```python 98 | calib.leave_validation_mode() 99 | ``` 100 | 101 | You can also use the with statement to simplify the workings with the ScreenBasedCalibrationValidation object. It will 102 | automatically enter and leave calibration mode. 103 | 104 | ```python 105 | sample_count = 30 106 | timeout_ms = 1000 107 | points_to_collect = [ 108 | Point2(0.1, 0.1), 109 | Point2(0.1, 0.9), 110 | Point2(0.5, 0.5), 111 | Point2(0.9, 0.1), 112 | Point2(0.9, 0.9)] 113 | 114 | with ScreenBasedCalibrationValidation(eyetracker, sample_count, timeout_ms) as calib: 115 | for point in points_to_collect: 116 | # Visualize point on screen 117 | # ... 118 | calib.start_collecting_data(point) 119 | while calib.is_collecting_data: 120 | time.sleep(0.5) 121 | calibration_result = calib.compute() 122 | 123 | # Do something with the result 124 | # ... 125 | ``` 126 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [bdist_wheel] 2 | # This flag says to generate wheels that support both Python 2 and Python 3 | # 3. If your code will not run unchanged on both Python 2 and 3, you will 4 | # need to generate separate wheels for each Python version that you 5 | # support. 6 | universal=1 7 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # Always prefer setuptools over distutils 2 | from setuptools import setup, find_packages 3 | # To use a consistent encoding 4 | from codecs import open 5 | from os import path 6 | 7 | here = path.abspath(path.dirname(__file__)) 8 | 9 | # Get the long description from the README file 10 | with open(path.join(here, 'README.md'), encoding='utf-8') as f: 11 | long_description = f.read() 12 | 13 | setup( 14 | name='tobii_research_addons', 15 | version='0.1.0', 16 | description='Addons for the Tobii Pro SDK.', 17 | long_description=long_description, 18 | url='https://github.com/tobiipro/prosdk-addons-python', 19 | author='Tobii Pro AB', 20 | author_email='tobiiprosdk@tobii.com', 21 | classifiers=[ 22 | # 3 - Alpha 23 | # 4 - Beta 24 | # 5 - Production/Stable 25 | 'Development Status :: 3 - Beta', 26 | 'Intended Audience :: Developers', 27 | 'Topic :: Multimedia :: Video :: Capture', 28 | 'Topic :: Scientific/Engineering', 29 | 'Topic :: Software Development :: Libraries', 30 | 'License :: OSI Approved :: MIT License', 31 | 'Programming Language :: Python :: 2.7', 32 | 'Programming Language :: Python :: 3', 33 | ], 34 | keywords='tobii research eyetracking sdk tobiipro', 35 | py_modules=["tobii_research_addons"], 36 | packages=find_packages(exclude=['contrib', 'docs', 'tests']), 37 | install_requires=['tobii_research'], 38 | extras_require={ 39 | 'dev': ['check-manifest'], 40 | 'test': ['coverage'], 41 | }, 42 | package_data={ 43 | 'sample': [], 44 | }, 45 | project_urls={ 46 | 'Bug Reports': 'https://github.com/tobiipro/prosdk-addons-python/issues', 47 | 'Source': 'https://github.com/tobiipro/prosdk-addons-python', 48 | }, 49 | ) 50 | -------------------------------------------------------------------------------- /tobii_research_addons/ScreenBasedCalibrationValidation.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Copyright 2019 Tobii Pro AB 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | ''' 16 | 17 | import math 18 | import threading 19 | from collections import defaultdict 20 | 21 | import tobii_research 22 | from . import vectormath 23 | 24 | 25 | class CalibrationValidationPoint(object): 26 | '''Represents a collected point that goes into the calibration validation. It contains calculated values for 27 | accuracy and precision as well as the original gaze samples collected for the point. 28 | ''' 29 | 30 | def __init__(self, 31 | accuracy_left_eye, 32 | accuracy_right_eye, 33 | precision_left_eye, 34 | precision_right_eye, 35 | precision_rms_left_eye, 36 | precision_rms_right_eye, 37 | timed_out, 38 | screen_point, 39 | gaze_data): 40 | self.__accuracy_left_eye = accuracy_left_eye 41 | self.__accuracy_right_eye = accuracy_right_eye 42 | self.__precision_left_eye = precision_left_eye 43 | self.__precision_right_eye = precision_right_eye 44 | self.__precision_rms_left_eye = precision_rms_left_eye 45 | self.__precision_rms_right_eye = precision_rms_right_eye 46 | self.__timed_out = timed_out 47 | self.__screen_point = screen_point 48 | self.__gaze_data = gaze_data 49 | 50 | @property 51 | def accuracy_left_eye(self): 52 | '''The accuracy in degrees for the left eye. 53 | ''' 54 | return self.__accuracy_left_eye 55 | 56 | @property 57 | def accuracy_right_eye(self): 58 | '''The accuracy in degrees for the right eye. 59 | ''' 60 | return self.__accuracy_right_eye 61 | 62 | @property 63 | def precision_left_eye(self): 64 | '''The precision (standard deviation) in degrees for the left eye. 65 | ''' 66 | return self.__precision_left_eye 67 | 68 | @property 69 | def precision_right_eye(self): 70 | '''The precision (standard deviation) in degrees for the right eye. 71 | ''' 72 | return self.__precision_right_eye 73 | 74 | @property 75 | def precision_rms_left_eye(self): 76 | '''The precision (root mean square of sample-to-sample error) in degrees for the left eye. 77 | ''' 78 | return self.__precision_rms_left_eye 79 | 80 | @property 81 | def precision_rms_right_eye(self): 82 | '''The precision (root mean square of sample-to-sample error) in degrees for the right eye. 83 | ''' 84 | return self.__precision_rms_right_eye 85 | 86 | @property 87 | def timed_out(self): 88 | '''A boolean indicating if there was a timeout while collecting data for this point. 89 | ''' 90 | return self.__timed_out 91 | 92 | @property 93 | def screen_point(self): 94 | '''The 2D coordinates of this point (in Active Display Coordinate System). 95 | ''' 96 | return self.__screen_point 97 | 98 | @property 99 | def gaze_data(self): 100 | '''The gaze data samples collected for this point. These samples are the base for the calculated accuracy 101 | and precision. 102 | ''' 103 | return self.__gaze_data 104 | 105 | 106 | class CalibrationValidationResult(object): 107 | '''Contains the result of the calibration validation. 108 | ''' 109 | 110 | def __init__(self, 111 | points, 112 | average_accuracy_left, 113 | average_accuracy_right, 114 | average_precision_left, 115 | average_precision_right, 116 | average_precision_rms_left, 117 | average_precision_rms_right): 118 | self.__points = points 119 | self.__average_accuracy_left = average_accuracy_left 120 | self.__average_accuracy_right = average_accuracy_right 121 | self.__average_precision_left = average_precision_left 122 | self.__average_precision_right = average_precision_right 123 | self.__average_precision_rms_left = average_precision_rms_left 124 | self.__average_precision_rms_right = average_precision_rms_right 125 | 126 | @property 127 | def points(self): 128 | '''The results of the calibration validation per point (same points as were collected). 129 | ''' 130 | return self.__points 131 | 132 | @property 133 | def average_accuracy_left(self): 134 | '''The accuracy in degrees averaged over all collected points for the left eye. 135 | ''' 136 | return self.__average_accuracy_left 137 | 138 | @property 139 | def average_accuracy_right(self): 140 | '''The accuracy in degrees averaged over all collected points for the right eye. 141 | ''' 142 | return self.__average_accuracy_right 143 | 144 | @property 145 | def average_precision_left(self): 146 | '''The precision (standard deviation) in degrees averaged over all collected points for the left eye. 147 | ''' 148 | return self.__average_precision_left 149 | 150 | @property 151 | def average_precision_right(self): 152 | '''The precision (standard deviation) in degrees averaged over all collected points for the right eye. 153 | ''' 154 | return self.__average_precision_right 155 | 156 | @property 157 | def average_precision_rms_left(self): 158 | '''The precision (root mean square of sample-to-sample error) in degrees averaged over all collected points 159 | for the left eye. 160 | ''' 161 | return self.__average_precision_rms_left 162 | 163 | @property 164 | def average_precision_rms_right(self): 165 | '''The precision (root mean square of sample-to-sample error) in degrees averaged over all collected points 166 | for the right eye. 167 | ''' 168 | return self.__average_precision_rms_right 169 | 170 | 171 | def _calculate_eye_accuracy(gaze_origin_mean, gaze_point_mean, stimuli_point): 172 | '''Calculate angle difference between actual gaze point and target point. 173 | ''' 174 | direction_gaze_point = vectormath.Vector3.from_points(gaze_origin_mean, gaze_point_mean).normalize() 175 | direction_target = vectormath.Vector3.from_points(gaze_origin_mean, stimuli_point).normalize() 176 | return direction_target.angle(direction_gaze_point) 177 | 178 | 179 | def _calculate_eye_precision(direction_gaze_point_list, direction_gaze_point_mean_list): 180 | '''Calculate standard deviation of gaze point angles. 181 | ''' 182 | angles = [] 183 | for dir_gaze_point, dir_gaze_point_mean in zip(direction_gaze_point_list, direction_gaze_point_mean_list): 184 | angles.append(dir_gaze_point.angle(dir_gaze_point_mean)) 185 | variance = sum([x**2 for x in angles]) / len(angles) 186 | standard_deviation = math.sqrt(variance) 187 | return standard_deviation 188 | 189 | 190 | def _calculate_eye_precision_rms(direction_gaze_point_list): 191 | '''Calculate root mean square (RMS) of gaze point angles. 192 | ''' 193 | consecutive_angle_diffs = [] 194 | last_gaze_point_vector = direction_gaze_point_list[0] 195 | for gaze_point_vector in direction_gaze_point_list[1:]: 196 | consecutive_angle_diffs.append(gaze_point_vector.angle(last_gaze_point_vector)) 197 | last_gaze_point_vector = gaze_point_vector 198 | variance = sum([x**2 for x in consecutive_angle_diffs]) / len(consecutive_angle_diffs) 199 | rms = math.sqrt(variance) 200 | return rms 201 | 202 | 203 | class ScreenBasedCalibrationValidation(object): 204 | '''Provides methods and properties for managing calibration validation for screen based eye trackers. 205 | ''' 206 | SAMPLE_COUNT_MIN = 10 207 | SAMPLE_COUNT_MAX = 3000 208 | TIMEOUT_MIN = 100 # ms 209 | TIMEOUT_MAX = 3000 # ms 210 | 211 | def __init__(self, 212 | eyetracker, 213 | sample_count=30, 214 | timeout_ms=1000): 215 | '''Create a calibration validation object for screen based eye trackers. 216 | 217 | Args: 218 | eyetracker: See @ref EyeTracker. 219 | sample_count: The number of samples to collect. Default 30, minimum 10, maximum 3000. 220 | timeout_ms: Timeout in milliseconds. Default 1000, minimum 100, maximum 3000. 221 | 222 | Raises: 223 | ValueError 224 | ''' 225 | if not isinstance(eyetracker, tobii_research.EyeTracker): 226 | raise ValueError("Not a valid EyeTracker object") 227 | self.__eyetracker = eyetracker 228 | 229 | if not self.SAMPLE_COUNT_MIN <= sample_count <= self.SAMPLE_COUNT_MAX: 230 | raise ValueError("Samples must be between 10 and 3000") 231 | self.__sample_count = sample_count 232 | 233 | if not self.TIMEOUT_MIN <= timeout_ms <= self.TIMEOUT_MAX: 234 | raise ValueError("Timeout must be between 100 and 3000") 235 | self.__timeout_ms = timeout_ms 236 | 237 | self.__current_point = None 238 | self.__current_gaze_data = [] 239 | self.__collected_points = defaultdict(list) 240 | 241 | self.__is_collecting_data = False 242 | self.__validation_mode = False 243 | 244 | self.__timeout = False 245 | self.__timeout_thread = None 246 | self.__lock = threading.RLock() # synchronization between timer and gaze data subscription callback 247 | 248 | def _calibration_timeout_handler(self): 249 | self.__lock.acquire() 250 | if self.__is_collecting_data: 251 | self.__timeout = True 252 | self.__is_collecting_data = False 253 | self.__lock.release() 254 | 255 | def _gaze_data_received(self, gaze_data): 256 | self.__lock.acquire() 257 | if self.__is_collecting_data: 258 | if len(self.__current_gaze_data) < self.__sample_count: 259 | if gaze_data.left_eye.gaze_point.validity and gaze_data.right_eye.gaze_point.validity: 260 | self.__current_gaze_data.append(gaze_data) 261 | else: 262 | # Data collecting stopped on sample count condition, timer might still be running 263 | self.__timeout_thread.cancel() 264 | 265 | # Data collecting done for this point 266 | self.__collected_points[self.__current_point] += self.__current_gaze_data 267 | self.__current_gaze_data = [] 268 | self.__is_collecting_data = False 269 | self.__lock.release() 270 | 271 | def __enter__(self): 272 | self.enter_validation_mode() 273 | return self 274 | 275 | def __exit__(self, exc_type, exc_value, traceback): 276 | if self.is_validation_mode: 277 | if self.is_collecting_data: 278 | # Stop data collection 279 | self.__lock.acquire() 280 | self.__timeout_thread.cancel() 281 | self.__is_collecting_data = False 282 | self.__lock.release() 283 | self.leave_validation_mode() 284 | 285 | def enter_validation_mode(self): 286 | '''Enter the calibration validation mode and starts subscribing to gaze data from the eye tracker. 287 | 288 | Raises: 289 | RuntimeWarning 290 | ''' 291 | if self.__validation_mode or self.__is_collecting_data: 292 | raise RuntimeWarning("Validation mode already entered") 293 | 294 | self.__collected_points = defaultdict(list) 295 | self.__eyetracker.subscribe_to(tobii_research.EYETRACKER_GAZE_DATA, self._gaze_data_received) 296 | self.__validation_mode = True 297 | 298 | def leave_validation_mode(self): 299 | '''Leaves the calibration validation mode, clears all collected data, and unsubscribes from the eye tracker. 300 | 301 | Raises: 302 | RuntimeWarning 303 | ''' 304 | if not self.__validation_mode: 305 | raise RuntimeWarning("Not in validation mode") 306 | if self.__is_collecting_data: 307 | raise RuntimeWarning("Cannot leave validation mode while collecting data") 308 | 309 | self.__current_point = None 310 | self.__current_gaze_data = [] 311 | self.__eyetracker.unsubscribe_from(tobii_research.EYETRACKER_GAZE_DATA, self._gaze_data_received) 312 | self.__validation_mode = False 313 | 314 | def start_collecting_data(self, screen_point): 315 | '''Starts collecting data for a calibration validation point.The argument used is the point the user 316 | is assumed to be looking at and is given in the active display area coordinate system. 317 | Please check State property to know when data collection is completed (or timed out). 318 | 319 | Args: 320 | screen_point: The normalized 2D point on the display area. 321 | 322 | Raises: 323 | ValueError 324 | RuntimeWarning 325 | ''' 326 | if type(screen_point) is not vectormath.Point2: 327 | raise ValueError("A screen point must be of Point2 type") 328 | if not (0.0 <= screen_point.x <= 1.0 and 0.0 <= screen_point.y <= 1.0): 329 | raise ValueError("Screen point must be within coordinates (0.0, 0.0) and (1.0, 1.0)") 330 | if not self.__validation_mode: 331 | raise RuntimeWarning("Not in validation mode") 332 | if self.__is_collecting_data: 333 | raise RuntimeWarning("Already collecting data") 334 | 335 | self.__current_point = screen_point 336 | self.__current_gaze_data = [] 337 | self.__timeout = False 338 | self.__timeout_thread = threading.Timer(self.__timeout_ms / 1000.0, self._calibration_timeout_handler) 339 | self.__timeout_thread.start() 340 | self.__is_collecting_data = True 341 | 342 | def clear(self): 343 | '''Clears all collected data. 344 | 345 | Raises: 346 | RuntimeWarning 347 | ''' 348 | if self.__is_collecting_data: 349 | raise RuntimeWarning("Attempted to discard data while collecting data") 350 | 351 | self.__current_point = None 352 | self.__current_gaze_data = [] 353 | self.__collected_points = defaultdict(list) 354 | 355 | def discard_data(self, screen_point): 356 | '''Removes the collected data for a specific calibration validation point. 357 | 358 | Args: 359 | screen_point: The calibration point to remove. 360 | 361 | Raises: 362 | RuntimeWarning 363 | ''' 364 | if not self.__validation_mode: 365 | raise RuntimeWarning("Not in validation mode, no points to discard") 366 | if self.__is_collecting_data: 367 | raise RuntimeWarning("Attempted to discard data while collecting data") 368 | if screen_point not in self.__collected_points: 369 | raise RuntimeWarning("Attempt to discard non-collected point") 370 | del self.__collected_points[screen_point] 371 | 372 | def compute(self): 373 | '''Uses the collected data and tries to compute accuracy and precision values for all points. 374 | If the calculation is successful, the result is returned, and stored in the Result property 375 | of the CalibrationValidation object. If there is insufficient data to compute the results 376 | for a certain point that CalibrationValidationPoint will contain invalid data (NaN) for the 377 | results. Gaze data will still be untouched. If there is no valid data for any point, the 378 | average results of CalibrationValidationResult will be invalid (NaN) as well. 379 | 380 | Returns: 381 | An instance of @ref CalibrationValidationResult. 382 | ''' 383 | if self.__is_collecting_data: 384 | raise RuntimeWarning("Still collecting data") 385 | 386 | points = defaultdict(list) 387 | accuracy_left_eye_all = [] 388 | accuracy_right_eye_all = [] 389 | precision_left_eye_all = [] 390 | precision_right_eye_all = [] 391 | precision_rms_left_eye_all = [] 392 | precision_rms_right_eye_all = [] 393 | 394 | for screen_point, samples in self.__collected_points.items(): 395 | if len(samples) < self.__sample_count: 396 | # Timeout before collecting enough valid samples, no calculations to be done 397 | points[screen_point] += [CalibrationValidationPoint( 398 | screen_point, math.nan, math.nan, math.nan, math.nan, math.nan, math.nan, True, samples)] 399 | continue 400 | 401 | stimuli_point = vectormath.calculate_normalized_point2_to_point3( 402 | self.__eyetracker.get_display_area(), screen_point) 403 | 404 | # Prepare data from samples 405 | gaze_origin_left_all = [] 406 | gaze_origin_right_all = [] 407 | gaze_point_left_all = [] 408 | gaze_point_right_all = [] 409 | direction_gaze_point_left_all = [] 410 | direction_gaze_point_left_mean_all = [] 411 | direction_gaze_point_right_all = [] 412 | direction_gaze_point_right_mean_all = [] 413 | 414 | for sample in samples: 415 | gaze_origin_left_all.append( 416 | vectormath.Point3.from_list(sample.left_eye.gaze_origin.position_in_user_coordinates)) 417 | gaze_origin_right_all.append( 418 | vectormath.Point3.from_list(sample.right_eye.gaze_origin.position_in_user_coordinates)) 419 | gaze_point_left_all.append( 420 | vectormath.Point3.from_list(sample.left_eye.gaze_point.position_in_user_coordinates)) 421 | gaze_point_right_all.append( 422 | vectormath.Point3.from_list(sample.right_eye.gaze_point.position_in_user_coordinates)) 423 | 424 | gaze_origin_left_mean = vectormath.calculate_mean_point(gaze_origin_left_all) 425 | gaze_origin_right_mean = vectormath.calculate_mean_point(gaze_origin_right_all) 426 | gaze_point_left_mean = vectormath.calculate_mean_point(gaze_point_left_all) 427 | gaze_point_right_mean = vectormath.calculate_mean_point(gaze_point_right_all) 428 | 429 | for sample in samples: 430 | gaze_origin_left = vectormath.Point3.from_list( 431 | sample.left_eye.gaze_origin.position_in_user_coordinates) 432 | gaze_origin_right = vectormath.Point3.from_list( 433 | sample.right_eye.gaze_origin.position_in_user_coordinates) 434 | gaze_point_left = vectormath.Point3.from_list( 435 | sample.left_eye.gaze_point.position_in_user_coordinates) 436 | gaze_point_right = vectormath.Point3.from_list( 437 | sample.right_eye.gaze_point.position_in_user_coordinates) 438 | direction_gaze_point_left_all.append( 439 | vectormath.Vector3.from_points(gaze_origin_left, gaze_point_left).normalize()) 440 | direction_gaze_point_left_mean_all.append( 441 | vectormath.Vector3.from_points(gaze_origin_left, gaze_point_left_mean).normalize()) 442 | direction_gaze_point_right_all.append( 443 | vectormath.Vector3.from_points(gaze_origin_right, gaze_point_right).normalize()) 444 | direction_gaze_point_right_mean_all.append( 445 | vectormath.Vector3.from_points(gaze_origin_right, gaze_point_right_mean).normalize()) 446 | 447 | # Accuracy calculations 448 | accuracy_left_eye = _calculate_eye_accuracy(gaze_origin_left_mean, gaze_point_left_mean, stimuli_point) 449 | accuracy_right_eye = _calculate_eye_accuracy(gaze_origin_right_mean, gaze_point_right_mean, stimuli_point) 450 | 451 | # Precision calculations 452 | precision_left_eye = _calculate_eye_precision( 453 | direction_gaze_point_left_all, direction_gaze_point_left_mean_all) 454 | precision_right_eye = _calculate_eye_precision( 455 | direction_gaze_point_right_all, direction_gaze_point_right_mean_all) 456 | 457 | # RMS precision calculations 458 | precision_rms_left_eye = _calculate_eye_precision_rms(direction_gaze_point_left_all) 459 | precision_rms_right_eye = _calculate_eye_precision_rms(direction_gaze_point_right_all) 460 | 461 | # Add a calibration validation point 462 | points[screen_point] += [CalibrationValidationPoint( 463 | accuracy_left_eye, 464 | accuracy_right_eye, 465 | precision_left_eye, 466 | precision_right_eye, 467 | precision_rms_left_eye, 468 | precision_rms_right_eye, 469 | False, # no timeout 470 | screen_point, 471 | samples)] 472 | 473 | # Cache all calculations 474 | accuracy_left_eye_all.append(accuracy_left_eye) 475 | accuracy_right_eye_all.append(accuracy_right_eye) 476 | precision_left_eye_all.append(precision_left_eye) 477 | precision_right_eye_all.append(precision_right_eye) 478 | precision_rms_left_eye_all.append(precision_rms_left_eye) 479 | precision_rms_right_eye_all.append(precision_rms_right_eye) 480 | 481 | # Create a result 482 | num_points = len(accuracy_left_eye_all) 483 | if num_points > 0: 484 | accuracy_left_eye_average = sum(accuracy_left_eye_all) / num_points 485 | accuracy_right_eye_average = sum(accuracy_right_eye_all) / num_points 486 | precision_left_eye_average = sum(precision_left_eye_all) / num_points 487 | precision_right_eye_average = sum(precision_right_eye_all) / num_points 488 | precision_rms_left_eye_average = sum(precision_rms_left_eye_all) / num_points 489 | precision_rms_right_eye_average = sum(precision_rms_right_eye_all) / num_points 490 | else: 491 | accuracy_left_eye_average = math.nan 492 | accuracy_right_eye_average = math.nan 493 | precision_left_eye_average = math.nan 494 | precision_right_eye_average = math.nan 495 | precision_rms_left_eye_average = math.nan 496 | precision_rms_right_eye_average = math.nan 497 | 498 | result = CalibrationValidationResult(points, 499 | accuracy_left_eye_average, 500 | accuracy_right_eye_average, 501 | precision_left_eye_average, 502 | precision_right_eye_average, 503 | precision_rms_left_eye_average, 504 | precision_rms_right_eye_average) 505 | return result 506 | 507 | @property 508 | def is_collecting_data(self): 509 | '''Gets if data collecting is in progess. 510 | 511 | Returns: 512 | True if data collectin is in progress. 513 | ''' 514 | return self.__is_collecting_data 515 | 516 | @property 517 | def is_validation_mode(self): 518 | '''Gets if in validation mode. 519 | 520 | Returns: 521 | True if in validation mode. 522 | ''' 523 | return self.__validation_mode 524 | -------------------------------------------------------------------------------- /tobii_research_addons/__init__.py: -------------------------------------------------------------------------------- 1 | from .ScreenBasedCalibrationValidation import ScreenBasedCalibrationValidation 2 | from .ScreenBasedCalibrationValidation import CalibrationValidationPoint 3 | from .ScreenBasedCalibrationValidation import CalibrationValidationResult 4 | from .vectormath import calculate_mean_point, calculate_normalized_point2_to_point3 5 | from .vectormath import Point2, Point3, Vector3 6 | 7 | __all__ = ("ScreenBasedCalibrationValidation", "CalibrationValidationPoint", "CalibrationValidationResult", 8 | "calculate_mean_point", "calculate_normalized_point2_to_point3", "Point2", "Point3", "Vector3") 9 | 10 | __author__ = 'Tobii Pro AB' 11 | __licence__ = 'BSD' 12 | __copyright__ = ''' 13 | Copyright 2019 Tobii Pro AB 14 | 15 | Licensed under the Apache License, Version 2.0 (the "License"); 16 | you may not use this file except in compliance with the License. 17 | You may obtain a copy of the License at 18 | 19 | http://www.apache.org/licenses/LICENSE-2.0 20 | 21 | Unless required by applicable law or agreed to in writing, software 22 | distributed under the License is distributed on an "AS IS" BASIS, 23 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 24 | See the License for the specific language governing permissions and 25 | limitations under the License. 26 | ''' 27 | -------------------------------------------------------------------------------- /tobii_research_addons/vectormath.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Copyright 2019 Tobii Pro AB 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | ''' 16 | 17 | import math 18 | 19 | 20 | def _isclose(a, b, rel_tol=1e-09, abs_tol=0.0): 21 | return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol) 22 | 23 | 24 | def _clamp(value, lower, upper): 25 | return max(lower, min(value, upper)) 26 | 27 | 28 | class Point2(object): 29 | '''Represents a 2D point. 30 | ''' 31 | def __init__(self, x=0.0, y=0.0): 32 | self.__x = float(x) 33 | self.__y = float(y) 34 | 35 | @property 36 | def x(self): 37 | return self.__x 38 | 39 | @property 40 | def y(self): 41 | return self.__y 42 | 43 | def __eq__(self, other): 44 | return _isclose(self.x, other.x) and _isclose(self.y, other.y) 45 | 46 | def __ne__(self, other): 47 | return not self == other 48 | 49 | def __hash__(self): 50 | return hash((self.x, self.y)) 51 | 52 | def __repr__(self): 53 | return "{0}({1:.3f}, {2:.3f})".format(self.__class__.__name__, self.x, self.y) 54 | 55 | @classmethod 56 | def from_list(cls, lst): 57 | x, y = map(float, lst) 58 | return cls(x, y) 59 | 60 | 61 | class Point3(object): 62 | '''Represents a 3D point. 63 | ''' 64 | def __init__(self, x=0.0, y=0.0, z=0.0): 65 | self.__x = float(x) 66 | self.__y = float(y) 67 | self.__z = float(z) 68 | 69 | @property 70 | def x(self): 71 | return self.__x 72 | 73 | @property 74 | def y(self): 75 | return self.__y 76 | 77 | @property 78 | def z(self): 79 | return self.__z 80 | 81 | def __add__(self, rhs): 82 | return Point3(self.x + rhs.x, self.y + rhs.y, self.z + rhs.z) 83 | 84 | def __sub__(self, rhs): 85 | return Point3(self.x - rhs.x, self.y - rhs.y, self.z - rhs.z) 86 | 87 | def __mul__(self, rhs): 88 | return Point3(self.x * float(rhs), self.y * float(rhs), self.z * float(rhs)) 89 | 90 | def __eq__(self, other): 91 | return _isclose(self.x, other.x) and _isclose(self.y, other.y) and _isclose(self.z, other.z) 92 | 93 | def __ne__(self, other): 94 | return not self == other 95 | 96 | def __repr__(self): 97 | return '{0}({1:.3f}, {2:.3f}, {3:.3f})'.format(self.__class__.__name__, self.x, self.y, self.z) 98 | 99 | def distance(self, other_point): 100 | return math.sqrt((other_point.x - self.x) ** 2 + (other_point.y - self.y) ** 2 + (other_point.z - self.z) ** 2) 101 | 102 | @classmethod 103 | def from_list(cls, lst): 104 | x, y, z = map(float, lst) 105 | return cls(x, y, z) 106 | 107 | 108 | class Vector3(Point3): 109 | '''Represents a 3D vector. 110 | ''' 111 | def __init__(self, x=0.0, y=0.0, z=0.0): 112 | super(Vector3, self).__init__(x, y, z) 113 | 114 | def __add__(self, rhs): 115 | if isinstance(rhs, Point3): 116 | return Vector3(self.x + rhs.x, self.y + rhs.y, self.z + rhs.z) 117 | elif type(rhs) in [float, int]: 118 | return Vector3(self.x + float(rhs), self.y + float(rhs), self.z + float(rhs)) 119 | else: 120 | raise TypeError 121 | 122 | def __sub__(self, rhs): 123 | if isinstance(rhs, Point3): 124 | return Vector3(self.x - rhs.x, self.y - rhs.y, self.z - rhs.z) 125 | elif type(rhs) in [float, int]: 126 | return Vector3(self.x - float(rhs), self.y - float(rhs), self.z - float(rhs)) 127 | else: 128 | raise TypeError 129 | 130 | def __mul__(self, rhs): 131 | if type(rhs) in [float, int]: 132 | return Vector3(self.x * float(rhs), self.y * float(rhs), self.z * float(rhs)) 133 | else: 134 | # Do not allow dot or cross products with multiplication operator due to ambiguity issues 135 | raise TypeError 136 | 137 | def dot(self, vector3): 138 | '''Dot product.''' 139 | return self.x * vector3.x + self.y * vector3.y + self.z * vector3.z 140 | 141 | def magnitude(self): 142 | return math.sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2) 143 | 144 | def normalize(self): 145 | return self * (1.0 / self.magnitude()) 146 | 147 | def angle(self, vector3): 148 | '''Return the angle between two vectors in degrees.''' 149 | tmp = self.dot(vector3) / (self.magnitude() * vector3.magnitude()) 150 | return math.degrees(math.acos(_clamp(tmp, -1.0, 1.0))) 151 | 152 | @classmethod 153 | def from_points(cls, from_point, to_point): 154 | if isinstance(from_point, Point3) and isinstance(to_point, Point3): 155 | displacement = to_point - from_point 156 | return cls(displacement.x, displacement.y, displacement.z) 157 | raise TypeError 158 | 159 | 160 | def calculate_normalized_point2_to_point3(display_area, target_point): 161 | '''Get the 3D gaze point representation based on the normalized 2D point and the @ref GazeData information. 162 | 163 | Args: 164 | display_area: @ref DisplayArea object. 165 | target_point: Screen point as a normalized @ref Point2 object. 166 | 167 | Returns: 168 | The @ref Point3 gaze point. 169 | ''' 170 | display_area_top_right = Point3.from_list(display_area.top_right) 171 | display_area_top_left = Point3.from_list(display_area.top_left) 172 | display_area_bottom_left = Point3.from_list(display_area.bottom_left) 173 | dx = (display_area_top_right - display_area_top_left) * target_point.x 174 | dy = (display_area_bottom_left - display_area_top_left) * target_point.y 175 | return display_area_top_left + dx + dy 176 | 177 | 178 | def calculate_mean_point(points): 179 | '''Calculate an average point from a set of points. 180 | 181 | Args: 182 | points: An iterable container of @ref Point3 objects. 183 | 184 | Returns: 185 | The mean point as a @ref Point3 object. 186 | ''' 187 | average_point = Point3() 188 | for point in points: 189 | average_point = average_point + point 190 | average_point = average_point * (1.0 / len(points)) 191 | return average_point 192 | --------------------------------------------------------------------------------