pywib 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pywib-0.1.0/.gitignore ADDED
@@ -0,0 +1,7 @@
1
+ src/pywib/__pycache__
2
+ src/pywib/tests/__pycache__
3
+ src/pywib/utils/__pycache__
4
+ src/pywib/core/__pycache__
5
+ test/__pycache__
6
+ dist
7
+ .vscode/
pywib-0.1.0/LICENSE ADDED
@@ -0,0 +1,201 @@
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.
pywib-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,35 @@
1
+ Metadata-Version: 2.4
2
+ Name: pywib
3
+ Version: 0.1.0
4
+ Summary: HCI Web Interaction Analyzer - A library for analyzing web user interactions
5
+ Project-URL: Homepage, https://github.com/HumanCommunicationInteraction/pywib
6
+ Project-URL: Bug Tracker, https://github.com/HumanCommunicationInteraction/pywib/issues
7
+ Project-URL: Documentation, https://pywib.readthedocs.io/
8
+ Project-URL: Repository, https://github.com/HumanCommunicationInteraction/pywib.git
9
+ Author-email: Guillermo Dylan Carvajal Aza <carvajalguillermo@uniovi.es>, Alejandro Álvarez Varela <avarela@uniovi.es>
10
+ License-File: LICENSE
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Topic :: Scientific/Engineering
22
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
23
+ Requires-Python: >=3.9
24
+ Requires-Dist: matplotlib>=3.5.0
25
+ Requires-Dist: numpy>=1.21.0
26
+ Requires-Dist: pandas>=1.3.0
27
+ Description-Content-Type: text/markdown
28
+
29
+ # pywib
30
+
31
+ Pywib (Python Web Interaction Behaviour) is a library desgined for analysing and obtaning metrics from users interaction with web pages.
32
+
33
+ ## How to
34
+
35
+ ```
pywib-0.1.0/README.md ADDED
@@ -0,0 +1,7 @@
1
+ # pywib
2
+
3
+ Pywib (Python Web Interaction Behaviour) is a library desgined for analysing and obtaning metrics from users interaction with web pages.
4
+
5
+ ## How to
6
+
7
+ ```
@@ -0,0 +1,42 @@
1
+ [build-system]
2
+ requires = ["hatchling >= 1.26"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "pywib"
7
+ version = "0.1.0"
8
+ authors = [
9
+ { name="Guillermo Dylan Carvajal Aza", email="carvajalguillermo@uniovi.es" },
10
+ { name="Alejandro Álvarez Varela", email="avarela@uniovi.es"}
11
+ ]
12
+ description = "HCI Web Interaction Analyzer - A library for analyzing web user interactions"
13
+ readme = "README.md"
14
+ requires-python = ">=3.9"
15
+ dependencies = [
16
+ "pandas>=1.3.0",
17
+ "numpy>=1.21.0",
18
+ "matplotlib>=3.5.0",
19
+ ]
20
+ classifiers = [
21
+ "Development Status :: 3 - Alpha",
22
+ "Intended Audience :: Developers",
23
+ "Intended Audience :: Science/Research",
24
+ "License :: OSI Approved :: MIT License",
25
+ "Operating System :: OS Independent",
26
+ "Programming Language :: Python :: 3",
27
+ "Programming Language :: Python :: 3.9",
28
+ "Programming Language :: Python :: 3.10",
29
+ "Programming Language :: Python :: 3.11",
30
+ "Programming Language :: Python :: 3.12",
31
+ "Topic :: Scientific/Engineering",
32
+ "Topic :: Software Development :: Libraries :: Python Modules",
33
+ ]
34
+
35
+ [project.urls]
36
+ Homepage = "https://github.com/HumanCommunicationInteraction/pywib"
37
+ "Bug Tracker" = "https://github.com/HumanCommunicationInteraction/pywib/issues"
38
+ Documentation = "https://pywib.readthedocs.io/"
39
+ Repository = "https://github.com/HumanCommunicationInteraction/pywib.git"
40
+
41
+ [tool.hatch.build.targets.wheel]
42
+ packages = ["pywib"]
@@ -0,0 +1 @@
1
+ pandas>=1.3.0
pywib-0.1.0/setup.py ADDED
@@ -0,0 +1,48 @@
1
+ from setuptools import setup, find_packages
2
+
3
+ with open("README.md", "r", encoding="utf-8") as fh:
4
+ long_description = fh.read()
5
+
6
+ with open("requirements.txt", "r", encoding="utf-8") as fh:
7
+ requirements = [line.strip() for line in fh if line.strip() and not line.startswith("#")]
8
+
9
+
10
+ setup(
11
+ name='pywib',
12
+ packages=find_packages(),
13
+ version='0.1.0',
14
+ description='HCI Web Interaction Analyzer - A library for analyzing web user interactions',
15
+ long_description=long_description,
16
+ long_description_content_type="text/markdown",
17
+ url="https://github.com/HumanCommunicationInteraction/pywib",
18
+ packages=find_packages(),
19
+ author='Guillermo Dylan Carvajal Aza',
20
+ author_email='carvajalguillermo@uniovi.es',
21
+ keywords=['HCI', 'Web Interaction', 'Analyzer'],
22
+ classifiers=[
23
+ "Development Status :: 3 - Alpha",
24
+ "Intended Audience :: Developers",
25
+ "Intended Audience :: Science/Research",
26
+ "License :: OSI Approved :: MIT License",
27
+ "Operating System :: OS Independent",
28
+ "Programming Language :: Python :: 3",
29
+ "Programming Language :: Python :: 3.9",
30
+ "Programming Language :: Python :: 3.10",
31
+ "Programming Language :: Python :: 3.11",
32
+ "Programming Language :: Python :: 3.12",
33
+ "Topic :: Scientific/Engineering",
34
+ "Topic :: Software Development :: Libraries :: Python Modules",
35
+ ],
36
+ python_requires=">=3.9",
37
+ install_requires=requirements,
38
+ extras_require={
39
+ "dev": [
40
+ "pytest>=6.0",
41
+ "pytest-cov",
42
+ "black",
43
+ "flake8",
44
+ ],
45
+ },
46
+ include_package_data=True,
47
+ zip_safe=False,
48
+ )
@@ -0,0 +1,43 @@
1
+ """
2
+ """
3
+
4
+ __version__ = "0.1.0"
5
+ __author__ = "Guillermo Dylan Carvajal Aza"
6
+ __email__ = "carvajalguillermo@uniovi.es"
7
+
8
+ from .constants import *
9
+ from .utils import validate_dataframe, validate_dataframe_keyboard, extract_traces_by_session, visualize_trace
10
+ from .core.movement import velocity, acceleration, jerkiness, path, auc_ratio
11
+ from .core.timing import execution_time, movement_time, pauses_metrics
12
+ from .utils.utils import compute_space_time_diff
13
+
14
+ __all__ = [
15
+ # Version info
16
+ "__version__",
17
+ "__author__",
18
+ "__email__",
19
+
20
+ # Constants
21
+ "EventTypes",
22
+ "ComponentTypes",
23
+
24
+ # Utility functions
25
+ "validate_dataframe",
26
+ "validate_dataframe_keyboard",
27
+ "extract_trace",
28
+ "visualize_trace",
29
+
30
+ # Movement functions
31
+ "velocity",
32
+ "acceleration",
33
+ "auc_ratio",
34
+ "jerkiness",
35
+ "path",
36
+
37
+ # Timing
38
+ "pauses_metrics",
39
+
40
+ # Utils
41
+ "compute_space_time_diff",
42
+ "extract_traces_by_session",
43
+ ]
@@ -0,0 +1,54 @@
1
+ """
2
+
3
+ """
4
+
5
+ # Version and library information
6
+ LIBRARY_NAME = "pywib"
7
+ LIBRARY_VERSION = "0.1.0"
8
+
9
+ # Event types for interaction tracking
10
+ class EventTypes:
11
+ """ Event type constants for interaction tracking."""
12
+ EVENT_ON_MOUSE_MOVE = 0
13
+ EVENT_ON_CLICK = 1
14
+ EVENT_ON_DOUBLE_CLICK = 2
15
+ EVENT_ON_MOUSE_DOWN = 3
16
+ EVENT_ON_MOUSE_UP = 4
17
+ EVENT_ON_WHEEL = 5
18
+ EVENT_CONTEXT_MENU = 6
19
+ EVENT_ON_TOUCH_MOVE = 7
20
+ EVENT_WINDOW_SCROLL = 11
21
+ EVENT_WINDOW_RESIZE = 12
22
+ EVENT_KEY_DOWN = 13
23
+ EVENT_KEY_PRESS = 14
24
+ EVENT_KEY_UP = 15
25
+ EVENT_FOCUS = 16
26
+ EVENT_BLUR = 17
27
+ EVENT_ON_CHANGE_SELECTION_OBJECT = 18
28
+ EVENT_ON_CLICK_SELECTION_OBJECT = 19
29
+ EVENT_INIT_TRACKING = 100
30
+ EVENT_TRACKING_END = 200
31
+
32
+ class ComponentTypes:
33
+ """ Component type constants for UI elements."""
34
+ COMPONENT_TEXT_FIELD = 1
35
+ COMPONENT_COMBOBOX = 2
36
+ COMPONENT_OPTION = 3
37
+ COMPONENT_RADIO_BUTTON = 4
38
+ COMPONENT_CHECK_BOX = 5
39
+
40
+ class ColumnNames:
41
+ """ Standard column names for DataFrame operations."""
42
+ SESSION_ID = 'sessionId'
43
+ SCENE_ID = 'sceneId'
44
+ EVENT_TYPE = 'eventType'
45
+ ELEMENT_ID = 'elementId'
46
+ TIME_STAMP = 'timeStamp'
47
+ X = 'x'
48
+ Y = 'y'
49
+ KEY_VALUE_EVENT = 'keyValueEvent'
50
+ KEY_CODE_EVENT = 'keyCodeEvent'
51
+ SOURCE_SESSION_ID = 'sourceSessionId'
52
+ DT = 'dt'
53
+ DX = 'dx'
54
+ DY = 'dy'
@@ -0,0 +1,5 @@
1
+ """
2
+ Analysis module for HCI Web Interaction Analyzer
3
+
4
+ This module provides methods to analyze interaction data from DataFrames.
5
+ """
@@ -0,0 +1,226 @@
1
+ import pandas as pd
2
+ import numpy as np
3
+ from ..utils.validation import validate_dataframe
4
+ from ..utils.utils import compute_space_time_diff
5
+ from ..utils.segmentation import extract_traces_by_session
6
+ from ..constants import ColumnNames
7
+
8
+ def velocity(df: pd.DataFrame, traces: dict[str, list[pd.DataFrame]] = None) -> dict:
9
+ """
10
+ Calculate the velocity for the given DataFrame or traces.
11
+ This function computes the velocity based on the distance and time difference between consecutive points.
12
+
13
+ Parameters:
14
+ df (pd.DataFrame): DataFrame containing 'x', 'y', and 'timeStamp' columns.
15
+ traces (dict): A dictionary with keys as (sessionId) and values as lists of DataFrames. If None, traces will be computed from df.
16
+ Returns:
17
+ dict: A dictionary with keys as (sessionId) and values as DataFrames with an additional 'velocity' column.
18
+ """
19
+
20
+ if traces is None:
21
+ validate_dataframe(df)
22
+ traces = extract_traces_by_session(df)
23
+
24
+ for session_id, session_traces in traces.items():
25
+ for i in range(len(session_traces)):
26
+ validate_dataframe(session_traces[i])
27
+
28
+ for j in range(len(session_traces)):
29
+ session_traces[j] = _path(session_traces[j])
30
+ session_traces[j]['velocity'] = session_traces[j]['distance'] / session_traces[j]['dt']
31
+ # Fix NaN velocity for first point - set to 0
32
+ session_traces[j]['velocity'] = session_traces[j]['velocity'].fillna(0)
33
+
34
+ traces[session_id] = session_traces
35
+ return traces
36
+
37
+ def acceleration(df: pd.DataFrame, traces: dict[str, list[pd.DataFrame]] = None) -> dict:
38
+ """
39
+ Calculate the acceleration for the given DataFrame.
40
+ This function computes the acceleration based on the change in velocity over time.
41
+
42
+ Parameters:
43
+ df (pd.DataFrame): DataFrame containing 'velocity' and 'dt' columns.
44
+ traces (dict): A dictionary with keys as (sessionId) and values as lists of DataFrames. If None, traces will be computed from df.
45
+ Returns:
46
+ dict: A dictionary with keys as (sessionId) and values as DataFrames with an additional 'acceleration' column.
47
+ """
48
+
49
+ if traces is None:
50
+ validate_dataframe(df)
51
+ traces = extract_traces_by_session(df)
52
+
53
+ for session_id, session_traces in traces.items():
54
+ for i in range(len(session_traces)):
55
+ validate_dataframe(session_traces[i])
56
+ for j in range(len(session_traces)):
57
+ session_traces[j]['acceleration'] = session_traces[j]["velocity"].diff().fillna(0) / session_traces[j]['dt']
58
+ session_traces[j]['acceleration'] = session_traces[j]['acceleration'].fillna(0)
59
+
60
+ traces[session_id] = session_traces
61
+ return traces
62
+
63
+ def jerkiness(df: pd.DataFrame, traces: dict[str, list[pd.DataFrame]] = None) -> dict:
64
+ """
65
+ Calculate the jerkiness for the given DataFrame.
66
+ This function computes the jerkiness based on the change in acceleration over time.
67
+
68
+ Parameters:
69
+ df (pd.DataFrame): DataFrame containing 'acceleration' and 'dt' columns.
70
+ traces (dict): A dictionary with keys as (sessionId) and values as lists of DataFrames. If None, traces will be computed from df.
71
+
72
+ Returns:
73
+ dict: A dictionary with keys as (sessionId) and values as DataFrames with an additional 'jerkiness' column.
74
+ """
75
+
76
+ if traces is None:
77
+ validate_dataframe(df)
78
+ traces = extract_traces_by_session(df)
79
+
80
+ for session_id, session_traces in traces.items():
81
+ for i in range(len(session_traces)):
82
+ validate_dataframe(session_traces[i])
83
+ # TODO revisar
84
+ for j in range(len(session_traces)):
85
+ session_traces[j] = session_traces[j]["acceleration"].diff().fillna(0) / session_traces[j]['dt']
86
+
87
+ traces[session_id] = session_traces
88
+
89
+ return traces
90
+
91
+ def path(df: pd.DataFrame = None, traces: dict[str, list[pd.DataFrame]] = None) -> pd.DataFrame:
92
+ """
93
+ Calculate the path length for the given DataFrame.
94
+ This function computes the path length based on the Euclidean distance between consecutive points.
95
+
96
+ Parameters:
97
+ df (pd.DataFrame): DataFrame containing 'x' and 'y' columns.
98
+ traces (dict): A dictionary with keys as (sessionId) and values as lists of DataFrames. If None, traces will be computed from df.
99
+
100
+ Returns:
101
+ pd.DataFrame: DataFrame with an additional 'distance' column representing the path length.
102
+ """
103
+
104
+ if traces is None:
105
+ validate_dataframe(df)
106
+ traces = extract_traces_by_session(df)
107
+
108
+ for session_id, session_traces in traces.items():
109
+ for i in range(len(session_traces)):
110
+ validate_dataframe(session_traces[i])
111
+
112
+ # Compute the distance for each trace
113
+ for j in range(len(session_traces)):
114
+ session_traces[j]['distance'] = _path(session_traces[j])['distance']
115
+
116
+ # Store the traces with distance in the dictionary
117
+ df[session_id] = session_traces
118
+
119
+ return df
120
+
121
+ def _path(trace: pd.DataFrame) -> pd.DataFrame:
122
+ """
123
+ Helper function to calculate the path length for a single trace.
124
+ This function computes the path length based on the Euclidean distance between consecutive points.
125
+
126
+ Parameters:
127
+ trace (pd.DataFrame): A single trace DataFrame.
128
+
129
+ Returns:
130
+ pd.DataFrame: DataFrame with an additional 'distance' column representing the path length.
131
+ """
132
+
133
+ if trace is None:
134
+ raise ValueError("Trace DataFrame must be provided.")
135
+
136
+ validate_dataframe(trace)
137
+
138
+ trace = compute_space_time_diff(trace)
139
+ trace['distance'] = np.sqrt(trace['dx'] ** 2 + trace['dy'] ** 2)
140
+
141
+ return trace
142
+
143
+ def auc(df: pd.DataFrame, validation: bool = True, computeTraces: bool = True) -> float:
144
+ """
145
+ Calculate the Area Under the Curve (AUC) for the given DataFrame.
146
+
147
+ Parameters:
148
+ df (pd.DataFrame): DataFrame containing 'timeStamp' and 'y' columns.
149
+ validation (bool): Whether to validate the DataFrame structure, by default True.
150
+ computeTraces (bool): Whether to compute traces by sessionId, by default True.
151
+
152
+ Returns:
153
+ float: The computed AUC value.
154
+ """
155
+
156
+ if(validation):
157
+ validate_dataframe(df)
158
+
159
+ if computeTraces:
160
+ df = extract_traces_by_session(df)
161
+
162
+ df = df.sort_values(by=ColumnNames.TIME_STAMP)
163
+
164
+ df = compute_space_time_diff(df)
165
+
166
+ # Área bajo la curva real
167
+ area_real = np.trapezoid(df[ColumnNames.Y], df[ColumnNames.X])
168
+
169
+ return area_real
170
+
171
+ def auc_optimal(df: pd.DataFrame, validation: bool = True, computeTraces: bool = True) -> float:
172
+ """
173
+ Calculate the Optimal Area Under the Curve (AUC) for the given DataFrame.
174
+
175
+ Parameters:
176
+ df (pd.DataFrame): DataFrame containing 'timeStamp' and 'y' columns.
177
+ validation (bool): Whether to validate the DataFrame structure, by default True.
178
+ computeTraces (bool): Whether to compute traces by sessionId, by default True.
179
+
180
+ Returns:
181
+ float: The computed optimal AUC value.
182
+ """
183
+
184
+ if(validation):
185
+ validate_dataframe(df)
186
+
187
+ if computeTraces:
188
+ df = extract_traces_by_session(df)
189
+
190
+
191
+ df = compute_space_time_diff(df)
192
+
193
+ # Área bajo la línea óptima
194
+ x0, y0 = df[ColumnNames.X].iloc[0], df[ColumnNames.Y].iloc[0]
195
+ x1, y1 = df[ColumnNames.X].iloc[-1], df[ColumnNames.Y].iloc[-1]
196
+ x_opt = np.linspace(x0, x1, len(df))
197
+ y_opt = np.linspace(y0, y1, len(df))
198
+ area_optimal = np.trapezoid(y_opt, x_opt)
199
+
200
+ return area_optimal
201
+
202
+ def auc_ratio(df: pd.DataFrame, computeTraces: bool = True) -> dict:
203
+ """
204
+ Calculate the AUC ratio for the given DataFrame.
205
+
206
+ Parameters:
207
+ df (pd.DataFrame): DataFrame containing 'timeStamp' and 'y' columns.
208
+ computeTraces (bool): Whether to compute traces by sessionId, by default True. If False, df is assumed to be already segmented by sessionId.
209
+
210
+ Returns:
211
+ auc_per_session (dict): A dictionary with sessionId as keys and a tuple (area_real, area_optimal, auc_ratio) as values.
212
+ """
213
+
214
+ validate_dataframe(df)
215
+
216
+ if computeTraces:
217
+ df = extract_traces_by_session(df)
218
+
219
+ auc_per_session = {}
220
+ for session_id, session_traces in df.items():
221
+ area_real = auc(session_traces, False, False)
222
+ area_optimal = auc_optimal(session_traces, False, False)
223
+ auc_per_session[session_id] = (area_real, area_optimal, abs(area_real - area_optimal) / (abs(area_optimal) + 1e-6))
224
+
225
+ return auc_per_session
226
+
@@ -0,0 +1,129 @@
1
+ import pandas as pd
2
+ from ..utils.validation import validate_dataframe
3
+ from ..utils.segmentation import extract_traces_by_session
4
+ from ..utils.utils import compute_space_time_diff
5
+ from ..constants import ColumnNames
6
+
7
+ def execution_time(df: pd.DataFrame) -> float:
8
+ """
9
+ Calculate the total execution time of a session in seconds.
10
+
11
+ Parameters:
12
+ df (pd.DataFrame): DataFrame containing 'timeStamp' column.
13
+ Returns:
14
+ float: Total execution time in seconds.
15
+ """
16
+ validate_dataframe(df)
17
+
18
+ start_time = df[ColumnNames.TIME_STAMP].min()
19
+ end_time = df[ColumnNames.TIME_STAMP].max()
20
+ total_time = (end_time - start_time) / 1000.0 # Convert milliseconds to seconds
21
+ return total_time
22
+
23
+ def movement_time(df: pd.DataFrame, traces: dict[str, list[pd.DataFrame]] = None) -> float:
24
+ """
25
+ Calculate the total movement time from traces in seconds.
26
+
27
+ Parameters:
28
+ df (pd.DataFrame): DataFrame containing 'timeStamp' column.
29
+ traces (dict): Dictionary with sessionId as keys and list of DataFrames as values.
30
+ Returns:
31
+ float: Total movement time in seconds.
32
+ """
33
+ if traces is None:
34
+ validate_dataframe(df)
35
+ traces = extract_traces_by_session(df)
36
+
37
+ total_movement_time = 0.0
38
+ for session_id, session_traces in traces.items():
39
+ for trace in session_traces:
40
+ trace = compute_space_time_diff(trace)
41
+ total_movement_time += trace[ColumnNames.DT].sum() / 1000.0 # Convert milliseconds to seconds
42
+
43
+ return total_movement_time
44
+
45
+ def num_pauses(df: pd.DataFrame, threshold: float = 100, computeTraces: bool = True) -> tuple[dict, dict]:
46
+ """
47
+ Calculate the number of pauses in the DataFrame.
48
+
49
+ Parameters:
50
+ df (pd.DataFrame): DataFrame containing 'timeStamp' column.
51
+ threshold (float): Time threshold in milliseconds to consider a pause, by default 100 ms.
52
+ computeTraces (bool): Whether to compute traces by sessionId, by default True. If False, df is assumed to be already segmented by sessionId.
53
+
54
+ Returns:
55
+ tuple (tuple[dict, dict]): A tuple containing two dictionaries with the number of pauses per session and the mean number of pauses per trace, with the sessionId as keys.
56
+ """
57
+
58
+ if computeTraces:
59
+ validate_dataframe(df)
60
+ df = extract_traces_by_session(df)
61
+
62
+ num_pauses_per_session = {}
63
+ mean_pause_per_trace = {}
64
+ for session_id, session_traces in df.items():
65
+ total_pauses_session = 0
66
+ for trace in session_traces:
67
+ df_pauses = _num_pauses_trace(trace, threshold)
68
+ total_pauses_session += df_pauses.shape[0]
69
+ num_pauses_per_session[session_id] = total_pauses_session
70
+ mean_pause_per_trace[session_id] = total_pauses_session / len(session_traces) if len(session_traces) > 0 else 0
71
+ return num_pauses_per_session, mean_pause_per_trace
72
+
73
+ def _num_pauses_trace(df: pd.DataFrame, threshold: float) -> pd.DataFrame:
74
+ """
75
+ Helper function to calculate pauses in a single trace.
76
+ """
77
+ df = df.sort_values(by=ColumnNames.TIME_STAMP).reset_index(drop=True)
78
+ df[ColumnNames.DT] = df[ColumnNames.TIME_STAMP].diff().fillna(0)
79
+ pauses = df[df[ColumnNames.DT] > threshold]
80
+ return pauses
81
+
82
+
83
+ def pauses_metrics(df: pd.DataFrame, threshold: float = 100, traces: dict[str, list[pd.DataFrame]] = None) -> dict:
84
+ """
85
+ Calculate pause metrics for the given DataFrame.
86
+
87
+ Parameters:
88
+ df (pd.DataFrame): DataFrame containing 'timeStamp' column.
89
+ threshold (float): Time threshold in milliseconds to consider a pause, by default 100 ms.
90
+ traces (dict): Dictionary with sessionId as keys and list of DataFrames as values.
91
+
92
+ Returns:
93
+ dict: A dictionary with sessionId as keys and a dictionary of pause metrics as values.
94
+ """
95
+
96
+ if traces is None:
97
+ validate_dataframe(df)
98
+ traces = extract_traces_by_session(df)
99
+
100
+ pause_metrics_per_session = {}
101
+ number_pauses_session, number_pauses_trace = num_pauses(traces, threshold, computeTraces=False)
102
+ for session_id, session_traces in traces.items():
103
+ total_pauses = 0
104
+ total_pause_duration = 0.0
105
+ pause_durations = []
106
+
107
+ for trace in session_traces:
108
+ trace = compute_space_time_diff(trace)
109
+ pauses = trace[trace[ColumnNames.DT] > threshold]
110
+ total_pauses += pauses.shape[0]
111
+ total_pause_duration += pauses[ColumnNames.DT].sum()
112
+ pause_durations.extend(pauses[ColumnNames.DT].tolist())
113
+
114
+ # Compute pause metrics for the session
115
+ if total_pauses > 0:
116
+ mean_pause_duration = total_pause_duration / total_pauses
117
+ else:
118
+ mean_pause_duration = 0
119
+
120
+ pause_metrics_per_session[session_id] = {
121
+ "total_pauses": total_pauses,
122
+ "mean_pause_duration": mean_pause_duration,
123
+ "pause_durations": pause_durations,
124
+ "mean_pauses_per_trace": number_pauses_trace.get(session_id, 0),
125
+ "max_pause": max(pause_durations) if pause_durations else 0,
126
+ "min_pause": min(pause_durations) if pause_durations else 0,
127
+ }
128
+
129
+ return pause_metrics_per_session
@@ -0,0 +1,14 @@
1
+ """
2
+ Utility functions for PyWib
3
+ """
4
+
5
+ from .validation import validate_dataframe, validate_dataframe_keyboard
6
+ from .segmentation import extract_traces_by_session
7
+ from .visualization import visualize_trace
8
+
9
+ __all__ = [
10
+ 'validate_dataframe',
11
+ 'validate_dataframe_keyboard',
12
+ 'extract_traces_by_session',
13
+ 'visualize_trace'
14
+ ]
@@ -0,0 +1,42 @@
1
+ import pandas as pd
2
+ from ..constants import EventTypes, ColumnNames
3
+ from ..utils.validation import validate_dataframe
4
+
5
+ def extract_trace(dt: pd.DataFrame) -> list:
6
+ """
7
+ Extracts trace from the DataFrame.
8
+ Each trace is considered as a sequence of consecutive ON_MOUSE_MOVE events
9
+ between two non-move events.
10
+ Returns a list of DataFrames, each corresponding to a trace.
11
+ """
12
+ validate_dataframe(dt)
13
+ dt = dt.sort_values(by=ColumnNames.TIME_STAMP).reset_index(drop=True)
14
+ is_move = (dt[ColumnNames.EVENT_TYPE] == EventTypes.EVENT_ON_MOUSE_MOVE) | (dt[ColumnNames.EVENT_TYPE] == EventTypes.EVENT_ON_TOUCH_MOVE)
15
+ group_id = (~is_move).cumsum()
16
+ traces = []
17
+ for _, group in dt[is_move].groupby(group_id[is_move]):
18
+ if len(group) > 1:
19
+ traces.append(group)
20
+ return traces
21
+
22
+ def extract_traces_by_session(dt: pd.DataFrame) -> dict:
23
+ """
24
+ Extracts traces from the DataFrame, grouped by (sessionId, sceneId).
25
+ Each trace is considered as a sequence of consecutive ON_MOUSE_MOVE events
26
+ between two non-move events.
27
+
28
+ Returns:
29
+ dict: a dictionary with keys as (sessionId) and values as lists of DataFrames.
30
+ """
31
+ validate_dataframe(dt)
32
+ dt = dt.sort_values(by=ColumnNames.TIME_STAMP).reset_index(drop=True)
33
+ traces_by_session = {}
34
+ for session_id, group in dt.groupby(ColumnNames.SESSION_ID):
35
+ is_move = (group[ColumnNames.EVENT_TYPE] == EventTypes.EVENT_ON_MOUSE_MOVE) | (group[ColumnNames.EVENT_TYPE] == EventTypes.EVENT_ON_TOUCH_MOVE)
36
+ group_id = (~is_move).cumsum()
37
+ traces = []
38
+ for _, sub_group in group[is_move].groupby(group_id[is_move]):
39
+ if len(sub_group) > 1:
40
+ traces.append(sub_group)
41
+ traces_by_session[session_id] = traces
42
+ return traces_by_session
@@ -0,0 +1,26 @@
1
+ import pandas as pd
2
+ from ..constants import ColumnNames
3
+
4
+ def compute_space_time_diff(df: pd.DataFrame) -> pd.DataFrame:
5
+ """
6
+ Compute space and time differences (dx, dy, dt) for the given DataFrame.
7
+
8
+ Parameters:
9
+ df (pd.DataFrame): DataFrame containing 'x', 'y', and 'timeStamp' columns.
10
+
11
+ Returns:
12
+ pd.DataFrame: DataFrame with additional 'dx', 'dy', and 'dt' columns.
13
+ """
14
+ if(ColumnNames.X not in df.columns or
15
+ ColumnNames.Y not in df.columns or
16
+ ColumnNames.TIME_STAMP not in df.columns or
17
+ ColumnNames.SESSION_ID not in df.columns):
18
+ raise ValueError(f"DataFrame must contain '{ColumnNames.X}', '{ColumnNames.Y}', '{ColumnNames.TIME_STAMP}', and '{ColumnNames.SESSION_ID}' columns.")
19
+
20
+ df = df.copy()
21
+ df.sort_values(by=[ColumnNames.TIME_STAMP], inplace=True)
22
+ df[ColumnNames.TIME_STAMP] = pd.to_numeric(df[ColumnNames.TIME_STAMP], errors='coerce')
23
+ df['dt'] = df.groupby([ColumnNames.SESSION_ID])[ColumnNames.TIME_STAMP].diff().fillna(0)
24
+ df['dx'] = df.groupby([ColumnNames.SESSION_ID])[ColumnNames.X].diff().fillna(0)
25
+ df['dy'] = df.groupby([ColumnNames.SESSION_ID])[ColumnNames.Y].diff().fillna(0)
26
+ return df
@@ -0,0 +1,24 @@
1
+ import pandas as pd
2
+ from ..constants import ColumnNames
3
+
4
+ required_columns = [
5
+ ColumnNames.SESSION_ID, ColumnNames.EVENT_TYPE, ColumnNames.TIME_STAMP, ColumnNames.X, ColumnNames.Y
6
+ ]
7
+
8
+ keyboard_columns = [
9
+ ColumnNames.KEY_VALUE_EVENT, ColumnNames.KEY_CODE_EVENT
10
+ ]
11
+
12
+ def validate_dataframe(df: pd.DataFrame):
13
+
14
+ for col in required_columns:
15
+ if col not in df.columns:
16
+ raise ValueError(f"Missing required column: {col}")
17
+
18
+ def validate_dataframe_keyboard(df: pd.DataFrame):
19
+
20
+ columns_to_check = required_columns + keyboard_columns
21
+
22
+ for col in columns_to_check:
23
+ if col not in df.columns:
24
+ raise ValueError(f"Missing required column: {col}")
@@ -0,0 +1,23 @@
1
+ import pandas as pd
2
+
3
+ required_columns = [
4
+ "id", "eventType", "timeStamp", "x", "y"
5
+ ]
6
+
7
+ keyboard_columns = [
8
+ "keyValueEvent", "keyCodeEvent"
9
+ ]
10
+
11
+ def validate_dataframe(df: pd.DataFrame):
12
+
13
+ for col in required_columns:
14
+ if col not in df.columns:
15
+ raise ValueError(f"Missing required column: {col}")
16
+
17
+ def validate_dataframe_keyboard(df: pd.DataFrame):
18
+
19
+ columns_to_check = required_columns + keyboard_columns
20
+
21
+ for col in columns_to_check:
22
+ if col not in df.columns:
23
+ raise ValueError(f"Missing required column: {col}")
@@ -0,0 +1,23 @@
1
+ import matplotlib.pyplot as plt
2
+
3
+ def visualize_trace(df, stroke_indices, stroke_id):
4
+ stroke_data = df.loc[stroke_indices]
5
+ plt.figure(figsize=(10, 8))
6
+ plt.plot(stroke_data['x'], stroke_data['y'], 'b-o', linewidth=2, markersize=4, label='Trazo real')
7
+
8
+ x_start, y_start = stroke_data['x'].iloc[0], stroke_data['y'].iloc[0]
9
+ x_end, y_end = stroke_data['x'].iloc[-1], stroke_data['y'].iloc[-1]
10
+ plt.plot([x_start, x_end], [y_start, y_end], 'r--', linewidth=2, label='Línea óptima')
11
+
12
+ plt.plot(x_start, y_start, 'go', markersize=8, label='Inicio')
13
+ plt.plot(x_end, y_end, 'ro', markersize=8, label='Fin')
14
+
15
+ duration = stroke_data['timeStamp'].iloc[-1] - stroke_data['timeStamp'].iloc[0]
16
+ plt.xlabel('X (píxeles)')
17
+ plt.ylabel('Y (píxeles)')
18
+ plt.title(f'Trazo {stroke_id} - Duración: {duration:.0f}ms - Puntos: {len(stroke_data)}')
19
+ plt.legend()
20
+ plt.grid(True, alpha=0.3)
21
+ plt.gca().invert_yaxis()
22
+ plt.show()
23
+
File without changes
@@ -0,0 +1,60 @@
1
+ import unittest
2
+ import pandas as pd
3
+ import numpy as np
4
+
5
+ # Now you can import directly since the package is installed
6
+ from src.pywib.core.movement import velocity, acceleration
7
+ from src.pywib.utils.utils import compute_space_time_diff
8
+ from utils import process_csv
9
+
10
+ class TestMovement(unittest.TestCase):
11
+
12
+ def setUp(self):
13
+ """Set up test data"""
14
+ # Create sample test data instead of relying on external CSV
15
+ self.test_data = process_csv('E:\\Documents\\Guille\\Uni\\2025\\HCI-Web-Interaction-Analyzer\\test_window_resize_error.csv')
16
+
17
+ def test_velocity(self):
18
+ """Test velocity calculation"""
19
+ # Compute space-time differences
20
+ df = compute_space_time_diff(self.test_data.copy())
21
+
22
+ # Calculate velocity
23
+ df_velocity = velocity(df)
24
+
25
+ # Check if the velocity column is added
26
+ for session_id, traces in df_velocity.items():
27
+ for trace in traces:
28
+ self.assertIn('velocity', trace.columns)
29
+ # Check if velocity values are non-negative
30
+ self.assertTrue((trace['velocity'] >= 0).all())
31
+ self.assertGreaterEqual(trace['velocity'].mean(), 0)
32
+ # Verify velocity calculation
33
+ dt = trace.timeStamp.diff()
34
+ dx = trace.x.diff()
35
+ dy = trace.y.diff()
36
+ expected_velocity = np.sqrt(dx**2 + dy**2) / dt
37
+ expected_velocity.fillna(0, inplace=True)
38
+ np.testing.assert_allclose(trace['velocity'], expected_velocity, rtol=1e-5, atol=1e-8)
39
+
40
+ def test_acceleration(self):
41
+ """Test acceleration calculation"""
42
+ df = compute_space_time_diff(self.test_data.copy())
43
+ traces_velocity = velocity(df)
44
+
45
+ # Calculate acceleration
46
+ df_acceleration = acceleration(None, traces_velocity)
47
+
48
+ # Check if the acceleration column is added
49
+ for session_id, traces in df_acceleration.items():
50
+ for trace in traces:
51
+ self.assertIn('acceleration', trace.columns)
52
+ # Verify acceleration calculation
53
+ dt = trace.timeStamp.diff()
54
+ dv = trace['velocity'].diff()
55
+ expected_acceleration = dv / dt
56
+ expected_acceleration.fillna(0, inplace=True)
57
+ np.testing.assert_allclose(trace['acceleration'], expected_acceleration, rtol=1e-5, atol=1e-8)
58
+
59
+ if __name__ == '__main__':
60
+ unittest.main()
@@ -0,0 +1,43 @@
1
+ import pandas as pd
2
+ from collections import defaultdict
3
+
4
+ def process_csv(file_path):
5
+ """
6
+ Reads a semicolon-separated CSV file and processes it into matrices grouped by sessionId and sceneId.
7
+ Args:
8
+ file_path (str): Path to the CSV file.
9
+ """
10
+ # Read the CSV file with semicolon separator
11
+ df = pd.read_csv(file_path, encoding='utf-8', sep=',')
12
+
13
+ # Dictionary to store matrices for each sessionId and sceneId
14
+ matrices = defaultdict(list)
15
+
16
+ # Process each row in the DataFrame
17
+ for _, row in df.iterrows():
18
+ session_id = row['sessionId']
19
+
20
+ # Create a key combining sessionId and sceneId
21
+ key = (session_id)
22
+
23
+ # Extract the relevant values and append to the matrix
24
+ matrices[key].append([
25
+ row['eventType'],
26
+ row['timeStamp'],
27
+ row['x'],
28
+ row['y'],
29
+ row['keyValueEvent'],
30
+ row['keyCodeEvent'],
31
+ ])
32
+
33
+ all_sessions = []
34
+ for (session_id), matrix in matrices.items():
35
+ df = pd.DataFrame(matrix, columns=[
36
+ 'eventType', 'timeStamp', 'x', 'y', 'keyValueEvent', 'keyCodeEvent' ])
37
+ df['sessionId'] = session_id
38
+ all_sessions.append(df)
39
+
40
+ df_all_sessions = pd.concat(all_sessions, ignore_index=True)
41
+ df_all_sessions['timeStamp'] = df_all_sessions['timeStamp'].astype(str).str.replace(',', '', regex=False)
42
+ df_all_sessions['timeStamp'] = pd.to_numeric(df_all_sessions['timeStamp'], errors='coerce')
43
+ return df_all_sessions