@biolibs/bionet-space 0.0.0-stage → 0.2.0

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.
package/src/arrange.ts ADDED
@@ -0,0 +1,263 @@
1
+ /**
2
+ * Giving every place somewhere to stand.
3
+ *
4
+ * A place that says where it stands is put there. One that does not is arranged by what it is:
5
+ * shelves split a freezer's height between them, racks share a shelf side by side, boxes stack in a
6
+ * rack. So a lab that has only ever said what is inside what still has a shape that can be drawn,
7
+ * and one that has been measured is drawn as measured.
8
+ *
9
+ * The result is in the lab's own coordinates, with turning already worked in. Every place comes out
10
+ * as a box with its sides along the axes, because places turn only by quarter turns — which is what
11
+ * keeps this arithmetic and not geometry.
12
+ */
13
+ import type { Arranged, Layout, Place, Slot, Standing, Turn } from "./model.js";
14
+
15
+ /** How big something is when nobody has said, by kind, in metres: wide, tall, deep. */
16
+ export const DEFAULT_SIZE: Readonly<Record<string, readonly [number, number, number]>> = {
17
+ room: [6, 2.8, 5],
18
+ freezer: [0.9, 2.0, 0.85],
19
+ fridge: [0.7, 1.8, 0.7],
20
+ bench: [1.8, 0.9, 0.75],
21
+ instrument: [0.4, 0.3, 0.4],
22
+ box: [0.134, 0.052, 0.134],
23
+ };
24
+
25
+ /** How big an instrument is by model, where that differs from the default. */
26
+ export const INSTRUMENT_SIZE: Readonly<Record<string, readonly [number, number, number]>> = {
27
+ thermocycler: [0.35, 0.25, 0.45],
28
+ "gel-station": [0.45, 0.18, 0.3],
29
+ centrifuge: [0.4, 0.3, 0.45],
30
+ computer: [0.5, 0.4, 0.25],
31
+ microscope: [0.3, 0.45, 0.4],
32
+ };
33
+
34
+ /** How much of a place's inside is kept clear of its walls, as a fraction of each side. */
35
+ const INSET = 0.06;
36
+ /** The gap left between things arranged side by side, in metres. */
37
+ const GAP = 0.02;
38
+
39
+ const sizeOf = (place: Place): [number, number, number] => {
40
+ if (place.standing !== undefined) return [...place.standing.size];
41
+ const size = (place.kind === "instrument" && place.model !== undefined ? INSTRUMENT_SIZE[place.model] : undefined)
42
+ ?? DEFAULT_SIZE[place.kind] ?? [0.5, 0.5, 0.5];
43
+ return [...size];
44
+ };
45
+
46
+ /** Turn an offset measured in a turned place into the lab's directions. */
47
+ function turned([x, y, z]: [number, number, number], turn: Turn): [number, number, number] {
48
+ switch (turn) {
49
+ case 90: return [-z, y, x];
50
+ case 180: return [-x, y, -z];
51
+ case 270: return [z, y, -x];
52
+ default: return [x, y, z];
53
+ }
54
+ }
55
+
56
+ /** A size as it lies once turned: a quarter turn swaps wide and deep. */
57
+ const lying = ([w, h, d]: [number, number, number], turn: Turn): [number, number, number] =>
58
+ (turn === 90 || turn === 270 ? [d, h, w] : [w, h, d]);
59
+
60
+ /**
61
+ * Where each child stands inside a parent that has not been told, measured from the centre of the
62
+ * parent's base, with the parent facing front.
63
+ *
64
+ * @param parent - The size of the parent: wide, tall, deep.
65
+ * @param kind - What the parent is.
66
+ * @param children - The children with no standing of their own, in order.
67
+ * @returns A standing for each, in the same order.
68
+ */
69
+ function byDefault(parent: [number, number, number], kind: string, children: Place[]): Standing[] {
70
+ const [W, H, D] = parent;
71
+ const inside: [number, number, number] = [W * (1 - 2 * INSET), H * (1 - 2 * INSET), D * (1 - 2 * INSET)];
72
+ const floor = H * INSET;
73
+ const count = children.length;
74
+ const sample = children[0]!.kind;
75
+
76
+ if (sample === "shelf") {
77
+ // Shelves split the height between them, the first at the top.
78
+ const each = inside[1] / count;
79
+ return children.map((_, at) => ({ position: [0, floor + (count - 1 - at) * each, 0], size: [inside[0], each - GAP, inside[2]] }));
80
+ }
81
+ if (sample === "box") {
82
+ // Boxes keep their own size and stack: upwards first, then across, then towards the back.
83
+ const [w, h, d] = sizeOf(children[0]!);
84
+ const high = Math.max(1, Math.floor((inside[1] + GAP) / (h + GAP)));
85
+ const across = Math.max(1, Math.floor((inside[0] + GAP) / (w + GAP)));
86
+ return children.map((_, at) => {
87
+ const level = at % high;
88
+ const column = Math.floor(at / high) % across;
89
+ const back = Math.floor(at / (high * across));
90
+ return {
91
+ position: [-inside[0] / 2 + w / 2 + column * (w + GAP), floor + level * (h + GAP), inside[2] / 2 - d / 2 - back * (d + GAP)],
92
+ size: [w, h, d],
93
+ };
94
+ });
95
+ }
96
+ if (kind === "room") {
97
+ // Whatever stands on a room's floor lines up along the back wall, at its own size.
98
+ const sizes = children.map(sizeOf);
99
+ const total = sizes.reduce((sum, size) => sum + size[0], 0) + 0.4 * (count - 1);
100
+ let x = -total / 2;
101
+ return sizes.map((size) => {
102
+ const standing: Standing = { position: [x + size[0] / 2, 0, -D / 2 + size[2] / 2 + 0.1], size };
103
+ x += size[0] + 0.4;
104
+ return standing;
105
+ });
106
+ }
107
+ if (kind === "bench") {
108
+ // Things on a bench stand on its top, spread along it.
109
+ const sizes = children.map(sizeOf);
110
+ const step = W / count;
111
+ return sizes.map((size, at) => ({ position: [-W / 2 + step * (at + 0.5), H, 0], size }));
112
+ }
113
+ // Anything else shares the width side by side: racks on a shelf, or whatever a lab has invented.
114
+ const each = (inside[0] - GAP * (count - 1)) / count;
115
+ return children.map((_, at) => ({ position: [-inside[0] / 2 + each / 2 + at * (each + GAP), floor, 0], size: [each, inside[1], inside[2]] }));
116
+ }
117
+
118
+ /**
119
+ * Give every place somewhere to stand.
120
+ *
121
+ * @param layout - The lab. Only its places are used.
122
+ * @returns Every place, with the space it takes up in the lab's coordinates, in an order where a
123
+ * place always comes after the place it is in. A place whose parent does not exist is left out.
124
+ *
125
+ * @example
126
+ * ```ts
127
+ * import { arrange, exampleLab } from "@biolibs/bionet-space";
128
+ *
129
+ * const arranged = arrange(exampleLab());
130
+ * arranged.find((one) => one.place.kind === "freezer")?.size; // [ 0.9, 2, 0.85 ]
131
+ * ```
132
+ */
133
+ export function arrange(layout: Pick<Layout, "places">): Arranged[] {
134
+ const children = new Map<string | null, Place[]>();
135
+ for (const place of layout.places) children.set(place.parent, [...(children.get(place.parent) ?? []), place]);
136
+ const out: Arranged[] = [];
137
+
138
+ /**
139
+ * Put `places` inside a parent whose base is centred at `base`, with size `size` and turn `turn`.
140
+ * `given` holds standings already chosen for places that did not say where they stand.
141
+ */
142
+ const settle = (places: Place[], base: [number, number, number], size: [number, number, number], kind: string, turn: Turn,
143
+ path: string[], given: Map<Place, Standing> = new Map()): void => {
144
+ const chosen = new Map(given);
145
+ const unplaced = places.filter((place) => place.standing === undefined && !chosen.has(place));
146
+ // Shelves and boxes each have a rule of their own. Everything else in the same place is arranged
147
+ // together, so a freezer and a fridge in one room stand side by side and not on top of each other.
148
+ const sort = (place: Place): string => (place.kind === "shelf" || place.kind === "box" ? place.kind : "other");
149
+ for (const which of new Set(unplaced.map(sort))) {
150
+ const group = unplaced.filter((place) => sort(place) === which);
151
+ byDefault(size, kind, group).forEach((standing, at) => chosen.set(group[at]!, standing));
152
+ }
153
+ for (const place of places) {
154
+ const standing = place.standing ?? chosen.get(place)!;
155
+ const whole = ((turn + (standing.turn ?? 0)) % 360) as Turn;
156
+ const offset = turned(standing.position, turn);
157
+ const at: [number, number, number] = [base[0] + offset[0], base[1] + offset[1], base[2] + offset[2]];
158
+ const space = lying([...standing.size], whole);
159
+ const here = [...path, place.id];
160
+ out.push({ place, center: [at[0], at[1] + space[1] / 2, at[2]], size: space, turn: whole, path: here,
161
+ placed: place.standing === undefined ? "by default" : "by hand" });
162
+ const inside = children.get(place.id);
163
+ if (inside !== undefined) settle(inside, at, [...standing.size], place.kind, whole, here);
164
+ }
165
+ };
166
+
167
+ // Rooms that have not been told where to stand line up in a row, a little apart.
168
+ const rooms = children.get(null) ?? [];
169
+ const row = new Map<Place, Standing>();
170
+ let x = 0;
171
+ for (const room of rooms) {
172
+ if (room.standing !== undefined) continue;
173
+ const size = sizeOf(room);
174
+ row.set(room, { position: [x + size[0] / 2, 0, 0], size });
175
+ x += size[0] + 1.5;
176
+ }
177
+ settle(rooms, [0, 0, 0], [0, 0, 0], "lab", 0, [], row);
178
+ return out;
179
+ }
180
+
181
+ /**
182
+ * Where one position in a box is, in the lab's coordinates.
183
+ *
184
+ * @param box - The box, arranged.
185
+ * @param slot - Which position.
186
+ * @returns The centre of that position on the floor of the box, or `null` if the box has no such position.
187
+ */
188
+ export function slotCenter(box: Arranged, slot: Slot): [number, number, number] | null {
189
+ const grid = box.place.grid;
190
+ if (grid === undefined || slot.row < 0 || slot.column < 0 || slot.row >= grid.rows || slot.column >= grid.columns) return null;
191
+ // Rows run from the back to the front and columns from left to right, in the box's own facing.
192
+ const [w, , d] = lying([...box.size], box.turn); // undo the turn to get the box's own wide and deep
193
+ const across = -w / 2 + (w / grid.columns) * (slot.column + 0.5);
194
+ const forward = -d / 2 + (d / grid.rows) * (slot.row + 0.5);
195
+ const offset = turned([across, 0, forward], box.turn);
196
+ return [box.center[0] + offset[0], box.center[1] - box.size[1] / 2, box.center[2] + offset[2]];
197
+ }
198
+
199
+ /**
200
+ * How big one position in a box is.
201
+ *
202
+ * @param box - The box, arranged.
203
+ * @returns The side of the square each position gets, in metres, or 0 if the box has no positions.
204
+ */
205
+ export function slotSize(box: Arranged): number {
206
+ const grid = box.place.grid;
207
+ if (grid === undefined) return 0;
208
+ const [w, , d] = lying([...box.size], box.turn);
209
+ return Math.min(w / grid.columns, d / grid.rows);
210
+ }
211
+
212
+ /**
213
+ * The first position in a box that nothing is stored in.
214
+ *
215
+ * @param box - The box.
216
+ * @param taken - The positions already used.
217
+ * @returns A free position, row by row from the back left, or `null` if the box is full or has none.
218
+ */
219
+ export function firstFreeSlot(box: Place, taken: readonly Slot[]): Slot | null {
220
+ if (box.grid === undefined) return null;
221
+ const used = new Set(taken.map((slot) => `${slot.row},${slot.column}`));
222
+ for (let row = 0; row < box.grid.rows; row++) {
223
+ for (let column = 0; column < box.grid.columns; column++) {
224
+ if (!used.has(`${row},${column}`)) return { row, column };
225
+ }
226
+ }
227
+ return null;
228
+ }
229
+
230
+ /**
231
+ * What a position is called, the way it is written on a box lid: a letter for the row, a number for
232
+ * the column.
233
+ *
234
+ * @param slot - The position.
235
+ * @returns Something like `C4`.
236
+ */
237
+ export function slotName(slot: Slot): string {
238
+ let row = "";
239
+ for (let at = slot.row; at >= 0; at = Math.floor(at / 26) - 1) row = String.fromCharCode(65 + (at % 26)) + row;
240
+ return `${row}${slot.column + 1}`;
241
+ }
242
+
243
+ /**
244
+ * Read a position the way it is written on a box lid.
245
+ *
246
+ * @param name - Something like `C4` or `c4`.
247
+ * @returns The position, or `null` if that is not how one is written.
248
+ *
249
+ * @example
250
+ * ```ts
251
+ * import { slotFrom, slotName } from "@biolibs/bionet-space";
252
+ *
253
+ * slotFrom("C4"); // { row: 2, column: 3 }
254
+ * slotName(slotFrom("AB12")!); // "AB12"
255
+ * slotFrom("4C"); // null
256
+ * ```
257
+ */
258
+ export function slotFrom(name: string): Slot | null {
259
+ const found = /^([A-Za-z]{1,2})([1-9][0-9]{0,2})$/.exec(name.trim());
260
+ if (found === null) return null;
261
+ const row = [...found[1]!.toUpperCase()].reduce((sum, letter) => sum * 26 + (letter.charCodeAt(0) - 64), 0) - 1;
262
+ return { row, column: Number(found[2]) - 1 };
263
+ }
package/src/example.ts ADDED
@@ -0,0 +1,95 @@
1
+ /**
2
+ * A lab to look at: one room, a −80 freezer full of boxes, a fridge, two benches and their
3
+ * instruments.
4
+ *
5
+ * It is here so that anything that draws a lab has one to draw before a real one exists, and so that
6
+ * tests have something of a realistic size. The room, the freezer, the fridge and the benches say
7
+ * where they stand; the shelves, racks and boxes do not, and are arranged for them — which is the
8
+ * mix a real lab will have.
9
+ *
10
+ * It is the same every time it is made. The tubes are scattered by a fixed sequence, not by chance.
11
+ */
12
+ import type { Layout, Place, Stored } from "./model.js";
13
+
14
+ /** What the example freezer is stocked with. The first seven are the parts the Wren Lab publishes. */
15
+ const PARTS = ["f1", "f2", "acceptor", "part1", "part2", "template", "backbone", "pUC19", "pET-28a", "pBR322", "pGEX-4T-1",
16
+ "GFP insert", "mCherry insert", "lacZα", "T7 promoter", "Cas9", "sgRNA scaffold", "AmpR cassette", "KanR cassette",
17
+ "pSB1C3", "RFP reporter"];
18
+
19
+ /** A sequence of numbers between 0 and 1 that is the same every time. */
20
+ function sequence(seed: number): () => number {
21
+ let state = seed >>> 0;
22
+ return () => {
23
+ state = (state + 0x6d2b79f5) >>> 0;
24
+ let mixed = Math.imul(state ^ (state >>> 15), 1 | state);
25
+ mixed = (mixed + Math.imul(mixed ^ (mixed >>> 7), 61 | mixed)) ^ mixed;
26
+ return ((mixed ^ (mixed >>> 14)) >>> 0) / 4294967296;
27
+ };
28
+ }
29
+
30
+ /**
31
+ * Make the example lab.
32
+ *
33
+ * @returns Its places and what is stored in them.
34
+ *
35
+ * @example
36
+ * ```ts
37
+ * import { arrange, exampleLab, search } from "@biolibs/bionet-space";
38
+ *
39
+ * const lab = exampleLab();
40
+ * lab.places.filter((place) => place.kind === "box").length; // 72
41
+ * search(lab, "puc19").length > 0; // true
42
+ * arrange(lab).length === lab.places.length; // true: everything has somewhere to stand
43
+ * ```
44
+ */
45
+ export function exampleLab(): Layout {
46
+ const next = sequence(20261115);
47
+ const places: Place[] = [
48
+ { id: "main", kind: "room", name: "Main lab", parent: null, standing: { position: [0, 0, 0], size: [7, 2.8, 5] } },
49
+ { id: "minus80", kind: "freezer", name: "−80 freezer", parent: "main", standing: { position: [-2.7, 0, -1.975], size: [0.9, 2.0, 0.85] } },
50
+ { id: "fridge", kind: "fridge", name: "4 °C fridge", parent: "main", standing: { position: [-1.6, 0, -2.05], size: [0.7, 1.8, 0.7] } },
51
+ { id: "bench1", kind: "bench", name: "Bench 1", parent: "main", standing: { position: [0.7, 0, -2.0], size: [2.4, 0.9, 0.75] } },
52
+ { id: "bench2", kind: "bench", name: "Bench 2", parent: "main", standing: { position: [3.0, 0, 0.3], size: [2.2, 0.9, 0.75], turn: 90 } },
53
+ { id: "thermocycler", kind: "instrument", model: "thermocycler", name: "Thermocycler", parent: "bench1" },
54
+ { id: "gel", kind: "instrument", model: "gel-station", name: "Gel station", parent: "bench1" },
55
+ { id: "centrifuge", kind: "instrument", model: "centrifuge", name: "Centrifuge", parent: "bench1" },
56
+ { id: "computer", kind: "instrument", model: "computer", name: "Computer", parent: "bench2" },
57
+ { id: "microscope", kind: "instrument", model: "microscope", name: "Microscope", parent: "bench2" },
58
+ ];
59
+ const stored: Stored[] = [];
60
+ let tubes = 0;
61
+
62
+ /** Add a box, and scatter tubes in it. */
63
+ const box = (id: string, name: string, parent: string, rows: number, columns: number, fullness: number): void => {
64
+ places.push({ id, kind: "box", name, parent, grid: { rows, columns } });
65
+ for (let row = 0; row < rows; row++) {
66
+ for (let column = 0; column < columns; column++) {
67
+ if (next() >= fullness) continue;
68
+ const part = PARTS[Math.floor(next() * PARTS.length)]!;
69
+ tubes++;
70
+ stored.push({ item: `tube-${String(tubes).padStart(4, "0")}`, place: id, slot: { row, column }, part: `example:${part}`, name: part,
71
+ amount: 5 + Math.floor(next() * 46), unit: "µL", ...(next() < 0.012 ? { needsRecount: true } : {}) });
72
+ }
73
+ }
74
+ };
75
+
76
+ // The freezer: four shelves, three racks on each, five boxes of 81 in each rack.
77
+ for (let shelf = 1; shelf <= 4; shelf++) {
78
+ places.push({ id: `minus80-s${shelf}`, kind: "shelf", name: `Shelf ${shelf}`, parent: "minus80" });
79
+ for (const rack of ["A", "B", "C"]) {
80
+ const rackId = `minus80-s${shelf}-${rack}`;
81
+ places.push({ id: rackId, kind: "rack", name: `Rack ${shelf}${rack}`, parent: `minus80-s${shelf}` });
82
+ for (let at = 1; at <= 5; at++) {
83
+ // Some boxes are nearly full, some nearly empty, and a few have nothing in them yet.
84
+ const fullness = next() < 0.15 ? 0 : 0.15 + next() * 0.8;
85
+ box(`${rackId}-${at}`, `Box ${shelf}${rack}${at}`, rackId, 9, 9, fullness);
86
+ }
87
+ }
88
+ }
89
+ // The fridge: three shelves with four boxes of 25 standing on each.
90
+ for (let shelf = 1; shelf <= 3; shelf++) {
91
+ places.push({ id: `fridge-s${shelf}`, kind: "shelf", name: `Shelf ${shelf}`, parent: "fridge" });
92
+ for (let at = 1; at <= 4; at++) box(`fridge-s${shelf}-${at}`, `Box F${shelf}-${at}`, `fridge-s${shelf}`, 5, 5, 0.2 + next() * 0.6);
93
+ }
94
+ return { places, stored };
95
+ }
package/src/find.ts ADDED
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Finding your way around an arranged lab: what is inside what, what a search turns up, and where a
3
+ * camera should look to see a place.
4
+ */
5
+ import type { Arranged, Layout, Stored } from "./model.js";
6
+
7
+ /** How close a place is to the things in it: a room, something standing in one, or a box of positions. */
8
+ export type Level = "lab" | "room" | "unit" | "inside" | "box";
9
+
10
+ /**
11
+ * How close a look at a place is.
12
+ *
13
+ * @param arranged - The place, or `null` for the whole lab.
14
+ * @returns `lab` for everything, `room` for a room, `unit` for whatever stands in a room (a freezer, a
15
+ * bench, an instrument), `box` for a place with positions, and `inside` for anything between.
16
+ */
17
+ export function levelOf(arranged: Arranged | null): Level {
18
+ if (arranged === null) return "lab";
19
+ if (arranged.place.grid !== undefined) return "box";
20
+ if (arranged.path.length === 1) return "room";
21
+ if (arranged.path.length === 2) return "unit";
22
+ return "inside";
23
+ }
24
+
25
+ /** A box that everything fits in. */
26
+ export interface Bounds {
27
+ center: [number, number, number];
28
+ size: [number, number, number];
29
+ }
30
+
31
+ /**
32
+ * The space some places take up together.
33
+ *
34
+ * @param places - The places.
35
+ * @returns The smallest box around all of them, or `null` if there are none.
36
+ */
37
+ export function boundsOf(places: readonly Pick<Arranged, "center" | "size">[]): Bounds | null {
38
+ if (places.length === 0) return null;
39
+ const low = [Infinity, Infinity, Infinity];
40
+ const high = [-Infinity, -Infinity, -Infinity];
41
+ for (const { center, size } of places) {
42
+ for (let axis = 0; axis < 3; axis++) {
43
+ low[axis] = Math.min(low[axis]!, center[axis]! - size[axis]! / 2);
44
+ high[axis] = Math.max(high[axis]!, center[axis]! + size[axis]! / 2);
45
+ }
46
+ }
47
+ return {
48
+ center: [(low[0]! + high[0]!) / 2, (low[1]! + high[1]!) / 2, (low[2]! + high[2]!) / 2],
49
+ size: [high[0]! - low[0]!, high[1]! - low[1]!, high[2]! - low[2]!],
50
+ };
51
+ }
52
+
53
+ /** Where a camera stands and what it looks at. */
54
+ export interface Pose {
55
+ /** Where the camera is. */
56
+ position: [number, number, number];
57
+ /** What it looks at. */
58
+ target: [number, number, number];
59
+ }
60
+
61
+ /** Which way to look from, by level, for something facing front: across, up, towards the viewer. */
62
+ const FROM: Readonly<Record<Level, readonly [number, number, number]>> = {
63
+ lab: [0.45, 0.62, 1],
64
+ room: [0.4, 0.6, 1],
65
+ unit: [0.42, 0.28, 1],
66
+ inside: [0.3, 0.2, 1],
67
+ box: [0, 1, 0.42],
68
+ };
69
+
70
+ /**
71
+ * Where a camera should stand to see a place whole.
72
+ *
73
+ * It looks from in front and a little above, closer the smaller the thing is, and from nearly
74
+ * straight above for a box, since a box is read like a page. A place that is turned is looked at
75
+ * from its own front.
76
+ *
77
+ * @param arranged - Every place, arranged.
78
+ * @param id - The place to look at, or `null` for the whole lab.
79
+ * @param fov - The camera's vertical field of view, in degrees.
80
+ * @returns Where to stand and what to look at.
81
+ */
82
+ export function poseFor(arranged: readonly Arranged[], id: string | null, fov = 45): Pose {
83
+ const one = id === null ? null : arranged.find((each) => each.place.id === id) ?? null;
84
+ const bounds = one ?? boundsOf(arranged.filter((each) => each.place.parent === null)) ?? { center: [0, 0, 0], size: [4, 3, 4] };
85
+ const level = levelOf(one);
86
+ const [x, y, z] = FROM[level];
87
+ // Turn the direction with the place, so a freezer facing a side wall is still seen from its front.
88
+ const turn = one?.turn ?? 0;
89
+ const [dx, dz] = turn === 90 ? [-z, x] : turn === 180 ? [-x, -z] : turn === 270 ? [z, -x] : [x, z];
90
+ const length = Math.hypot(dx, y, dz);
91
+ const reach = Math.max(bounds.size[0], bounds.size[1], bounds.size[2]);
92
+ const distance = (reach * (level === "lab" || level === "room" ? 0.68 : level === "box" ? 1.25 : 1.0)) / Math.tan((fov * Math.PI) / 360);
93
+ return {
94
+ target: [...bounds.center] as [number, number, number],
95
+ position: [bounds.center[0] + (dx / length) * distance, bounds.center[1] + (y / length) * distance, bounds.center[2] + (dz / length) * distance],
96
+ };
97
+ }
98
+
99
+ /**
100
+ * Everything stored in a place or in anything inside it.
101
+ *
102
+ * @param layout - The lab.
103
+ * @param arranged - Its places, arranged.
104
+ * @param id - The place.
105
+ * @returns What is stored there, however deep.
106
+ */
107
+ export function storedWithin(layout: Pick<Layout, "stored">, arranged: readonly Arranged[], id: string): Stored[] {
108
+ const inside = new Set(arranged.filter((one) => one.path.includes(id)).map((one) => one.place.id));
109
+ return layout.stored.filter((one) => inside.has(one.place));
110
+ }
111
+
112
+ /**
113
+ * Search what is stored, by the name of the part.
114
+ *
115
+ * @param layout - The lab.
116
+ * @param words - What was typed. Case does not matter, and every word has to appear.
117
+ * @returns What matched, in the order it is stored. Nothing, if nothing was typed.
118
+ */
119
+ export function search(layout: Pick<Layout, "stored">, words: string): Stored[] {
120
+ const wanted = words.toLowerCase().split(/\s+/).filter((word) => word !== "");
121
+ if (wanted.length === 0) return [];
122
+ return layout.stored.filter((one) => wanted.every((word) => one.name.toLowerCase().includes(word)));
123
+ }
package/src/from.ts ADDED
@@ -0,0 +1,105 @@
1
+ /**
2
+ * A layout made from a lab's own record of itself.
3
+ *
4
+ * A lab's signed log says what places it has, which is inside which, and where each item was put.
5
+ * This turns that into a `Layout`. It asks for the lab structurally, by the few fields it reads, so
6
+ * this package still depends on nothing: `@biolibs/bionet`'s lab state fits, and so does anything
7
+ * else shaped like it.
8
+ */
9
+ import type { Layout, Place, Stored, Turn } from "./model.js";
10
+
11
+ /** A place, as a lab records it. Lengths are whole millimetres. */
12
+ export interface RecordedPlace {
13
+ place: string;
14
+ kind: string;
15
+ name: string;
16
+ parent: string | null;
17
+ grid: { rows: number; columns: number } | null;
18
+ standing: { at: readonly number[]; size: readonly number[]; turn: number } | null;
19
+ retired: boolean;
20
+ fields?: Readonly<Record<string, string | number | null>>;
21
+ }
22
+
23
+ /** An item, as a lab records it. */
24
+ export interface RecordedItem {
25
+ item: string;
26
+ part: string;
27
+ unit: string | null;
28
+ amount: number;
29
+ retired: boolean;
30
+ needsRecount: boolean;
31
+ where: { place: string; slot: { row: number; column: number } | null } | null;
32
+ }
33
+
34
+ /** As much of a lab as a layout is made from. */
35
+ export interface RecordedLab {
36
+ places: readonly RecordedPlace[];
37
+ items: readonly RecordedItem[];
38
+ parts: readonly { checksum: string; name: string }[];
39
+ }
40
+
41
+ /** The ID of the room that is made up when a lab has places standing in no room. */
42
+ export const UNNAMED_ROOM = "~room";
43
+
44
+ const metres = (list: readonly number[]): [number, number, number] => [list[0]! / 1000, list[1]! / 1000, list[2]! / 1000];
45
+
46
+ /**
47
+ * Make a layout from a lab.
48
+ *
49
+ * Retired places are left out, with everything in them. Items that have been retired, or that
50
+ * nobody has put anywhere, are left out too: a layout is of what can be found. A place that stands
51
+ * in no room is put in one made up for the purpose, so that a lab which has only said "there is a
52
+ * freezer" can still be drawn.
53
+ *
54
+ * @param lab - The lab's places, items and parts.
55
+ * @param options - `room` is what to call the room that is made up if one is needed.
56
+ * @returns The layout.
57
+ *
58
+ * @example
59
+ * ```ts
60
+ * import { layoutFrom } from "@biolibs/bionet-space";
61
+ *
62
+ * const layout = layoutFrom({
63
+ * places: [{ place: "f", kind: "freezer", name: "−80", parent: null, grid: null, standing: null, retired: false }],
64
+ * items: [], parts: [],
65
+ * });
66
+ * layout.places.map((one) => [one.id, one.parent]); // [ [ "~room", null ], [ "f", "~room" ] ]
67
+ * ```
68
+ */
69
+ export function layoutFrom(lab: RecordedLab, options: { room?: string } = {}): Layout {
70
+ const byId = new Map(lab.places.map((one) => [one.place, one]));
71
+ /** Whether a place, and everything it is inside, is still in use. */
72
+ const kept = (id: string): boolean => {
73
+ const passed = new Set<string>();
74
+ for (let at: string | null = id; at !== null; at = byId.get(at)!.parent) {
75
+ const one = byId.get(at);
76
+ if (one === undefined || one.retired || passed.has(at)) return false;
77
+ passed.add(at);
78
+ }
79
+ return true;
80
+ };
81
+
82
+ const loose = lab.places.some((one) => one.parent === null && one.kind !== "room" && kept(one.place));
83
+ const places: Place[] = loose ? [{ id: UNNAMED_ROOM, kind: "room", name: options.room ?? "Lab", parent: null }] : [];
84
+ for (const one of lab.places) {
85
+ if (!kept(one.place)) continue;
86
+ const model = one.fields?.["model"];
87
+ places.push({
88
+ id: one.place, kind: one.kind, name: one.name,
89
+ parent: one.parent ?? (one.kind === "room" ? null : UNNAMED_ROOM),
90
+ ...(one.standing === null ? {} : { standing: { position: metres(one.standing.at), size: metres(one.standing.size), turn: one.standing.turn as Turn } }),
91
+ ...(one.grid === null ? {} : { grid: { rows: one.grid.rows, columns: one.grid.columns } }),
92
+ ...(typeof model === "string" ? { model } : {}),
93
+ });
94
+ }
95
+
96
+ const names = new Map(lab.parts.map((part) => [part.checksum, part.name]));
97
+ const stored: Stored[] = [];
98
+ for (const item of lab.items) {
99
+ if (item.retired || item.where === null || !byId.has(item.where.place) || !kept(item.where.place)) continue;
100
+ stored.push({ item: item.item, place: item.where.place, slot: item.where.slot, part: item.part,
101
+ name: names.get(item.part) ?? "A part the lab no longer lists", amount: item.amount, unit: item.unit,
102
+ needsRecount: item.needsRecount });
103
+ }
104
+ return { places, stored };
105
+ }
package/src/index.ts ADDED
@@ -0,0 +1,23 @@
1
+ /**
2
+ * @packageDocumentation
3
+ * `@biolibs/bionet-space`: where things are in a lab.
4
+ *
5
+ * A lab is a tree of places with things stored at the ends of it. This package says what that tree
6
+ * is, gives every place somewhere to stand, and answers the questions a view of a lab asks: what is
7
+ * inside what, where a position in a box is, what a search turns up, where a camera should look.
8
+ *
9
+ * It draws nothing and depends on nothing. It is the contract between whatever knows what a lab
10
+ * holds and whatever shows it, so a 3D scene, a flat grid of a box and a list can all be views of
11
+ * the same data.
12
+ *
13
+ * - `model.ts` — places, what is stored in them, and a place with somewhere to stand
14
+ * - `arrange.ts` — giving every place somewhere to stand, and the positions inside a box
15
+ * - `find.ts` — levels, bounds, camera poses, searching
16
+ * - `from.ts` — a layout made from a lab's own record of itself
17
+ * - `example.ts` — a lab to look at
18
+ */
19
+ export * from "./model.js";
20
+ export * from "./arrange.js";
21
+ export * from "./find.js";
22
+ export * from "./example.js";
23
+ export * from "./from.js";