plexora 0.0.1__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.
- plexora/__init__.py +129 -0
- plexora/__main__.py +15 -0
- plexora/_url.py +105 -0
- plexora/api/__init__.py +55 -0
- plexora/api/dataset.py +398 -0
- plexora/api/http.py +19 -0
- plexora/api/plugin.py +541 -0
- plexora/api/store.py +221 -0
- plexora/cli.py +777 -0
- plexora/client/dist/354_bundle.js +2 -0
- plexora/client/dist/354_bundle.js.LICENSE.txt +20 -0
- plexora/client/dist/418_bundle.js +2 -0
- plexora/client/dist/418_bundle.js.LICENSE.txt +1 -0
- plexora/client/dist/693b935cb1f907814be9c6199a68c217.svg +19 -0
- plexora/client/dist/713c134ff47cd328a5b711526f151082.svg +18 -0
- plexora/client/dist/770_bundle.js +1 -0
- plexora/client/dist/ff743f408972e0e96ca9153ed5ae4c83.svg +23 -0
- plexora/client/dist/vendor_bundle.js +2 -0
- plexora/client/dist/vendor_bundle.js.LICENSE.txt +308 -0
- plexora/client/external/openseadragon-bin-2.4.0/LICENSE.txt +28 -0
- plexora/client/external/openseadragon-bin-2.4.0/canvas-overlay-hd.js +140 -0
- plexora/client/external/openseadragon-bin-2.4.0/changelog.txt +501 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/.gitattributes +17 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/LICENSE.txt +116 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/Photoshop/Toolbar.png +0 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/Photoshop/fullpage.psd +0 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/Photoshop/home.psd +0 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/Photoshop/next.psd +0 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/Photoshop/previous.psd +0 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/Photoshop/rotateleft.psd +0 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/Photoshop/rotateright.psd +0 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/Photoshop/zoom.psd +0 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/README.md +9 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/images/fullpage_grouphover.png +0 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/images/fullpage_hover.png +0 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/images/fullpage_pressed.png +0 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/images/fullpage_rest.png +0 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/images/home_grouphover.png +0 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/images/home_hover.png +0 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/images/home_pressed.png +0 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/images/home_rest.png +0 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/images/next_grouphover.png +0 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/images/next_hover.png +0 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/images/next_pressed.png +0 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/images/next_rest.png +0 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/images/previous_grouphover.png +0 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/images/previous_hover.png +0 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/images/previous_pressed.png +0 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/images/previous_rest.png +0 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/images/rotateleft_grouphover.png +0 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/images/rotateleft_hover.png +0 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/images/rotateleft_pressed.png +0 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/images/rotateleft_rest.png +0 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/images/rotateright_grouphover.png +0 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/images/rotateright_hover.png +0 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/images/rotateright_pressed.png +0 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/images/rotateright_rest.png +0 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/images/zoomin_grouphover.png +0 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/images/zoomin_hover.png +0 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/images/zoomin_pressed.png +0 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/images/zoomin_rest.png +0 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/images/zoomout_grouphover.png +0 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/images/zoomout_hover.png +0 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/images/zoomout_pressed.png +0 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/images/zoomout_rest.png +0 -0
- plexora/client/external/openseadragon-bin-2.4.0/openseadragon-scalebar.js +562 -0
- plexora/client/src/css/import.css +474 -0
- plexora/client/src/css/main.css +903 -0
- plexora/client/src/css/openProject.css +363 -0
- plexora/client/src/css/quickView.css +166 -0
- plexora/client/src/css/tokens.css +51 -0
- plexora/client/src/css/viewer.css +1655 -0
- plexora/client/src/img/apple-touch-icon.png +0 -0
- plexora/client/src/img/favicon.ico +0 -0
- plexora/client/src/img/logo.ai +8892 -33
- plexora/client/src/img/logo.svg +1 -0
- plexora/client/src/img/logo_with_text.ai +9011 -34
- plexora/client/src/img/logo_with_text.svg +1 -0
- plexora/client/src/js/main.js +704 -0
- plexora/client/src/js/pluginRegistry.js +108 -0
- plexora/client/src/js/services/appStatus.js +286 -0
- plexora/client/src/js/services/browsePicker.js +73 -0
- plexora/client/src/js/services/dataLayer.js +400 -0
- plexora/client/src/js/services/datasetContext.js +143 -0
- plexora/client/src/js/services/glRenderer.js +143 -0
- plexora/client/src/js/services/importFormValidation.js +257 -0
- plexora/client/src/js/services/numericData.js +100 -0
- plexora/client/src/js/services/passVariablesToFrontend.js +20 -0
- plexora/client/src/js/services/simpleEventHandler.js +25 -0
- plexora/client/src/js/vendor.js +29 -0
- plexora/client/src/js/views/channelList.js +663 -0
- plexora/client/src/js/views/colorSwatchPicker.js +202 -0
- plexora/client/src/js/views/columnClassifier.js +146 -0
- plexora/client/src/js/views/coordinateField.js +133 -0
- plexora/client/src/js/views/dataSourceField.js +276 -0
- plexora/client/src/js/views/imageViewer.js +3306 -0
- plexora/client/src/js/views/miniMap.js +787 -0
- plexora/client/src/js/views/navbarControls.js +178 -0
- plexora/client/src/js/views/openProjectPage.js +239 -0
- plexora/client/src/js/views/projectEdit.js +335 -0
- plexora/client/src/js/views/quickViewLanding.js +136 -0
- plexora/client/src/js/views/rainbow.js +326 -0
- plexora/client/src/js/views/requirementsModal.js +572 -0
- plexora/client/src/js/views/rgbImageViewer.js +115 -0
- plexora/client/src/js/views/searchableSelect.js +411 -0
- plexora/client/src/js/views/segmentationProgress.js +122 -0
- plexora/client/src/js/views/toolLoader.js +747 -0
- plexora/client/src/js/views/viewerControls.js +689 -0
- plexora/client/src/js/views/viewerManager.js +434 -0
- plexora/client/src/js/views/viewerSidebar.js +1117 -0
- plexora/client/src/js/workers/tileDecoder.js +130 -0
- plexora/client/src/shaders/frag.glsl +528 -0
- plexora/client/src/shaders/vert.glsl +12 -0
- plexora/client/templates/base.html +212 -0
- plexora/client/templates/index.html +238 -0
- plexora/client/templates/open_project.html +96 -0
- plexora/client/templates/project_columns.html +86 -0
- plexora/client/templates/project_edit.html +196 -0
- plexora/client/templates/upload.html +118 -0
- plexora/connect.py +528 -0
- plexora/datasource.py +782 -0
- plexora/jupyter.py +406 -0
- plexora/notebook_env.py +232 -0
- plexora/paths.py +486 -0
- plexora/plugins/__init__.py +12 -0
- plexora/plugins/cell_explorer/__init__.py +100 -0
- plexora/plugins/cell_explorer/server/__init__.py +11 -0
- plexora/plugins/cell_explorer/server/routes.py +167 -0
- plexora/plugins/cell_explorer/server/state.py +281 -0
- plexora/plugins/cell_explorer/server/values.py +145 -0
- plexora/plugins/cell_explorer/server/variables.py +367 -0
- plexora/plugins/cell_explorer/static/cellExplorerApi.js +158 -0
- plexora/plugins/cell_explorer/static/cellExplorerColors.js +316 -0
- plexora/plugins/cell_explorer/static/cellExplorerContinuous.js +403 -0
- plexora/plugins/cell_explorer/static/cellExplorerFigureBridge.js +133 -0
- plexora/plugins/cell_explorer/static/cellExplorerLegend.js +188 -0
- plexora/plugins/cell_explorer/static/cellExplorerRoiBridge.js +822 -0
- plexora/plugins/cell_explorer/static/cellExplorerSidebarController.js +826 -0
- plexora/plugins/cell_explorer/static/cellExplorerState.js +372 -0
- plexora/plugins/cell_explorer/static/cell_explorer.css +752 -0
- plexora/plugins/cell_explorer/templates/cell_explorer/panel.html +137 -0
- plexora/plugins/figure_builder/__init__.py +125 -0
- plexora/plugins/figure_builder/server/__init__.py +7 -0
- plexora/plugins/figure_builder/server/compose.py +365 -0
- plexora/plugins/figure_builder/server/export.py +784 -0
- plexora/plugins/figure_builder/server/export_jobs.py +148 -0
- plexora/plugins/figure_builder/server/operations.py +556 -0
- plexora/plugins/figure_builder/server/pixels.py +142 -0
- plexora/plugins/figure_builder/server/provenance.py +174 -0
- plexora/plugins/figure_builder/server/render.py +278 -0
- plexora/plugins/figure_builder/server/repository.py +701 -0
- plexora/plugins/figure_builder/server/routes.py +594 -0
- plexora/plugins/figure_builder/server/schema.py +1023 -0
- plexora/plugins/figure_builder/server/sources.py +120 -0
- plexora/plugins/figure_builder/server/textmetrics.py +155 -0
- plexora/plugins/figure_builder/static/figureActions.js +363 -0
- plexora/plugins/figure_builder/static/figureBuilderApi.js +255 -0
- plexora/plugins/figure_builder/static/figureCanvas.js +2362 -0
- plexora/plugins/figure_builder/static/figureCaptureBoxes.js +369 -0
- plexora/plugins/figure_builder/static/figureCaptureDock.js +466 -0
- plexora/plugins/figure_builder/static/figureCaptureTool.js +1034 -0
- plexora/plugins/figure_builder/static/figureConfirm.js +136 -0
- plexora/plugins/figure_builder/static/figureContextBar.js +1193 -0
- plexora/plugins/figure_builder/static/figureContextMenu.js +253 -0
- plexora/plugins/figure_builder/static/figureDocumentState.js +275 -0
- plexora/plugins/figure_builder/static/figureExportUi.js +174 -0
- plexora/plugins/figure_builder/static/figureLibrary.js +247 -0
- plexora/plugins/figure_builder/static/figureQuickEdit.js +628 -0
- plexora/plugins/figure_builder/static/figureRichText.js +634 -0
- plexora/plugins/figure_builder/static/figureSceneSnapshot.js +361 -0
- plexora/plugins/figure_builder/static/figureSchema.js +218 -0
- plexora/plugins/figure_builder/static/figureSidebarController.js +1159 -0
- plexora/plugins/figure_builder/static/figureTextEditor.js +503 -0
- plexora/plugins/figure_builder/static/figureTextPanel.js +491 -0
- plexora/plugins/figure_builder/static/figureViewOptions.js +273 -0
- plexora/plugins/figure_builder/static/figureWorkspace.js +2030 -0
- plexora/plugins/figure_builder/static/figure_builder.css +3292 -0
- plexora/plugins/figure_builder/templates/figure_builder/library.html +74 -0
- plexora/plugins/figure_builder/templates/figure_builder/workspace.html +27 -0
- plexora/plugins/figure_builder/templates/figure_builder/workspace_body.html +458 -0
- plexora/plugins/gating/__init__.py +76 -0
- plexora/plugins/gating/server/__init__.py +0 -0
- plexora/plugins/gating/server/anndata_gates.py +367 -0
- plexora/plugins/gating/server/database.py +16 -0
- plexora/plugins/gating/server/model.py +320 -0
- plexora/plugins/gating/server/routes.py +235 -0
- plexora/plugins/gating/static/csvGatingList.js +947 -0
- plexora/plugins/gating/static/gating.css +289 -0
- plexora/plugins/gating/static/gatingApi.js +221 -0
- plexora/plugins/gating/static/gatingSidebarController.js +513 -0
- plexora/plugins/gating/templates/gating/legacy.html +26 -0
- plexora/plugins/gating/templates/gating/panel.html +69 -0
- plexora/plugins/roi/__init__.py +95 -0
- plexora/plugins/roi/server/__init__.py +8 -0
- plexora/plugins/roi/server/adapters.py +655 -0
- plexora/plugins/roi/server/geojson.py +267 -0
- plexora/plugins/roi/server/geometry.py +181 -0
- plexora/plugins/roi/server/mapping.py +169 -0
- plexora/plugins/roi/server/operations.py +293 -0
- plexora/plugins/roi/server/repository.py +215 -0
- plexora/plugins/roi/server/routes.py +409 -0
- plexora/plugins/roi/server/schema.py +323 -0
- plexora/plugins/roi/static/roi.css +583 -0
- plexora/plugins/roi/static/roiApi.js +177 -0
- plexora/plugins/roi/static/roiFigureBridge.js +107 -0
- plexora/plugins/roi/static/roiGeometry.js +350 -0
- plexora/plugins/roi/static/roiRenderer.js +278 -0
- plexora/plugins/roi/static/roiSidebarController.js +1038 -0
- plexora/plugins/roi/static/roiState.js +518 -0
- plexora/plugins/roi/static/roiTools.js +993 -0
- plexora/plugins/roi/templates/roi/panel.html +240 -0
- plexora/proxy.py +57 -0
- plexora/server/models/adapters/__init__.py +94 -0
- plexora/server/models/adapters/anndata_adapter.py +388 -0
- plexora/server/models/adapters/base.py +93 -0
- plexora/server/models/adapters/classify.py +192 -0
- plexora/server/models/adapters/csv_adapter.py +105 -0
- plexora/server/models/adapters/inspection.py +265 -0
- plexora/server/models/adapters/spatialdata_adapter.py +248 -0
- plexora/server/models/centroid_tiles.py +305 -0
- plexora/server/models/data_model.py +1659 -0
- plexora/server/models/database_model.py +169 -0
- plexora/server/models/project.py +1270 -0
- plexora/server/plugins.py +199 -0
- plexora/server/routes/browse_routes.py +41 -0
- plexora/server/routes/data_routes.py +294 -0
- plexora/server/routes/import_routes.py +603 -0
- plexora/server/routes/page_routes.py +139 -0
- plexora/server/routes/project_routes.py +438 -0
- plexora/server/routes/quick_view_routes.py +62 -0
- plexora/server/routes/system_routes.py +39 -0
- plexora/server/routes/tool_routes.py +418 -0
- plexora/server/utils/addHEColumns.py +11 -0
- plexora/server/utils/fast_png.py +97 -0
- plexora/server/utils/fullConversion.py +50 -0
- plexora/server/utils/native_dialog.py +168 -0
- plexora/server/utils/pre_normalization.py +47 -0
- plexora/server/utils/segmentation_pyramid.py +598 -0
- plexora/server/utils/smallestenclosingcircle.py +126 -0
- plexora/server/utils/tiffsurgeon.py +372 -0
- plexora/server_cli.py +48 -0
- plexora/test.py +0 -0
- plexora-0.0.1.dist-info/METADATA +341 -0
- plexora-0.0.1.dist-info/RECORD +248 -0
- plexora-0.0.1.dist-info/WHEEL +5 -0
- plexora-0.0.1.dist-info/entry_points.txt +12 -0
- plexora-0.0.1.dist-info/licenses/LICENSE +207 -0
- plexora-0.0.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,1270 @@
|
|
|
1
|
+
"""The project record: one typed view of one config.json entry.
|
|
2
|
+
|
|
3
|
+
A project used to be a bare dict written by four different functions with four
|
|
4
|
+
slightly different key sets, and read by everything. The keys drifted: roles
|
|
5
|
+
shared a dict with file paths and processing flags (`featureData[0]`), only
|
|
6
|
+
element `[0]` of that list was ever used, `has_feature_data` duplicated a fact
|
|
7
|
+
already implied by whether there was a table at all, and `image_id` was declared
|
|
8
|
+
in the plugin contract but written by nobody.
|
|
9
|
+
|
|
10
|
+
This module is the one place that knows the on-disk shape. Everything else asks
|
|
11
|
+
it questions -- `project.dataset.roles.x`, `project.has_table` -- so adding a
|
|
12
|
+
field is a change here rather than a search across the tree.
|
|
13
|
+
|
|
14
|
+
Two rules make it safe to write through:
|
|
15
|
+
|
|
16
|
+
**Unknown keys survive.** Anything this module does not model lands in `extra`
|
|
17
|
+
and is written back verbatim. A save can therefore never silently drop a key it
|
|
18
|
+
did not know about, which is exactly how editing an AnnData project used to
|
|
19
|
+
destroy it (the old save rebuilt the entry from `{}` and lost `data_type` and
|
|
20
|
+
the read spec).
|
|
21
|
+
|
|
22
|
+
**Changes go through `patch()`.** It merges. There is deliberately no API for
|
|
23
|
+
replacing an entry wholesale.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import json
|
|
29
|
+
import os
|
|
30
|
+
import threading
|
|
31
|
+
import time
|
|
32
|
+
from contextlib import contextmanager
|
|
33
|
+
from dataclasses import dataclass, field, replace
|
|
34
|
+
from pathlib import Path
|
|
35
|
+
from typing import Any, Iterable, Mapping
|
|
36
|
+
|
|
37
|
+
from plexora import paths
|
|
38
|
+
|
|
39
|
+
#: Serializes read-modify-write of config.json within the process. Needed
|
|
40
|
+
#: because the segmentation job patches the same file from a background thread
|
|
41
|
+
#: while a request may be saving an edit -- without this, whichever wrote last
|
|
42
|
+
#: silently discarded the other's change. Re-entrant so `mutate()` can hold it
|
|
43
|
+
#: across a load/save pair that each take it again.
|
|
44
|
+
_CONFIG_LOCK = threading.RLock()
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@contextmanager
|
|
48
|
+
def config_transaction():
|
|
49
|
+
"""Hold the config write lock across several operations.
|
|
50
|
+
|
|
51
|
+
Use it when a decision depends on what is already stored -- `mutate()` is
|
|
52
|
+
this plus a load and a save, and is what most callers want.
|
|
53
|
+
"""
|
|
54
|
+
with _CONFIG_LOCK:
|
|
55
|
+
yield
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def read_config(path) -> dict:
|
|
59
|
+
"""Read the whole of config.json, or {} if there isn't one yet.
|
|
60
|
+
|
|
61
|
+
Every reader in the process goes through this, so that no read can land in
|
|
62
|
+
the middle of a write. Reading the file directly is what produced
|
|
63
|
+
"Expecting value: line 1 column 1 (char 0)" during an import: the reader
|
|
64
|
+
caught a truncated file while another thread was rewriting it.
|
|
65
|
+
"""
|
|
66
|
+
path = Path(path)
|
|
67
|
+
with _CONFIG_LOCK:
|
|
68
|
+
if not path.exists():
|
|
69
|
+
return {}
|
|
70
|
+
text = _past_transient_locks(lambda: path.read_text(encoding="utf-8"))
|
|
71
|
+
# A zero-byte config is "no projects", not a parse error. It can only come
|
|
72
|
+
# from a crash or from a version of this code that wrote in place, and
|
|
73
|
+
# treating it as {} loses nothing that is still on disk.
|
|
74
|
+
if not text.strip():
|
|
75
|
+
return {}
|
|
76
|
+
return json.loads(text) or {}
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def write_config(path, config) -> None:
|
|
80
|
+
"""Replace config.json in one step.
|
|
81
|
+
|
|
82
|
+
The new copy is written to a sibling temp file and renamed over the old
|
|
83
|
+
one, so a concurrent reader sees either the whole previous file or the
|
|
84
|
+
whole new one -- never the empty window that `open(path, "w")` opens for as
|
|
85
|
+
long as it takes to serialize a few hundred KB. The lock keeps writers off
|
|
86
|
+
each other; the rename is what protects readers in other processes (a
|
|
87
|
+
notebook sidecar and a CLI server can share one data directory).
|
|
88
|
+
"""
|
|
89
|
+
path = Path(path)
|
|
90
|
+
with _CONFIG_LOCK:
|
|
91
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
92
|
+
tmp = path.with_name(f"{path.name}.{os.getpid()}.tmp")
|
|
93
|
+
try:
|
|
94
|
+
with tmp.open("w", encoding="utf-8") as handle:
|
|
95
|
+
json.dump(config, handle, indent=4)
|
|
96
|
+
handle.flush()
|
|
97
|
+
os.fsync(handle.fileno())
|
|
98
|
+
_past_transient_locks(lambda: os.replace(tmp, path))
|
|
99
|
+
finally:
|
|
100
|
+
# Nothing to remove on the happy path -- the rename consumed it.
|
|
101
|
+
tmp.unlink(missing_ok=True)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _past_transient_locks(action, attempts: int = 100, delay: float = 0.02):
|
|
105
|
+
"""Run a file operation, retrying past Windows' brief sharing violations.
|
|
106
|
+
|
|
107
|
+
Windows refuses to replace a file another process has open, and refuses to
|
|
108
|
+
open one that is being replaced -- and unlike POSIX there is no way to ask
|
|
109
|
+
to be let through. Both windows are one rename long, so a short retry turns
|
|
110
|
+
a hard failure into a wait. This only matters between processes (a notebook
|
|
111
|
+
sidecar and a CLI server sharing a data directory); readers and writers in
|
|
112
|
+
one process are already serialized by the lock. Giving up re-raises rather
|
|
113
|
+
than leaving the caller with a half-truth.
|
|
114
|
+
|
|
115
|
+
Two seconds of budget, not the 400 ms this started with: the thing holding
|
|
116
|
+
the handle is often not another Plexora process at all but a scanner --
|
|
117
|
+
Defender, or a sync client walking a data directory that lives in Dropbox --
|
|
118
|
+
and those hold on for longer than one rename. The cost is paid only when a
|
|
119
|
+
write is genuinely blocked, and losing a project record is far worse than
|
|
120
|
+
waiting.
|
|
121
|
+
"""
|
|
122
|
+
for attempt in range(attempts):
|
|
123
|
+
try:
|
|
124
|
+
return action()
|
|
125
|
+
except PermissionError:
|
|
126
|
+
if attempt == attempts - 1:
|
|
127
|
+
raise
|
|
128
|
+
time.sleep(delay)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
#: Column roles the core records centrally. A plugin names these, never a
|
|
132
|
+
#: literal column name -- see plexora/api/dataset.py.
|
|
133
|
+
ROLE_NAMES = ("cell_id", "x", "y", "image_id", "celltype")
|
|
134
|
+
|
|
135
|
+
#: Human labels for the roles, used by the requirements modal and the edit page
|
|
136
|
+
#: so the wording is identical wherever a role is asked for.
|
|
137
|
+
ROLE_LABELS = {
|
|
138
|
+
"cell_id": "Cell ID column",
|
|
139
|
+
"x": "X coordinate column",
|
|
140
|
+
"y": "Y coordinate column",
|
|
141
|
+
"image_id": "Image ID column",
|
|
142
|
+
"celltype": "Cell type column",
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
#: The roles the CSV import screen confirms, in ask order.
|
|
146
|
+
#:
|
|
147
|
+
#: Every one of these decides how the table is *read*: which column identifies
|
|
148
|
+
#: a cell, where the cell sits, and which image it belongs to. The user is
|
|
149
|
+
#: already looking at the columns there, so confirming them costs nothing.
|
|
150
|
+
#:
|
|
151
|
+
#: `celltype` is deliberately absent. Nothing in core reads it, so asking at
|
|
152
|
+
#: import puts a question in front of every user for the benefit of whichever
|
|
153
|
+
#: plugin might eventually want an annotation column -- and a plugin that does
|
|
154
|
+
#: want one declares it (`Requires(roles=("celltype",))`) and gets asked
|
|
155
|
+
#: through the requirements modal at the moment it matters. The edit page still
|
|
156
|
+
#: offers every role, because that is an editor rather than a checkpoint.
|
|
157
|
+
IMPORT_ROLES = ("cell_id", "x", "y", "image_id")
|
|
158
|
+
|
|
159
|
+
#: Feature-table formats. The key doubles as the adapter registry key
|
|
160
|
+
#: (server/models/adapters/__init__.py).
|
|
161
|
+
DATA_TYPES = ("csv", "anndata", "spatialdata")
|
|
162
|
+
|
|
163
|
+
#: How per-cell results are drawn over the image, best first. A segmentation
|
|
164
|
+
#: mask shows the real cell shape and is preferred whenever one exists;
|
|
165
|
+
#: centroids are the fallback for a project that has coordinates but no mask.
|
|
166
|
+
#:
|
|
167
|
+
#: The order is the default: `Project.cell_layer` resolves to the first option
|
|
168
|
+
#: the project can actually draw, and the stored value only ever records a user
|
|
169
|
+
#: overriding that on the edit page. This used to be a question the host asked
|
|
170
|
+
#: before a cell-drawing tool could open, on the grounds that both look
|
|
171
|
+
#: plausible on screen -- but a user who supplied a mask wants the mask, and
|
|
172
|
+
#: making them say so before Thresholding would open was a dialog with a
|
|
173
|
+
#: foregone conclusion.
|
|
174
|
+
CELL_LAYERS = ("segmentation", "centroids")
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _clean(mapping):
|
|
178
|
+
"""Drop None values so an absent role is absent from the JSON rather than
|
|
179
|
+
stored as an explicit null -- keeps hand-inspected config files readable."""
|
|
180
|
+
return {k: v for k, v in (mapping or {}).items() if v is not None}
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
@dataclass(frozen=True)
|
|
184
|
+
class ColumnRoles:
|
|
185
|
+
"""Role -> column name. A None role is not an error; it is information that
|
|
186
|
+
has not been collected yet, and something may ask for it later."""
|
|
187
|
+
|
|
188
|
+
cell_id: str | None = None
|
|
189
|
+
x: str | None = None
|
|
190
|
+
y: str | None = None
|
|
191
|
+
image_id: str | None = None
|
|
192
|
+
celltype: str | None = None
|
|
193
|
+
|
|
194
|
+
@classmethod
|
|
195
|
+
def from_dict(cls, raw: Mapping[str, Any] | None) -> "ColumnRoles":
|
|
196
|
+
raw = raw or {}
|
|
197
|
+
return cls(**{role: raw.get(role) or None for role in ROLE_NAMES})
|
|
198
|
+
|
|
199
|
+
def to_dict(self) -> dict:
|
|
200
|
+
return _clean({role: getattr(self, role) for role in ROLE_NAMES})
|
|
201
|
+
|
|
202
|
+
def get(self, role: str) -> str | None:
|
|
203
|
+
if role not in ROLE_NAMES:
|
|
204
|
+
raise KeyError(f"Unknown column role: {role!r}")
|
|
205
|
+
return getattr(self, role)
|
|
206
|
+
|
|
207
|
+
def missing(self, roles: Iterable[str]) -> list[str]:
|
|
208
|
+
"""Which of `roles` have no column assigned, in the order given."""
|
|
209
|
+
return [role for role in roles if not self.get(role)]
|
|
210
|
+
|
|
211
|
+
def with_values(self, values: Mapping[str, Any]) -> "ColumnRoles":
|
|
212
|
+
"""Copy with `values` applied. An empty string clears a role, which is
|
|
213
|
+
how the edit form expresses "unset this"; an absent key leaves it be."""
|
|
214
|
+
changes = {}
|
|
215
|
+
for role, value in (values or {}).items():
|
|
216
|
+
if role not in ROLE_NAMES:
|
|
217
|
+
continue
|
|
218
|
+
changes[role] = (value or None) if isinstance(value, str) else None
|
|
219
|
+
return replace(self, **changes)
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
@dataclass(frozen=True)
|
|
223
|
+
class ColumnGroups:
|
|
224
|
+
"""The marker/metadata split for this dataset.
|
|
225
|
+
|
|
226
|
+
A property of the imported data, not of any one plugin, so it is stored
|
|
227
|
+
centrally and every plugin reads the same answer. Empty means nobody has
|
|
228
|
+
classified the columns yet.
|
|
229
|
+
"""
|
|
230
|
+
|
|
231
|
+
markers: tuple[str, ...] = ()
|
|
232
|
+
metadata: tuple[str, ...] = ()
|
|
233
|
+
|
|
234
|
+
@classmethod
|
|
235
|
+
def from_dict(cls, raw: Mapping[str, Any] | None) -> "ColumnGroups":
|
|
236
|
+
raw = raw or {}
|
|
237
|
+
return cls(
|
|
238
|
+
markers=tuple(raw.get("markers") or ()),
|
|
239
|
+
metadata=tuple(raw.get("metadata") or ()),
|
|
240
|
+
)
|
|
241
|
+
|
|
242
|
+
def to_dict(self) -> dict:
|
|
243
|
+
return {"markers": list(self.markers), "metadata": list(self.metadata)}
|
|
244
|
+
|
|
245
|
+
@property
|
|
246
|
+
def classified(self) -> bool:
|
|
247
|
+
"""Whether the split has been established. Metadata alone does not
|
|
248
|
+
count: a table with no markers has nothing to threshold or plot, and
|
|
249
|
+
treating that as classified would let a marker-hungry plugin open onto
|
|
250
|
+
an empty panel."""
|
|
251
|
+
return bool(self.markers)
|
|
252
|
+
|
|
253
|
+
@property
|
|
254
|
+
def all(self) -> tuple[str, ...]:
|
|
255
|
+
return tuple(self.markers) + tuple(self.metadata)
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
@dataclass(frozen=True)
|
|
259
|
+
class DataSpec:
|
|
260
|
+
"""The feature table: where it is, how to read it, and what its columns mean.
|
|
261
|
+
|
|
262
|
+
`coordinates`/`features`/`subset` are the AnnData/SpatialData read spec and
|
|
263
|
+
stay opaque here -- the adapters own their shape. Everything else is
|
|
264
|
+
format-independent.
|
|
265
|
+
"""
|
|
266
|
+
|
|
267
|
+
type: str
|
|
268
|
+
src: str
|
|
269
|
+
table: str | None = None
|
|
270
|
+
coordinates: Mapping[str, Any] = field(default_factory=dict)
|
|
271
|
+
features: Mapping[str, Any] = field(default_factory=dict)
|
|
272
|
+
subset: Mapping[str, Any] = field(default_factory=dict)
|
|
273
|
+
#: AnnData/SpatialData only: which obs column supplies the cell identifier,
|
|
274
|
+
#: or None to use the positional row index.
|
|
275
|
+
#:
|
|
276
|
+
#: This looks like a duplicate of `roles.cell_id` and is not. The role
|
|
277
|
+
#: names a column in the table that comes OUT of the adapter; this names an
|
|
278
|
+
#: input to it. They usually hold the same string, but None here means
|
|
279
|
+
#: "number the rows", which is a different instruction from the role naming
|
|
280
|
+
#: a column that happens to be called "id" -- and real exemplar data does
|
|
281
|
+
#: have an obs column literally named "id". Collapsing the two turned the
|
|
282
|
+
#: adapter's "that name is reserved" error into a silent fallback to
|
|
283
|
+
#: positional ids, quietly ignoring the column the user picked.
|
|
284
|
+
obs_id_field: str | None = None
|
|
285
|
+
normalization: str = "none"
|
|
286
|
+
is_transformed: bool = False
|
|
287
|
+
celltype_data: str | None = None
|
|
288
|
+
roles: ColumnRoles = field(default_factory=ColumnRoles)
|
|
289
|
+
columns: ColumnGroups = field(default_factory=ColumnGroups)
|
|
290
|
+
#: AnnData/SpatialData only: the source file's `obs` column names, exactly
|
|
291
|
+
#: as the file carries them and in its own order.
|
|
292
|
+
#:
|
|
293
|
+
#: Recorded because it is the vocabulary the role questions are asked in
|
|
294
|
+
#: for these formats. `columns.metadata` is not: the adapter builds the
|
|
295
|
+
#: table from a read spec and emits four columns (`id`, `X`, `Y`, the id
|
|
296
|
+
#: field) plus the markers, so offering that list asked the user to choose
|
|
297
|
+
#: which of Plexora's own synthesized columns holds the cell id -- a
|
|
298
|
+
#: question with only one possible answer, and never the one they wanted.
|
|
299
|
+
obs_columns: tuple[str, ...] = ()
|
|
300
|
+
#: AnnData/SpatialData only: the extra expression matrices the source file
|
|
301
|
+
#: carries alongside `X`. Recorded for the same reason as `obs_columns` --
|
|
302
|
+
#: it is what the user picks between when saying which matrix holds the
|
|
303
|
+
#: marker intensities, and re-reading the file to find out would mean
|
|
304
|
+
#: opening it every time the edit page loads.
|
|
305
|
+
layers: tuple[str, ...] = ()
|
|
306
|
+
#: AnnData/SpatialData only: the source file's `obsm` arrays, as
|
|
307
|
+
#: {"name": str, "shape": [int, ...]}. Recorded for the same reason as
|
|
308
|
+
#: `layers`, and the shape travels with the name because it is the only
|
|
309
|
+
#: thing that distinguishes one candidate from another: a store commonly
|
|
310
|
+
#: carries `spatial` and `X_umap` with identical (n, 2) float32 shapes, so
|
|
311
|
+
#: the user picking between them needs to see both listed rather than have
|
|
312
|
+
#: one chosen for them by name.
|
|
313
|
+
obsm: tuple[Mapping[str, Any], ...] = ()
|
|
314
|
+
#: The user's explicit answer that this table covers exactly one image, as
|
|
315
|
+
#: opposed to simply having no image-id column recorded.
|
|
316
|
+
#:
|
|
317
|
+
#: A separate field rather than a blank `roles.image_id`, because those are
|
|
318
|
+
#: different states: "I looked and there is one image" is an answer, while
|
|
319
|
+
#: an absent role is a question nobody has put. Whether a table spans
|
|
320
|
+
#: several images cannot be told from the data -- deciding it needs to know
|
|
321
|
+
#: WHICH column is the image id, which is the very thing being asked -- so
|
|
322
|
+
#: it is asked rather than inferred from a column-name heuristic.
|
|
323
|
+
single_image: bool = False
|
|
324
|
+
#: The user's explicit answer that no obs column holds the cell identifier,
|
|
325
|
+
#: so the rows are numbered instead.
|
|
326
|
+
#:
|
|
327
|
+
#: The same distinction `single_image` draws, for the same reason. An unset
|
|
328
|
+
#: `obs_id_field` cannot carry it: that is also the state of a project
|
|
329
|
+
#: nobody has asked yet, and the importer leaves it unset on every AnnData
|
|
330
|
+
#: and SpatialData it registers. Without somewhere to record the answer,
|
|
331
|
+
#: "number the rows" could only be said by leaving the question blank -- and
|
|
332
|
+
#: a blank that satisfies a requirement is indistinguishable from a default
|
|
333
|
+
#: that was never looked at, which is how a project came to keep a
|
|
334
|
+
#: positional cell id while its mask was labelled by an obs column.
|
|
335
|
+
row_number_ids: bool = False
|
|
336
|
+
|
|
337
|
+
@classmethod
|
|
338
|
+
def from_dict(cls, raw: Mapping[str, Any] | None) -> "DataSpec | None":
|
|
339
|
+
if not raw or not raw.get("src"):
|
|
340
|
+
return None
|
|
341
|
+
return cls(
|
|
342
|
+
type=raw.get("type") or "csv",
|
|
343
|
+
src=raw["src"],
|
|
344
|
+
table=raw.get("table") or None,
|
|
345
|
+
coordinates=dict(raw.get("coordinates") or {}),
|
|
346
|
+
features=dict(raw.get("features") or {}),
|
|
347
|
+
subset=dict(raw.get("subset") or {}),
|
|
348
|
+
obs_id_field=raw.get("obsIdField") or None,
|
|
349
|
+
normalization=raw.get("normalization") or "none",
|
|
350
|
+
is_transformed=bool(raw.get("isTransformed")),
|
|
351
|
+
celltype_data=raw.get("celltypeData") or None,
|
|
352
|
+
roles=ColumnRoles.from_dict(raw.get("roles")),
|
|
353
|
+
columns=ColumnGroups.from_dict(raw.get("columns")),
|
|
354
|
+
obs_columns=tuple(raw.get("obsColumns") or ()),
|
|
355
|
+
layers=tuple(raw.get("layers") or ()),
|
|
356
|
+
obsm=tuple(dict(entry) for entry in (raw.get("obsm") or ())),
|
|
357
|
+
single_image=bool(raw.get("singleImage")),
|
|
358
|
+
row_number_ids=bool(raw.get("rowNumberIds")),
|
|
359
|
+
)
|
|
360
|
+
|
|
361
|
+
def to_dict(self) -> dict:
|
|
362
|
+
out = {
|
|
363
|
+
"type": self.type,
|
|
364
|
+
"src": self.src,
|
|
365
|
+
"normalization": self.normalization,
|
|
366
|
+
"isTransformed": self.is_transformed,
|
|
367
|
+
"roles": self.roles.to_dict(),
|
|
368
|
+
"columns": self.columns.to_dict(),
|
|
369
|
+
}
|
|
370
|
+
if self.table:
|
|
371
|
+
out["table"] = self.table
|
|
372
|
+
if self.coordinates:
|
|
373
|
+
out["coordinates"] = dict(self.coordinates)
|
|
374
|
+
if self.features:
|
|
375
|
+
out["features"] = dict(self.features)
|
|
376
|
+
if self.subset:
|
|
377
|
+
out["subset"] = dict(self.subset)
|
|
378
|
+
if self.obs_id_field:
|
|
379
|
+
out["obsIdField"] = self.obs_id_field
|
|
380
|
+
if self.celltype_data:
|
|
381
|
+
out["celltypeData"] = self.celltype_data
|
|
382
|
+
if self.obs_columns:
|
|
383
|
+
out["obsColumns"] = list(self.obs_columns)
|
|
384
|
+
if self.layers:
|
|
385
|
+
out["layers"] = list(self.layers)
|
|
386
|
+
if self.obsm:
|
|
387
|
+
out["obsm"] = [dict(entry) for entry in self.obsm]
|
|
388
|
+
if self.single_image:
|
|
389
|
+
out["singleImage"] = True
|
|
390
|
+
if self.row_number_ids:
|
|
391
|
+
out["rowNumberIds"] = True
|
|
392
|
+
return out
|
|
393
|
+
|
|
394
|
+
@property
|
|
395
|
+
def path(self) -> Path:
|
|
396
|
+
return Path(self.src)
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
@dataclass(frozen=True)
|
|
400
|
+
class ImageSpec:
|
|
401
|
+
"""The one input every project has.
|
|
402
|
+
|
|
403
|
+
`channels` keeps the stored `imageData` shape ({name, fullname, src}) --
|
|
404
|
+
the viewer's tile path indexes it directly and is deliberately untouched by
|
|
405
|
+
this refactor.
|
|
406
|
+
"""
|
|
407
|
+
|
|
408
|
+
src: str | None = None
|
|
409
|
+
kind: str = "ome_tiff"
|
|
410
|
+
channels: tuple[Mapping[str, Any], ...] = ()
|
|
411
|
+
width: int | None = None
|
|
412
|
+
height: int | None = None
|
|
413
|
+
max_level: int | None = None
|
|
414
|
+
tile_width: int | None = None
|
|
415
|
+
tile_height: int | None = None
|
|
416
|
+
num_channels: int | None = None
|
|
417
|
+
|
|
418
|
+
@classmethod
|
|
419
|
+
def from_entry(cls, entry: Mapping[str, Any]) -> "ImageSpec":
|
|
420
|
+
return cls(
|
|
421
|
+
src=entry.get("channelFile"),
|
|
422
|
+
kind=entry.get("image_kind") or "ome_tiff",
|
|
423
|
+
channels=tuple(entry.get("imageData") or ()),
|
|
424
|
+
width=entry.get("width"),
|
|
425
|
+
height=entry.get("height"),
|
|
426
|
+
max_level=entry.get("maxLevel"),
|
|
427
|
+
tile_width=entry.get("tileWidth"),
|
|
428
|
+
tile_height=entry.get("tileHeight"),
|
|
429
|
+
num_channels=entry.get("num_channels"),
|
|
430
|
+
)
|
|
431
|
+
|
|
432
|
+
def to_entry(self) -> dict:
|
|
433
|
+
return _clean({
|
|
434
|
+
"channelFile": self.src,
|
|
435
|
+
"image_kind": self.kind,
|
|
436
|
+
"imageData": list(self.channels),
|
|
437
|
+
"width": self.width,
|
|
438
|
+
"height": self.height,
|
|
439
|
+
"maxLevel": self.max_level,
|
|
440
|
+
"tileWidth": self.tile_width,
|
|
441
|
+
"tileHeight": self.tile_height,
|
|
442
|
+
"num_channels": self.num_channels,
|
|
443
|
+
})
|
|
444
|
+
|
|
445
|
+
@property
|
|
446
|
+
def real_channels(self) -> list[Mapping[str, Any]]:
|
|
447
|
+
"""Image channels, excluding the 'Area' placeholder that only exists
|
|
448
|
+
when segmentation was registered."""
|
|
449
|
+
return [c for c in self.channels if c.get("fullname") != "Area"]
|
|
450
|
+
|
|
451
|
+
@property
|
|
452
|
+
def channel_names(self) -> list[str]:
|
|
453
|
+
return [c["fullname"] for c in self.real_channels]
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
@dataclass(frozen=True)
|
|
457
|
+
class SegmentationSpec:
|
|
458
|
+
"""The mask, when there is one.
|
|
459
|
+
|
|
460
|
+
`derived` is the pyramid Plexora serves; `source`/`source_key` fingerprint
|
|
461
|
+
the user's original so a later load can confirm the derived file is still
|
|
462
|
+
current with a stat instead of rebuilding it.
|
|
463
|
+
"""
|
|
464
|
+
|
|
465
|
+
derived: str | None = None
|
|
466
|
+
source: str | None = None
|
|
467
|
+
source_key: str | None = None
|
|
468
|
+
mode: str | None = None
|
|
469
|
+
status: str = "ready"
|
|
470
|
+
|
|
471
|
+
@classmethod
|
|
472
|
+
def from_entry(cls, entry: Mapping[str, Any]) -> "SegmentationSpec":
|
|
473
|
+
return cls(
|
|
474
|
+
derived=entry.get("segmentation") or None,
|
|
475
|
+
source=entry.get("segmentationSource") or None,
|
|
476
|
+
source_key=entry.get("segmentationSourceKey") or None,
|
|
477
|
+
mode=entry.get("segmentationMode") or None,
|
|
478
|
+
status=entry.get("segmentation_status") or "ready",
|
|
479
|
+
)
|
|
480
|
+
|
|
481
|
+
def to_entry(self) -> dict:
|
|
482
|
+
out = {"segmentation": self.derived, "segmentation_status": self.status}
|
|
483
|
+
out.update(_clean({
|
|
484
|
+
"segmentationSource": self.source,
|
|
485
|
+
"segmentationSourceKey": self.source_key,
|
|
486
|
+
"segmentationMode": self.mode,
|
|
487
|
+
}))
|
|
488
|
+
return out
|
|
489
|
+
|
|
490
|
+
@property
|
|
491
|
+
def available(self) -> bool:
|
|
492
|
+
"""A mask the viewer can serve right now. A pending job has a source but
|
|
493
|
+
no derived pyramid yet, so this is False until it lands."""
|
|
494
|
+
return bool(self.derived)
|
|
495
|
+
|
|
496
|
+
@property
|
|
497
|
+
def pending(self) -> bool:
|
|
498
|
+
return self.status == "pending"
|
|
499
|
+
|
|
500
|
+
@property
|
|
501
|
+
def requested(self) -> bool:
|
|
502
|
+
"""The user has supplied a mask, whether or not it is servable yet."""
|
|
503
|
+
return bool(self.derived or self.source)
|
|
504
|
+
|
|
505
|
+
|
|
506
|
+
#: Keys ImageSpec, SegmentationSpec and the Project itself own. Anything else
|
|
507
|
+
#: in an entry is unmodelled and round-trips through `extra`.
|
|
508
|
+
_MODELLED_KEYS = frozenset({
|
|
509
|
+
"channelFile", "image_kind", "imageData", "width", "height", "maxLevel",
|
|
510
|
+
"tileWidth", "tileHeight", "num_channels",
|
|
511
|
+
"segmentation", "segmentation_status", "segmentationSource",
|
|
512
|
+
"segmentationSourceKey", "segmentationMode",
|
|
513
|
+
"dataset", "createdAt", "lastOpenedAt", "cellLayer", "confirmed",
|
|
514
|
+
})
|
|
515
|
+
|
|
516
|
+
#: Requirement keys that describe the feature table rather than the project.
|
|
517
|
+
#: Swapping the data file invalidates the answers to these -- the columns they
|
|
518
|
+
#: name may not exist in the new file -- while the mask and the cell-layer
|
|
519
|
+
#: choice are unaffected by it.
|
|
520
|
+
def _is_table_scoped(key: str) -> bool:
|
|
521
|
+
return (key in ("table", "markers", "features", "coordinates")
|
|
522
|
+
or key.startswith("role:"))
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
def _with_coordinate_spec(spec, answer: Mapping[str, Any]):
|
|
526
|
+
"""Validate one coordinate answer and write it onto a DataSpec.
|
|
527
|
+
|
|
528
|
+
Shared by `with_coordinates` and the obs half of `with_role_answers`, so
|
|
529
|
+
the two cannot disagree about what a valid answer is.
|
|
530
|
+
|
|
531
|
+
Validation is against what the file was recorded as carrying. An obsm key
|
|
532
|
+
is only checked when that list is known: a project imported before obsm was
|
|
533
|
+
recorded has an empty list, and refusing every answer because we never
|
|
534
|
+
looked would block the one control that can fix it.
|
|
535
|
+
"""
|
|
536
|
+
answer = dict(answer or {})
|
|
537
|
+
source = answer.get("source")
|
|
538
|
+
if source == "obsm":
|
|
539
|
+
key = (answer.get("obsm_key") or "").strip()
|
|
540
|
+
if not key:
|
|
541
|
+
raise ValueError("Choose which obsm array holds the coordinates.")
|
|
542
|
+
known = [entry.get("name") for entry in spec.obsm]
|
|
543
|
+
if known and key not in known:
|
|
544
|
+
raise ValueError(f"This file has no obsm array named {key!r}.")
|
|
545
|
+
return replace(spec, coordinates={"source": "obsm", "obsm_key": key})
|
|
546
|
+
if source == "obs":
|
|
547
|
+
x = (answer.get("x_column") or "").strip()
|
|
548
|
+
y = (answer.get("y_column") or "").strip()
|
|
549
|
+
if not x or not y:
|
|
550
|
+
raise ValueError("Pick both an X and a Y coordinate column, or neither.")
|
|
551
|
+
known = list(spec.obs_columns)
|
|
552
|
+
missing = [c for c in (x, y) if known and c not in known]
|
|
553
|
+
if missing:
|
|
554
|
+
raise ValueError(f"This file has no obs column named {missing[0]!r}.")
|
|
555
|
+
return replace(spec, coordinates={
|
|
556
|
+
"source": "obs", "x_column": x, "y_column": y})
|
|
557
|
+
raise ValueError("Say whether the coordinates are in obs or obsm.")
|
|
558
|
+
|
|
559
|
+
|
|
560
|
+
#: Written by a requirements modal that could not name the role it was asking
|
|
561
|
+
#: about (Requirement.describe() did not send `role`, so every select posted
|
|
562
|
+
#: under this one key). Its presence in a stored `confirmed` list means the
|
|
563
|
+
#: role answers recorded alongside it were discarded before they reached the
|
|
564
|
+
#: project -- see _repair_confirmed.
|
|
565
|
+
_LOST_ROLE_KEY = "role:undefined"
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
def _repair_confirmed(keys: Iterable[str]) -> tuple[str, ...]:
|
|
569
|
+
"""Drop role confirmations that were recorded without the answer.
|
|
570
|
+
|
|
571
|
+
A project carrying `role:undefined` was set up through the broken modal:
|
|
572
|
+
the user picked columns, the answers were thrown away, and the questions
|
|
573
|
+
were marked answered anyway -- so the project kept its guessed roles and
|
|
574
|
+
nothing would ever ask again. Un-confirming the roles is what puts them
|
|
575
|
+
back in front of the user once, which is the only way the real answer can
|
|
576
|
+
still be given. Every other confirmation is left alone; those keys were
|
|
577
|
+
posted correctly.
|
|
578
|
+
|
|
579
|
+
Done on read so existing configs repair themselves without a migration.
|
|
580
|
+
"""
|
|
581
|
+
keys = tuple(keys or ())
|
|
582
|
+
if _LOST_ROLE_KEY not in keys:
|
|
583
|
+
return keys
|
|
584
|
+
return tuple(k for k in keys if not k.startswith("role:"))
|
|
585
|
+
|
|
586
|
+
|
|
587
|
+
@dataclass(frozen=True)
|
|
588
|
+
class Project:
|
|
589
|
+
"""One registered project."""
|
|
590
|
+
|
|
591
|
+
name: str
|
|
592
|
+
image: ImageSpec = field(default_factory=ImageSpec)
|
|
593
|
+
segmentation: SegmentationSpec = field(default_factory=SegmentationSpec)
|
|
594
|
+
dataset: DataSpec | None = None
|
|
595
|
+
created_at: str | None = None
|
|
596
|
+
last_opened_at: str | None = None
|
|
597
|
+
#: One of CELL_LAYERS when the user has overridden the default on the edit
|
|
598
|
+
#: page, None otherwise. Read `cell_layer` rather than this: that resolves
|
|
599
|
+
#: the default, and it is what every drawing surface wants.
|
|
600
|
+
cell_layer_choice: str | None = None
|
|
601
|
+
#: Requirement keys the user has explicitly answered, as opposed to values
|
|
602
|
+
#: the column predictor guessed. The two are indistinguishable by looking at
|
|
603
|
+
#: the stored value, and they are not the same thing: a guess should be put
|
|
604
|
+
#: in front of the user once, an answer never again.
|
|
605
|
+
confirmed: tuple[str, ...] = ()
|
|
606
|
+
#: Keys this module does not model, preserved verbatim across a save.
|
|
607
|
+
extra: Mapping[str, Any] = field(default_factory=dict)
|
|
608
|
+
#: The root this project's registry entry was read from, and therefore
|
|
609
|
+
#: where its image, mask and feature table live.
|
|
610
|
+
#:
|
|
611
|
+
#: None for a project built in memory rather than loaded -- `save()` then
|
|
612
|
+
#: falls back to the user's own root, which is what the programmatic
|
|
613
|
+
#: registration API in plexora/datasource.py wants.
|
|
614
|
+
#:
|
|
615
|
+
#: Never serialized: it is a fact about where the entry was found, not a
|
|
616
|
+
#: field of the entry, and writing it would freeze one machine's layout
|
|
617
|
+
#: into a file that another machine reads.
|
|
618
|
+
home_root: Path | None = None
|
|
619
|
+
|
|
620
|
+
# -- construction ----------------------------------------------------
|
|
621
|
+
|
|
622
|
+
@classmethod
|
|
623
|
+
def from_entry(cls, name: str, entry: Mapping[str, Any] | None,
|
|
624
|
+
home_root=None) -> "Project":
|
|
625
|
+
entry = entry or {}
|
|
626
|
+
return cls(
|
|
627
|
+
name=name,
|
|
628
|
+
home_root=Path(home_root) if home_root is not None else None,
|
|
629
|
+
image=ImageSpec.from_entry(entry),
|
|
630
|
+
segmentation=SegmentationSpec.from_entry(entry),
|
|
631
|
+
dataset=DataSpec.from_dict(entry.get("dataset")),
|
|
632
|
+
created_at=entry.get("createdAt"),
|
|
633
|
+
last_opened_at=entry.get("lastOpenedAt"),
|
|
634
|
+
cell_layer_choice=(entry.get("cellLayer")
|
|
635
|
+
if entry.get("cellLayer") in CELL_LAYERS else None),
|
|
636
|
+
confirmed=_repair_confirmed(entry.get("confirmed")),
|
|
637
|
+
extra={k: v for k, v in entry.items() if k not in _MODELLED_KEYS},
|
|
638
|
+
)
|
|
639
|
+
|
|
640
|
+
def to_entry(self) -> dict:
|
|
641
|
+
entry = dict(self.extra)
|
|
642
|
+
entry.update(self.image.to_entry())
|
|
643
|
+
entry.update(self.segmentation.to_entry())
|
|
644
|
+
entry.update(_clean({
|
|
645
|
+
"createdAt": self.created_at,
|
|
646
|
+
"lastOpenedAt": self.last_opened_at,
|
|
647
|
+
# The user's override only. Writing the resolved default would
|
|
648
|
+
# freeze today's answer into the file, so a project that later
|
|
649
|
+
# gained a mask would go on drawing centroids.
|
|
650
|
+
"cellLayer": self.cell_layer_choice,
|
|
651
|
+
}))
|
|
652
|
+
if self.confirmed:
|
|
653
|
+
entry["confirmed"] = list(self.confirmed)
|
|
654
|
+
# Written even when None: an explicit null is what says "this project
|
|
655
|
+
# has no feature table", as opposed to an older entry that predates the
|
|
656
|
+
# key. Nothing here has to guess.
|
|
657
|
+
entry["dataset"] = self.dataset.to_dict() if self.dataset else None
|
|
658
|
+
return entry
|
|
659
|
+
|
|
660
|
+
def patch(self, **changes) -> "Project":
|
|
661
|
+
"""Copy with the named fields replaced. Merge semantics: a field not
|
|
662
|
+
named is carried across untouched, `extra` included."""
|
|
663
|
+
return replace(self, **changes)
|
|
664
|
+
|
|
665
|
+
# -- questions everything else asks ----------------------------------
|
|
666
|
+
|
|
667
|
+
@property
|
|
668
|
+
def has_table(self) -> bool:
|
|
669
|
+
return self.dataset is not None
|
|
670
|
+
|
|
671
|
+
@property
|
|
672
|
+
def source_kind(self) -> str | None:
|
|
673
|
+
return self.dataset.type if self.dataset else None
|
|
674
|
+
|
|
675
|
+
@property
|
|
676
|
+
def roles(self) -> ColumnRoles:
|
|
677
|
+
return self.dataset.roles if self.dataset else ColumnRoles()
|
|
678
|
+
|
|
679
|
+
@property
|
|
680
|
+
def columns(self) -> ColumnGroups:
|
|
681
|
+
return self.dataset.columns if self.dataset else ColumnGroups()
|
|
682
|
+
|
|
683
|
+
@property
|
|
684
|
+
def columns_are_structural(self) -> bool:
|
|
685
|
+
"""Whether the marker/metadata split comes from the file's own shape.
|
|
686
|
+
|
|
687
|
+
AnnData and SpatialData draw the line themselves -- `var` is markers,
|
|
688
|
+
`obs` is annotations -- so there is nothing for the user to confirm. A
|
|
689
|
+
CSV header does not, which is the entire reason the classification
|
|
690
|
+
screen exists.
|
|
691
|
+
"""
|
|
692
|
+
return self.source_kind in ("anndata", "spatialdata")
|
|
693
|
+
|
|
694
|
+
def with_roles(self, values: Mapping[str, Any]) -> "Project":
|
|
695
|
+
"""Assign column roles centrally. No-op without a table -- a role names
|
|
696
|
+
a column, and there are no columns until there is one."""
|
|
697
|
+
if not self.dataset:
|
|
698
|
+
return self
|
|
699
|
+
return self.patch(dataset=replace(self.dataset, roles=self.roles.with_values(values)))
|
|
700
|
+
|
|
701
|
+
# -- which matrix the intensities come from ------------------------------
|
|
702
|
+
|
|
703
|
+
@property
|
|
704
|
+
def feature_source(self) -> str:
|
|
705
|
+
"""Which matrix is read, as the picker words it: `"X"` for the main
|
|
706
|
+
matrix, `"layer:<name>"` for one of `adata.layers`.
|
|
707
|
+
|
|
708
|
+
Prefixed rather than bare so a layer that anndata permits to be called
|
|
709
|
+
"X" cannot be confused with the main matrix.
|
|
710
|
+
"""
|
|
711
|
+
layer = (self.dataset.features or {}).get("layer") if self.dataset else None
|
|
712
|
+
return f"layer:{layer}" if layer else "X"
|
|
713
|
+
|
|
714
|
+
@property
|
|
715
|
+
def feature_options(self) -> list[dict]:
|
|
716
|
+
"""Every matrix this file offers, worded for a picker.
|
|
717
|
+
|
|
718
|
+
Empty for a CSV, which has exactly one table of numbers and nothing to
|
|
719
|
+
choose between. For AnnData and SpatialData it is always at least `X`,
|
|
720
|
+
so a file with no layers still gets a one-option list rather than an
|
|
721
|
+
empty one -- the caller decides whether one option is worth a control,
|
|
722
|
+
and the log switch beside it is a real question either way.
|
|
723
|
+
"""
|
|
724
|
+
if not self.dataset or not self.columns_are_structural:
|
|
725
|
+
return []
|
|
726
|
+
return [{"value": "X", "label": "X — the main matrix"}] + [
|
|
727
|
+
{"value": f"layer:{name}", "label": f'layers["{name}"]'}
|
|
728
|
+
for name in self.dataset.layers
|
|
729
|
+
]
|
|
730
|
+
|
|
731
|
+
@property
|
|
732
|
+
def log_transformed(self) -> bool:
|
|
733
|
+
"""Whether the values are log1p'd as they are read."""
|
|
734
|
+
return bool(self.dataset.is_transformed) if self.dataset else False
|
|
735
|
+
|
|
736
|
+
def with_log_transform(self, enabled: bool) -> "Project":
|
|
737
|
+
"""Log1p the matrix on the way in, or stop doing so.
|
|
738
|
+
|
|
739
|
+
Separate from which matrix is read because it composes with it: a file
|
|
740
|
+
may carry raw counts in `X` and nothing else, and thresholding raw
|
|
741
|
+
counts on a linear axis is unreadable. This is the only way to say "the
|
|
742
|
+
values I have are counts" without going back and editing the file.
|
|
743
|
+
"""
|
|
744
|
+
if not self.dataset:
|
|
745
|
+
return self
|
|
746
|
+
return self.patch(dataset=replace(self.dataset, is_transformed=bool(enabled)))
|
|
747
|
+
|
|
748
|
+
def with_layers(self, names: Iterable[str]) -> "Project":
|
|
749
|
+
"""Record which matrices the source file carries.
|
|
750
|
+
|
|
751
|
+
Backfill for a project imported before they were recorded, so the
|
|
752
|
+
choice below can be validated against a real list rather than an empty
|
|
753
|
+
one -- see project_routes._source_layers.
|
|
754
|
+
"""
|
|
755
|
+
if not self.dataset:
|
|
756
|
+
return self
|
|
757
|
+
return self.patch(dataset=replace(self.dataset, layers=tuple(names or ())))
|
|
758
|
+
|
|
759
|
+
def with_obsm(self, entries: Iterable[Mapping[str, Any]]) -> "Project":
|
|
760
|
+
"""Record which obsm arrays the source file carries, and their shapes.
|
|
761
|
+
|
|
762
|
+
Backfill for a project imported before they were recorded, exactly like
|
|
763
|
+
`with_layers` -- and needed for the same reason: without it the one
|
|
764
|
+
control that can correct a project reading its coordinates from the
|
|
765
|
+
wrong array is the one control that has nothing to offer.
|
|
766
|
+
"""
|
|
767
|
+
if not self.dataset:
|
|
768
|
+
return self
|
|
769
|
+
return self.patch(dataset=replace(
|
|
770
|
+
self.dataset, obsm=tuple(dict(entry) for entry in (entries or ()))))
|
|
771
|
+
|
|
772
|
+
def with_feature_source(self, value: str) -> "Project":
|
|
773
|
+
"""Point the reader at a different expression matrix.
|
|
774
|
+
|
|
775
|
+
Worth being able to change after import, not only during it: raw counts
|
|
776
|
+
and a log-transformed copy live side by side in one file, and which one
|
|
777
|
+
was read decides what every marker histogram in the app is a histogram
|
|
778
|
+
of. Getting it wrong is not a cosmetic mistake -- thresholds set against
|
|
779
|
+
raw counts mean nothing on a log-scaled panel.
|
|
780
|
+
"""
|
|
781
|
+
if not self.dataset:
|
|
782
|
+
return self
|
|
783
|
+
value = (value or "").strip()
|
|
784
|
+
if value == "X":
|
|
785
|
+
features = {"source": "X"}
|
|
786
|
+
elif value.startswith("layer:"):
|
|
787
|
+
layer = value.split(":", 1)[1]
|
|
788
|
+
if layer not in self.dataset.layers:
|
|
789
|
+
raise ValueError(f"This file has no matrix named {layer!r}.")
|
|
790
|
+
features = {"source": "layer", "layer": layer}
|
|
791
|
+
else:
|
|
792
|
+
# Neither an answer nor a clearing -- leave the spec alone rather
|
|
793
|
+
# than writing something the adapter cannot read.
|
|
794
|
+
return self
|
|
795
|
+
return self.patch(dataset=replace(self.dataset, features=features))
|
|
796
|
+
|
|
797
|
+
# -- the role questions, in the vocabulary they are asked in -------------
|
|
798
|
+
#
|
|
799
|
+
# For a CSV a role simply names a column of the table, and asking, storing
|
|
800
|
+
# and reading it are all the same string. For AnnData and SpatialData the
|
|
801
|
+
# table does not exist until the adapter builds it, and three of the roles
|
|
802
|
+
# are really instructions for building it: which obs column identifies a
|
|
803
|
+
# cell, and which two hold its coordinates. The three properties below are
|
|
804
|
+
# the translation, so every surface asks one question ("which obs column?")
|
|
805
|
+
# and every reader still gets a name that is in the loaded table.
|
|
806
|
+
|
|
807
|
+
@property
|
|
808
|
+
def role_columns(self) -> list[str]:
|
|
809
|
+
"""The columns to offer when asking which one fills a role.
|
|
810
|
+
|
|
811
|
+
Unfiltered on purpose. Which of a file's own annotations holds the cell
|
|
812
|
+
id is not something a name heuristic gets to decide -- guessing is what
|
|
813
|
+
the prefilled answer is for, and narrowing the list just hides the
|
|
814
|
+
column the user was looking for.
|
|
815
|
+
"""
|
|
816
|
+
if not self.dataset:
|
|
817
|
+
return []
|
|
818
|
+
if self.dataset.obs_columns:
|
|
819
|
+
return list(self.dataset.obs_columns)
|
|
820
|
+
# A CSV, or an AnnData imported before obs columns were recorded: every
|
|
821
|
+
# column of the table, metadata first because a role names a
|
|
822
|
+
# measurement about a cell far more often than a marker measured on one.
|
|
823
|
+
return list(self.columns.metadata) + list(self.columns.markers)
|
|
824
|
+
|
|
825
|
+
@property
|
|
826
|
+
def role_answers(self) -> dict:
|
|
827
|
+
"""The current answers, in the same vocabulary. Inverse of
|
|
828
|
+
`with_role_answers`, and what a form prefills its selects from."""
|
|
829
|
+
if not self.dataset:
|
|
830
|
+
return {}
|
|
831
|
+
if not self.columns_are_structural:
|
|
832
|
+
return self.roles.to_dict()
|
|
833
|
+
# x/y are deliberately absent: for these formats the coordinate source
|
|
834
|
+
# is one question with its own answer shape (see `coordinate_options`),
|
|
835
|
+
# not two independent column roles. An obsm array supplies both axes at
|
|
836
|
+
# once, so "which obs column is X" has no answer for it -- which is why
|
|
837
|
+
# this used to report a blank and let `role_defaults` label it.
|
|
838
|
+
return _clean({
|
|
839
|
+
# None means "number the rows", which is a real answer and not a
|
|
840
|
+
# gap -- see DataSpec.obs_id_field.
|
|
841
|
+
"cell_id": self.dataset.obs_id_field,
|
|
842
|
+
# Read straight off the source file by whatever needs it, so this
|
|
843
|
+
# one is an obs name in both vocabularies.
|
|
844
|
+
"image_id": self.roles.image_id,
|
|
845
|
+
"celltype": self.roles.celltype,
|
|
846
|
+
})
|
|
847
|
+
|
|
848
|
+
@property
|
|
849
|
+
def role_defaults(self) -> dict:
|
|
850
|
+
"""The answer a role has that names no column, worded for an option.
|
|
851
|
+
|
|
852
|
+
Only the cell id has one, and only for the formats where the adapter
|
|
853
|
+
can number the rows itself. It is offered as a real choice rather than
|
|
854
|
+
as the wording on a blank: a blank that satisfies the question looks
|
|
855
|
+
exactly like a default nobody read, which is the whole failure this
|
|
856
|
+
replaces. See DataSpec.row_number_ids.
|
|
857
|
+
"""
|
|
858
|
+
if not self.dataset or not self.columns_are_structural:
|
|
859
|
+
return {}
|
|
860
|
+
return {"cell_id": "Row number (0, 1, 2 … in file order)"}
|
|
861
|
+
|
|
862
|
+
@property
|
|
863
|
+
def coordinate_options(self) -> dict:
|
|
864
|
+
"""What the coordinate question is made of: the candidate sources, and
|
|
865
|
+
which one is currently recorded.
|
|
866
|
+
|
|
867
|
+
Both vocabularies are offered because a file can answer in either -- an
|
|
868
|
+
`obsm` array holding both axes, or a pair of `obs` columns -- and which
|
|
869
|
+
one a given file uses is not something a name heuristic gets to settle.
|
|
870
|
+
Every obsm array is listed with its shape rather than filtered down to
|
|
871
|
+
the ones that "look spatial": a store routinely carries `spatial` and
|
|
872
|
+
`X_umap` at identical (n, 2) float32, so filtering cannot separate them
|
|
873
|
+
and choosing by name is the mistake this replaces.
|
|
874
|
+
|
|
875
|
+
`current` is the recorded read spec, which for a fresh import is the
|
|
876
|
+
importer's proposal -- a prefill to accept or correct, never a settled
|
|
877
|
+
answer. It is empty when nothing was detected.
|
|
878
|
+
"""
|
|
879
|
+
if not self.dataset or not self.columns_are_structural:
|
|
880
|
+
return {}
|
|
881
|
+
return {
|
|
882
|
+
"obsm": [dict(entry) for entry in self.dataset.obsm],
|
|
883
|
+
"obs": list(self.dataset.obs_columns),
|
|
884
|
+
"current": dict(self.dataset.coordinates or {}),
|
|
885
|
+
}
|
|
886
|
+
|
|
887
|
+
def with_role_answers(self, values: Mapping[str, Any]) -> "Project":
|
|
888
|
+
"""Record answers to the role questions.
|
|
889
|
+
|
|
890
|
+
For AnnData and SpatialData this writes the read spec as well as the
|
|
891
|
+
roles: naming an obs column in `roles.cell_id` alone would point the
|
|
892
|
+
role at a column the loaded table does not have. Going through the read
|
|
893
|
+
spec is what makes the answer take effect -- and it matters, because a
|
|
894
|
+
segmentation overlay only lines up when the cell ids are the mask's own
|
|
895
|
+
label values, which live in obs and never in a positional row index.
|
|
896
|
+
"""
|
|
897
|
+
if not self.dataset:
|
|
898
|
+
return self
|
|
899
|
+
values = {role: value for role, value in (values or {}).items()
|
|
900
|
+
if role in ROLE_NAMES}
|
|
901
|
+
# Naming an image-id column is the other answer to the question
|
|
902
|
+
# `single_image` answers, so it retracts it. Applied before the format
|
|
903
|
+
# split because it holds for every format -- a CSV spans several images
|
|
904
|
+
# exactly as readily as an AnnData does.
|
|
905
|
+
project = self
|
|
906
|
+
if values.get("image_id"):
|
|
907
|
+
project = project.patch(dataset=replace(project.dataset, single_image=False))
|
|
908
|
+
if not project.columns_are_structural:
|
|
909
|
+
return project.with_roles(values)
|
|
910
|
+
|
|
911
|
+
spec = project.dataset
|
|
912
|
+
roles = {}
|
|
913
|
+
if "cell_id" in values:
|
|
914
|
+
column = values["cell_id"] or None
|
|
915
|
+
# Naming a column is the other answer to the question
|
|
916
|
+
# `row_number_ids` answers, so it retracts it -- the same way
|
|
917
|
+
# naming an image-id column retracts `single_image` above.
|
|
918
|
+
spec = replace(spec, obs_id_field=column,
|
|
919
|
+
row_number_ids=spec.row_number_ids and not column)
|
|
920
|
+
# The adapter names the emitted column after the obs field it was
|
|
921
|
+
# given, and falls back to its positional "id" when given none.
|
|
922
|
+
roles["cell_id"] = column or "id"
|
|
923
|
+
if "x" in values or "y" in values:
|
|
924
|
+
# The obs half of the coordinate question, still reachable from the
|
|
925
|
+
# programmatic API and from a CSV-shaped payload. The surfaces ask
|
|
926
|
+
# it through `with_coordinates` now, which can also express the
|
|
927
|
+
# obsm answer these two selects have no way to name.
|
|
928
|
+
coordinates = dict(spec.coordinates or {})
|
|
929
|
+
x = (values["x"] if "x" in values else coordinates.get("x_column")) or None
|
|
930
|
+
y = (values["y"] if "y" in values else coordinates.get("y_column")) or None
|
|
931
|
+
if x and y:
|
|
932
|
+
spec = _with_coordinate_spec(
|
|
933
|
+
spec, {"source": "obs", "x_column": x, "y_column": y})
|
|
934
|
+
elif not x and not y:
|
|
935
|
+
spec = replace(spec, coordinates={})
|
|
936
|
+
else:
|
|
937
|
+
# Half a position is not a position, and applying it would read
|
|
938
|
+
# one axis from obs and the other from obsm.
|
|
939
|
+
raise ValueError(
|
|
940
|
+
"Pick both an X and a Y coordinate column, or neither.")
|
|
941
|
+
# The adapter always emits its coordinates under these two names,
|
|
942
|
+
# whichever obs columns they were read from.
|
|
943
|
+
roles["x"], roles["y"] = "X", "Y"
|
|
944
|
+
for role in ("image_id", "celltype"):
|
|
945
|
+
if role in values:
|
|
946
|
+
roles[role] = values[role]
|
|
947
|
+
return self.patch(dataset=replace(spec, roles=spec.roles.with_values(roles)))
|
|
948
|
+
|
|
949
|
+
def with_coordinates(self, answer: Mapping[str, Any]) -> "Project":
|
|
950
|
+
"""Record where each cell's position is read from.
|
|
951
|
+
|
|
952
|
+
One question with two answer shapes, because the file has two places to
|
|
953
|
+
put the same thing:
|
|
954
|
+
|
|
955
|
+
{"source": "obsm", "obsm_key": "spatial"}
|
|
956
|
+
{"source": "obs", "x_column": "X_centroid", "y_column": "Y_centroid"}
|
|
957
|
+
|
|
958
|
+
Validated against what the file actually carries, so a stale form or a
|
|
959
|
+
renamed key is refused rather than stored and discovered later by the
|
|
960
|
+
adapter -- at which point the project is already unreadable.
|
|
961
|
+
"""
|
|
962
|
+
if not self.dataset:
|
|
963
|
+
return self
|
|
964
|
+
spec = _with_coordinate_spec(self.dataset, answer)
|
|
965
|
+
# The adapter always emits its coordinates under these two names,
|
|
966
|
+
# whichever source they were read from.
|
|
967
|
+
return self.patch(dataset=replace(
|
|
968
|
+
spec, roles=spec.roles.with_values({"x": "X", "y": "Y"})))
|
|
969
|
+
|
|
970
|
+
def with_single_image(self, flag: bool = True) -> "Project":
|
|
971
|
+
"""Record the user's answer that this table covers exactly one image.
|
|
972
|
+
|
|
973
|
+
Kept apart from `roles.image_id` on purpose -- see DataSpec.single_image.
|
|
974
|
+
Setting it clears any image-id column, since the two are alternative
|
|
975
|
+
answers to one question rather than facts that can both hold.
|
|
976
|
+
"""
|
|
977
|
+
if not self.dataset:
|
|
978
|
+
return self
|
|
979
|
+
spec = self.dataset
|
|
980
|
+
if flag:
|
|
981
|
+
spec = replace(spec, roles=spec.roles.with_values({"image_id": None}))
|
|
982
|
+
return self.patch(dataset=replace(spec, single_image=bool(flag)))
|
|
983
|
+
|
|
984
|
+
def with_row_number_ids(self, flag: bool = True) -> "Project":
|
|
985
|
+
"""Record the user's answer that no obs column holds the cell id.
|
|
986
|
+
|
|
987
|
+
Kept apart from an unset `obs_id_field` on purpose -- see
|
|
988
|
+
DataSpec.row_number_ids. Setting it clears any named column, since the
|
|
989
|
+
two are alternative answers to one question.
|
|
990
|
+
|
|
991
|
+
AnnData and SpatialData only: a CSV's cell id is a column of the file
|
|
992
|
+
the user classified, and there is no row-numbering fallback to choose.
|
|
993
|
+
"""
|
|
994
|
+
if not self.dataset or not self.columns_are_structural:
|
|
995
|
+
return self
|
|
996
|
+
spec = self.dataset
|
|
997
|
+
if flag:
|
|
998
|
+
spec = replace(spec, obs_id_field=None,
|
|
999
|
+
roles=spec.roles.with_values({"cell_id": "id"}))
|
|
1000
|
+
return self.patch(dataset=replace(spec, row_number_ids=bool(flag)))
|
|
1001
|
+
|
|
1002
|
+
def with_columns(self, markers: Iterable[str], metadata: Iterable[str]) -> "Project":
|
|
1003
|
+
if not self.dataset:
|
|
1004
|
+
return self
|
|
1005
|
+
groups = ColumnGroups(markers=tuple(markers or ()), metadata=tuple(metadata or ()))
|
|
1006
|
+
return self.patch(dataset=replace(self.dataset, columns=groups))
|
|
1007
|
+
|
|
1008
|
+
# -- the cell layer --------------------------------------------------
|
|
1009
|
+
|
|
1010
|
+
@property
|
|
1011
|
+
def cell_layer_options(self) -> list[str]:
|
|
1012
|
+
"""How this project could draw per-cell results, best first.
|
|
1013
|
+
|
|
1014
|
+
Segmentation leads because it shows the real cell shape; centroids are
|
|
1015
|
+
the fallback and need only coordinates. An empty list means the project
|
|
1016
|
+
can draw neither, and whatever wants to is missing something more basic
|
|
1017
|
+
-- a mask, or the coordinate roles.
|
|
1018
|
+
"""
|
|
1019
|
+
options = []
|
|
1020
|
+
if self.segmentation.requested:
|
|
1021
|
+
options.append("segmentation")
|
|
1022
|
+
if self.roles.x and self.roles.y:
|
|
1023
|
+
options.append("centroids")
|
|
1024
|
+
return options
|
|
1025
|
+
|
|
1026
|
+
@property
|
|
1027
|
+
def cell_layer(self) -> str | None:
|
|
1028
|
+
"""How this project draws per-cell results.
|
|
1029
|
+
|
|
1030
|
+
The user's override if they made one on the edit page, otherwise the
|
|
1031
|
+
best this project can do: the mask when there is one, centroids
|
|
1032
|
+
otherwise. None only when it can draw neither, in which case whatever
|
|
1033
|
+
wanted to draw is missing something more basic.
|
|
1034
|
+
|
|
1035
|
+
A stale override -- centroids chosen back when there was no mask, say --
|
|
1036
|
+
is honoured, because it is still a choice somebody made.
|
|
1037
|
+
"""
|
|
1038
|
+
options = self.cell_layer_options
|
|
1039
|
+
if self.cell_layer_choice in options:
|
|
1040
|
+
return self.cell_layer_choice
|
|
1041
|
+
return options[0] if options else None
|
|
1042
|
+
|
|
1043
|
+
def with_cell_layer(self, value: str | None) -> "Project":
|
|
1044
|
+
"""Record an override, or clear one.
|
|
1045
|
+
|
|
1046
|
+
None and "" both mean "no override" -- go back to whatever this project
|
|
1047
|
+
resolves to. Being able to say that matters as much as being able to
|
|
1048
|
+
choose: an override outlives the state it was made in, so a project
|
|
1049
|
+
whose mask was still converting when somebody saved the edit page would
|
|
1050
|
+
otherwise be pinned to centroids for good, with no way back.
|
|
1051
|
+
|
|
1052
|
+
An unknown value is ignored rather than stored -- the client sends this
|
|
1053
|
+
and the viewer would have nothing to draw.
|
|
1054
|
+
"""
|
|
1055
|
+
if value and value not in CELL_LAYERS:
|
|
1056
|
+
return self
|
|
1057
|
+
return self.patch(cell_layer_choice=value or None)
|
|
1058
|
+
|
|
1059
|
+
# -- what the user has actually answered -----------------------------
|
|
1060
|
+
|
|
1061
|
+
def with_confirmed(self, keys: Iterable[str]) -> "Project":
|
|
1062
|
+
"""Mark requirement keys as explicitly answered.
|
|
1063
|
+
|
|
1064
|
+
Additive: confirming one thing never un-confirms another, so the modal
|
|
1065
|
+
can post only the keys it showed.
|
|
1066
|
+
"""
|
|
1067
|
+
seen = set(self.confirmed)
|
|
1068
|
+
added = []
|
|
1069
|
+
for key in keys or ():
|
|
1070
|
+
# Deduped against the batch as well as against what is stored: the
|
|
1071
|
+
# modal's `confirm` list and the answers it carries name the same
|
|
1072
|
+
# keys, and both reach here.
|
|
1073
|
+
if key and key not in seen:
|
|
1074
|
+
seen.add(key)
|
|
1075
|
+
added.append(key)
|
|
1076
|
+
if not added:
|
|
1077
|
+
return self
|
|
1078
|
+
return self.patch(confirmed=self.confirmed + tuple(added))
|
|
1079
|
+
|
|
1080
|
+
def unconfirmed(self, keys: Iterable[str]) -> list[str]:
|
|
1081
|
+
"""Which of `keys` the user has never answered, in the order given."""
|
|
1082
|
+
return [key for key in keys if key not in self.confirmed]
|
|
1083
|
+
|
|
1084
|
+
def forget_table_answers(self) -> "Project":
|
|
1085
|
+
"""Drop the answers that describe the feature table.
|
|
1086
|
+
|
|
1087
|
+
Called when the data file is replaced: the roles and the marker split
|
|
1088
|
+
were confirmed against columns that may not exist in the new file, so
|
|
1089
|
+
the fresh predictions have to be put in front of the user again.
|
|
1090
|
+
|
|
1091
|
+
The two answers that name no column go with them. "One image" and
|
|
1092
|
+
"number the rows" were said about the old table and say nothing about
|
|
1093
|
+
the new one -- and left standing they would keep their questions
|
|
1094
|
+
answered, so neither would ever be asked about the file that replaced
|
|
1095
|
+
it.
|
|
1096
|
+
"""
|
|
1097
|
+
project = self.patch(
|
|
1098
|
+
confirmed=tuple(k for k in self.confirmed if not _is_table_scoped(k)))
|
|
1099
|
+
if not project.dataset:
|
|
1100
|
+
return project
|
|
1101
|
+
return project.patch(dataset=replace(
|
|
1102
|
+
project.dataset, single_image=False, row_number_ids=False))
|
|
1103
|
+
|
|
1104
|
+
# -- persistence -----------------------------------------------------
|
|
1105
|
+
|
|
1106
|
+
@staticmethod
|
|
1107
|
+
def _config_path(data_root=None) -> Path:
|
|
1108
|
+
return paths.config_path(data_root)
|
|
1109
|
+
|
|
1110
|
+
@property
|
|
1111
|
+
def is_shared(self) -> bool:
|
|
1112
|
+
"""Whether this project belongs to a root the user cannot write to.
|
|
1113
|
+
|
|
1114
|
+
A shared project is readable by everyone on the machine and editable by
|
|
1115
|
+
nobody through Plexora: the site administrator who provisioned the root
|
|
1116
|
+
owns it. What a user produces while exploring one -- gates, ROIs,
|
|
1117
|
+
figures -- is theirs and goes to their own root instead, which is what
|
|
1118
|
+
`paths.project_state_dir` is for.
|
|
1119
|
+
"""
|
|
1120
|
+
return self.home_root is not None and self.home_root != paths.data_root()
|
|
1121
|
+
|
|
1122
|
+
@property
|
|
1123
|
+
def read_dir(self) -> Path:
|
|
1124
|
+
"""Where this project's image, mask and feature table are read from."""
|
|
1125
|
+
return paths.project_dir(self.name, self.home_root)
|
|
1126
|
+
|
|
1127
|
+
@property
|
|
1128
|
+
def state_dir(self) -> Path:
|
|
1129
|
+
"""Where this user's own state for this project is written."""
|
|
1130
|
+
return paths.project_state_dir(self.name)
|
|
1131
|
+
|
|
1132
|
+
@classmethod
|
|
1133
|
+
def load(cls, name: str, data_root=None) -> "Project":
|
|
1134
|
+
"""Read one project. Raises KeyError if it is not registered.
|
|
1135
|
+
|
|
1136
|
+
Searches every root when `data_root` is not given, the user's own
|
|
1137
|
+
first, so a project of the user's own shadows a shared one of the same
|
|
1138
|
+
name -- somebody who has made their own copy means to open it.
|
|
1139
|
+
"""
|
|
1140
|
+
for root in ([Path(data_root)] if data_root is not None else paths.roots()):
|
|
1141
|
+
config = read_config(paths.config_path(root))
|
|
1142
|
+
if name in config:
|
|
1143
|
+
return cls.from_entry(name, config[name], home_root=root)
|
|
1144
|
+
raise KeyError(f"Unknown datasource: {name!r}")
|
|
1145
|
+
|
|
1146
|
+
@classmethod
|
|
1147
|
+
def find(cls, name: str, data_root=None) -> "Project | None":
|
|
1148
|
+
"""Read one project, or None. For the many callers that already have a
|
|
1149
|
+
fallback for an unknown/stale datasource name."""
|
|
1150
|
+
try:
|
|
1151
|
+
return cls.load(name, data_root)
|
|
1152
|
+
except KeyError:
|
|
1153
|
+
return None
|
|
1154
|
+
|
|
1155
|
+
@staticmethod
|
|
1156
|
+
def load_all(data_root=None) -> dict:
|
|
1157
|
+
"""Every registered project, as raw entries keyed by name.
|
|
1158
|
+
|
|
1159
|
+
Merged across the roots when `data_root` is not given. Earlier roots
|
|
1160
|
+
win, and `paths.roots()` puts the user's own first -- the same
|
|
1161
|
+
precedence `load()` applies, kept in step because the two disagreeing
|
|
1162
|
+
would mean a name listed from one root opened the other.
|
|
1163
|
+
"""
|
|
1164
|
+
if data_root is not None:
|
|
1165
|
+
return read_config(paths.config_path(data_root))
|
|
1166
|
+
merged: dict = {}
|
|
1167
|
+
for root in paths.roots():
|
|
1168
|
+
for name, entry in read_config(paths.config_path(root)).items():
|
|
1169
|
+
merged.setdefault(name, entry)
|
|
1170
|
+
return merged
|
|
1171
|
+
|
|
1172
|
+
@staticmethod
|
|
1173
|
+
def load_roots() -> dict:
|
|
1174
|
+
"""Which root each visible project came from, keyed by name.
|
|
1175
|
+
|
|
1176
|
+
Same precedence as `load_all`. Lets a caller that already has the
|
|
1177
|
+
merged entries tell the user's projects from the shared ones without
|
|
1178
|
+
re-reading every config.
|
|
1179
|
+
"""
|
|
1180
|
+
found: dict = {}
|
|
1181
|
+
for root in paths.roots():
|
|
1182
|
+
for name in read_config(paths.config_path(root)):
|
|
1183
|
+
found.setdefault(name, root)
|
|
1184
|
+
return found
|
|
1185
|
+
|
|
1186
|
+
@staticmethod
|
|
1187
|
+
def root_for(name: str) -> Path | None:
|
|
1188
|
+
"""The root whose config.json holds `name`, or None if none does."""
|
|
1189
|
+
for root in paths.roots():
|
|
1190
|
+
if name in read_config(paths.config_path(root)):
|
|
1191
|
+
return root
|
|
1192
|
+
return None
|
|
1193
|
+
|
|
1194
|
+
@staticmethod
|
|
1195
|
+
def config_path_for(name: str) -> Path:
|
|
1196
|
+
"""The config.json holding `name`'s entry.
|
|
1197
|
+
|
|
1198
|
+
Falls back to the user's own root for a name nobody has registered,
|
|
1199
|
+
which is what a caller writing a brand-new entry wants. Callers that
|
|
1200
|
+
intend to WRITE must also check `paths.is_writable` on the parent: this
|
|
1201
|
+
happily returns a path inside a read-only shared root, because that is
|
|
1202
|
+
genuinely where the entry lives.
|
|
1203
|
+
"""
|
|
1204
|
+
root = Project.root_for(name)
|
|
1205
|
+
return paths.config_path(root if root is not None else paths.data_root())
|
|
1206
|
+
|
|
1207
|
+
def _write_root(self, data_root=None) -> Path:
|
|
1208
|
+
"""The root this project's entry is written to.
|
|
1209
|
+
|
|
1210
|
+
An explicit argument wins, then the root it was loaded from, then the
|
|
1211
|
+
user's own. A shared project resolves to the shared root and the write
|
|
1212
|
+
will fail there -- deliberately, since silently redirecting it into the
|
|
1213
|
+
user's root would fork the registry entry and leave two projects with
|
|
1214
|
+
one name. Callers that can do something better refuse earlier, on
|
|
1215
|
+
`is_shared`.
|
|
1216
|
+
"""
|
|
1217
|
+
if data_root is not None:
|
|
1218
|
+
return Path(data_root)
|
|
1219
|
+
return self.home_root if self.home_root is not None else paths.data_root()
|
|
1220
|
+
|
|
1221
|
+
def save(self, data_root=None) -> dict:
|
|
1222
|
+
"""Write this project back, leaving every other project untouched.
|
|
1223
|
+
|
|
1224
|
+
Only the target root's own config.json is read and rewritten -- never
|
|
1225
|
+
the merged view, which would copy every shared project into the user's
|
|
1226
|
+
registry the first time they saved anything.
|
|
1227
|
+
"""
|
|
1228
|
+
root = self._write_root(data_root)
|
|
1229
|
+
path = paths.config_path(root)
|
|
1230
|
+
with _CONFIG_LOCK:
|
|
1231
|
+
config = read_config(path)
|
|
1232
|
+
config[self.name] = self.to_entry()
|
|
1233
|
+
write_config(path, config)
|
|
1234
|
+
return config[self.name]
|
|
1235
|
+
|
|
1236
|
+
@classmethod
|
|
1237
|
+
def mutate(cls, name: str, change, data_root=None) -> "Project | None":
|
|
1238
|
+
"""Read-modify-write one project atomically with respect to other
|
|
1239
|
+
writers in this process.
|
|
1240
|
+
|
|
1241
|
+
`change` takes a Project and returns one. Returns None if the project
|
|
1242
|
+
vanished before the lock was taken -- which really happens: the
|
|
1243
|
+
segmentation job outlives a delete.
|
|
1244
|
+
"""
|
|
1245
|
+
with _CONFIG_LOCK:
|
|
1246
|
+
project = cls.find(name, data_root)
|
|
1247
|
+
if project is None:
|
|
1248
|
+
return None
|
|
1249
|
+
updated = change(project)
|
|
1250
|
+
updated.save(data_root)
|
|
1251
|
+
return updated
|
|
1252
|
+
|
|
1253
|
+
def delete(self, data_root=None) -> None:
|
|
1254
|
+
"""Remove this project from the registry. Does not touch its data
|
|
1255
|
+
directory -- the caller owns that, since it may want the files kept."""
|
|
1256
|
+
root = self._write_root(data_root)
|
|
1257
|
+
path = paths.config_path(root)
|
|
1258
|
+
with _CONFIG_LOCK:
|
|
1259
|
+
config = read_config(path)
|
|
1260
|
+
config.pop(self.name, None)
|
|
1261
|
+
write_config(path, config)
|
|
1262
|
+
|
|
1263
|
+
|
|
1264
|
+
def all_projects(data_root=None) -> list[Project]:
|
|
1265
|
+
if data_root is not None:
|
|
1266
|
+
return [Project.from_entry(name, entry, home_root=data_root)
|
|
1267
|
+
for name, entry in Project.load_all(data_root).items()]
|
|
1268
|
+
homes = Project.load_roots()
|
|
1269
|
+
return [Project.from_entry(name, entry, home_root=homes.get(name))
|
|
1270
|
+
for name, entry in Project.load_all().items()]
|