misleep 0.3.0__py3-none-any.whl

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 (94) hide show
  1. misleep/__init__.py +111 -0
  2. misleep/__main__.py +16 -0
  3. misleep/analysis/__init__.py +23 -0
  4. misleep/analysis/auto_stage.py +158 -0
  5. misleep/analysis/detection.py +198 -0
  6. misleep/analysis/features.py +131 -0
  7. misleep/analysis/models/P30_EEG_F_lightgbm.pkl +0 -0
  8. misleep/analysis/models/P30_EEG_P_lightgbm.pkl +0 -0
  9. misleep/analysis/models/__init__.py +0 -0
  10. misleep/analysis/models/ado_EEG_F_lightgbm.pkl +0 -0
  11. misleep/analysis/models/ado_EEG_P_lightgbm.pkl +0 -0
  12. misleep/analysis/models/adult_EEG_F_lightgbm.pkl +0 -0
  13. misleep/analysis/models/adult_EEG_P_lightgbm.pkl +0 -0
  14. misleep/analysis/transformer/__init__.py +46 -0
  15. misleep/analysis/transformer/checkpoints/CausalTransformer_best.pt +0 -0
  16. misleep/analysis/transformer/checkpoints/__init__.py +0 -0
  17. misleep/analysis/transformer/configs.py +52 -0
  18. misleep/analysis/transformer/data.py +362 -0
  19. misleep/analysis/transformer/inference.py +328 -0
  20. misleep/analysis/transformer/models.py +220 -0
  21. misleep/analysis/transformer/preprocessing.py +105 -0
  22. misleep/config/__init__.py +105 -0
  23. misleep/config/default_config.ini +38 -0
  24. misleep/data/__init__.py +13 -0
  25. misleep/data/annotation.py +114 -0
  26. misleep/data/midata.py +387 -0
  27. misleep/gui/__init__.py +23 -0
  28. misleep/gui/app.py +183 -0
  29. misleep/gui/config_dialog.py +429 -0
  30. misleep/gui/dialogs.py +1107 -0
  31. misleep/gui/event_filters.py +26 -0
  32. misleep/gui/main_window.py +2699 -0
  33. misleep/gui/qt_utils.py +277 -0
  34. misleep/gui/resources/__init__.py +9 -0
  35. misleep/gui/resources/entire_logo.png +0 -0
  36. misleep/gui/resources/logo.png +0 -0
  37. misleep/gui/resources/misleep.ico +0 -0
  38. misleep/gui/resources/misleep.qrc +7 -0
  39. misleep/gui/resources/misleep_rc.py +1324 -0
  40. misleep/gui/spec_window.py +187 -0
  41. misleep/gui/style.py +994 -0
  42. misleep/gui/uis/SWA_detect_dialog.ui +181 -0
  43. misleep/gui/uis/SWA_detect_dialog_ui.py +176 -0
  44. misleep/gui/uis/__init__.py +6 -0
  45. misleep/gui/uis/about.ui +88 -0
  46. misleep/gui/uis/about_ui.py +80 -0
  47. misleep/gui/uis/auto_stage_causalTransformer_dialog.ui +77 -0
  48. misleep/gui/uis/auto_stage_causalTransformer_dialog_ui.py +90 -0
  49. misleep/gui/uis/auto_stage_lightGBM_dialog.ui +124 -0
  50. misleep/gui/uis/auto_stage_lightGBM_dialog_ui.py +124 -0
  51. misleep/gui/uis/horizontal_line_dialog.ui +166 -0
  52. misleep/gui/uis/horizontal_line_dialog_ui.py +157 -0
  53. misleep/gui/uis/label_dialog.ui +65 -0
  54. misleep/gui/uis/label_dialog_ui.py +72 -0
  55. misleep/gui/uis/main_window.ui +871 -0
  56. misleep/gui/uis/main_window_ui.py +616 -0
  57. misleep/gui/uis/save_data_dialog.ui +95 -0
  58. misleep/gui/uis/save_data_dialog_ui.py +98 -0
  59. misleep/gui/uis/spec_window.ui +109 -0
  60. misleep/gui/uis/spec_window_ui.py +103 -0
  61. misleep/gui/uis/spindle_detect_dialog.ui +202 -0
  62. misleep/gui/uis/spindle_detect_dialog_ui.py +194 -0
  63. misleep/gui/uis/state_spectral_dialog.ui +240 -0
  64. misleep/gui/uis/state_spectral_dialog_ui.py +204 -0
  65. misleep/gui/uis/transfer_result_dialog.ui +104 -0
  66. misleep/gui/uis/transfer_result_dialog_ui.py +94 -0
  67. misleep/gui/workers.py +69 -0
  68. misleep/io/__init__.py +68 -0
  69. misleep/io/annotation.py +367 -0
  70. misleep/io/array.py +209 -0
  71. misleep/io/base.py +174 -0
  72. misleep/io/edf.py +109 -0
  73. misleep/io/mat.py +189 -0
  74. misleep/logger.py +79 -0
  75. misleep/preprocessing/__init__.py +23 -0
  76. misleep/preprocessing/artifacts.py +76 -0
  77. misleep/preprocessing/filtering.py +94 -0
  78. misleep/preprocessing/segment.py +59 -0
  79. misleep/preprocessing/spectral.py +169 -0
  80. misleep/utils/__init__.py +45 -0
  81. misleep/utils/annotation.py +130 -0
  82. misleep/utils/entropy.py +135 -0
  83. misleep/utils/misc.py +69 -0
  84. misleep/utils/time_utils.py +61 -0
  85. misleep/viz/__init__.py +12 -0
  86. misleep/viz/hypnogram.py +48 -0
  87. misleep/viz/signals.py +51 -0
  88. misleep/viz/spectral.py +98 -0
  89. misleep-0.3.0.dist-info/METADATA +249 -0
  90. misleep-0.3.0.dist-info/RECORD +94 -0
  91. misleep-0.3.0.dist-info/WHEEL +5 -0
  92. misleep-0.3.0.dist-info/entry_points.txt +15 -0
  93. misleep-0.3.0.dist-info/licenses/LICENSE +29 -0
  94. misleep-0.3.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,61 @@
1
+ # -*- coding: UTF-8 -*-
2
+ """Time helpers: add seconds to an acquisition time and format it."""
3
+
4
+ import datetime
5
+
6
+
7
+ def transfer_time(date_time, seconds, date_time_format="%d:%H:%M:%S", ms=False):
8
+ """Add ``seconds`` to a datetime and format it.
9
+
10
+ Parameters
11
+ ----------
12
+ date_time : datetime.datetime
13
+ The starting datetime (typically the recording acquisition time).
14
+ seconds : int or float
15
+ Seconds to add.
16
+ date_time_format : str
17
+ Output strftime format. Defaults to ``'%d:%H:%M:%S'``.
18
+ ms : bool
19
+ Whether to keep the millisecond part in the output.
20
+
21
+ Returns
22
+ -------
23
+ str
24
+ The formatted target time.
25
+
26
+ Examples
27
+ --------
28
+ >>> import datetime
29
+ >>> transfer_time(datetime.datetime(2024, 1, 30, 10, 50, 0), 40)
30
+ '30-10:50:40'
31
+ """
32
+ temp_time = date_time + datetime.timedelta(seconds=seconds)
33
+ if ms:
34
+ seconds_str = str(seconds)
35
+ ms_part = seconds_str.split(".")[1] if "." in seconds_str else "000"
36
+ return f"{temp_time.strftime(date_time_format)}.{ms_part}"
37
+ return temp_time.strftime(date_time_format)
38
+
39
+
40
+ def second2time(second, ac_time, ms=False):
41
+ """Format a number of seconds relative to the acquisition time.
42
+
43
+ Parameters
44
+ ----------
45
+ second : int or float
46
+ Seconds since acquisition.
47
+ ac_time : datetime.datetime
48
+ Acquisition time.
49
+ ms : bool
50
+ Whether to keep the millisecond part.
51
+
52
+ Returns
53
+ -------
54
+ str
55
+ Time formatted as ``DD:HH:MM:SS`` (with ``.mmm`` when ``ms=True``).
56
+ """
57
+ if ms:
58
+ seconds_str = str(second)
59
+ ms_part = seconds_str.split(".")[1] if "." in seconds_str else "000"
60
+ return (ac_time + datetime.timedelta(seconds=second)).strftime(f"%d:%H:%M:%S:{ms_part}")
61
+ return (ac_time + datetime.timedelta(seconds=second)).strftime("%d:%H:%M:%S")
@@ -0,0 +1,12 @@
1
+ # -*- coding: UTF-8 -*-
2
+ """Plotting module (matplotlib, GUI-independent).
3
+
4
+ These functions are used both by the GUI (embedded in Qt canvases) and by
5
+ scripts/Jupyter notebooks to preview signals, spectra and hypnograms.
6
+ """
7
+
8
+ from .signals import plot_signals
9
+ from .spectral import plot_spectrum, plot_spectrogram
10
+ from .hypnogram import plot_hypno
11
+
12
+ __all__ = ["plot_signals", "plot_spectrum", "plot_spectrogram", "plot_hypno"]
@@ -0,0 +1,48 @@
1
+ # -*- coding: UTF-8 -*-
2
+ """Visualization of hypnograms."""
3
+
4
+ import matplotlib.pyplot as plt
5
+
6
+ DEFAULT_STATE_MAP = {1: "NREM", 2: "REM", 3: "Wake", 4: "Init"}
7
+
8
+
9
+ def plot_hypno(sleep_state, state_map=None, time_range=[0, -1]):
10
+ """Draw a hypnogram from a per-second sleep state sequence.
11
+
12
+ Parameters
13
+ ----------
14
+ sleep_state : list
15
+ Per-second state codes (integers), interpreted through ``state_map``.
16
+ state_map : dict, optional
17
+ State code -> name mapping. Defaults to
18
+ ``{1: 'NREM', 2: 'REM', 3: 'Wake', 4: 'Init'}``.
19
+ time_range : list of two ints, optional
20
+ Time window to plot, ``[start, end]`` seconds. Default plots all.
21
+
22
+ Returns
23
+ -------
24
+ (fig, ax) : tuple
25
+ The matplotlib figure and axis.
26
+ """
27
+ if not isinstance(sleep_state, list):
28
+ raise TypeError(f"'sleep_state' should be a list, got {type(sleep_state)}")
29
+
30
+ sleep_state_ = sleep_state
31
+ if time_range != [0, -1]:
32
+ try:
33
+ sleep_state_ = sleep_state[time_range[0]:time_range[1]]
34
+ except Exception:
35
+ print("Invalid time range, plot as default")
36
+ sleep_state_ = sleep_state
37
+
38
+ if state_map is None:
39
+ state_map = DEFAULT_STATE_MAP
40
+
41
+ fig = plt.figure(figsize=(20, 3))
42
+ ax = fig.subplots(nrows=1, ncols=1)
43
+ ax.step(range(len(sleep_state_)), sleep_state_, where="mid", linewidth=1)
44
+ ax.set_ylim(0.5, max(state_map.keys()) + 0.5)
45
+ ax.set_xlim(0, len(sleep_state_) - 1)
46
+ ax.yaxis.set_ticks(list(state_map.keys()), list(state_map.values()))
47
+
48
+ return fig, ax
misleep/viz/signals.py ADDED
@@ -0,0 +1,51 @@
1
+ # -*- coding: UTF-8 -*-
2
+ """Visualization of raw signals."""
3
+
4
+ import math
5
+
6
+ import matplotlib.pyplot as plt
7
+
8
+
9
+ def plot_signals(signals, sf=None, ch_names=None):
10
+ """Plot one or several signal channels on a shared time axis.
11
+
12
+ Parameters
13
+ ----------
14
+ signals : list of ndarray
15
+ Signal data, one array per channel.
16
+ sf : list of float, optional
17
+ Sampling frequency of each channel.
18
+ ch_names : list of str, optional
19
+ Channel names. Defaults to ``None`` (all channels, generic labels).
20
+
21
+ Returns
22
+ -------
23
+ (fig, axs) : tuple
24
+ The matplotlib figure and axes.
25
+ """
26
+ duration = math.floor(len(signals[0]) / sf[0])
27
+ fig = plt.figure(figsize=(duration * 0.3 if duration < 60 else 18, 1 * len(signals)))
28
+ axs = fig.subplots(nrows=len(signals), ncols=1)
29
+ if len(signals) == 1:
30
+ axs = [axs]
31
+ fig.tight_layout(h_pad=0, w_pad=0)
32
+ fig.subplots_adjust(hspace=0)
33
+
34
+ for i in range(len(signals)):
35
+ axs[i].plot(signals[i], color="black", linewidth=0.5)
36
+ y_lim = max(signals[i][:int(60 * sf[i])])
37
+ axs[i].set_ylim(ymin=-y_lim, ymax=y_lim)
38
+ axs[i].set_xlim(xmin=0, xmax=len(signals[i]))
39
+ axs[i].xaxis.set_ticks([])
40
+ axs[i].yaxis.set_ticks([])
41
+ name = ch_names[i] if ch_names is not None else f"ch{i + 1}"
42
+ axs[i].set_ylabel(f"{name}\n{y_lim:.2e}")
43
+
44
+ axs[-1].set_xticks(
45
+ [int(each * sf[-1]) for each in range(0, duration, 5)],
46
+ range(0, duration, 5),
47
+ rotation=45,
48
+ )
49
+ axs[-1].set_xticks([int(each * sf[-1]) for each in range(0, duration)], minor=True)
50
+
51
+ return fig, axs
@@ -0,0 +1,98 @@
1
+ # -*- coding: UTF-8 -*-
2
+ """Visualization of spectral results (spectrum and spectrogram)."""
3
+
4
+ import matplotlib.pyplot as plt
5
+ import numpy as np
6
+
7
+
8
+ def spectrogram_color_limits(Sxx, percentile=99.7):
9
+ """Return a stable v2-style power color range for a spectrogram.
10
+
11
+ Spectrogram power is non-negative. Anchoring the lower limit at zero and
12
+ clipping only the brightest tail at ``percentile`` keeps the low-power
13
+ background dark and the EEG bands easy to distinguish.
14
+ """
15
+ if not isinstance(percentile, (int, float)) or not 0 < percentile <= 100:
16
+ raise ValueError("'percentile' must be greater than 0 and at most 100")
17
+ values = np.asarray(Sxx)
18
+ finite = values[np.isfinite(values)]
19
+ if finite.size == 0:
20
+ return 0.0, 1.0
21
+ vmax = float(np.percentile(finite, percentile))
22
+ if vmax <= 0:
23
+ vmax = float(np.max(finite)) if np.max(finite) > 0 else 1.0
24
+ return 0.0, vmax
25
+
26
+
27
+ def plot_spectrum(f, p):
28
+ """Plot a power spectrum.
29
+
30
+ Parameters
31
+ ----------
32
+ f : array_like
33
+ Frequency bins.
34
+ p : array_like
35
+ Power values.
36
+
37
+ Returns
38
+ -------
39
+ (fig, ax) : tuple
40
+ The matplotlib figure and axis.
41
+ """
42
+ fig = plt.figure(figsize=(10, 8))
43
+ ax = fig.subplots(nrows=1, ncols=1)
44
+ ax.plot(f, p)
45
+ y_lim = max(p) * 1.1
46
+ ax.set_ylim(0, y_lim)
47
+ ax.set_xlim(0, f[-1])
48
+ ax.set_xlabel("Frequency (Hz)")
49
+ ax.set_ylabel("Power spectral density (Power/Hz)")
50
+
51
+ return fig, ax
52
+
53
+
54
+ def plot_spectrogram(f, t, Sxx, percentile=100, band=None, color_bar=False):
55
+ """Plot a spectrogram.
56
+
57
+ Parameters
58
+ ----------
59
+ f : ndarray
60
+ Frequency bins.
61
+ t : ndarray
62
+ Time bins.
63
+ Sxx : ndarray
64
+ Spectrogram values.
65
+ percentile : float, optional
66
+ Color-scale upper percentile. Default is 100.
67
+ band : list, optional
68
+ Y-axis frequency limits, e.g. ``[0.5, 30]``.
69
+ color_bar : bool
70
+ Whether to draw a color bar.
71
+
72
+ Returns
73
+ -------
74
+ (fig, ax) : tuple
75
+ The matplotlib figure and axis.
76
+ """
77
+ if not isinstance(percentile, (int, float)):
78
+ raise TypeError(f"'percentile' should be a float between 0~100, got {percentile}")
79
+
80
+ cmap = plt.get_cmap("jet")
81
+ vmin, vmax = spectrogram_color_limits(Sxx, percentile)
82
+ fig = plt.figure(figsize=(15, 4))
83
+ ax = fig.subplots(nrows=1, ncols=1)
84
+ if band is not None:
85
+ ax.set_ylim(band[0], band[1])
86
+
87
+ if color_bar:
88
+ pcm = ax.pcolormesh(t, f, Sxx, cmap=cmap, vmin=vmin, vmax=vmax,
89
+ shading="auto")
90
+ fig.colorbar(pcm, ax=ax)
91
+ else:
92
+ ax.pcolormesh(t, f, Sxx, cmap=cmap, vmin=vmin, vmax=vmax,
93
+ shading="auto")
94
+ ax.set_facecolor(cmap(0.0))
95
+ ax.set_xlabel("Time (S)")
96
+ ax.set_ylabel("Frequency (HZ)")
97
+
98
+ return fig, ax
@@ -0,0 +1,249 @@
1
+ Metadata-Version: 2.4
2
+ Name: misleep
3
+ Version: 0.3.0
4
+ Summary: MiSleep: Mice sleep EEG/EMG visualization, scoring, and analysis
5
+ Author-email: Xueqiang Wang <swang9194@gmail.com>
6
+ Maintainer-email: Xueqiang Wang <swang9194@gmail.com>
7
+ License: BSD 3-Clause License
8
+
9
+ Copyright (c) 2023, Xueqiang Wang
10
+ All rights reserved.
11
+
12
+ Redistribution and use in source and binary forms, with or without
13
+ modification, are permitted provided that the following conditions are met:
14
+
15
+ 1. Redistributions of source code must retain the above copyright notice, this
16
+ list of conditions and the following disclaimer.
17
+
18
+ 2. Redistributions in binary form must reproduce the above copyright notice,
19
+ this list of conditions and the following disclaimer in the documentation
20
+ and/or other materials provided with the distribution.
21
+
22
+ 3. Neither the name of the copyright holder nor the names of its
23
+ contributors may be used to endorse or promote products derived from
24
+ this software without specific prior written permission.
25
+
26
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
27
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
29
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
30
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
32
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
33
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
34
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
35
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36
+ Project-URL: Homepage, https://github.com/BryanWang0702/MiSleep
37
+ Project-URL: Repository, https://github.com/BryanWang0702/MiSleep
38
+ Project-URL: Documentation, https://bryanwang.cn/MiSleep/
39
+ Project-URL: Bug Tracker, https://github.com/BryanWang0702/MiSleep/issues
40
+ Keywords: sleep,EEG,EMG,mice,neuroscience,scoring,hypnogram,spectrogram,signal-processing,pyside6
41
+ Classifier: Development Status :: 4 - Beta
42
+ Classifier: Intended Audience :: Science/Research
43
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
44
+ Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
45
+ Classifier: Programming Language :: Python :: 3
46
+ Classifier: Programming Language :: Python :: 3.9
47
+ Classifier: Programming Language :: Python :: 3.10
48
+ Classifier: Programming Language :: Python :: 3.11
49
+ Classifier: Programming Language :: Python :: 3.12
50
+ Classifier: Programming Language :: Python :: 3.13
51
+ Classifier: Programming Language :: Python :: 3.14
52
+ Classifier: License :: OSI Approved :: BSD License
53
+ Classifier: Operating System :: Microsoft :: Windows
54
+ Classifier: Operating System :: POSIX :: Linux
55
+ Classifier: Operating System :: MacOS
56
+ Requires-Python: >=3.9
57
+ Description-Content-Type: text/markdown
58
+ License-File: LICENSE
59
+ Requires-Dist: numpy>=1.20
60
+ Requires-Dist: scipy>=1.8
61
+ Requires-Dist: matplotlib>=3.5
62
+ Requires-Dist: pandas>=1.4
63
+ Requires-Dist: pyedflib>=0.1.30
64
+ Requires-Dist: mat73>=0.60
65
+ Requires-Dist: openpyxl>=3.0
66
+ Requires-Dist: joblib>=1.1
67
+ Requires-Dist: scikit-learn>=1.0
68
+ Provides-Extra: gui
69
+ Requires-Dist: PySide6>=6.6; extra == "gui"
70
+ Provides-Extra: analysis
71
+ Requires-Dist: lightgbm>=3.3; extra == "analysis"
72
+ Provides-Extra: transformer
73
+ Requires-Dist: torch>=2.0; extra == "transformer"
74
+ Provides-Extra: full
75
+ Requires-Dist: PySide6>=6.6; extra == "full"
76
+ Requires-Dist: lightgbm>=3.3; extra == "full"
77
+ Provides-Extra: dev
78
+ Requires-Dist: pytest>=7.0; extra == "dev"
79
+ Requires-Dist: pytest-cov; extra == "dev"
80
+ Dynamic: license-file
81
+
82
+ # MiSleep
83
+
84
+ **MiSleep** is an open-source Python toolbox for **mice sleep EEG/EMG**
85
+ visualization, scoring, and analysis.
86
+
87
+ ![logo](src/misleep/gui/resources/entire_logo.png)
88
+
89
+ The name *MiSleep* comes from "**Mi**ce **Sleep**" and sounds like
90
+ "**my sleep**".
91
+
92
+ | | |
93
+ |---|---|
94
+ | License | BSD 3-Clause |
95
+ | Python | 3.9 – 3.14 |
96
+ | GUI toolkit | PySide6 (Qt6) — Windows, macOS, Linux |
97
+ | Documentation | [https://bryanwang.cn/MiSleep/](https://bryanwang.cn/MiSleep/) |
98
+
99
+ ---
100
+
101
+ ## Features
102
+
103
+ - **Cross-platform desktop GUI** built on **PySide6** (Qt6). Works on
104
+ Windows, macOS and Linux without any platform-specific code.
105
+ - **Flexible data input** — load MATLAB, EDF/EDF+, BDF, NumPy NPY/NPZ,
106
+ CSV and TSV recordings; JSON/CSV/TSV annotation imports are also built in.
107
+ - **Full scoring workflow** — per-second sleep state scoring (NREM / REM /
108
+ Wake / Init), single time-point markers, start-end events, hypnogram,
109
+ spectrogram and per-state spectral analysis.
110
+ - **Event detection** — slow-wave activity (SWA) and sleep spindle
111
+ detection with state-specific thresholds.
112
+ - **Automatic sleep staging** — a LightGBM classifier (trained on
113
+ time- and frequency-domain features) and an optional PyTorch
114
+ causal-transformer model.
115
+ - **Analysis export** — per-hour and 12 h light/dark phase sleep
116
+ statistics exported to Excel.
117
+ - **Clean, modular architecture** — data, I/O, preprocessing, analysis,
118
+ visualization and GUI are separate modules with a stable public API and
119
+ plugin-friendly extension points (see the
120
+ [developer guide](docs/developer_guide.md)).
121
+
122
+ ## Installation
123
+
124
+ ```bash
125
+ # Core package (data, I/O, preprocessing, analysis, visualization)
126
+ pip install misleep
127
+
128
+ # With the PySide6 GUI (recommended for most users)
129
+ pip install "misleep[gui]"
130
+
131
+ # With everything, including the LightGBM auto-staging model
132
+ pip install "misleep[full]"
133
+
134
+ # For development / contributing
135
+ git clone https://github.com/BryanWang0702/MiSleep.git
136
+ cd misleepv3
137
+ pip install -e ".[gui,analysis,dev]"
138
+ ```
139
+
140
+ > **Note on PyTorch:** the causal-transformer auto-staging model requires
141
+ > `torch`, which is not available on every platform. Install it
142
+ > separately with `pip install "misleep[transformer]"`.
143
+
144
+ ## Quick start
145
+
146
+ ### Launch the GUI
147
+
148
+ ```bash
149
+ python -m misleep
150
+ # or, after installation:
151
+ misleep
152
+ ```
153
+
154
+ ### Open files directly (command line)
155
+
156
+ ```bash
157
+ misleep data.mat # open a recording
158
+ misleep data.mat anno.txt # open a recording + its annotation
159
+ misleep --data data.edf --anno anno.txt
160
+ python -m misleep data.mat # same via the module
161
+ ```
162
+
163
+ ### Open files by double-clicking (Windows)
164
+
165
+ Register MiSleep as the handler for your recording files:
166
+
167
+ ```bash
168
+ python tools/install_file_associations.py
169
+ ```
170
+
171
+ After that, **double-clicking a `.mat` or `.edf` file opens it in MiSleep**
172
+ (no console window). Annotation `.txt` files get an **"Open with MiSleep"**
173
+ right-click menu item without changing their default handler. The previous
174
+ `.mat`/`.edf` handlers are backed up automatically and restored with:
175
+
176
+ ```bash
177
+ python tools/install_file_associations.py --uninstall
178
+ ```
179
+
180
+ On macOS/Linux, run the same script for instructions (or open files from
181
+ the command line as shown above).
182
+
183
+ ### Use the library
184
+
185
+ ```python
186
+ import misleep as ms
187
+
188
+ # Load a recording
189
+ midata = ms.load_signal("data.npz") # MAT, EDF/BDF, NPY/NPZ, CSV or TSV
190
+
191
+ # Inspect it
192
+ print(midata.channels, midata.sf, midata.duration)
193
+
194
+ # Preprocess
195
+ midata.filter(chans=["EEG"], btype="bandpass", low=0.5, high=30)
196
+ nrem, rem, wake, init = ms.crop_state_data(midata, mianno)
197
+
198
+ # Analyze
199
+ freq, psd = ms.spectrum(midata.signals[0], midata.sf[0])
200
+ swa = ms.SWA_detection(midata.signals[0], midata.sf[0], df=True)
201
+
202
+ # Plot
203
+ fig, ax = ms.plot_hypno(mianno.sleep_state)
204
+ ```
205
+
206
+ See [docs/getting_started.md](docs/getting_started.md) and the
207
+ [examples](examples/) folder for more.
208
+
209
+ ## Project layout
210
+
211
+ ```
212
+ misleepv3/
213
+ ├── pyproject.toml # modern packaging (PEP 621)
214
+ ├── src/misleep/
215
+ │ ├── data/ # data model: MiData, MiAnnotation
216
+ │ ├── io/ # input/output: MAT, EDF, annotations (+ plugin registry)
217
+ │ ├── preprocessing/ # filtering, artifact rejection, spectral analysis
218
+ │ ├── analysis/ # detection, feature extraction, auto staging
219
+ │ ├── viz/ # matplotlib plotting (signals, spectra, hypnograms)
220
+ │ ├── gui/ # PySide6 desktop application
221
+ │ ├── utils/ # shared helpers
222
+ │ ├── config.py # INI configuration handling
223
+ │ └── logger.py # logging setup
224
+ ├── tests/ # pytest suite
225
+ ├── docs/ # user + developer documentation
226
+ ├── examples/ # runnable examples
227
+ └── tools/ # UI/resource compilation scripts
228
+ ```
229
+
230
+ ## Documentation
231
+
232
+ - [Getting started](docs/getting_started.md) — installation and first steps
233
+ - [User guide](docs/user_guide.md) — the GUI in detail
234
+ - [Data formats](docs/data_formats.md) — how data and annotations are stored
235
+ - [Configuration](docs/config_file.md) — the `config.ini` reference
236
+ - [API reference](docs/api_reference.md) — full API documentation
237
+ - [Developer guide](docs/developer_guide.md) — architecture and how to extend MiSleep
238
+ - [Changelog](CHANGELOG.md)
239
+
240
+ ## Citing MiSleep
241
+
242
+ If you use this software in your research, please cite it as:
243
+
244
+ > Xueqiang Wang. (2024). BryanWang0702/MiSleep. Zenodo.
245
+ > https://doi.org/10.5281/zenodo.14511905
246
+
247
+ ## License
248
+
249
+ BSD 3-Clause. See [LICENSE](LICENSE).
@@ -0,0 +1,94 @@
1
+ misleep/__init__.py,sha256=KYqa1MDJgsgQnV9hDYXhuifXrdGn7JxmRELaG8PPgIM,3780
2
+ misleep/__main__.py,sha256=KunVlmRzkG7XwPLW82KjTqPrOuEuqu6upsuqy2cVJ3c,354
3
+ misleep/logger.py,sha256=J_KqmR1HHBLsEM5BPEkyDmdh6M0QHNOB_ttqReiqjl4,2498
4
+ misleep/analysis/__init__.py,sha256=AtBmV_16Daswx9cFvAmdHwiThJhBZNalfzoceq-ThKQ,824
5
+ misleep/analysis/auto_stage.py,sha256=xGlCW2QzD40sQoJNbFNAcoH0i2OSEUr3ayZzSj56HjY,5721
6
+ misleep/analysis/detection.py,sha256=mplIa7jp3sxT1j3drq6IDhjMkS_uFdK2Nggbhomu1bg,7089
7
+ misleep/analysis/features.py,sha256=Y0e-mHd7Ge3EUSFUfrpvGkYriRaaYiwMEXoNbhvsPqI,4676
8
+ misleep/analysis/models/P30_EEG_F_lightgbm.pkl,sha256=N9ohL1XeI-fVGsBumzLgwL0mBleAZozqcZ48ai4MKF0,2192900
9
+ misleep/analysis/models/P30_EEG_P_lightgbm.pkl,sha256=4uNe4Vl-0lCU_Xuyh9_EtHorKg23fSqo2xmgQYmEPxo,2194276
10
+ misleep/analysis/models/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
+ misleep/analysis/models/ado_EEG_F_lightgbm.pkl,sha256=vg0zFdxSICzJxgQ1rdODNM1v8VdieX2aHA0nBz68sBo,1647420
12
+ misleep/analysis/models/ado_EEG_P_lightgbm.pkl,sha256=WwqEFMyNZQ-RH71X8zq3UyZYNfaoliNKuEVEngfQxwY,1647244
13
+ misleep/analysis/models/adult_EEG_F_lightgbm.pkl,sha256=NuU88CvFCzdcCIuYpdepb_Jg9Wu-i-wWgCO0gFFiVbs,1648988
14
+ misleep/analysis/models/adult_EEG_P_lightgbm.pkl,sha256=27gpT4udP8wrloHPNDcMTF_zgDTga10dq65a_CE-Gxg,1648460
15
+ misleep/analysis/transformer/__init__.py,sha256=6g19j7R5vwXeTR_r9ez55K9EQGGuZFutRpJsQrhGAYM,1771
16
+ misleep/analysis/transformer/configs.py,sha256=sPLCDnLIR4rySXWGAh4pmgd2vVQ40JQgVSBLdVtCngc,1308
17
+ misleep/analysis/transformer/data.py,sha256=oldRC6R9O1njCMMxFYKR1EQTVQjCz-z-P0FKLHzmRck,13561
18
+ misleep/analysis/transformer/inference.py,sha256=QOTF9N2ycAfRthjiojybGAQV1HTHCxx2QkSHhG4kpsQ,10988
19
+ misleep/analysis/transformer/models.py,sha256=GheCJvGxVtkHTkY_q-CGwVPvsgroiVW1evULnjllcgw,8466
20
+ misleep/analysis/transformer/preprocessing.py,sha256=rChoAjclJ62bNbZmOJcYk0r63PgsY6kDhANrqZmlghc,4145
21
+ misleep/analysis/transformer/checkpoints/CausalTransformer_best.pt,sha256=bY-u6juKXsb67MfrNodxhzAyofzSxyYTtylHfR1g64Y,3595561
22
+ misleep/analysis/transformer/checkpoints/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
23
+ misleep/config/__init__.py,sha256=iksyHwbIyHbFrlNydakUAMO7uqs9N6VG37GLtaXelLc,3352
24
+ misleep/config/default_config.ini,sha256=B5RNTx2IpR5HxcTGHorUwZP5UYiYOjAa5gtai6wPzs8,1360
25
+ misleep/data/__init__.py,sha256=lQb_pxIhLqFRyysR6MsZyGLvdFRrxcwPiCutypbrKb0,366
26
+ misleep/data/annotation.py,sha256=vjf49gOMj-O9-dfaWCSLB3BjDZuS8a3A88zBgciI_lg,4124
27
+ misleep/data/midata.py,sha256=pEjgs38VnLnn8FArC25eAIUUL58p9cIG_8hXU4B8-5c,15425
28
+ misleep/gui/__init__.py,sha256=7_s_RWlWlsGoFLuS9H5Z0PdrYHD0WCzX469REwVLx0w,664
29
+ misleep/gui/app.py,sha256=B0pG7SdlXL5Kds1km8_gsEOXKB4Xd8voNF4wGRogMak,5972
30
+ misleep/gui/config_dialog.py,sha256=BTV8ZHUArBe6oY4DdeZZ7QP13mP1oKVmdIgQNOyB_So,15345
31
+ misleep/gui/dialogs.py,sha256=xs09WQKeergBH0nCoGpI3yOSglXAekOyiRQ946hM0-E,43532
32
+ misleep/gui/event_filters.py,sha256=87xBn8YzLXItmu-zasD-dVrzZpUWiNg1urzO1bhigUM,1077
33
+ misleep/gui/main_window.py,sha256=IbWdj5BKjkIfwC92RIhZgU_Ux9EYo5PB6YSEdtJuYIo,115155
34
+ misleep/gui/qt_utils.py,sha256=v_LpEpWi7BPtvtOToQqH9vONMSjUjnZDGv7vt8i2Hws,9902
35
+ misleep/gui/spec_window.py,sha256=PWGC9Nd3Lds7J80NAw4L1hDIs5w1WAsaIgwqtPL6QRQ,7292
36
+ misleep/gui/style.py,sha256=kJcZXVVae3TeE_4GJv2Ws6evt3PExMbHZunU35G1Des,31532
37
+ misleep/gui/workers.py,sha256=SrdD5JAFl2q5uBd7oLpAkvqCKVkeX0pVUY7UV7AL4X8,1994
38
+ misleep/gui/resources/__init__.py,sha256=cYaWf3E5yGPWY54ZaYjYrrZtLd3bUzsSb_YhMktdQ0M,270
39
+ misleep/gui/resources/entire_logo.png,sha256=iaak4kT_t5CLLWWqsdlEd2DLw-igQdhDNVyrN_g8z5A,9826
40
+ misleep/gui/resources/logo.png,sha256=KS6PNgJHM145c81hEJmokRVHa7XN_yXUi0VRudVwSLo,2670
41
+ misleep/gui/resources/misleep.ico,sha256=aD2CD20no6squzWZXv8C5oLdwsiA41b_BeLRAkwGNWE,7782
42
+ misleep/gui/resources/misleep.qrc,sha256=1WcAovt94Gz7tpmuQb71DqCBvOkQ90n5BT-PKOcWQ4c,151
43
+ misleep/gui/resources/misleep_rc.py,sha256=4Cu8mFiQpF2yVUX0dB9SAMpAVC0VzHfS9a8sBSNnbXU,64005
44
+ misleep/gui/uis/SWA_detect_dialog.ui,sha256=L4_EiOSjsDPbpL5WRc8Rw5fXtJyckEdOPc4YxAYtUEE,5399
45
+ misleep/gui/uis/SWA_detect_dialog_ui.py,sha256=WSNl3ElJetvO1HssNL6w0v7qP-HCgGL2otB9XFHcD1M,7524
46
+ misleep/gui/uis/__init__.py,sha256=RxgwzikYO4wnshmRlgokTcgo0dRooUOvuTvdJMrfUuU,168
47
+ misleep/gui/uis/about.ui,sha256=r-jdclg0DnZZIGk5YcFS_K_c0qC-KiWUHnMzagg-9kM,2447
48
+ misleep/gui/uis/about_ui.py,sha256=gcQHqJZDRfP4b5oyOogJb8K2zUwcjJm6-y5ZCu6A8W8,3545
49
+ misleep/gui/uis/auto_stage_causalTransformer_dialog.ui,sha256=zv7bhwFeBWXhbSjUhLCmqaRQWzEMEiqJpWEP5tmgJuk,2290
50
+ misleep/gui/uis/auto_stage_causalTransformer_dialog_ui.py,sha256=Jjw-mEop0uD7hmS4BxgDIklDnJuYRkKIjEnxZGcjJkQ,4299
51
+ misleep/gui/uis/auto_stage_lightGBM_dialog.ui,sha256=zJXXOI0WUYvLyHbzMokBYX2Po3Kh6DROB_6pKDLv1oM,3559
52
+ misleep/gui/uis/auto_stage_lightGBM_dialog_ui.py,sha256=Oobf4EV8qlFIQ66WomFATstn_up6lYwsRSDqZ0mtvpo,5735
53
+ misleep/gui/uis/horizontal_line_dialog.ui,sha256=hh18rtthgkmfVNK2B8TaQEaaXas-KW5xPqp-zQI7I_c,4945
54
+ misleep/gui/uis/horizontal_line_dialog_ui.py,sha256=WLlGky7lNyxnjY3qXKJjf-D61UXeXOakFwHp5TcmwFk,7168
55
+ misleep/gui/uis/label_dialog.ui,sha256=PUT9-mftZfr3IqzltRTiSuwFIc9lY3NvMjv-dlmohBA,1718
56
+ misleep/gui/uis/label_dialog_ui.py,sha256=W-Ezww9fGqFEka5PjeV3m0Fk2i2ln8Lb0pxYMyxM5sk,2866
57
+ misleep/gui/uis/main_window.ui,sha256=LLJz7NeyRjHYGEYkKSjKvmTwViJLRF15MeJh1sEFQnc,25536
58
+ misleep/gui/uis/main_window_ui.py,sha256=EOIqcdHEVYFeKawqviGEqKGNF9tOtoxnKxdl5hI_0_s,31882
59
+ misleep/gui/uis/save_data_dialog.ui,sha256=838xa4wxIzPkymwu75OzsST1s9SzC3wQFevV-fSP-0E,2875
60
+ misleep/gui/uis/save_data_dialog_ui.py,sha256=FIk9owtXGwLLDALh_UAG4N-UD2uCviqqo9Fg9gVdNEg,4653
61
+ misleep/gui/uis/spec_window.ui,sha256=kuMDkzpG34Jt6IIkSEjr2wch2XrFXCKJGXvTXAOkhAY,3248
62
+ misleep/gui/uis/spec_window_ui.py,sha256=cQW-fmxKB0xXtLTVvOtWGhU6J_Ln8_6OZ3G_REx1EMw,5066
63
+ misleep/gui/uis/spindle_detect_dialog.ui,sha256=APo-zlAlLsQORdp1vvIXMMwObbCQZsp4lGfEIItix1A,6099
64
+ misleep/gui/uis/spindle_detect_dialog_ui.py,sha256=4NVA6S1m3_dStPr6BTVVGjYc0S9MSqRvDzBYrd-c_bM,8505
65
+ misleep/gui/uis/state_spectral_dialog.ui,sha256=3xP8MyJOtkUWr7iaB3zlyYZKGQM5hbPTlzNboEE9JmA,7557
66
+ misleep/gui/uis/state_spectral_dialog_ui.py,sha256=B0tQbaHiBLh0xWesTMoWF5p7cQjyqSTjCcDxAOdNSK4,9734
67
+ misleep/gui/uis/transfer_result_dialog.ui,sha256=1iRNDpavAxJAukW8CXaaC7NCt1FUpYWQ_s93vkPFv8s,3054
68
+ misleep/gui/uis/transfer_result_dialog_ui.py,sha256=nDb76y2POgjFOIQhFMn8kFzCFXj1XKe47HkadZC6LvE,4541
69
+ misleep/io/__init__.py,sha256=VsrWbk1wyqpRZD2-HsyBQbSfZRKn3XjfvGamL-lgX5k,1674
70
+ misleep/io/annotation.py,sha256=yQS1gSjLVdKRLcd7xRIhgB6tcyuuq7uOAx5Qd7hc5M0,14834
71
+ misleep/io/array.py,sha256=N_SeaAW2co-DWOkoefSQUPxT2DTaQDNwqiMBNvRGlQQ,8428
72
+ misleep/io/base.py,sha256=aSFjNfw2lJt3jszmHU1vOiXnxORlcYMA1Z1atN2uSh8,5638
73
+ misleep/io/edf.py,sha256=RgdZNg5bGGkKDduhZBnnQlykKKUW-tt3rb5NJBBt9qA,2919
74
+ misleep/io/mat.py,sha256=nsv8vybRHhYkzNSqy1YwLss61IZ1nag6z2xEKV8ao4Y,6146
75
+ misleep/preprocessing/__init__.py,sha256=Xp52QCmwhod8k-TR_BmnhDaieu45nS8-B3jBlzFXeP4,670
76
+ misleep/preprocessing/artifacts.py,sha256=6-qIG2Q_fSreBi1hdF0zHFV_X0VkZmJ--o0jWAA_ABc,2220
77
+ misleep/preprocessing/filtering.py,sha256=kPDYjTHdFBGYp7zkevDixK2AxVmiK5XltPw3nc5XNog,3059
78
+ misleep/preprocessing/segment.py,sha256=Ow4A1tSfFGZgyU3DZxm2-5H5wRXt6tjKWIab-Oi7GAY,1948
79
+ misleep/preprocessing/spectral.py,sha256=QsL57XAybZSq0lnXq6KsT3hvdhpfMuHtUV57TIHxJ-w,5207
80
+ misleep/utils/__init__.py,sha256=TOhTYYsqFbudaUSztxEEhRDJhEAH_Zme5osFVHB4Bz4,1130
81
+ misleep/utils/annotation.py,sha256=STDpa2FtX5DsO_siNIb5gxX5_t-3GiAqtqjwLY4DrTM,4214
82
+ misleep/utils/entropy.py,sha256=_KLtPg6agHhXFYTTN02VfaK_1SkSMwCwpaL-hIcdnks,4188
83
+ misleep/utils/misc.py,sha256=yHEsaEKDs1O6ap_ivkkg-gMBZPxcFbiuoWdxcpx1pZE,1820
84
+ misleep/utils/time_utils.py,sha256=h4sHfrUS7jQmbYFltS43VVmOdtLd1Q5re0_sXG9-NVM,1858
85
+ misleep/viz/__init__.py,sha256=QvbDFiDFI4Aj-6egS_BnfOLd_ShdDceFQDmfDkP-bks,425
86
+ misleep/viz/hypnogram.py,sha256=iMwFs8OX_XS6dJTicIt1_8wFYiV4rfasEj5xPxCZC1I,1567
87
+ misleep/viz/signals.py,sha256=pGgeRP1aJMDJGJxsJqB_3R49-IYMGid5iPqBVjHcuO4,1623
88
+ misleep/viz/spectral.py,sha256=XunKfPB1cykgY6haO4qwQRBzftBONR4uO7w_YwRUM8c,2823
89
+ misleep-0.3.0.dist-info/licenses/LICENSE,sha256=EXDMC0XQdWf9aV8yJcD5rQmqGbz7NVEZ9Bqc_1LnLh0,1548
90
+ misleep-0.3.0.dist-info/METADATA,sha256=Y2l1tJiEBim1osJeGc8VjA3XUGUO3FBlRQmIbEqWpYc,9769
91
+ misleep-0.3.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
92
+ misleep-0.3.0.dist-info/entry_points.txt,sha256=EYYrUjo7cUVOdNFAETcnVdpGkHjMWtCP2xdpAdeVIcQ,384
93
+ misleep-0.3.0.dist-info/top_level.txt,sha256=OplTFH8FCebgxrq0NkA-sPMDuRrQHLmfPGWsHfqnLoM,8
94
+ misleep-0.3.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,15 @@
1
+ [console_scripts]
2
+ misleep = misleep.gui.app:main
3
+
4
+ [misleep.signal_readers]
5
+ csv = misleep.io.array:load_csv
6
+ edf = misleep.io.edf:load_edf
7
+ mat = misleep.io.mat:load_mat
8
+ npy = misleep.io.array:load_npy
9
+ npz = misleep.io.array:load_npz
10
+ tsv = misleep.io.array:load_tsv
11
+
12
+ [misleep.signal_writers]
13
+ edf = misleep.io.edf:write_edf
14
+ mat = misleep.io.mat:write_mat
15
+ npz = misleep.io.array:write_npz
@@ -0,0 +1,29 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2023, Xueqiang Wang
4
+ All rights reserved.
5
+
6
+ Redistribution and use in source and binary forms, with or without
7
+ modification, are permitted provided that the following conditions are met:
8
+
9
+ 1. Redistributions of source code must retain the above copyright notice, this
10
+ list of conditions and the following disclaimer.
11
+
12
+ 2. Redistributions in binary form must reproduce the above copyright notice,
13
+ this list of conditions and the following disclaimer in the documentation
14
+ and/or other materials provided with the distribution.
15
+
16
+ 3. Neither the name of the copyright holder nor the names of its
17
+ contributors may be used to endorse or promote products derived from
18
+ this software without specific prior written permission.
19
+
20
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
26
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1 @@
1
+ misleep