logqbit 0.5__tar.gz → 0.6__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 (55) hide show
  1. {logqbit-0.5 → logqbit-0.6}/.gitignore +1 -0
  2. {logqbit-0.5 → logqbit-0.6}/PKG-INFO +15 -18
  3. {logqbit-0.5 → logqbit-0.6}/README.md +8 -11
  4. {logqbit-0.5 → logqbit-0.6}/pyproject.toml +9 -6
  5. logqbit-0.6/src/logqbit/__init__.py +14 -0
  6. logqbit-0.6/src/logqbit/catalog.py +261 -0
  7. logqbit-0.6/src/logqbit/cli/__init__.py +5 -0
  8. logqbit-0.6/src/logqbit/cli/__main__.py +5 -0
  9. logqbit-0.6/src/logqbit/cli/demo.py +137 -0
  10. logqbit-0.6/src/logqbit/cli/main.py +121 -0
  11. logqbit-0.6/src/logqbit/cli/shortcuts.py +108 -0
  12. {logqbit-0.5/src/logqbit/misc → logqbit-0.6/src/logqbit/cli}/svg2ico.py +6 -7
  13. logqbit-0.6/src/logqbit/dataframe.py +208 -0
  14. logqbit-0.6/src/logqbit/file_version.py +41 -0
  15. logqbit-0.6/src/logqbit/gui/browser/__init__.py +5 -0
  16. logqbit-0.6/src/logqbit/gui/browser/__main__.py +5 -0
  17. logqbit-0.5/src/logqbit/gui/detail_view.py → logqbit-0.6/src/logqbit/gui/browser/detail.py +328 -265
  18. logqbit-0.5/src/logqbit/gui/browser.py → logqbit-0.6/src/logqbit/gui/browser/window.py +210 -415
  19. logqbit-0.6/src/logqbit/gui/plot/__init__.py +5 -0
  20. logqbit-0.6/src/logqbit/gui/plot/cursor.py +338 -0
  21. logqbit-0.6/src/logqbit/gui/plot/fit.py +350 -0
  22. logqbit-0.6/src/logqbit/gui/plot/mesh.py +241 -0
  23. logqbit-0.6/src/logqbit/gui/plot/widget.py +653 -0
  24. {logqbit-0.5 → logqbit-0.6}/src/logqbit/logfolder.py +48 -23
  25. logqbit-0.6/src/logqbit/metadata.py +179 -0
  26. {logqbit-0.5 → logqbit-0.6}/src/logqbit/registry.py +101 -58
  27. {logqbit-0.5 → logqbit-0.6}/src/logqbit/templates/move_from_labrad.py +1 -1
  28. logqbit-0.6/tests/core/test_cli.py +42 -0
  29. logqbit-0.6/tests/core/test_dataframe.py +123 -0
  30. logqbit-0.6/tests/core/test_log_catalog.py +225 -0
  31. logqbit-0.6/tests/core/test_logfolder.py +239 -0
  32. logqbit-0.6/tests/core/test_metadata.py +129 -0
  33. logqbit-0.6/tests/core/test_public_api.py +8 -0
  34. {logqbit-0.5/tests → logqbit-0.6/tests/core}/test_registry.py +100 -1
  35. {logqbit-0.5 → logqbit-0.6}/tests/for_all_pythons.ps1 +3 -3
  36. logqbit-0.6/tests/gui/test_browser.py +981 -0
  37. logqbit-0.6/tests/gui/test_plotter.py +471 -0
  38. logqbit-0.5/src/logqbit/__init__.py +0 -0
  39. logqbit-0.5/src/logqbit/cli.py +0 -445
  40. logqbit-0.5/src/logqbit/dataframe.py +0 -147
  41. logqbit-0.5/src/logqbit/gui/plotter.py +0 -529
  42. logqbit-0.5/src/logqbit/metadata.py +0 -107
  43. logqbit-0.5/tests/test_browser.py +0 -623
  44. logqbit-0.5/tests/test_dataframe.py +0 -58
  45. logqbit-0.5/tests/test_flush_issue.py +0 -21
  46. logqbit-0.5/tests/test_logfolder.py +0 -127
  47. logqbit-0.5/tests/test_metadata.py +0 -55
  48. logqbit-0.5/tests/test_plotter.py +0 -164
  49. {logqbit-0.5 → logqbit-0.6}/LICENSE +0 -0
  50. {logqbit-0.5 → logqbit-0.6}/src/logqbit/assets/browser.svg +0 -0
  51. {logqbit-0.5 → logqbit-0.6}/src/logqbit/assets/live_plotter.svg +0 -0
  52. {logqbit-0.5 → logqbit-0.6}/src/logqbit/gui/__init__.py +0 -0
  53. {logqbit-0.5 → logqbit-0.6}/src/logqbit/gui/live_plotter.py +0 -0
  54. {logqbit-0.5/tests → logqbit-0.6/tests/gui}/conftest.py +0 -0
  55. {logqbit-0.5/tests → logqbit-0.6/tests/gui}/test_live_plotter.py +0 -0
@@ -1,5 +1,6 @@
1
1
  logqbit_example/
2
2
  AGENTS.md
3
+ src/logqbit/assets/*.ico
3
4
 
4
5
  # Python-generated files
5
6
  __pycache__/
@@ -1,23 +1,23 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: logqbit
3
- Version: 0.5
3
+ Version: 0.6
4
4
  Summary: Simple data logger and live plotter for lab-scale experiments.
5
5
  Project-URL: Homepage, https://github.com/Qiujv/logqbit
6
6
  Author-email: Qiujv <qiujv@outlook.com>
7
7
  License-File: LICENSE
8
8
  Requires-Python: >=3.11
9
- Requires-Dist: numba>=0.65.0
10
9
  Requires-Dist: numpy>=2.3.3
11
10
  Requires-Dist: pandas>=2.3.3
12
11
  Requires-Dist: pyarrow>=21.0.0
13
- Requires-Dist: pyqtgraph>=0.14.0
14
- Requires-Dist: pyside6>=6.9.3
15
12
  Requires-Dist: ruamel-yaml>=0.18.15
16
- Requires-Dist: send2trash>=1.8.3
17
13
  Requires-Dist: tqdm>=4.67.1
18
14
  Requires-Dist: typing-extensions>=4.15.0
19
- Provides-Extra: labrad
20
- Requires-Dist: pylabrad>=0.98.3; extra == 'labrad'
15
+ Provides-Extra: gui
16
+ Requires-Dist: numba>=0.65.0; extra == 'gui'
17
+ Requires-Dist: pyqtgraph>=0.14.0; extra == 'gui'
18
+ Requires-Dist: pyside6>=6.9.3; extra == 'gui'
19
+ Requires-Dist: scipy>=1.16.0; extra == 'gui'
20
+ Requires-Dist: send2trash>=1.8.3; extra == 'gui'
21
21
  Description-Content-Type: text/markdown
22
22
 
23
23
  # LogQbit
@@ -26,7 +26,7 @@ LogQbit 是一个面向实验室场景的轻量数据记录工具包,适合记
26
26
 
27
27
  它的核心设计目标是:
28
28
 
29
- - 用简单的接口和运行逻辑实验数据。
29
+ - 用简单的接口记录和管理实验数据。
30
30
  - 基于目录的实验数据组织,用通用可读的格式储存数据。
31
31
  - 在需要时再启用浏览器和实时绘图等 GUI 能力。
32
32
 
@@ -40,15 +40,12 @@ LogQbit 是一个面向实验室场景的轻量数据记录工具包,适合记
40
40
  pip install logqbit
41
41
  ```
42
42
 
43
- 如果你不想让安装过程修改当前 Python 环境,可以跳过依赖解析:
43
+ 如果还需要 GUI:
44
44
 
45
45
  ```bash
46
- pip install --no-deps logqbit
46
+ pip install "logqbit[gui]"
47
47
  ```
48
48
 
49
- 通常 `logqbit.logfolder.LogFolder`、`logqbit.registry.Registry` 等核心接口仍然可用;
50
- 但浏览器、实时绘图和快捷方式等 GUI 功能仍然依赖 `PySide6`、`pyqtgraph` 等组件。
51
-
52
49
  更详细的安装说明见:https://qiujv.github.io/logqbit/install/
53
50
 
54
51
  ## 用例
@@ -56,9 +53,7 @@ pip install --no-deps logqbit
56
53
  ### 用例 1:记录一组实验数据
57
54
 
58
55
  ```python
59
- from pathlib import Path
60
-
61
- from logqbit.logfolder import LogFolder
56
+ from logqbit import LogFolder
62
57
 
63
58
  lf = LogFolder.new("./demo_data", title="My Experiment")
64
59
 
@@ -80,17 +75,19 @@ logqbit browser
80
75
 
81
76
  或者也可以通过 `logqbit shortcuts` 创建桌面快捷方式(仅 Windows 可用)。
82
77
 
83
- ### 用例 3:快速生成示例数据并打开浏览器
78
+ ### 用例 3:生成示例数据并打开浏览器
84
79
 
85
80
  ```bash
86
81
  logqbit browser-demo
87
82
  ```
88
83
 
89
- 这会在当前目录创建 `logqbit_example/`,生成多组示例数据,并启动图形化浏览器。
84
+ 这会在当前目录创建 `logqbit_example/`,生成五组示例数据并启动图形化浏览器。其中两组
85
+ 包含一百万个数据点,首次生成可能需要一点时间。
90
86
 
91
87
  更多内容:
92
88
 
93
89
  - 文档首页:https://qiujv.github.io/logqbit/
90
+ - LogBrowser:https://qiujv.github.io/logqbit/browser/
94
91
  - 命令行工具:https://qiujv.github.io/logqbit/cli/
95
92
  - LabRAD 迁移:https://qiujv.github.io/logqbit/migration_guide/
96
93
  - Python API:https://qiujv.github.io/logqbit/api/
@@ -4,7 +4,7 @@ LogQbit 是一个面向实验室场景的轻量数据记录工具包,适合记
4
4
 
5
5
  它的核心设计目标是:
6
6
 
7
- - 用简单的接口和运行逻辑实验数据。
7
+ - 用简单的接口记录和管理实验数据。
8
8
  - 基于目录的实验数据组织,用通用可读的格式储存数据。
9
9
  - 在需要时再启用浏览器和实时绘图等 GUI 能力。
10
10
 
@@ -18,15 +18,12 @@ LogQbit 是一个面向实验室场景的轻量数据记录工具包,适合记
18
18
  pip install logqbit
19
19
  ```
20
20
 
21
- 如果你不想让安装过程修改当前 Python 环境,可以跳过依赖解析:
21
+ 如果还需要 GUI:
22
22
 
23
23
  ```bash
24
- pip install --no-deps logqbit
24
+ pip install "logqbit[gui]"
25
25
  ```
26
26
 
27
- 通常 `logqbit.logfolder.LogFolder`、`logqbit.registry.Registry` 等核心接口仍然可用;
28
- 但浏览器、实时绘图和快捷方式等 GUI 功能仍然依赖 `PySide6`、`pyqtgraph` 等组件。
29
-
30
27
  更详细的安装说明见:https://qiujv.github.io/logqbit/install/
31
28
 
32
29
  ## 用例
@@ -34,9 +31,7 @@ pip install --no-deps logqbit
34
31
  ### 用例 1:记录一组实验数据
35
32
 
36
33
  ```python
37
- from pathlib import Path
38
-
39
- from logqbit.logfolder import LogFolder
34
+ from logqbit import LogFolder
40
35
 
41
36
  lf = LogFolder.new("./demo_data", title="My Experiment")
42
37
 
@@ -58,17 +53,19 @@ logqbit browser
58
53
 
59
54
  或者也可以通过 `logqbit shortcuts` 创建桌面快捷方式(仅 Windows 可用)。
60
55
 
61
- ### 用例 3:快速生成示例数据并打开浏览器
56
+ ### 用例 3:生成示例数据并打开浏览器
62
57
 
63
58
  ```bash
64
59
  logqbit browser-demo
65
60
  ```
66
61
 
67
- 这会在当前目录创建 `logqbit_example/`,生成多组示例数据,并启动图形化浏览器。
62
+ 这会在当前目录创建 `logqbit_example/`,生成五组示例数据并启动图形化浏览器。其中两组
63
+ 包含一百万个数据点,首次生成可能需要一点时间。
68
64
 
69
65
  更多内容:
70
66
 
71
67
  - 文档首页:https://qiujv.github.io/logqbit/
68
+ - LogBrowser:https://qiujv.github.io/logqbit/browser/
72
69
  - 命令行工具:https://qiujv.github.io/logqbit/cli/
73
70
  - LabRAD 迁移:https://qiujv.github.io/logqbit/migration_guide/
74
71
  - Python API:https://qiujv.github.io/logqbit/api/
@@ -6,14 +6,10 @@ readme = "README.md"
6
6
  requires-python = ">=3.11"
7
7
  authors = [{ name = "Qiujv", email = "qiujv@outlook.com" }]
8
8
  dependencies = [
9
- "numba>=0.65.0",
10
9
  "numpy>=2.3.3",
11
10
  "pandas>=2.3.3",
12
11
  "pyarrow>=21.0.0",
13
- "pyqtgraph>=0.14.0",
14
- "pyside6>=6.9.3",
15
12
  "ruamel-yaml>=0.18.15",
16
- "send2trash>=1.8.3",
17
13
  "tqdm>=4.67.1",
18
14
  "typing-extensions>=4.15.0",
19
15
  ]
@@ -41,6 +37,9 @@ packages = ["src/logqbit"]
41
37
  [tool.hatch.build.targets.sdist]
42
38
  include = ["src/", "tests/", "README.md", "LICENSE", "pyproject.toml"]
43
39
 
40
+ [tool.pytest.ini_options]
41
+ testpaths = ["tests"]
42
+
44
43
  [dependency-groups]
45
44
  dev = [
46
45
  "ipykernel>=6.30.1",
@@ -54,6 +53,10 @@ dev = [
54
53
  ]
55
54
 
56
55
  [project.optional-dependencies]
57
- labrad = [
58
- "pylabrad>=0.98.3",
56
+ gui = [
57
+ "numba>=0.65.0",
58
+ "pyqtgraph>=0.14.0",
59
+ "pyside6>=6.9.3",
60
+ "scipy>=1.16.0",
61
+ "send2trash>=1.8.3",
59
62
  ]
@@ -0,0 +1,14 @@
1
+ """Public API for LogQbit's core logging and catalog concepts."""
2
+
3
+ from logqbit.catalog import LogCatalog, LogRecord
4
+ from logqbit.logfolder import LogFolder
5
+ from logqbit.metadata import LogMetadata
6
+ from logqbit.registry import Registry
7
+
8
+ __all__ = [
9
+ "LogCatalog",
10
+ "LogFolder",
11
+ "LogMetadata",
12
+ "LogRecord",
13
+ "Registry",
14
+ ]
@@ -0,0 +1,261 @@
1
+ """Cached records and disk access for LogQbit catalogs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import shutil
7
+ from collections.abc import Callable, Iterable
8
+ from dataclasses import dataclass
9
+ from functools import cached_property
10
+ from pathlib import Path
11
+
12
+ import pandas as pd
13
+ import pyarrow
14
+ import pyarrow.ipc
15
+
16
+ from .file_version import FileVersion
17
+ from .metadata import LogMetadata
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+ _IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".webp", ".bmp", ".gif"}
22
+ _KNOWN_LOG_FILENAMES = {"const.yaml", "data.feather", "metadata.json"}
23
+
24
+
25
+ _RETRY_VERSION = FileVersion(mtime_ns=-1, size=-1, inode=-1)
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class LogRecord:
30
+ """One catalog record with cached summary fields and explicit disk access."""
31
+
32
+ path: Path
33
+ row_count: int = 0
34
+ columns: tuple[str, ...] = ()
35
+ data_version: FileVersion | None = None
36
+
37
+ def __post_init__(self) -> None:
38
+ path = Path(self.path)
39
+ if not path.is_dir():
40
+ raise FileNotFoundError(f"Log directory at '{path}' does not exist.")
41
+ object.__setattr__(self, "path", path)
42
+
43
+ @property
44
+ def log_id(self) -> int | str:
45
+ """Return numeric directory names as integers, otherwise as text."""
46
+ return int(self.path.name) if self.path.name.isdecimal() else self.path.name
47
+
48
+ @property
49
+ def meta_path(self) -> Path:
50
+ return self.path / "metadata.json"
51
+
52
+ @property
53
+ def data_path(self) -> Path:
54
+ return self.path / "data.feather"
55
+
56
+ @property
57
+ def const_path(self) -> Path:
58
+ return self.path / "const.yaml"
59
+
60
+ @cached_property
61
+ def meta(self) -> LogMetadata:
62
+ """Proxy to modify metadata.json on setting values."""
63
+ return LogMetadata(
64
+ self.meta_path,
65
+ create=False,
66
+ default_on_error=True,
67
+ )
68
+
69
+ # Read-only metadata fields cached in memory. Sync by manual meta.reload().
70
+ @property
71
+ def title(self) -> str:
72
+ return str(self.meta.root.get("title", "untitled"))
73
+
74
+ @property
75
+ def star(self) -> int:
76
+ return int(self.meta.root.get("star", 0))
77
+
78
+ @property
79
+ def trash(self) -> bool:
80
+ return bool(self.meta.root.get("trash", False))
81
+
82
+ @property
83
+ def plot_axes(self) -> tuple[str, ...]:
84
+ return tuple(str(item) for item in self.meta.root.get("plot_axes", []))
85
+
86
+ @property
87
+ def plot_fields(self) -> tuple[str, ...]:
88
+ return tuple(str(item) for item in self.meta.root.get("plot_fields", []))
89
+
90
+ @property
91
+ def create_time(self) -> str:
92
+ return str(self.meta.root.get("create_time", ""))
93
+
94
+ @property
95
+ def create_machine(self) -> str:
96
+ return str(self.meta.root.get("create_machine", ""))
97
+
98
+ def read_dataframe(self) -> pd.DataFrame | None:
99
+ """Read the current Feather file once, without retaining a cache."""
100
+ if not self.data_path.exists():
101
+ return None
102
+ try:
103
+ return pd.read_feather(_read_data_buffer(self.data_path))
104
+ except Exception as exc: # pragma: no cover - defensive
105
+ logger.error("Failed to read feather file %s: %s", self.data_path, exc)
106
+ return None
107
+
108
+ def refresh(self) -> LogRecord:
109
+ """Return a record whose metadata and data summary match the disk state."""
110
+ self.meta.reload()
111
+ data_version = FileVersion.from_path(self.data_path)
112
+ if self.data_version == data_version:
113
+ return self
114
+
115
+ try:
116
+ row_count, columns = _inspect_data(self.data_path, data_version)
117
+ except Exception as exc: # pragma: no cover - defensive
118
+ logger.warning("Failed to inspect feather file %s: %s", self.data_path, exc)
119
+ row_count, columns = 0, ()
120
+ data_version = _RETRY_VERSION
121
+ return LogRecord(
122
+ path=self.path,
123
+ row_count=row_count,
124
+ columns=columns,
125
+ data_version=data_version,
126
+ )
127
+
128
+ def read_yaml_text(self) -> str:
129
+ if not self.const_path.exists():
130
+ return "const.yaml not found."
131
+ try:
132
+ text = self.const_path.read_text(encoding="utf-8", errors="ignore")
133
+ except Exception as exc: # pragma: no cover - defensive
134
+ logger.error("Failed to read yaml file %s: %s", self.const_path, exc)
135
+ return f"Failed to read const.yaml: {exc}"
136
+ return text if text.strip() else "(const.yaml is empty)"
137
+
138
+ def list_image_files(self) -> list[Path]:
139
+ return self._list_files(lambda path: path.suffix.lower() in _IMAGE_EXTENSIONS)
140
+
141
+ def list_other_files(self) -> list[Path]:
142
+ return self._list_files(
143
+ lambda path: (
144
+ path.name not in _KNOWN_LOG_FILENAMES
145
+ and path.suffix.lower() not in _IMAGE_EXTENSIONS
146
+ )
147
+ )
148
+
149
+ def _list_files(self, predicate: Callable[[Path], bool]) -> list[Path]:
150
+ try:
151
+ files = [
152
+ child
153
+ for child in self.path.iterdir()
154
+ if child.is_file() and predicate(child)
155
+ ]
156
+ except OSError:
157
+ return []
158
+ return sorted(files)
159
+
160
+
161
+ def _read_data_buffer(data_path: Path) -> pyarrow.BufferReader:
162
+ # Close the disk handle before Arrow parsing to reduce Windows replace races.
163
+ return pyarrow.BufferReader(data_path.read_bytes())
164
+
165
+
166
+ def _inspect_data(
167
+ data_path: Path,
168
+ version: FileVersion | None,
169
+ ) -> tuple[int, tuple[str, ...]]:
170
+ if version is None:
171
+ return 0, ()
172
+ with pyarrow.ipc.open_file(_read_data_buffer(data_path)) as reader:
173
+ row_count = sum(
174
+ reader.get_batch(index).num_rows
175
+ for index in range(reader.num_record_batches)
176
+ )
177
+ columns = tuple(str(name) for name in reader.schema.names)
178
+ return row_count, columns
179
+
180
+
181
+ class LogCatalog:
182
+ """Scan one parent directory and reuse unchanged records."""
183
+
184
+ def __init__(self, directory: str | Path | None = None) -> None:
185
+ self._directory = Path(directory) if directory is not None else None
186
+ self._records: dict[Path, LogRecord] = {}
187
+
188
+ def refresh(self, directory: str | Path | None = None) -> list[LogRecord]:
189
+ """Refresh records, ordered by numeric then named directory."""
190
+ if directory is None:
191
+ if self._directory is None:
192
+ raise TypeError("directory is required on the first refresh")
193
+ directory = self._directory
194
+ directory = Path(directory)
195
+ if self._directory != directory:
196
+ self._directory = directory
197
+ self._records.clear()
198
+
199
+ if not directory.is_dir():
200
+ self._records.clear()
201
+ return []
202
+
203
+ paths = {
204
+ path for path in directory.iterdir() if (path / "metadata.json").is_file()
205
+ }
206
+
207
+ for removed_path in self._records.keys() - paths:
208
+ del self._records[removed_path]
209
+
210
+ for path in paths:
211
+ previous = self._records.get(path)
212
+ if previous is None:
213
+ previous = LogRecord(path)
214
+ self._records[path] = previous.refresh()
215
+
216
+ return sorted(
217
+ self._records.values(),
218
+ key=lambda record: _log_name_sort_key(record.path.name),
219
+ )
220
+
221
+
222
+ def _log_name_sort_key(name: str) -> tuple[int, int | str]:
223
+ if name.isdecimal():
224
+ return 0, int(name)
225
+ return 1, name.casefold()
226
+
227
+
228
+ def _next_export_logfolder_path(parent_path: Path) -> Path:
229
+ max_index = max(
230
+ (
231
+ int(entry.name)
232
+ for entry in parent_path.iterdir()
233
+ if entry.is_dir() and entry.name.isdecimal()
234
+ ),
235
+ default=-1,
236
+ )
237
+ next_index = max_index + 1
238
+ while (parent_path / str(next_index)).exists():
239
+ next_index += 1
240
+ return parent_path / str(next_index)
241
+
242
+
243
+ def export_records(
244
+ records: Iterable[LogRecord], destination_parent: str | Path
245
+ ) -> list[Path]:
246
+ """Copy selected records into newly numbered destination directories."""
247
+ destination_parent = Path(destination_parent)
248
+ destination_parent.mkdir(parents=True, exist_ok=True)
249
+ exported_paths: list[Path] = []
250
+ for record in sorted(
251
+ records,
252
+ key=lambda item: _log_name_sort_key(item.path.name),
253
+ ):
254
+ target_path = _next_export_logfolder_path(destination_parent)
255
+ target_path.mkdir(parents=True, exist_ok=False)
256
+ shutil.copytree(record.path, target_path, dirs_exist_ok=True)
257
+ import_from_path = target_path / "import_from"
258
+ if not import_from_path.exists():
259
+ import_from_path.write_text(str(record.path), encoding="utf-8")
260
+ exported_paths.append(target_path)
261
+ return exported_paths
@@ -0,0 +1,5 @@
1
+ """Command-line utilities for LogQbit."""
2
+
3
+ from logqbit.cli.main import copy_template, main
4
+
5
+ __all__ = ["copy_template", "main"]
@@ -0,0 +1,5 @@
1
+ """Support launching the CLI with ``python -m logqbit.cli``."""
2
+
3
+ from logqbit.cli import main
4
+
5
+ raise SystemExit(main())
@@ -0,0 +1,137 @@
1
+ """Implementation of the ``logqbit browser-demo`` command."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import shutil
6
+ import sys
7
+ import traceback
8
+ from pathlib import Path
9
+
10
+ import numpy as np
11
+ import pandas as pd
12
+
13
+ from logqbit.logfolder import LogFolder
14
+
15
+
16
+ def create_example_data() -> int:
17
+ """Create five example logs in ``./logqbit_example`` and open the browser."""
18
+ try:
19
+ example_dir = Path.cwd() / "logqbit_example"
20
+ if example_dir.exists():
21
+ response = input(
22
+ f"Directory '{example_dir}' already exists. Overwrite? (y/N): "
23
+ )
24
+ if response.lower() != "y":
25
+ print("Cancelled.")
26
+ return 0
27
+ shutil.rmtree(example_dir)
28
+
29
+ example_dir.mkdir(parents=True)
30
+ print(f"Creating example data in: {example_dir}")
31
+
32
+ print(" Creating example 0: Linear relationship...")
33
+ with LogFolder(example_dir / "0") as log:
34
+ log.meta.update(
35
+ title="Linear Relationship Example",
36
+ star=1,
37
+ plot_axes=["x"],
38
+ )
39
+ x_values = np.linspace(0, 10, 50)
40
+ log.add_df(
41
+ pd.DataFrame({"x": x_values, "y": 2 * x_values + 1, "z": x_values**2})
42
+ )
43
+ log.add_const(
44
+ description="y = 2x + 1, z = x^2",
45
+ experiment_type="simulation",
46
+ )
47
+
48
+ print(" Creating example 1: Sinusoidal with noise...")
49
+ with LogFolder(example_dir / "1") as log:
50
+ log.meta.update(
51
+ title="Noisy Sinusoidal Signal",
52
+ star=2,
53
+ plot_axes=["time"],
54
+ )
55
+ time_values = np.linspace(0, 4 * np.pi, 100)
56
+ signal = np.sin(time_values)
57
+ noisy = signal + np.random.default_rng().normal(0, 0.1, len(signal))
58
+ log.add_df(
59
+ pd.DataFrame({"time": time_values, "signal": signal, "noisy": noisy})
60
+ )
61
+ log.add_const(
62
+ description="sin(t) with Gaussian noise",
63
+ frequency="1 Hz",
64
+ noise_level=0.1,
65
+ )
66
+
67
+ print(" Creating example 2: 2D parameter scan...")
68
+ with LogFolder(example_dir / "2") as log:
69
+ log.meta.update(
70
+ title="2D Parameter Scan",
71
+ star=3,
72
+ plot_axes=["voltage", "frequency"],
73
+ )
74
+ voltage, frequency = np.meshgrid(
75
+ np.linspace(-1, 1, 20),
76
+ np.linspace(1, 10, 20),
77
+ indexing="ij",
78
+ )
79
+ response = np.exp(-((frequency - 5.5) ** 2) / 2) * np.exp(
80
+ -((voltage - 0.2) ** 2) / 0.5
81
+ )
82
+ response += np.random.default_rng().normal(0, 0.05, response.shape)
83
+ log.add_df(
84
+ pd.DataFrame(
85
+ {
86
+ "voltage": voltage.ravel(),
87
+ "frequency": frequency.ravel(),
88
+ "response": response.ravel(),
89
+ }
90
+ )
91
+ )
92
+ log.add_const(
93
+ description="Simulated resonance scan",
94
+ voltage_unit="V",
95
+ frequency_unit="GHz",
96
+ )
97
+
98
+ print(" Creating example 3: 1M-point 1D signal (large scale)...")
99
+ with LogFolder(example_dir / "3") as log:
100
+ log.meta.update(title="1M-Point 1D Signal", plot_axes=["t"])
101
+ point_count = 1_000_000
102
+ time_values = np.linspace(0, 100, point_count)
103
+ signal = np.sin(2 * np.pi * 0.5 * time_values) * np.exp(-time_values / 50)
104
+ signal += np.random.default_rng(42).normal(0, 0.05, point_count)
105
+ log.add_df(pd.DataFrame({"t": time_values, "signal": signal}))
106
+ log.add_const(
107
+ description="Damped sine, 1 million points",
108
+ points=point_count,
109
+ )
110
+
111
+ print(" Creating example 4: 1M-point 2D scan (large scale)...")
112
+ with LogFolder(example_dir / "4") as log:
113
+ log.meta.update(title="1M-Point 2D Scan", plot_axes=["x", "y"])
114
+ x_count = y_count = 1000
115
+ x_values = np.repeat(np.linspace(0, 1, x_count), y_count)
116
+ y_values = np.tile(np.linspace(0, 1, y_count), x_count)
117
+ z_values = np.sin(4 * np.pi * x_values) * np.cos(4 * np.pi * y_values)
118
+ z_values += np.random.default_rng(7).normal(0, 0.05, len(z_values))
119
+ log.add_df(pd.DataFrame({"x": x_values, "y": y_values, "z": z_values}))
120
+ log.add_const(
121
+ description="sin(4πx)cos(4πy) + noise, 1000×1000 grid",
122
+ points=x_count * y_count,
123
+ )
124
+
125
+ print(f"\n✓ Created 5 example log folders in: {example_dir}")
126
+ print("\nLaunching browser...")
127
+ from logqbit.gui.browser import main as browser_main
128
+
129
+ return browser_main([str(example_dir)])
130
+ except ImportError as exc:
131
+ print(f"Error: Missing required dependency: {exc}", file=sys.stderr)
132
+ print("Please ensure logqbit is properly installed.", file=sys.stderr)
133
+ return 1
134
+ except Exception as exc:
135
+ print(f"Error creating example data: {exc}", file=sys.stderr)
136
+ traceback.print_exc()
137
+ return 1