pywib 3.0.0__tar.gz → 3.0.2__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.
Files changed (119) hide show
  1. {pywib-3.0.0 → pywib-3.0.2}/CHANGELOG.md +19 -0
  2. {pywib-3.0.0 → pywib-3.0.2}/PKG-INFO +9 -1
  3. {pywib-3.0.0 → pywib-3.0.2}/README.md +8 -0
  4. {pywib-3.0.0 → pywib-3.0.2}/docs/source/api/keyboard/keystrokes.rst +0 -3
  5. {pywib-3.0.0 → pywib-3.0.2}/docs/source/conf.py +1 -1
  6. {pywib-3.0.0 → pywib-3.0.2}/docs/source/keyboard.rst +2 -0
  7. {pywib-3.0.0 → pywib-3.0.2}/pyproject.toml +1 -1
  8. {pywib-3.0.0 → pywib-3.0.2}/setup.py +1 -1
  9. {pywib-3.0.0 → pywib-3.0.2}/src/pywib/__init__.py +1 -1
  10. {pywib-3.0.0 → pywib-3.0.2}/src/pywib/constants.py +1 -1
  11. {pywib-3.0.0 → pywib-3.0.2}/src/pywib/core/keyboard/keyboard.py +32 -14
  12. {pywib-3.0.0 → pywib-3.0.2}/src/pywib/core/movement/trajectory.py +75 -17
  13. pywib-3.0.2/src/pywib/utils/cleanup.py +10 -0
  14. {pywib-3.0.0 → pywib-3.0.2}/src/pywib/utils/keyboard.py +35 -19
  15. {pywib-3.0.0 → pywib-3.0.2}/src/pywib/utils/segmentation.py +12 -11
  16. pywib-3.0.2/test/test_data/test_keyboard_simple.csv +17 -0
  17. {pywib-3.0.0 → pywib-3.0.2}/test/test_data/test_trajectory_single.csv +2 -0
  18. {pywib-3.0.0 → pywib-3.0.2}/test/test_keyboard.py +33 -13
  19. {pywib-3.0.0 → pywib-3.0.2}/test/test_trajectory.py +21 -5
  20. {pywib-3.0.0 → pywib-3.0.2}/.github/workflows/deply_docs.yml +0 -0
  21. {pywib-3.0.0 → pywib-3.0.2}/.github/workflows/publish.yml +0 -0
  22. {pywib-3.0.0 → pywib-3.0.2}/.github/workflows/test_on_pr.yml +0 -0
  23. {pywib-3.0.0 → pywib-3.0.2}/.gitignore +0 -0
  24. {pywib-3.0.0 → pywib-3.0.2}/AGENTS.md +0 -0
  25. {pywib-3.0.0 → pywib-3.0.2}/CLAUDE.md +0 -0
  26. {pywib-3.0.0 → pywib-3.0.2}/LICENSE +0 -0
  27. {pywib-3.0.0 → pywib-3.0.2}/context7.json +0 -0
  28. {pywib-3.0.0 → pywib-3.0.2}/docs/Makefile +0 -0
  29. {pywib-3.0.0 → pywib-3.0.2}/docs/make.bat +0 -0
  30. {pywib-3.0.0 → pywib-3.0.2}/docs/source/_static/custom.css +0 -0
  31. {pywib-3.0.0 → pywib-3.0.2}/docs/source/_static/images/aad_diagram.svg +0 -0
  32. {pywib-3.0.0 → pywib-3.0.2}/docs/source/_static/images/keyboard_heatmap_example.png +0 -0
  33. {pywib-3.0.0 → pywib-3.0.2}/docs/source/_static/images/logo-pywib.svg +0 -0
  34. {pywib-3.0.0 → pywib-3.0.2}/docs/source/_static/images/mad_diagram.svg +0 -0
  35. {pywib-3.0.0 → pywib-3.0.2}/docs/source/_static/images/trace_visualization_example.png +0 -0
  36. {pywib-3.0.0 → pywib-3.0.2}/docs/source/_templates/attribute_table.rst +0 -0
  37. {pywib-3.0.0 → pywib-3.0.2}/docs/source/android-chrome-192x192.png +0 -0
  38. {pywib-3.0.0 → pywib-3.0.2}/docs/source/android-chrome-512x512.png +0 -0
  39. {pywib-3.0.0 → pywib-3.0.2}/docs/source/api/index.rst +0 -0
  40. {pywib-3.0.0 → pywib-3.0.2}/docs/source/api/keyboard/index.rst +0 -0
  41. {pywib-3.0.0 → pywib-3.0.2}/docs/source/api/mouse/clicks.rst +0 -0
  42. {pywib-3.0.0 → pywib-3.0.2}/docs/source/api/movement/acceleration.rst +0 -0
  43. {pywib-3.0.0 → pywib-3.0.2}/docs/source/api/movement/angle.rst +0 -0
  44. {pywib-3.0.0 → pywib-3.0.2}/docs/source/api/movement/index.rst +0 -0
  45. {pywib-3.0.0 → pywib-3.0.2}/docs/source/api/movement/jerkiness.rst +0 -0
  46. {pywib-3.0.0 → pywib-3.0.2}/docs/source/api/movement/velocity.rst +0 -0
  47. {pywib-3.0.0 → pywib-3.0.2}/docs/source/api/timing/index.rst +0 -0
  48. {pywib-3.0.0 → pywib-3.0.2}/docs/source/api/timing/pauses.rst +0 -0
  49. {pywib-3.0.0 → pywib-3.0.2}/docs/source/api/timing/time.rst +0 -0
  50. {pywib-3.0.0 → pywib-3.0.2}/docs/source/api/trajectory/auc.rst +0 -0
  51. {pywib-3.0.0 → pywib-3.0.2}/docs/source/api/trajectory/deviations.rst +0 -0
  52. {pywib-3.0.0 → pywib-3.0.2}/docs/source/api/trajectory/index.rst +0 -0
  53. {pywib-3.0.0 → pywib-3.0.2}/docs/source/api/trajectory/path.rst +0 -0
  54. {pywib-3.0.0 → pywib-3.0.2}/docs/source/api/utils/data_processing.rst +0 -0
  55. {pywib-3.0.0 → pywib-3.0.2}/docs/source/api/utils/index.rst +0 -0
  56. {pywib-3.0.0 → pywib-3.0.2}/docs/source/api/utils/visualization.rst +0 -0
  57. {pywib-3.0.0 → pywib-3.0.2}/docs/source/apple-touch-icon.png +0 -0
  58. {pywib-3.0.0 → pywib-3.0.2}/docs/source/constants.rst +0 -0
  59. {pywib-3.0.0 → pywib-3.0.2}/docs/source/context_specific_metrics.rst +0 -0
  60. {pywib-3.0.0 → pywib-3.0.2}/docs/source/data_structure.rst +0 -0
  61. {pywib-3.0.0 → pywib-3.0.2}/docs/source/dependent_cases.rst +0 -0
  62. {pywib-3.0.0 → pywib-3.0.2}/docs/source/favicon-16x16.png +0 -0
  63. {pywib-3.0.0 → pywib-3.0.2}/docs/source/favicon-32x32.png +0 -0
  64. {pywib-3.0.0 → pywib-3.0.2}/docs/source/favicon.ico +0 -0
  65. {pywib-3.0.0 → pywib-3.0.2}/docs/source/favicon_old.ico +0 -0
  66. {pywib-3.0.0 → pywib-3.0.2}/docs/source/index.rst +0 -0
  67. {pywib-3.0.0 → pywib-3.0.2}/docs/source/introduction.rst +0 -0
  68. {pywib-3.0.0 → pywib-3.0.2}/docs/source/mouse.rst +0 -0
  69. {pywib-3.0.0 → pywib-3.0.2}/docs/source/movement.rst +0 -0
  70. {pywib-3.0.0 → pywib-3.0.2}/docs/source/normalization.rst +0 -0
  71. {pywib-3.0.0 → pywib-3.0.2}/docs/source/patterns.rst +0 -0
  72. {pywib-3.0.0 → pywib-3.0.2}/docs/source/references.bib +0 -0
  73. {pywib-3.0.0 → pywib-3.0.2}/docs/source/segmentation.rst +0 -0
  74. {pywib-3.0.0 → pywib-3.0.2}/docs/source/site.webmanifest +0 -0
  75. {pywib-3.0.0 → pywib-3.0.2}/docs/source/timing.rst +0 -0
  76. {pywib-3.0.0 → pywib-3.0.2}/docs/source/trajectory.rst +0 -0
  77. {pywib-3.0.0 → pywib-3.0.2}/docs/source/visualization.rst +0 -0
  78. {pywib-3.0.0 → pywib-3.0.2}/llms.txt +0 -0
  79. {pywib-3.0.0 → pywib-3.0.2}/requirements.txt +0 -0
  80. {pywib-3.0.0 → pywib-3.0.2}/src/pywib/core/__init__.py +0 -0
  81. {pywib-3.0.0 → pywib-3.0.2}/src/pywib/core/keyboard/__init__.py +0 -0
  82. {pywib-3.0.0 → pywib-3.0.2}/src/pywib/core/mouse/__init__.py +0 -0
  83. {pywib-3.0.0 → pywib-3.0.2}/src/pywib/core/mouse/mouse.py +0 -0
  84. {pywib-3.0.0 → pywib-3.0.2}/src/pywib/core/movement/__init__.py +0 -0
  85. {pywib-3.0.0 → pywib-3.0.2}/src/pywib/core/movement/movement.py +0 -0
  86. {pywib-3.0.0 → pywib-3.0.2}/src/pywib/core/timing/__init__.py +0 -0
  87. {pywib-3.0.0 → pywib-3.0.2}/src/pywib/core/timing/timing.py +0 -0
  88. {pywib-3.0.0 → pywib-3.0.2}/src/pywib/utils/__init__.py +0 -0
  89. {pywib-3.0.0 → pywib-3.0.2}/src/pywib/utils/movement/__init__.py +0 -0
  90. {pywib-3.0.0 → pywib-3.0.2}/src/pywib/utils/movement/movement.py +0 -0
  91. {pywib-3.0.0 → pywib-3.0.2}/src/pywib/utils/movement/trajectory.py +0 -0
  92. {pywib-3.0.0 → pywib-3.0.2}/src/pywib/utils/normalization.py +0 -0
  93. {pywib-3.0.0 → pywib-3.0.2}/src/pywib/utils/timing.py +0 -0
  94. {pywib-3.0.0 → pywib-3.0.2}/src/pywib/utils/utils.py +0 -0
  95. {pywib-3.0.0 → pywib-3.0.2}/src/pywib/utils/validation.py +0 -0
  96. {pywib-3.0.0 → pywib-3.0.2}/src/pywib/utils/visualization/__init__.py +0 -0
  97. {pywib-3.0.0 → pywib-3.0.2}/src/pywib/utils/visualization/trace_strategies.py +0 -0
  98. {pywib-3.0.0 → pywib-3.0.2}/src/pywib/utils/visualization/visualization.py +0 -0
  99. {pywib-3.0.0 → pywib-3.0.2}/test/__init__.py +0 -0
  100. {pywib-3.0.0 → pywib-3.0.2}/test/test.py +0 -0
  101. {pywib-3.0.0 → pywib-3.0.2}/test/test_data/pauses.csv +0 -0
  102. {pywib-3.0.0 → pywib-3.0.2}/test/test_data/test.csv +0 -0
  103. {pywib-3.0.0 → pywib-3.0.2}/test/test_data/test_auc.csv +0 -0
  104. {pywib-3.0.0 → pywib-3.0.2}/test/test_data/test_duplicate_timestamps.csv +0 -0
  105. {pywib-3.0.0 → pywib-3.0.2}/test/test_data/test_incorrect_columns.csv +0 -0
  106. {pywib-3.0.0 → pywib-3.0.2}/test/test_data/test_missing_keyboard_cols.csv +0 -0
  107. {pywib-3.0.0 → pywib-3.0.2}/test/test_data/test_mouse.csv +0 -0
  108. {pywib-3.0.0 → pywib-3.0.2}/test/test_data/test_mouse_keyboard.csv +1 -1
  109. {pywib-3.0.0 → pywib-3.0.2}/test/test_data/test_trajectory.csv +0 -0
  110. {pywib-3.0.0 → pywib-3.0.2}/test/test_data/test_window_resize_error.csv +0 -0
  111. {pywib-3.0.0 → pywib-3.0.2}/test/test_data/test_window_resize_multiple_error.csv +0 -0
  112. {pywib-3.0.0 → pywib-3.0.2}/test/test_mouse.py +0 -0
  113. {pywib-3.0.0 → pywib-3.0.2}/test/test_movement.py +0 -0
  114. {pywib-3.0.0 → pywib-3.0.2}/test/test_normalization.py +0 -0
  115. {pywib-3.0.0 → pywib-3.0.2}/test/test_public_exports.py +0 -0
  116. {pywib-3.0.0 → pywib-3.0.2}/test/test_timing.py +0 -0
  117. {pywib-3.0.0 → pywib-3.0.2}/test/test_validation.py +0 -0
  118. {pywib-3.0.0 → pywib-3.0.2}/test/test_visualzation.py +0 -0
  119. {pywib-3.0.0 → pywib-3.0.2}/test/utils.py +0 -0
@@ -5,6 +5,25 @@ All notable changes to PyWIB will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [3.0.2] - 2026-12-02
9
+
10
+ ### Fixed
11
+ The method `typing_speed_metrics`, which had an error when obtaining the durations for the key-press/releases. The method hs been fixed to preserve an order, pair key-up/down events correctly and ignore intermediate, repeated key down events. Unit tests have been added to ensure this errors are now validated.
12
+ Documentation for this method has also been updated to explain how the key `total_chars` is obtained.
13
+
14
+ ## [3.0.1] - 2026-11-11
15
+
16
+ ### Changed
17
+ - Updated return type annotations of `typing_durations`, `typing_durations_df` and `typing_durations_traces` to reflect that they can return `float` values (with `single=True`) or per-session dictionaries. (#55)
18
+
19
+ ### Fixed
20
+ - Bugs in `typing_durations` and its helpers in `core/keyboard` and `utils/keyboard`. Results may differ from previous versions. (#55)
21
+ - Bug in the direction-change metrics (`direction_changes`, `x_flips`, `y_flips`). Results may differ from previous versions. (#58)
22
+ - As part of the fix, `direction_changes`, `x_flips` and `y_flips` accept an optional `per_user` argument, and `direction_changes` accepts an optional `threshold` (radians, default `np.pi / 4`).
23
+
24
+ ### Documentation
25
+ - Added an interview section to the README.
26
+
8
27
  ## [3.0.0] - 2026-11-05
9
28
 
10
29
  ### Added
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: pywib
3
- Version: 3.0.0
3
+ Version: 3.0.2
4
4
  Summary: HCI Web Interaction Analyzer - A library for analyzing web user interactions
5
5
  Project-URL: Homepage, https://github.com/uniovi-hci/pywib
6
6
  Project-URL: Bug Tracker, https://github.com/uniovi-hci/pywib/issues
@@ -140,4 +140,12 @@ And then access `docs/build/html/index.html` to navigate.
140
140
  <sub>Oct 27, 2026</sub>
141
141
  </td>
142
142
  </tr>
143
+ <tr>
144
+ <td width="200" valign="top">
145
+ Interview on Cadena SER Gijón
146
+ </td>
147
+ <td valign="top">
148
+ <a href="https://cadenaser.com/embed/audio/460/ser_asturias_avivirquesondosdiasasturias_20261107_130418_140000/" target="_balank" rel="noopener">▶ Listen to the interview on Cadena SER at minute 26:20</a>
149
+ </td>
150
+ </tr>
143
151
  </table>
@@ -109,4 +109,12 @@ And then access `docs/build/html/index.html` to navigate.
109
109
  <sub>Oct 27, 2026</sub>
110
110
  </td>
111
111
  </tr>
112
+ <tr>
113
+ <td width="200" valign="top">
114
+ Interview on Cadena SER Gijón
115
+ </td>
116
+ <td valign="top">
117
+ <a href="https://cadenaser.com/embed/audio/460/ser_asturias_avivirquesondosdiasasturias_20261107_130418_140000/" target="_balank" rel="noopener">▶ Listen to the interview on Cadena SER at minute 26:20</a>
118
+ </td>
119
+ </tr>
112
120
  </table>
@@ -56,9 +56,6 @@ The first string corresponds to the sessionId, whereas the inner dictionary cont
56
56
  - total_time_seconds
57
57
  - avg_keydown_to_keyup_duration
58
58
 
59
- .. warning::
60
- As of version 2.1.0. avg_keydown_to_keyup_duration is experimenting a computational error and always returns .NaN
61
-
62
59
  .. autofunction:: pywib.typing_speed_metrics
63
60
 
64
61
 
@@ -18,7 +18,7 @@ from pybtex.style.template import (
18
18
  project = 'PyWIB'
19
19
  copyright = '2025, Guillermo Dylan Carvajal Aza, Alejandro Álvarez Varela'
20
20
  author = 'Guillermo Dylan Carvajal Aza, Alejandro Álvarez Varela'
21
- release = '3.0.0'
21
+ release = '3.0.2'
22
22
 
23
23
  # -- General configuration ---------------------------------------------------
24
24
  # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
@@ -34,6 +34,8 @@ With the function :py:func:`~pywib.typing_speed_metrics` the metrics returned in
34
34
 
35
35
  .. note::
36
36
  The method :py:func:`~pywib.typing_speed` computes the active time typing, meaning that the resulting CPM maesures characters divided by the interval between the first and last keydown events, rather than by the entire session duration.
37
+
38
+ In a similar basis, :py:func:`~pywib.typing_speed_metrics` returns the total characters typed as the number of *total keys actually produced*. This means that if a user presses down the 'a' key once and holds it down to produce 'aaa', the resulting value for the total chars is 3.
37
39
 
38
40
  Words Per minute
39
41
  ~~~~~~~~~~~~~~~~
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "pywib"
7
- version = "3.0.0"
7
+ version = "3.0.2"
8
8
  authors = [
9
9
  { name="Guillermo Dylan Carvajal Aza", email="carvajalguillermo@uniovi.es" },
10
10
  { name="Alejandro Álvarez Varela", email="avarela@uniovi.es"}
@@ -10,7 +10,7 @@ with open("requirements.txt", "r", encoding="utf-8") as fh:
10
10
  setup(
11
11
  name='pywib',
12
12
  packages=find_packages(),
13
- version='3.0.0',
13
+ version='3.0.2',
14
14
  description='HCI Web Interaction Analyzer - A library for analyzing web user interactions',
15
15
  long_description=long_description,
16
16
  long_description_content_type="text/markdown",
@@ -1,7 +1,7 @@
1
1
  """
2
2
  """
3
3
 
4
- __version__ = "3.0.0"
4
+ __version__ = "3.0.2"
5
5
  __author__ = "Guillermo Dylan Carvajal Aza"
6
6
  __email__ = "carvajalguillermo@uniovi.es"
7
7
 
@@ -1,6 +1,6 @@
1
1
  # Version and library information
2
2
  LIBRARY_NAME = "pywib"
3
- LIBRARY_VERSION = "3.0.0"
3
+ LIBRARY_VERSION = "3.0.2"
4
4
 
5
5
  # Event types for interaction tracking
6
6
  class EventTypes:
@@ -12,17 +12,26 @@ from pywib.constants import EventTypes, ColumnNames
12
12
  from pywib.utils.keyboard import (backspace_usage_df, backspace_usage_traces, typing_durations_df, typing_durations_traces, typing_speed_df, typing_speed_traces, word_per_minute, word_per_minute_traces)
13
13
  from pywib.utils.validation import validate_any_not_none
14
14
 
15
- def typing_durations(df: pd.DataFrame = None, traces: dict[str, list[pd.DataFrame]] = None, per_traces: bool = True, single: bool = False) -> list:
15
+ def typing_durations(df: pd.DataFrame = None, traces: dict[str, list[pd.DataFrame]] = None, per_traces: bool = True, single: bool = False) -> list | float | dict[str, list[pd.DataFrame]]:
16
16
  """
17
17
  Calculate the durations of individual keystrokes.
18
18
 
19
19
  Parameters:
20
20
  df (pd.DataFrame): DataFrame containing interaction data with 'event_type', 'timestamp', and 'key' columns.
21
21
  traces (dict[str, list[pd.DataFrame]]): optional Pre-extracted keystroke traces by session.
22
- per_traces (bool): optional whether to calculate durations per trace. Default is True.
23
- single (bool): optional, wether to compute durations fully (all the time the user is typing) or for every single keystroke (value for every single key press and release combination)
24
- Returns:
25
- list[float]: List of keystroke durations in milliseconds.
22
+ per_traces (bool): True by default, whether to calculate durations per trace. Default is True.
23
+ single (bool): False by default, wether to compute durations fully (all the time the user is typing) or for every single keystroke (value for every single key press and release combination)
24
+ Returns:
25
+ Return type depends on ``per_traces`` and ``single``:
26
+
27
+ - per_traces=False, single=True -> list[float]:
28
+ Keystroke durations in milliseconds.
29
+ - per_traces=False, single=False -> float:
30
+ Total typing duration in milliseconds.
31
+ - per_traces=True, single=True -> dict[str, list[float]]:
32
+ Session IDs mapped to per-trace keystroke durations.
33
+ - per_traces=True, single=False -> dict[str, float]:
34
+ Session IDs mapped to total duration per trace.
26
35
  """
27
36
 
28
37
  validate_any_not_none(df, traces)
@@ -34,7 +43,7 @@ def typing_durations(df: pd.DataFrame = None, traces: dict[str, list[pd.DataFram
34
43
 
35
44
  if not per_traces:
36
45
  validate_dataframe_keyboard(df)
37
- return typing_durations_df(df)
46
+ return typing_durations_df(df, single=single)
38
47
 
39
48
  return typing_durations_traces(traces, single=single)
40
49
 
@@ -78,6 +87,11 @@ def typing_speed_metrics(df: pd.DataFrame = None, traces: dict[str, list[pd.Data
78
87
  per_trace : bool, optional Whether to calculate metrics per trace. Default is True.
79
88
  Returns:
80
89
  dict: A dictionary with session IDs as keys and their corresponding typing speed metrics as values.
90
+ Key values:
91
+ - average_typing_speed
92
+ - total_characters
93
+ - avg_keydown_to_keyup_duration
94
+ - total_time_seconds
81
95
  """
82
96
 
83
97
  validate_any_not_none(df, traces)
@@ -93,14 +107,18 @@ def typing_speed_metrics(df: pd.DataFrame = None, traces: dict[str, list[pd.Data
93
107
  avg_speed = np.mean(speeds)
94
108
  total_chars = sum(session_traces[session_traces[ColumnNames.EVENT_TYPE] == EventTypes.EVENT_KEY_DOWN][ColumnNames.EVENT_TYPE].count() for session_traces in traces[session_id])
95
109
  total_time = sum((session_traces[ColumnNames.TIME_STAMP].diff().fillna(0).sum() / 1000.0) for session_traces in traces[session_id])
96
- keydown_to_keyup_durations = [
97
- keyup_time - keydown_time
98
- for trace in traces[session_id]
99
- for keydown_time, keyup_time in zip(
100
- trace[trace[ColumnNames.EVENT_TYPE] == EventTypes.EVENT_KEY_DOWN][ColumnNames.TIME_STAMP].values,
101
- trace[trace[ColumnNames.EVENT_TYPE] == EventTypes.EVENT_KEY_UP][ColumnNames.TIME_STAMP].values,
102
- )
103
- ]
110
+ keydown_to_keyup_durations = []
111
+ for trace in traces[session_id]:
112
+ pending_keydowns = {} # key_value -> timestamp
113
+ for event_type, timestamp, key_value in trace[
114
+ [ColumnNames.EVENT_TYPE, ColumnNames.TIME_STAMP, ColumnNames.KEY_VALUE]
115
+ ].itertuples(index=False, name=None):
116
+ if event_type == EventTypes.EVENT_KEY_DOWN:
117
+ pending_keydowns.setdefault(key_value, timestamp) # Ignore repeated keyDowns
118
+ elif event_type == EventTypes.EVENT_KEY_UP:
119
+ start = pending_keydowns.pop(key_value, None)
120
+ if start is not None: # `is not None`, not truthiness, so t=0 works
121
+ keydown_to_keyup_durations.append(timestamp - start)
104
122
  avg_keydown_to_keyup_duration = (
105
123
  np.mean(keydown_to_keyup_durations)
106
124
  if keydown_to_keyup_durations
@@ -4,7 +4,8 @@ import numpy as np
4
4
  from pywib.utils import (_path, validate_dataframe, compute_space_time_diff,
5
5
  extract_traces_by_session,
6
6
  auc_ratio_traces)
7
- from pywib.constants import ColumnNames
7
+ from pywib.constants import ColumnNames, EventTypes
8
+ from pywib.utils.cleanup import remove_init_tracking_events, remove_unpositioned_events
8
9
  from pywib.utils.movement import (auc_df, auc_traces, flips, _apply_metric_to_traces,
9
10
  _compute_angles, angular_acceleration_df, angular_velocity_df)
10
11
  from pywib.utils.utils import deprecated
@@ -341,19 +342,30 @@ def angular_acceleration(df: pd.DataFrame = None, traces: dict[str, list[pd.Data
341
342
  return traces
342
343
 
343
344
 
344
- def direction_changes(df: pd.DataFrame = None, traces: dict[str, list[pd.DataFrame]] = None, per_traces: bool = False) -> pd.DataFrame | dict:
345
+ def direction_changes(df: pd.DataFrame = None, traces: dict[str, list[pd.DataFrame]] = None, per_traces: bool = False, per_user: bool = False, threshold : int = (np.pi / 4)) -> pd.DataFrame | dict[str, list[int]]:
345
346
  """
346
347
  Calculate the number of direction changes in the given DataFrame.
347
348
 
348
349
  Parameters:
349
350
  df (pd.DataFrame): DataFrame containing 'x' and 'y' columns.
350
351
  traces (dict): A dictionary with keys as (sessionId) and values as lists of DataFrames. If None, traces will be computed from df.
351
- per_traces (bool): Whether to return the result for each trace separately. If False, returns the total count as an integer.
352
+ per_traces (bool?): Defaults to False. Whether to return the result for each trace separately. If False, returns the total count as an integer.
353
+ per_user (bool?): Defaults to False. If True, then it computes the number of direction changes for each user. The main difference with per traces is that this option does not segment the DataFrame, computing the total number of changes through the DataFrame.
354
+
355
+ Returns:
356
+ int (int): An integer if `per_traces` and `per_user` is False.
357
+ dict (dict[str,list[int]]): A dictionary if `per_traces` is True **or** if `per_user` is True, with sessionIds as keys and the number of direction changes on each trace as an integer.
358
+
352
359
  """
353
360
 
354
361
  validate_any_not_none(df, traces)
355
362
 
356
- if not per_traces and df is not None:
363
+ if df is not None:
364
+ df = remove_init_tracking_events(df).copy()
365
+ if (not per_traces) or per_user:
366
+ df = remove_unpositioned_events(df).copy()
367
+
368
+ if not per_traces and not per_user and df is not None:
357
369
  df = compute_space_time_diff(df)
358
370
  # Compute directly on the DataFrame (no trace extraction
359
371
  directions = np.arctan2(df[ColumnNames.DY], df[ColumnNames.DX])
@@ -365,23 +377,54 @@ def direction_changes(df: pd.DataFrame = None, traces: dict[str, list[pd.DataFra
365
377
  direction_changes = np.sum(np.abs(angle_diff) > np.pi / 4) # Consider a change if the angle changes more than 45 degrees
366
378
  return direction_changes
367
379
 
368
- if traces is None and per_traces:
380
+ if traces is None and (per_traces or per_user):
369
381
  validate_dataframe(df)
370
382
  traces = extract_traces_by_session(df)
371
383
 
372
384
  direction_changes_per_trace = {}
373
385
  for session_id, session_traces in traces.items():
386
+ direction_changes_per_trace[session_id] = []
374
387
  for trace in session_traces:
375
388
  trace = compute_space_time_diff(trace)
376
- directions = np.arctan2(trace[ColumnNames.DY], trace[ColumnNames.DX])
377
- angle_diff = np.diff(directions)
378
- angle_diff = np.arctan2(np.sin(angle_diff), np.cos(angle_diff))
379
- direction_changes = np.sum(np.abs(angle_diff) > np.pi / 4) # Consider a change if the angle changes more than 45 degrees
380
- direction_changes_per_trace[session_id] = direction_changes
389
+ dx = trace[ColumnNames.DX].to_numpy()
390
+ dy = trace[ColumnNames.DY].to_numpy()
391
+ direction_changes = count_direction_changes(dx, dy, threshold) # Consider a change if the angle changes more than the threshold (pi/4)
392
+ direction_changes_per_trace[session_id].append(direction_changes)
381
393
 
382
394
  return direction_changes_per_trace
383
395
 
384
- def x_flips(df: pd.DataFrame = None, traces: dict[str, list[pd.DataFrame]] = None, threshold: float = 0.1, per_traces: bool = False) -> int | dict:
396
+ def count_direction_changes(dx: np.ndarray, dy: np.ndarray, threshold=np.pi / 4):
397
+ """
398
+ Helper method that counts the number of direction changes given the computed dx and dy arrays.
399
+
400
+ Parameters:
401
+ dx (np.ndarray): Horizontal displacement values.
402
+ dy (np.ndarray): Vertical displacement values.
403
+ threshold (float, optional): Minimum absolute angle change, in radians,
404
+ required to count as a direction change. Defaults to pi / 4.
405
+
406
+ Returns:
407
+ int: Number of direction changes.
408
+ """
409
+ directions = np.arctan2(dy, dx)
410
+
411
+ # Remove zero-length displacement vectors
412
+ valid = (dx != 0) | (dy != 0)
413
+ directions = directions[valid]
414
+
415
+ if len(directions) < 2:
416
+ return 0
417
+
418
+ angle_diff = np.diff(directions)
419
+
420
+ angle_diff = np.arctan2(
421
+ np.sin(angle_diff),
422
+ np.cos(angle_diff)
423
+ )
424
+
425
+ return np.sum(np.abs(angle_diff) > threshold)
426
+
427
+ def x_flips(df: pd.DataFrame = None, traces: dict[str, list[pd.DataFrame]] = None, threshold: float = 0.1, per_traces: bool = False, per_user: bool = False) -> int | dict[str, list[int]]:
385
428
  """
386
429
  Calculate the number of x-direction flips in the given DataFrame.
387
430
 
@@ -393,13 +436,21 @@ def x_flips(df: pd.DataFrame = None, traces: dict[str, list[pd.DataFrame]] = Non
393
436
  df (pd.DataFrame): DataFrame containing 'x' and 'y' columns.
394
437
  traces (dict): A dictionary with keys as (sessionId) and values as lists of DataFrames. If None, traces will be computed from df.
395
438
  threshold (float): The threshold for considering a flip.
396
- per_traces (bool): Whether to return the result for each trace separately. If False, returns the total count as an integer.
439
+ per_traces (bool?): Defaults to False. Whether to return the result for each trace separately. If False, returns the total count as an integer.
440
+ per_user (bool?): Defaults to False. If True, then it computes the number of direction changes for each user. The main difference with per traces is that this option does not segment the DataFrame, computing the total number of changes through the DataFrame.
441
+
397
442
  Returns:
398
- int | dict: The number of x-direction flips or a dictionary with the count for each session.
443
+ int: The number of x-direction flips or a dictionary with the count for each session if `per_traces` and `per_user` are False.
444
+ dict (dict[str,list[int]]): A dictionary if `per_traces` is True **or** if `per_user` is True, with sessionIds as keys and the number of direction changes on each trace as an integer.
399
445
  """
400
446
  validate_any_not_none(df, traces)
401
447
 
402
- if not per_traces:
448
+ if df is not None:
449
+ df = remove_init_tracking_events(df).copy()
450
+ if (not per_traces) or per_user:
451
+ df = remove_unpositioned_events(df).copy()
452
+
453
+ if not per_traces and not per_user:
403
454
  validate_dataframe(df)
404
455
  if (ColumnNames.DX not in df.columns):
405
456
  df = compute_space_time_diff(df)
@@ -419,7 +470,7 @@ def x_flips(df: pd.DataFrame = None, traces: dict[str, list[pd.DataFrame]] = Non
419
470
 
420
471
  return flips_per_session
421
472
 
422
- def y_flips(df: pd.DataFrame = None, traces: dict[str, list[pd.DataFrame]] = None, threshold: float = 0.1, per_traces: bool = False) -> int | dict:
473
+ def y_flips(df: pd.DataFrame = None, traces: dict[str, list[pd.DataFrame]] = None, threshold: float = 0.1, per_traces: bool = False, per_user: bool = False) -> int | dict:
423
474
  """
424
475
  Calculate the number of y-direction flips in the given DataFrame.
425
476
 
@@ -431,13 +482,20 @@ def y_flips(df: pd.DataFrame = None, traces: dict[str, list[pd.DataFrame]] = Non
431
482
  df (pd.DataFrame): DataFrame containing 'x' and 'y' columns.
432
483
  traces (dict): A dictionary with keys as (sessionId) and values as lists of DataFrames. If None, traces will be computed from df.
433
484
  threshold (float): The threshold for considering a flip.
434
- per_traces (bool): Whether to return the result for each trace separately. If False, returns the total count as an integer.
485
+ per_traces (bool?): Defaults to False. Whether to return the result for each trace separately. If False, returns the total count as an integer.
486
+ per_user (bool?): Defaults to False. If True, then it computes the number of direction changes for each user. The main difference with per traces is that this option does not segment the DataFrame, computing the total number of changes through the DataFrame.
487
+
435
488
  Returns:
436
489
  int | dict: The number of y-direction flips or a dictionary with the count for each session.
437
490
  """
438
491
  validate_any_not_none(df, traces)
492
+
493
+ if df is not None:
494
+ df = remove_init_tracking_events(df).copy()
495
+ if (not per_traces) or per_user:
496
+ df = remove_unpositioned_events(df).copy()
439
497
 
440
- if not per_traces:
498
+ if not per_traces and not per_user:
441
499
  validate_dataframe(df)
442
500
  if (ColumnNames.DY not in df.columns):
443
501
  df = compute_space_time_diff(df)
@@ -0,0 +1,10 @@
1
+ import pandas as pd
2
+ from pywib.constants import EventTypes, ColumnNames
3
+
4
+
5
+ def remove_init_tracking_events(df: pd.DataFrame):
6
+ return df[(df[ColumnNames.EVENT_TYPE] != EventTypes.EVENT_INIT_TRACKING) & (df[ColumnNames.EVENT_TYPE] != EventTypes.EVENT_TRACKING_END)]
7
+
8
+
9
+ def remove_unpositioned_events(df: pd.DataFrame):
10
+ return df[(df[ColumnNames.X] != -1) & (df[ColumnNames.Y] != -1)]
@@ -24,20 +24,26 @@ def _typing_durations_per_key(df: pd.DataFrame) -> list[float]:
24
24
  Returns:
25
25
  list[float]: The times in ms of the typing trace
26
26
  """
27
- durations = []
28
- current_key = -1
29
- time_start = 0.0
30
- for _, event in df.iterrows():
31
- if(current_key != event[ColumnNames.KEY_VALUE]):
32
- current_key = event[ColumnNames.KEY_VALUE]
33
- time_start = event[ColumnNames.TIME_STAMP]
34
- else:
35
- if(event[ColumnNames.EVENT_TYPE] == EventTypes.EVENT_KEY_UP):
36
- durations.append(event[ColumnNames.TIME_STAMP] - time_start)
27
+ durations: list[float] = []
28
+ key_down_times: dict[object, float] = {}
29
+
30
+ event_types = df[ColumnNames.EVENT_TYPE].to_numpy()
31
+ keys = df[ColumnNames.KEY_VALUE].to_numpy()
32
+ timestamps = df[ColumnNames.TIME_STAMP].to_numpy()
33
+
34
+ for event_type, key, timestamp in zip(event_types, keys, timestamps):
35
+ if event_type == EventTypes.EVENT_KEY_DOWN:
36
+ key_down_times[key] = timestamp
37
+ elif event_type == EventTypes.EVENT_KEY_UP:
38
+ start_time = key_down_times.get(key)
39
+ if start_time is not None:
40
+ durations.append(timestamp - start_time)
41
+ del key_down_times[key]
42
+
37
43
  return durations
38
44
 
39
45
 
40
- def typing_durations_df(df: pd.DataFrame = None, validate: bool = True, single:bool=False) -> list:
46
+ def typing_durations_df(df: pd.DataFrame = None, validate: bool = True, single:bool=False) -> list | float:
41
47
  """
42
48
  Calculate the durations of individual keystrokes from a DataFrame.
43
49
 
@@ -46,21 +52,26 @@ def typing_durations_df(df: pd.DataFrame = None, validate: bool = True, single:b
46
52
  validate (bool): Whether to validate the input DataFrame. Default is True.
47
53
  single (bool): Wether to compute per single key press or by full keystroke interaction.
48
54
  Returns:
49
- list: List of keystroke durations in milliseconds.
55
+ list: List of keystroke durations in milliseconds if single is True.
56
+ float: Total duration of the typing session in milliseconds if single is False.
50
57
  """
51
58
  if validate:
52
59
  validate_dataframe_keyboard(df)
53
60
  durations = []
61
+ total_duration = 0.0
54
62
  traces = extract_keystroke_traces(df)
55
63
 
56
64
  for trace in traces:
57
65
  if single:
58
- durations.append(_typing_durations_per_key(trace))
66
+ durations.extend(_typing_durations_per_key(trace))
59
67
  else:
60
- durations += _typing_durations_full(trace)
68
+ total_duration += _typing_durations_full(trace)
69
+
70
+ if not single:
71
+ return total_duration
61
72
  return durations
62
73
 
63
- def typing_durations_traces(traces: dict[str, list[pd.DataFrame]], validate: bool = True, single: bool = False) -> dict[str, list[pd.DataFrame]]:
74
+ def typing_durations_traces(traces: dict[str, list[pd.DataFrame]], validate: bool = True, single: bool = False) -> dict[str, list[float]] | dict[str, float]:
64
75
  """
65
76
  Calculate the durations of individual keystrokes from pre-extracted keystroke traces.
66
77
 
@@ -69,18 +80,23 @@ def typing_durations_traces(traces: dict[str, list[pd.DataFrame]], validate: boo
69
80
  validate (bool): Whether to validate the input DataFrames. Default is True.
70
81
  single (bool): Wether to compute per single key press or by full keystroke interaction.
71
82
  Returns:
72
- dict (dict[str, list[number]]): A dictionary with session IDs as keys and lists of keystroke durations per trace as values.
83
+ dict (dict[str, list[float]]): A dictionary with session IDs as keys and lists of keystroke durations per trace as values if single is true.
84
+ dict (dict[str, float]): A dictionary with session IDs as keys and total durations per trace as values if single is false.
73
85
  """
74
86
  durations_per_session = {}
75
87
  for session_id, keystroke_traces in traces.items():
76
88
  durations = []
89
+ total_duration = 0.0
77
90
  for trace in keystroke_traces:
78
91
  validate_dataframe_keyboard(trace)
79
92
  if single:
80
- durations.append(_typing_durations_full(trace))
93
+ durations.extend(_typing_durations_per_key(trace))
81
94
  else:
82
- durations += _typing_durations_full(trace)
83
- durations_per_session[session_id] = durations
95
+ total_duration += _typing_durations_full(trace)
96
+ if single:
97
+ durations_per_session[session_id] = durations
98
+ else:
99
+ durations_per_session[session_id] = total_duration
84
100
  return durations_per_session
85
101
 
86
102
  def typing_speed_df(df: pd.DataFrame = None, validate: bool = True) -> float:
@@ -1,22 +1,23 @@
1
1
  from typing import List
2
2
 
3
3
  import pandas as pd
4
+
4
5
  from ..constants import EventTypes, ColumnNames
5
6
  from ..utils.validation import validate_dataframe, validate_dataframe_keyboard
6
7
 
7
- def extract_trace(dt: pd.DataFrame) -> list:
8
+ def extract_trace(df: pd.DataFrame) -> list:
8
9
  """
9
10
  Extracts trace from the DataFrame.
10
11
  Each trace is considered as a sequence of consecutive ON_MOUSE_MOVE events
11
12
  between two non-move events.
12
13
  Returns a list of DataFrames, each corresponding to a trace.
13
14
  """
14
- validate_dataframe(dt)
15
- dt = dt.sort_values(by=ColumnNames.TIME_STAMP).reset_index(drop=True)
16
- return _extract_move_trace(dt)
15
+ validate_dataframe(df)
16
+ df = df.sort_values(by=ColumnNames.TIME_STAMP).reset_index(drop=True)
17
+ return _extract_move_trace(df)
17
18
 
18
19
 
19
- def extract_traces_by_session(dt: pd.DataFrame) -> dict:
20
+ def extract_traces_by_session(df: pd.DataFrame) -> dict:
20
21
  """
21
22
  Extracts traces from the DataFrame, grouped by (sessionId, sceneId).
22
23
  Each trace is considered as a sequence of consecutive ON_MOUSE_MOVE events
@@ -26,10 +27,10 @@ def extract_traces_by_session(dt: pd.DataFrame) -> dict:
26
27
  Returns:
27
28
  dict: a dictionary with keys as (sessionId) and values as lists of DataFrames.
28
29
  """
29
- validate_dataframe(dt)
30
- dt = dt.sort_values(by=ColumnNames.TIME_STAMP).reset_index(drop=True)
30
+ validate_dataframe(df)
31
+ df = df.sort_values(by=ColumnNames.TIME_STAMP).reset_index(drop=True)
31
32
  traces_by_session = {}
32
- for session_id, group in dt.groupby(ColumnNames.SESSION_ID):
33
+ for session_id, group in df.groupby(ColumnNames.SESSION_ID):
33
34
  traces_by_session[session_id] = _extract_move_trace(group)
34
35
  return traces_by_session
35
36
 
@@ -99,10 +100,10 @@ def extract_mouse_click_traces_by_session(dt: pd.DataFrame) -> dict:
99
100
  click_traces_by_session[session_id] = click_traces
100
101
  return click_traces_by_session
101
102
 
102
- def extract_mouse_click_traces_by_session_with_intial_pause(dt: pd.DataFrame, pause_threshold: float = 200) -> dict:
103
- dt = dt.sort_values(by=ColumnNames.TIME_STAMP).reset_index(drop=True)
103
+ def extract_mouse_click_traces_by_session_with_intial_pause(df: pd.DataFrame, pause_threshold: float = 200) -> dict:
104
+ df = df.sort_values(by=ColumnNames.TIME_STAMP).reset_index(drop=True)
104
105
  click_traces_by_session = {}
105
- for session_id, group in dt.groupby(ColumnNames.SESSION_ID):
106
+ for session_id, group in df.groupby(ColumnNames.SESSION_ID):
106
107
  is_move = (group[ColumnNames.EVENT_TYPE] == EventTypes.EVENT_ON_MOUSE_MOVE) | (group[ColumnNames.EVENT_TYPE] == EventTypes.EVENT_ON_POINTER_MOVE)
107
108
  group_id = (~is_move).cumsum()
108
109
  click_traces = []
@@ -0,0 +1,17 @@
1
+ eventType,timeStamp,x,y,keyValue,keyCode,sessionId
2
+ 13,0,-1,-1,a,-1,K
3
+ 15,50,-1,-1,a,-1,K
4
+ 13,200,-1,-1,b,-1,K
5
+ 15,260,-1,-1,b,-1,K
6
+ 13,0,-1,-1,a,-1,H
7
+ 13,30,-1,-1,a,-1,H
8
+ 13,60,-1,-1,a,-1,H
9
+ 15,100,-1,-1,a,-1,H
10
+ 13,200,-1,-1,b,-1,H
11
+ 15,250,-1,-1,b,-1,H
12
+ 13,300,-1,-1,a,-1,H
13
+ 15,350,-1,-1,a,-1,H
14
+ 13,400,-1,-1,a,-1,H
15
+ 13,430,-1,-1,a,-1,H
16
+ 13,460,-1,-1,a,-1,H
17
+ 15,500,-1,-1,a,-1,H
@@ -7,6 +7,7 @@ eventType,timeStamp,x,y,keyValue,keyCode,sessionId
7
7
  0,1750792659600,100,1000,-1,-1,SESSION_A
8
8
  0,1750792659700,0,1000,-1,-1,SESSION_A
9
9
  0,1750792659800,100,1000,-1,-1,SESSION_A
10
+ 1,1750792659850,-1,-1,-1,-1,SESSION_A
10
11
  0,1750792659900,0,1000,-1,-1,SESSION_A
11
12
  0,1750792660000,100,1000,-1,-1,SESSION_A
12
13
  0,1750792660100,0,1000,-1,-1,SESSION_A
@@ -16,3 +17,4 @@ eventType,timeStamp,x,y,keyValue,keyCode,sessionId
16
17
  0,1750792660500,100,1000,-1,-1,SESSION_A
17
18
  0,1750792660600,100,0,-1,-1,SESSION_A
18
19
  0,1750792660700,100,1000,-1,-1,SESSION_A
20
+ 200,1750792660710,-1,-1,-1,-1,SESSION_A
@@ -2,6 +2,7 @@ import unittest
2
2
  import numpy as np
3
3
  import sys
4
4
  import os
5
+ import pandas as pd
5
6
  import pytest
6
7
  sys.path.insert(0, os.path.dirname(__file__))
7
8
  from utils import process_csv, import_pyModule
@@ -15,8 +16,10 @@ DEBUG = True
15
16
  class TestData:
16
17
  if(DEBUG):
17
18
  dataFile = 'test/test_data/test_mouse_keyboard.csv'
19
+ dataFile2 = 'test/test_data/test_keyboard_simple.csv'
18
20
  else:
19
21
  dataFile = 'pywib/test/test_data/test_mouse_keyboard.csv'
22
+ dataFile2 = 'pywib/test/test_data/test_keyboard_simple.csv'
20
23
 
21
24
  results = {
22
25
  "SESSION_A":{
@@ -35,7 +38,7 @@ class TestData:
35
38
  "ALL":{
36
39
  ColumnNames.TOTAL_CHARS: 9,
37
40
  ColumnNames.BACKSPACE_USAGE:3,
38
- "typing_durations":[float(1750792681050 - 1750792680900), float((1750792685500 - 1750792685400)), float((1750792680980 - 1750792680920)), float((1750792686150 - 1750792685600))]
41
+ "typing_durations":[float(1750792681050 - 1750792680900), float((1750792686000 - 1750792685400)), float((1750792686150 - 1750792686050))]
39
42
  }
40
43
  }
41
44
 
@@ -84,6 +87,7 @@ class TestKeyboard(unittest.TestCase):
84
87
  """Set up test data"""
85
88
  # Create sample test data instead of relying on external CSV
86
89
  self.test_data = process_csv(TestData.dataFile)
90
+ self.test_data_simple = process_csv(TestData.dataFile2)
87
91
 
88
92
  def test_typing_speed(self):
89
93
  """Test typing_speed function"""
@@ -124,20 +128,14 @@ class TestKeyboard(unittest.TestCase):
124
128
 
125
129
  def test_typing_durations(self):
126
130
  """Test typing durations function"""
127
- t_durations = typing_durations(self.test_data, per_traces=True)
128
- for session_id, durations in t_durations.items():
129
- i = 0
130
- for duration in durations:
131
- self.assertAlmostEqual(duration, TestData.results[session_id]["typing_durations"][i])
132
- i+=1
131
+ t_durations = typing_durations(self.test_data, per_traces=True, single=False)
132
+ for session_id, duration in t_durations.items():
133
+ self.assertAlmostEqual(duration, sum(TestData.results[session_id]["typing_durations"]))
133
134
 
134
135
  def test_typing_durations_df(self):
135
136
  """Test typing durations function for a single DataFrame"""
136
- t_durations = typing_durations(self.test_data, per_traces=False)
137
- i = 0
138
- for durations in t_durations:
139
- self.assertAlmostEqual(durations, TestData.results["ALL"]["typing_durations"][i])
140
- i+=1
137
+ t_durations = typing_durations(self.test_data, per_traces=False, single=False)
138
+ self.assertAlmostEqual(t_durations, sum(TestData.results["ALL"]["typing_durations"]))
141
139
 
142
140
  def test_words_per_minute(self):
143
141
  """Test WPM across all sessions."""
@@ -159,7 +157,29 @@ class TestKeyboard(unittest.TestCase):
159
157
  expected = [speed / 5 for speed in TestData.trace_cpm(session_id)]
160
158
  for computed, expected_value in zip(trace_wpm, expected):
161
159
  self.assertAlmostEqual(computed, expected_value, places=2)
162
-
160
+
161
+ def test_typing_durations_non_empty(self):
162
+ df = self.test_data_simple.copy()
163
+ self.assertTrue(len(typing_durations(df)) > 0)
164
+
165
+ def test_typing_durations_single(self):
166
+ df = self.test_data_simple.copy()
167
+ durations = typing_durations(df, per_traces=True, single=True)
168
+ self.assertEqual(len(durations["K"]), 2)
169
+ self.assertEqual(durations["K"][0], [50])
170
+ self.assertEqual(durations["K"][1], [60])
171
+
172
+ def test_typing_durations_single(self):
173
+ df = self.test_data_simple.copy()
174
+ durations = typing_durations(df[df["sessionId"] == "K"], per_traces=False, single=True)
175
+ self.assertEqual(durations[0], [50])
176
+ self.assertEqual(durations[1], [60])
177
+
178
+ def test_avg_keydown_to_keyup_duration(self):
179
+ df = self.test_data_simple.copy()
180
+ durations = typing_speed_metrics(df)
181
+ self.assertAlmostEqual(float(300.0/4), durations["H"]["avg_keydown_to_keyup_duration"])
182
+
163
183
 
164
184
  if __name__ == '__main__':
165
185
  unittest.main()
@@ -9,7 +9,7 @@ sys.path.insert(0, os.path.dirname(__file__))
9
9
  from utils import assert_between_zero_inf, process_csv, import_pyModule, build_trajectory_df
10
10
 
11
11
  import_pyModule()
12
- from pywib import (ColumnNames, extract_traces_by_session, auc, x_flips, y_flips, deviations, angle,
12
+ from pywib import (ColumnNames, extract_traces_by_session, auc, x_flips, y_flips, direction_changes, deviations, angle,
13
13
  angular_velocity, angular_acceleration, path, total_distance, visualize_trace)
14
14
  from pywib.utils.movement import trajectory as traj_mod
15
15
 
@@ -137,13 +137,13 @@ class TestTrajectory(unittest.TestCase):
137
137
  self.assertGreaterEqual(flips, 0)
138
138
  self.assertEqual(flips, 6)
139
139
 
140
- def test_x_flips_per_trace(self):
141
- flips = x_flips(self.test_data_flips_single.copy(), per_traces=True)
140
+ def test_x_flips_per_user(self):
141
+ flips = x_flips(self.test_data_flips_single.copy(), per_traces=False, per_user=True)
142
142
  self.assertGreaterEqual(flips.get("SESSION_A"), 0)
143
143
  self.assertEqual(flips.get("SESSION_A"), 8)
144
144
 
145
- def test_y_flips_per_trace(self):
146
- flips = y_flips(self.test_data_flips_single.copy(), per_traces=True)
145
+ def test_y_flips_per_user(self):
146
+ flips = y_flips(self.test_data_flips_single.copy(), per_traces=False, per_user=True)
147
147
  self.assertGreaterEqual(flips.get("SESSION_A"), 0)
148
148
  self.assertEqual(flips.get("SESSION_A"), 6)
149
149
 
@@ -163,6 +163,22 @@ class TestTrajectory(unittest.TestCase):
163
163
  self.assertGreaterEqual(flips.get("SESSION_B"), 0)
164
164
  self.assertEqual(flips.get("SESSION_B"), 6)
165
165
 
166
+
167
+ def test_direction_changes_per_traces(self):
168
+ changes = direction_changes(self.test_data_flips_single.copy(), None, True)
169
+ for _, values in changes.items():
170
+ self.assertEqual(sum(values), 12)
171
+
172
+ def test_direction_changes_per_user(self):
173
+ changes = direction_changes(self.test_data_flips_single.copy(), None, True, True)
174
+ for _, values in changes.items():
175
+ self.assertEqual(sum(values), 14)
176
+
177
+
178
+ def test_direction_changes(self):
179
+ changes = direction_changes(self.test_data_flips_single.copy(), None, False)
180
+ self.assertEqual(changes, 14)
181
+
166
182
  def test_deviations_greaterThanZero(self):
167
183
  """
168
184
  Deviation values (aad, mad_mean/max/min) must always be positive.
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
@@ -33,6 +33,7 @@ eventType,timeStamp,x,y,keyValue,keyCode,sessionId
33
33
  13,1750792685400,-1,-1,B,KeyB,SESSION_A
34
34
  14,1750792685450,-1,-1,B,KeyB,SESSION_A
35
35
  15,1750792685500,-1,-1,B,KeyB,SESSION_A
36
+ 200,1750792686000,-1,-1,-1,-1,SESSION_A
36
37
  13,1750792685600,-1,-1,C,KeyC,SESSION_B
37
38
  14,1750792685650,-1,-1,C,KeyC,SESSION_B
38
39
  15,1750792685700,-1,-1,C,KeyC,SESSION_B
@@ -45,5 +46,4 @@ eventType,timeStamp,x,y,keyValue,keyCode,sessionId
45
46
  13,1750792686050,-1,-1,Backspace,Backspace,SESSION_B
46
47
  14,1750792686100,-1,-1,Backspace,Backspace,SESSION_B
47
48
  15,1750792686150,-1,-1,Backspace,Backspace,SESSION_B
48
- 200,1750792686000,-1,-1,-1,-1,SESSION_A
49
49
  200,1750792686200,-1,-1,-1,-1,SESSION_B
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes