-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathapi_latest.ts
More file actions
3044 lines (2751 loc) · 97.9 KB
/
api_latest.ts
File metadata and controls
3044 lines (2751 loc) · 97.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { requestTask } from "admin/api/tasks";
import {
doWithToken,
finishAnnotation,
getMappingsForDatasetLayer,
sendAnalyticsEvent,
} from "admin/rest_api";
import PriorityQueue from "js-priority-queue";
import { InputKeyboardNoLoop, type KeyboardNoLoopHandler } from "libs/input";
import { M4x4, type Matrix4x4, V3 } from "libs/mjs";
import Request from "libs/request";
import type { ToastStyle } from "libs/toast";
import Toast from "libs/toast";
import UserLocalStorage from "libs/user_local_storage";
import { coalesce, map3, mod, sleep } from "libs/utils";
import window, { location } from "libs/window";
import cloneDeep from "lodash-es/cloneDeep";
import groupBy from "lodash-es/groupBy";
import isNumber from "lodash-es/isNumber";
import messages from "messages";
import type { Vector16 } from "mjs";
import { Euler, MathUtils, Quaternion } from "three";
import TWEEN from "tween.js";
import type { AdditionalCoordinate } from "types/api_types";
import { type APICompoundType, APICompoundTypeEnum, type ElementClass } from "types/api_types";
import type { BoundingBoxMinMaxType } from "types/bounding_box";
import type { Writeable } from "types/type_utils";
import type {
BucketAddress,
ControlMode,
LabeledVoxelsMap,
OrthoView,
TypedArray,
Vector3,
Vector4,
} from "viewer/constants";
import Constants, {
ControlModeEnum,
EMPTY_OBJECT,
MappingStatusEnum,
OrthoViews,
TDViewDisplayModeEnum,
} from "viewer/constants";
import { rotate3DViewTo } from "viewer/controller/camera_controller";
import { loadAgglomerateSkeletonForSegmentId } from "viewer/controller/combinations/segmentation_handlers";
import {
createSkeletonNode,
getOptionsForCreateSkeletonNode,
} from "viewer/controller/combinations/skeleton_handlers";
import UrlManager from "viewer/controller/url_manager";
import type { WebKnossosModel } from "viewer/model";
import {
getLayerBoundingBox,
getLayerByName,
getMagInfo,
getMappingInfo,
getMappingInfoOrNull,
getVisibleSegmentationLayer,
} from "viewer/model/accessors/dataset_accessor";
import { flatToNestedMatrix } from "viewer/model/accessors/dataset_layer_transformation_accessor";
import {
getActiveMagIndexForLayer,
getAdditionalCoordinatesAsString,
getPosition,
getRotationInRadian,
} from "viewer/model/accessors/flycam_accessor";
import {
findTreeByNodeId,
getActiveNode,
getActiveTree,
getActiveTreeGroup,
getFlatTreeGroups,
getNodePosition,
getTree,
getTreeAndNode,
getTreeAndNodeOrNull,
getTreeGroupsMap,
} from "viewer/model/accessors/skeletontracing_accessor";
import { AnnotationTool, type AnnotationToolId } from "viewer/model/accessors/tool_accessor";
import {
enforceActiveVolumeTracing,
getActiveCellId,
getActiveSegmentationTracing,
getNameOfRequestedOrVisibleSegmentationLayer,
getRequestedOrDefaultSegmentationTracingLayer,
getRequestedOrVisibleSegmentationLayer,
getRequestedOrVisibleSegmentationLayerEnforced,
getSegmentColorAsRGBA,
getSegmentsForLayer,
getVolumeDescriptors,
getVolumeTracingById,
getVolumeTracingByLayerName,
getVolumeTracings,
hasVolumeTracings,
} from "viewer/model/accessors/volumetracing_accessor";
import { restartSagaAction, wkInitializedAction } from "viewer/model/actions/actions";
import {
dispatchMaybeFetchMeshFilesAsync,
refreshMeshesAction,
removeMeshAction,
updateCurrentMeshFileAction,
updateMeshOpacityAction,
updateMeshVisibilityAction,
} from "viewer/model/actions/annotation_actions";
import { setLayerTransformsAction } from "viewer/model/actions/dataset_actions";
import { setPositionAction, setRotationAction } from "viewer/model/actions/flycam_actions";
import { disableSavingAction, discardSaveQueueAction } from "viewer/model/actions/save_actions";
import {
loadAdHocMeshAction,
loadPrecomputedMeshAction,
} from "viewer/model/actions/segmentation_actions";
import {
setMappingAction,
setMappingEnabledAction,
updateDatasetSettingAction,
updateLayerSettingAction,
updateUserSettingAction,
} from "viewer/model/actions/settings_actions";
import {
addTreesAndGroupsAction,
centerActiveNodeAction,
createCommentAction,
createTreeAction,
deleteNodeAction,
deleteTreeAction,
resetSkeletonTracingAction,
setActiveNodeAction,
setActiveTreeAction,
setActiveTreeByNameAction,
setActiveTreeGroupAction,
setNodeRadiusAction,
setTreeColorIndexAction,
setTreeEdgeVisibilityAction,
setTreeGroupAction,
setTreeGroupsAction,
setTreeNameAction,
setTreeVisibilityAction,
} from "viewer/model/actions/skeletontracing_actions";
import { setToolAction } from "viewer/model/actions/ui_actions";
import { centerTDViewAction } from "viewer/model/actions/view_mode_actions";
import {
type BatchableUpdateSegmentAction,
batchUpdateGroupsAndSegmentsAction,
clickSegmentAction,
finishAnnotationStrokeAction,
removeSegmentAction,
setActiveCellAction,
setSegmentGroupsAction,
updateSegmentAction,
} from "viewer/model/actions/volumetracing_actions";
import BoundingBox from "viewer/model/bucket_data_handling/bounding_box";
import type { Bucket, DataBucket } from "viewer/model/bucket_data_handling/bucket";
import type DataLayer from "viewer/model/data_layer";
import Dimensions from "viewer/model/dimensions";
import dimensions from "viewer/model/dimensions";
import { MagInfo } from "viewer/model/helpers/mag_info";
import { parseNml } from "viewer/model/helpers/nml_helpers";
import { overwriteAction } from "viewer/model/helpers/overwrite_action_middleware";
import {
bucketPositionToGlobalAddress,
globalPositionToBucketPosition,
scaleGlobalPositionWithMagnification,
zoomedAddressToZoomedPosition,
zoomedPositionToZoomedAddress,
} from "viewer/model/helpers/position_converter";
import { getConstructorForElementClass } from "viewer/model/helpers/typed_buffer";
import { getMaximumGroupId } from "viewer/model/reducers/skeletontracing_reducer_helpers";
import { getHalfViewportExtentsInUnitFromState } from "viewer/model/sagas/saga_selectors";
import { applyLabeledVoxelMapToAllMissingMags } from "viewer/model/sagas/volume/helpers";
import type { MutableNode, Node, Tree, TreeGroupTypeFlat } from "viewer/model/types/tree_types";
import { applyVoxelMap } from "viewer/model/volumetracing/volume_annotation_sampling";
import { api, Model } from "viewer/singletons";
import type {
DatasetConfiguration,
Mapping,
MappingType,
Segment,
SegmentGroup,
SkeletonTracing,
StoreAnnotation,
UserConfiguration,
VolumeTracing,
WebknossosState,
} from "viewer/store";
import Store from "viewer/store";
import {
callDeep,
createGroupHelper,
createGroupToSegmentsMap,
MISSING_GROUP_ID,
mapGroups,
moveGroupsHelper,
} from "viewer/view/right_border_tabs/trees_tab/tree_hierarchy_view_helpers";
type TransformSpec =
| { type: "scale"; args: [Vector3, Vector3] }
| { type: "rotate"; args: [number, Vector3] }
| { type: "translate"; args: Vector3 };
type OutdatedDatasetConfigurationKeys = "segmentationOpacity" | "isSegmentationDisabled";
function assertExists<T>(value: any, message: string): asserts value is NonNullable<T> {
if (value == null) {
throw new Error(message);
}
}
function assertSkeleton(annotation: StoreAnnotation): SkeletonTracing {
if (annotation.skeleton == null) {
throw new Error("This API function should only be called in a skeleton annotation.");
}
return annotation.skeleton;
}
function assertVolume(state: WebknossosState): VolumeTracing {
if (state.annotation.volumes.length === 0) {
throw new Error(
"This API function should only be called when a volume annotation layer exists.",
);
}
const tracing = getRequestedOrDefaultSegmentationTracingLayer(state, null);
if (tracing == null) {
throw new Error(
"This API function should only be called when a volume annotation layer is visible.",
);
}
return tracing;
}
/**
* All tracing related API methods. This is the newest version of the API (version 3).
* @version 3
* @class
* @example
* window.webknossos.apiReady(3).then(api => {
* api.tracing.getActiveNodeId();
* api.tracing.getActiveTreeId();
* ...
* }
*/
class TracingApi {
model: WebKnossosModel;
/**
* @private
*/
isFinishing: boolean = false;
/**
* @private
*/
constructor(model: WebKnossosModel) {
this.model = model;
}
// SKELETONTRACING API
/**
* Returns the id of the current active node.
*/
getActiveNodeId(): number | null | undefined {
const tracing = assertSkeleton(Store.getState().annotation);
return getActiveNode(tracing)?.id ?? null;
}
/**
* Returns the id of the current active tree.
*/
getActiveTreeId(): number | null | undefined {
const tracing = assertSkeleton(Store.getState().annotation);
return getActiveTree(tracing)?.treeId ?? null;
}
/**
* Returns the id of the current active group.
*/
getActiveTreeGroupId(): number | null | undefined {
const tracing = assertSkeleton(Store.getState().annotation);
return getActiveTreeGroup(tracing)?.groupId ?? null;
}
/**
* Deprecated! Use getActiveTreeGroupId instead.
*/
getActiveGroupId(): number | null | undefined {
return this.getActiveTreeGroupId();
}
/**
* Sets the active node given a node id.
*/
setActiveNode(
id: number,
suppressAnimation?: boolean,
suppressCentering?: boolean,
suppressRotation?: boolean,
) {
assertSkeleton(Store.getState().annotation);
assertExists(id, "Node id is missing.");
Store.dispatch(setActiveNodeAction(id, suppressAnimation, suppressCentering, suppressRotation));
}
/**
* Returns all nodes belonging to a tracing.
*/
getAllNodes(): Array<Node> {
const skeletonTracing = assertSkeleton(Store.getState().annotation);
return Array.from(skeletonTracing.trees.values().flatMap((tree) => tree.nodes.values()));
}
/**
* Returns all trees belonging to a tracing.
*/
getAllTrees(): Record<number, Tree> {
const skeletonTracing = assertSkeleton(Store.getState().annotation);
return skeletonTracing.trees.toObject();
}
/**
* Deletes the node with nodeId in the tree with treeId
*/
deleteNode(nodeId: number, treeId: number) {
assertSkeleton(Store.getState().annotation);
Store.dispatch(deleteNodeAction(nodeId, treeId));
}
/**
* Centers the active node.
*/
centerActiveNode() {
assertSkeleton(Store.getState().annotation);
Store.dispatch(centerActiveNodeAction());
}
/**
* Creates a new and empty tree. Returns the
* id of that tree.
*/
createTree() {
assertSkeleton(Store.getState().annotation);
let treeId = null;
Store.dispatch(
createTreeAction((id) => {
treeId = id;
}),
);
if (treeId == null) {
throw new Error("Could not create tree.");
}
return treeId;
}
/**
* Deletes the tree with the given treeId.
*/
deleteTree(treeId: number) {
assertSkeleton(Store.getState().annotation);
Store.dispatch(deleteTreeAction(treeId));
}
/**
* Creates a new node in the current tree.
* If the active tree already contains nodes, the new node will be connected to the currently active one via an edge.
*
* When the camera is rotated and centering animation is enabled, using unrounded (floating-point)
* coordinates [x, y, z] helps maintain a consistent viewing slice. This prevents the viewports from jumping
* between slices due to the animation.
*
* In scenarios without rotation or centering animation, rounded integer coordinates are sufficient.
*/
createNode(
position: Vector3,
options?: {
additionalCoordinates?: AdditionalCoordinate[];
rotation?: Vector3;
center?: boolean;
branchpoint?: boolean;
activate?: boolean;
skipCenteringAnimationInThirdDimension?: boolean;
},
) {
const globalPosition = { rounded: map3(Math.round, position), floating: position };
assertSkeleton(Store.getState().annotation);
const defaultOptions = getOptionsForCreateSkeletonNode();
createSkeletonNode(
globalPosition,
options?.additionalCoordinates ?? defaultOptions.additionalCoordinates,
options?.rotation ?? defaultOptions.rotation,
options?.center ?? defaultOptions.center,
options?.branchpoint ?? defaultOptions.branchpoint,
options?.activate ?? defaultOptions.activate,
// This is the only parameter where we don't fall back to the default option,
// as the parameter mostly makes sense when the user creates a node *manually*.
options?.skipCenteringAnimationInThirdDimension ?? false,
);
}
/**
* Completely resets the skeleton tracing.
*/
resetSkeletonTracing() {
assertSkeleton(Store.getState().annotation);
Store.dispatch(resetSkeletonTracingAction());
}
/**
* Sets the comment for a node.
*
* @example
* const activeNodeId = api.tracing.getActiveNodeId();
* api.tracing.setCommentForNode("This is a branch point", activeNodeId);
*/
setCommentForNode(commentText: string, nodeId: number, treeId?: number): void {
const skeletonTracing = assertSkeleton(Store.getState().annotation);
assertExists(commentText, "Comment text is missing.");
// Convert nodeId to node
if (isNumber(nodeId)) {
const tree =
treeId != null
? skeletonTracing.trees.getNullable(treeId)
: findTreeByNodeId(skeletonTracing.trees, nodeId);
assertExists(tree, `Couldn't find node ${nodeId}.`);
Store.dispatch(createCommentAction(commentText, nodeId, tree.treeId));
} else {
throw new Error("Node id is missing.");
}
}
/**
* Returns the comment for a given node and tree (optional).
* @param treeId - Supplying the tree id will provide a performance boost for looking up a comment.
*
* @example
* const comment = api.tracing.getCommentForNode(23);
*
* @example
* // Provide a tree for lookup speed boost
* const comment = api.tracing.getCommentForNode(23, api.getActiveTreeid());
*/
getCommentForNode(nodeId: number, treeId?: number): string | null | undefined {
const skeletonTracing = assertSkeleton(Store.getState().annotation);
assertExists(nodeId, "Node id is missing.");
// Convert treeId to tree
let tree = null;
if (treeId != null) {
tree = skeletonTracing.trees.getNullable(treeId);
assertExists(tree, `Couldn't find tree ${treeId}.`);
assertExists(
tree.nodes.getOrThrow(nodeId),
`Couldn't find node ${nodeId} in tree ${treeId}.`,
);
} else {
tree = skeletonTracing.trees.values().find((__) => __.nodes.has(nodeId));
assertExists(tree, `Couldn't find node ${nodeId}.`);
}
const comment = tree.comments.find((__) => __.nodeId === nodeId);
return comment != null ? comment.content : null;
}
/**
* Sets the name for a tree. If no tree id is given, the active tree is used.
*
* @example
* api.tracing.setTreeName("Special tree", 1);
*/
setTreeName(name: string, treeId?: number | null | undefined) {
const skeletonTracing = assertSkeleton(Store.getState().annotation);
if (treeId == null) {
treeId = skeletonTracing.activeTreeId;
}
Store.dispatch(setTreeNameAction(name, treeId));
}
/**
* Sets the visibility of the edges for a tree. If no tree id is given, the active tree is used.
*
* @example
* api.tracing.setTreeEdgeVisibility(false, 1);
*/
setTreeEdgeVisibility(edgesAreVisible: boolean, treeId: number | null | undefined) {
const skeletonTracing = assertSkeleton(Store.getState().annotation);
if (treeId == null) {
treeId = skeletonTracing.activeTreeId;
}
Store.dispatch(setTreeEdgeVisibilityAction(treeId, edgesAreVisible));
}
/**
* Makes the specified tree active. Within the tree, the node with the highest ID will be activated.
*
* @example
* api.tracing.setActiveTree(3);
*/
setActiveTree(treeId: number) {
const { annotation } = Store.getState();
assertSkeleton(annotation);
Store.dispatch(setActiveTreeAction(treeId));
}
/**
* Makes the tree specified by name active. Within the tree, the node with the highest ID will be activated.
*
* @example
* api.tracing.setActiveTree("tree_1");
*/
setActiveTreeByName(treeName: string) {
const { annotation } = Store.getState();
assertSkeleton(annotation);
Store.dispatch(setActiveTreeByNameAction(treeName));
}
/**
* Makes the specified group active. Nodes cannot be added through the UI when a group is active.
*
* @example
* api.tracing.setActiveTreeGroup(3);
*/
setActiveTreeGroup(groupId: number) {
const { annotation } = Store.getState();
assertSkeleton(annotation);
Store.dispatch(setActiveTreeGroupAction(groupId));
}
/**
* Deprecated! Use renameSkeletonGroup instead.
*/
setActiveGroup(groupId: number) {
this.setActiveTreeGroup(groupId);
}
/**
* Changes the color of the referenced tree. Internally, a pre-defined array of colors is used which is
* why this function uses a colorIndex (between 0 and 500) instead of a proper color.
*
* @example
* api.tracing.setTreeColorIndex(3, 10);
*/
setTreeColorIndex(treeId: number | null | undefined, colorIndex: number) {
const { annotation } = Store.getState();
assertSkeleton(annotation);
Store.dispatch(setTreeColorIndexAction(treeId, colorIndex));
}
/**
* Changes the visibility of the referenced tree.
*
* @example
* api.tracing.setTreeVisibility(3, false);
*/
setTreeVisibility(treeId: number | null | undefined, isVisible: boolean) {
const { annotation } = Store.getState();
assertSkeleton(annotation);
Store.dispatch(setTreeVisibilityAction(treeId, isVisible));
}
/**
* Gets a list of tree groups
*
* @example
* api.tracing.getTreeGroups();
*/
getTreeGroups(): Array<TreeGroupTypeFlat> {
const { annotation } = Store.getState();
return Array.from(getFlatTreeGroups(assertSkeleton(annotation)));
}
/**
* Sets the parent group of the referenced tree.
*
* @example
* api.tracing.setTreeGroup(
* 3,
* api.tracing.getTreeGroups.find(({ name }) => name === "My Tree Group").id,
* );
*/
setTreeGroup(treeId?: number, groupId?: number) {
const { annotation } = Store.getState();
const skeletonTracing = assertSkeleton(annotation);
const treeGroupMap = getTreeGroupsMap(skeletonTracing);
if (groupId != null && treeGroupMap[groupId] == null) {
throw new Error("Provided group ID does not exist");
}
Store.dispatch(setTreeGroupAction(groupId, treeId));
}
async importNmlAsString(nmlString: string) {
const { treeGroups, trees } = await parseNml(nmlString);
Store.dispatch(addTreesAndGroupsAction(trees, treeGroups));
}
/**
* Renames the group referenced by the provided id.
*
* @example
* api.tracing.renameSkeletonGroup(
* 3,
* "New group name",
* );
*/
renameSkeletonGroup(groupId: number, newName: string) {
const { annotation } = Store.getState();
const skeletonTracing = assertSkeleton(annotation);
const newTreeGroups = cloneDeep(skeletonTracing.treeGroups);
callDeep(newTreeGroups, groupId, (item) => {
// @ts-expect-error ts-migrate(2540) FIXME: Cannot assign to 'name' because it is a read-only ... Remove this comment to see the full error message
item.name = newName;
});
Store.dispatch(setTreeGroupsAction(newTreeGroups));
}
/**
* Moves one skeleton group to another one (or to the root node when providing null as the second parameter).
*
* @example
* api.tracing.moveSkeletonGroup(
* 3,
* null, // moves group with id 0 to the root node
* );
*/
moveSkeletonGroup(groupId: number, targetGroupId: number | null) {
const skeleton = Store.getState().annotation.skeleton;
if (!skeleton) {
throw new Error("No skeleton tracing found.");
}
const newTreeGroups = moveGroupsHelper(skeleton.treeGroups, groupId, targetGroupId);
Store.dispatch(setTreeGroupsAction(newTreeGroups));
}
/**
* Adds a segment to the segment list.
*
* @example
* api.tracing.registerSegment(
* 3,
* [1, 2, 3],
* null, // optional
* "volume-layer-id" // optional
* );
*/
registerSegment(
segmentId: number,
anchorPosition: Vector3,
additionalCoordinates: AdditionalCoordinate[] | undefined = undefined,
layerName?: string,
) {
Store.dispatch(clickSegmentAction(segmentId, anchorPosition, additionalCoordinates, layerName));
}
/**
* Registers all segments that exist at least partially in the given bounding box.
*
* @example
* api.tracing.registerSegmentsForBoundingBox(
* [0, 0, 0],
* [10, 10, 10],
* "My Bounding Box"
* );
*/
registerSegmentsForBoundingBox = async (
min: Vector3,
max: Vector3,
bbName: string,
options?: { maximumSegmentCount?: number; maximumVolume?: number },
) => {
const state = Store.getState();
const maximumVolume = options?.maximumVolume ?? Constants.REGISTER_SEGMENTS_BB_MAX_VOLUME_VX;
const maximumSegmentCount =
options?.maximumSegmentCount ?? Constants.REGISTER_SEGMENTS_BB_MAX_SEGMENT_COUNT;
const boundingBoxInMag1 = new BoundingBox({
min,
max,
});
const segmentationLayerName = api.data.getVisibleSegmentationLayerName();
if (segmentationLayerName == null) {
throw new Error(
"No segmentation layer is currently visible. Enable the one you want to register segments for.",
);
}
const magInfo = getMagInfo(getLayerByName(state.dataset, segmentationLayerName).mags);
const theoreticalMagIndex = getActiveMagIndexForLayer(state, segmentationLayerName);
const existingMagIndex = magInfo.getIndexOrClosestHigherIndex(theoreticalMagIndex);
if (existingMagIndex == null) {
throw new Error("The index of the current mag could not be found.");
}
const currentMag = magInfo.getMagByIndex(existingMagIndex);
if (currentMag == null) {
throw new Error("No mag could be found.");
}
const boundingBoxInMag = boundingBoxInMag1.fromMag1ToMag(currentMag);
const volume = boundingBoxInMag.getVolume();
if (volume > maximumVolume) {
throw new Error(
`The volume of the bounding box exceeds ${maximumVolume} vx, please make it smaller. Currently, the bounding box has a volume of ${volume} vx in the active magnification (${currentMag.join("-")}).`,
);
} else if (volume > maximumVolume / 8) {
Toast.warning(
"The volume of the bounding box is very large, registering all segments might take a while.",
);
}
const data = await api.data.getDataForBoundingBox(
segmentationLayerName,
{
min,
max,
},
existingMagIndex,
);
const [dx, dy, dz] = currentMag;
// getDataForBoundingBox grows the bounding box to be mag-aligned which can change the dimensions
const boundingBoxInMag1MagAligned = boundingBoxInMag1.alignWithMag(currentMag, "grow");
const dataMin = boundingBoxInMag1MagAligned.min;
const dataMax = boundingBoxInMag1MagAligned.max;
const segmentIdToPosition = new Map();
let idx = 0;
for (let z = dataMin[2]; z < dataMax[2]; z += dz) {
for (let y = dataMin[1]; y < dataMax[1]; y += dy) {
for (let x = dataMin[0]; x < dataMax[0]; x += dx) {
const id = data[idx];
if (id !== 0 && !segmentIdToPosition.has(id)) {
segmentIdToPosition.set(id, [x, y, z]);
}
idx++;
}
}
}
const segmentIdCount = Array.from(segmentIdToPosition.entries()).length;
const halfMaxNoSegments = maximumSegmentCount / 2;
if (segmentIdCount > maximumSegmentCount) {
throw new Error(
`The given bounding box contains ${segmentIdCount} segments, but only ${maximumSegmentCount} segments can be registered at once. Please reduce the size of the bounding box.`,
);
} else if (segmentIdCount > halfMaxNoSegments) {
Toast.warning(
`The bounding box contains more than ${halfMaxNoSegments} segments. Registering all segments might take a while.`,
);
}
let groupId = MISSING_GROUP_ID;
try {
groupId = api.tracing.createSegmentGroup(`Segments for ${bbName}`, -1, segmentationLayerName);
} catch (_e) {
console.info(
`Volume tracing could not be found for the currently visible segmentation layer, registering segments for ${bbName} within root group.`,
);
Toast.warning(
"The current segmentation layer is not editable and the segment list will not be persisted across page reloads. You can make it editable by clicking on the lock symbol to the right of the layer name.",
);
}
const updateSegmentActions: BatchableUpdateSegmentAction[] = [];
for (const [segmentId, position] of segmentIdToPosition.entries()) {
api.tracing.registerSegment(segmentId, position, undefined, segmentationLayerName);
updateSegmentActions.push(
updateSegmentAction(segmentId, { groupId, id: segmentId }, segmentationLayerName),
);
}
if (updateSegmentActions.length > 0)
Store.dispatch(batchUpdateGroupsAndSegmentsAction(updateSegmentActions));
};
/**
* Gets a segment object within the referenced volume layer. Note that this object
* does not support any modifications made to it.
*
* @example
* const segment = api.tracing.getSegment(
* 3,
* "volume-layer-id"
* );
* console.log(segment.groupId)
*/
getSegment(segmentId: number, layerName: string): Segment {
const segment = getSegmentsForLayer(Store.getState(), layerName).getOrThrow(segmentId);
// Return a copy to avoid mutations by third-party code.
return { ...segment };
}
/**
* Updates a segment. The segment parameter can contain all properties of a Segment
* (except for the id) or less.
*
* @example
* api.tracing.updateSegment(
* 3,
* {
* name: "A name",
* anchorPosition: [1, 2, 3],
* additionalCoordinates: [],
* color: [1, 2, 3],
* groupId: 1,
* },
* "volume-layer-id"
* );
*/
updateSegment(segmentId: number, segment: Partial<Segment>, layerName: string) {
Store.dispatch(updateSegmentAction(segmentId, { ...segment, id: segmentId }, layerName));
}
/**
* Removes a segment from the segment list. This does *not* mutate the actual voxel data.
*
* @example
* api.tracing.removeSegment(
* 3,
* "volume-layer-id"
* );
*/
removeSegment(segmentId: number, layerName: string) {
Store.dispatch(removeSegmentAction(segmentId, layerName));
}
/**
* Moves one segment group to another one (or to the root node when providing null as the second parameter).
*
* @example
* api.tracing.moveSegmentGroup(
* 3,
* null, // moves group with id 0 to the root node
* "volume-layer-id"
* );
*/
moveSegmentGroup(groupId: number, targetGroupId: number | undefined | null, layerName: string) {
const { segmentGroups } = getVolumeTracingById(Store.getState().annotation, layerName);
const newSegmentGroups = moveGroupsHelper(segmentGroups, groupId, targetGroupId);
Store.dispatch(setSegmentGroupsAction(newSegmentGroups, layerName));
}
/**
* Creates a new segment group and returns its id.
*
* @example
* api.tracing.createSegmentGroup(
* "Group name", // optional
* parentGroupId, // optional. use -1 for the root group
* volumeLayerName, // see getSegmentationLayerNames
* );
*/
createSegmentGroup(
name: string | null = null,
parentGroupId: number | null = MISSING_GROUP_ID,
volumeLayerName?: string,
): number {
const volumeTracing = volumeLayerName
? getVolumeTracingByLayerName(Store.getState().annotation, volumeLayerName)
: getActiveSegmentationTracing(Store.getState());
if (volumeTracing == null) {
throw new Error(`Could not find volume tracing layer with name ${volumeLayerName}`);
}
const { segmentGroups } = volumeTracing;
const { newSegmentGroups, newGroupId } = createGroupHelper(
segmentGroups,
name,
getMaximumGroupId(segmentGroups) + 1,
parentGroupId,
);
Store.dispatch(setSegmentGroupsAction(newSegmentGroups, volumeTracing.tracingId));
return newGroupId;
}
/**
* Renames the segment group referenced by the provided id.
*
* @example
* api.tracing.renameSegmentGroup(
* 3,
* "New group name",
* volumeLayerName, // see getSegmentationLayerNames
* );
*/
renameSegmentGroup(groupId: number, newName: string, volumeLayerName?: string) {
const volumeTracing = volumeLayerName
? getVolumeTracingByLayerName(Store.getState().annotation, volumeLayerName)
: getActiveSegmentationTracing(Store.getState());
if (volumeTracing == null) {
throw new Error(`Could not find volume tracing layer with name ${volumeLayerName}`);
}
const { segmentGroups } = volumeTracing;
const newSegmentGroups = mapGroups(segmentGroups, (group) => {
if (group.groupId === groupId) {
return {
...group,
name: newName,
};
} else {
return group;
}
});
Store.dispatch(setSegmentGroupsAction(newSegmentGroups, volumeTracing.tracingId));
}
/**
* Deletes the segment group referenced by the provided id. If deleteChildren is
* true, the deletion is recursive.
*
* @example
* api.tracing.deleteSegmentGroup(
* 3,
* true,
* volumeLayerName, // see getSegmentationLayerNames
* );
*/
deleteSegmentGroup(groupId: number, deleteChildren: boolean = false, volumeLayerName?: string) {
const volumeTracing = volumeLayerName
? getVolumeTracingByLayerName(Store.getState().annotation, volumeLayerName)
: getActiveSegmentationTracing(Store.getState());
if (volumeTracing == null) {
throw new Error(`Could not find volume tracing layer with name ${volumeLayerName}`);
}
const { segments, segmentGroups } = volumeTracing;
if (segments == null || segmentGroups == null) {
return;
}
let newSegmentGroups = cloneDeep(segmentGroups);
const groupToSegmentsMap = createGroupToSegmentsMap(segments);
let segmentIdsToDelete: number[] = [];
if (groupId === MISSING_GROUP_ID) {
// special case: delete Root group and all children (aka everything)
segmentIdsToDelete = segments
.values()
.map((t) => t.id)
.toArray();
newSegmentGroups = [];
}
const updateSegmentActions: BatchableUpdateSegmentAction[] = [];
callDeep(newSegmentGroups, groupId, (item, index, parentsChildren, parentGroupId) => {
const subsegments = groupToSegmentsMap[groupId] != null ? groupToSegmentsMap[groupId] : [];
// Remove group
parentsChildren.splice(index, 1);
if (!deleteChildren) {
// Move all subgroups to the parent group
parentsChildren.push(...item.children);
// Update all segments
for (const segment of subsegments.values()) {
updateSegmentActions.push(
updateSegmentAction(
segment.id,
{ groupId: parentGroupId === MISSING_GROUP_ID ? null : parentGroupId },
volumeTracing.tracingId,
// The parameter createsNewUndoState is not passed, since the action
// is added to a batch and batch updates always create a new undo state.
),
);
}
return;
}
// Finds all subsegments of the passed group recursively
const findChildrenRecursively = (group: SegmentGroup) => {
const currentSubsegments = groupToSegmentsMap[group.groupId] ?? [];
// Delete all segments of the current group
segmentIdsToDelete = segmentIdsToDelete.concat(
currentSubsegments.map((segment) => segment.id),
);
// Also delete the segments of all subgroups
group.children.forEach((subgroup) => {
findChildrenRecursively(subgroup);
});
};
findChildrenRecursively(item);
});
// Update the store at once
const removeSegmentActions: BatchableUpdateSegmentAction[] = segmentIdsToDelete.map(
(segmentId) => removeSegmentAction(segmentId, volumeTracing.tracingId),
);
Store.dispatch(
batchUpdateGroupsAndSegmentsAction(
updateSegmentActions.concat(removeSegmentActions, [
setSegmentGroupsAction(newSegmentGroups, volumeTracing.tracingId),
]),
),