1use std::collections::HashMap;
16#[cfg(not(target_arch = "wasm32"))]
17use std::io;
18
19use serde::{Deserialize, Serialize};
20
21use crate::q_hash;
22use crate::NQuin;
23#[cfg(not(target_arch = "wasm32"))]
24use crate::QUINS_PER_BLOCK;
25
26#[cfg(not(target_arch = "wasm32"))]
27use crate::q42::q42_volume::StreamingQ42VolumeWriter;
28
29#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
33pub enum AnatomicalOntologyStandard {
34 PlantOntologyPO,
36 UberonAnatomy,
38 GeneOntologyGO,
40 AustralianPlantCensusAPC,
42}
43
44impl AnatomicalOntologyStandard {
45 pub const fn prefix(&self) -> &'static str {
47 match self {
48 Self::PlantOntologyPO => "PO:",
49 Self::UberonAnatomy => "UBERON:",
50 Self::GeneOntologyGO => "GO:",
51 Self::AustralianPlantCensusAPC => "APC:",
52 }
53 }
54
55 pub const fn base_iri(&self) -> &'static str {
57 match self {
58 Self::PlantOntologyPO => "http://purl.obolibrary.org/obo/PO_",
59 Self::UberonAnatomy => "http://purl.obolibrary.org/obo/UBERON_",
60 Self::GeneOntologyGO => "http://purl.obolibrary.org/obo/GO_",
61 Self::AustralianPlantCensusAPC => "https://biodiversity.org.au/voc/apc/",
62 }
63 }
64
65 pub fn from_curie(curie: &str) -> Option<Self> {
67 if curie.starts_with("PO:") {
68 Some(Self::PlantOntologyPO)
69 } else if curie.starts_with("UBERON:") {
70 Some(Self::UberonAnatomy)
71 } else if curie.starts_with("GO:") {
72 Some(Self::GeneOntologyGO)
73 } else if curie.starts_with("APC:") {
74 Some(Self::AustralianPlantCensusAPC)
75 } else {
76 None
77 }
78 }
79}
80
81#[derive(Clone, Debug, Serialize, Deserialize)]
85pub struct AnatomicalCalloutPin {
86 pub pin_id: &'static str,
88 pub scale: u8,
90 pub ontology_curie: &'static str,
92 pub scientific_term: &'static str,
94 pub anchor_local_xyz: [f32; 3],
96 pub normal_xyz: [f32; 3],
98 pub camera_focus_offset: [f32; 3],
100 pub biophysical_formula: &'static str,
102 pub educational_summary: &'static str,
104 pub indigenous_custodial_context: &'static str,
106}
107
108impl AnatomicalCalloutPin {
109 pub fn standard(&self) -> Option<AnatomicalOntologyStandard> {
111 AnatomicalOntologyStandard::from_curie(self.ontology_curie)
112 }
113
114 pub fn full_ontology_iri(&self) -> String {
116 if let Some(id_part) = self.ontology_curie.strip_prefix("PO:") {
117 format!("http://purl.obolibrary.org/obo/PO_{id_part}")
118 } else if let Some(id_part) = self.ontology_curie.strip_prefix("UBERON:") {
119 format!("http://purl.obolibrary.org/obo/UBERON_{id_part}")
120 } else if let Some(id_part) = self.ontology_curie.strip_prefix("GO:") {
121 format!("http://purl.obolibrary.org/obo/GO_{id_part}")
122 } else if let Some(id_part) = self.ontology_curie.strip_prefix("APC:") {
123 format!("https://biodiversity.org.au/voc/apc/{id_part}")
124 } else {
125 format!("urn:qualia:ontology:{}", self.ontology_curie)
126 }
127 }
128}
129
130#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
134pub struct LoupeDissectionState {
135 pub active_scale: u8,
142 pub explode_layers_01: f32,
144 pub cutaway_plane_01: f32,
146 pub phenology_month: u8,
148 pub ontogenetic_progress_01: f32,
150 pub osteology_vis_01: f32,
152 pub myology_vis_01: f32,
154 pub integument_vis_01: f32,
156 pub selected_ontology_curie: &'static str,
158}
159
160impl Default for LoupeDissectionState {
161 fn default() -> Self {
162 Self::new()
163 }
164}
165
166impl LoupeDissectionState {
167 pub const fn new() -> Self {
169 Self {
170 active_scale: 1,
171 explode_layers_01: 0.0,
172 cutaway_plane_01: 0.0,
173 phenology_month: 1,
174 ontogenetic_progress_01: 0.65,
175 osteology_vis_01: 1.0,
176 myology_vis_01: 1.0,
177 integument_vis_01: 1.0,
178 selected_ontology_curie: "po:0009010",
179 }
180 }
181
182 pub fn select_scale(&mut self, scale: u8) {
184 self.active_scale = scale.clamp(1, 5);
185 self.selected_ontology_curie = match self.active_scale {
186 1 => "po:0025531",
187 2 => "po:0004708",
188 3 => "po:0009084",
189 4 => "po:0000032",
190 5 => "uberon:0002415",
191 _ => "po:0009010",
192 };
193 }
194
195 pub fn set_layer_peel(&mut self, peel_01: f32) {
197 self.cutaway_plane_01 = peel_01.clamp(0.0, 1.0);
198 }
199
200 pub fn set_anthesis_progress(&mut self, progress_01: f32) {
202 self.ontogenetic_progress_01 = progress_01.clamp(0.0, 1.0);
203 }
204
205 pub fn set_explode_layer(&mut self, explode_01: f32) {
207 self.explode_layers_01 = explode_01.clamp(0.0, 1.0);
208 }
209
210 pub fn set_vertebrate_layer_visibility(
212 &mut self,
213 osteology_vis_01: f32,
214 myology_vis_01: f32,
215 integument_vis_01: f32,
216 ) {
217 self.osteology_vis_01 = osteology_vis_01.clamp(0.0, 1.0);
218 self.myology_vis_01 = myology_vis_01.clamp(0.0, 1.0);
219 self.integument_vis_01 = integument_vis_01.clamp(0.0, 1.0);
220 }
221
222 pub fn pick_callout_pin(
225 &mut self,
226 ray_origin: [f32; 3],
227 ray_dir: [f32; 3],
228 max_dist: f32,
229 ) -> Option<&'static AnatomicalCalloutPin> {
230 let pin = query_closest_anatomical_pin_zero_heap(
231 self.active_scale,
232 ray_origin,
233 ray_dir,
234 max_dist,
235 )?;
236 self.selected_ontology_curie = pin.ontology_curie;
237 Some(pin)
238 }
239}
240
241pub const CANONICAL_ANATOMICAL_PINS: &[AnatomicalCalloutPin] = &[
245 AnatomicalCalloutPin {
249 pin_id: "pin_s1_lignotuber",
250 scale: 1,
251 ontology_curie: "PO:0025531",
252 scientific_term: "Lignotuber Epicormic Meristem",
253 anchor_local_xyz: [0.0, -0.25, 0.0],
254 normal_xyz: [0.0, 1.0, 0.0],
255 camera_focus_offset: [0.0, 0.35, 1.20],
256 biophysical_formula: "Epicormic Bud Density: D_bud = rho_m * (1.0 - exp(-t / tau_b)); Fire Survival P_surv = 1.0 / (1.0 + exp(-alpha_f * (B_bark - B_crit)))",
257 educational_summary: "A woody basal swelling of the root crown containing a dense reserve of dormant epicormic vegetative buds and starch reserves. When wild crown fires destroy the entire eucalypt foliage, the subterranean lignotuber activates hormone-mediated bud release, producing vigorous epicormic shoots within weeks.",
258 indigenous_custodial_context: "Known in Wiradjuri and Walgalu custodial botany as 'Gunhan' (resilient root base). Traditional custodial fire practitioners utilized frequent cool patch burns ('badhang') so fire intensity remained below the lethal cambium threshold, stimulating vegetative renewal without fracturing the lignotuber's starch core.",
259 },
260 AnatomicalCalloutPin {
261 pin_id: "pin_s1_taproot",
262 scale: 1,
263 ontology_curie: "PO:0000038",
264 scientific_term: "Primary Geotropic Taproot System",
265 anchor_local_xyz: [0.0, -1.80, 0.0],
266 normal_xyz: [0.0, -1.0, 0.0],
267 camera_focus_offset: [0.50, -1.20, 2.20],
268 biophysical_formula: "Darcy-Richards Unsaturated Soil Flux: q = -K_unsat(theta) * grad(psi_m + z); Hydraulic Lift Flux J_lift = sum(K_root * (psi_deep - psi_shallow))",
269 educational_summary: "The primary vertical axis penetrating several meters through weathered saprolite and bedrock fractures down to deep water tables. During drought, eucalypts perform hydraulic lift—passively drawing water from deep moist strata at night and exuding it into shallow roots, hydrating the rhizosphere.",
270 indigenous_custodial_context: "Traditional owners identified mature taproot surface expressions above dry watercourses as reliable indicators of subterranean soakages ('gnamma' or water trees), tapping roots sustainably for emergency drinking water during prolonged dry seasons.",
271 },
272 AnatomicalCalloutPin {
273 pin_id: "pin_s1_buttress_flare",
274 scale: 1,
275 ontology_curie: "PO:0000042",
276 scientific_term: "Lateral Buttress Flare & Root Plate",
277 anchor_local_xyz: [0.85, -0.10, 0.45],
278 normal_xyz: [0.88, 0.22, 0.42],
279 camera_focus_offset: [1.20, 0.40, 1.50],
280 biophysical_formula: "Root Plate Overturning Moment: M_crit = C_shear * A_plate * D_root + W_soil * r_hinge; Mattheck Axiom of Uniform Stress: sigma_surf = const",
281 educational_summary: "Flaring asymmetrical root adaptations that distribute wind drag forces acting on the crown into the shallow soil horizon. As the tree sways in alpine gales, windward roots experience severe tension while leeward roots absorb compression, governed by the biological axiom of uniform stress.",
282 indigenous_custodial_context: "The sheltered hollows between buttress roots served as temporary windbreaks and cool resting places along high-country trading tracks. Resilient fibrous bark from buttress margins was peeled in narrow strips without harming root stability.",
283 },
284 AnatomicalCalloutPin {
285 pin_id: "pin_s1_mycorrhizal_rhizosphere",
286 scale: 1,
287 ontology_curie: "PO:0005707",
288 scientific_term: "Ectomycorrhizal Absorptive Feeder Root Network",
289 anchor_local_xyz: [-0.65, -0.40, -0.50],
290 normal_xyz: [-0.70, 0.40, -0.58],
291 camera_focus_offset: [-0.80, -0.10, 1.40],
292 biophysical_formula: "Michaelis-Menten Phosphate Uptake: V_P = (V_max * [P_soil]) / (K_m + [P_soil]); Hyphal Surface Area Multiplier: A_eff = A_root * (1.0 + eta_hyphae)",
293 educational_summary: "Fine cluster roots enveloped in fungal mantles of Basidiomycetes (e.g. Pisolithus, Cortinarius). Australian soils are famously depauperate in available phosphorus; fungal hyphae secrete phosphatase enzymes and extend the effective root surface area by two orders of magnitude in exchange for host photosynthates.",
294 indigenous_custodial_context: "Ectomycorrhizal fruiting bodies (native truffles and mushrooms) associate with eucalypt roots and are prized seasonal foods ('mungar') tracked by bandicoots, potoroos, and Indigenous foragers who read soil crack patterns.",
295 },
296 AnatomicalCalloutPin {
297 pin_id: "pin_s1_da_vinci_pipe_bole",
298 scale: 1,
299 ontology_curie: "PO:0009005",
300 scientific_term: "Primary Bole Da Vinci / Shinozaki Pipe Model",
301 anchor_local_xyz: [0.0, 1.85, 0.0],
302 normal_xyz: [0.0, 0.0, 1.0],
303 camera_focus_offset: [0.0, 2.10, 3.50],
304 biophysical_formula: "Leonardo da Vinci / Shinozaki Pipe Model: r_bole^eta = sum(r_branch_i^eta) (eta = 2.49); Allometric Biomass M = a * (D^2 * H)^b",
305 educational_summary: "The main structural trunk maintains cross-sectional vessel area proportional to the total leaf area it supports above. Da Vinci observed that all branches at every height equal the trunk in combined thickness, a rule formalized as the Pipe Model of plant allometry with exponent eta ~ 2.49.",
306 indigenous_custodial_context: "Major trunks of Snow Gums and Ghost Gums carried custodial markers, boundary engravings, and scar markings where bark was respectfully harvested for coolamons, leaving the underlying sapwood intact to callus over.",
307 },
308 AnatomicalCalloutPin {
309 pin_id: "pin_s1_crown_space_colonization",
310 scale: 1,
311 ontology_curie: "PO:0020100",
312 scientific_term: "Scaffold Limb Architecture & Crown Space Colonization",
313 anchor_local_xyz: [1.20, 4.50, -0.80],
314 normal_xyz: [0.72, 0.60, -0.35],
315 camera_focus_offset: [1.80, 5.00, 2.80],
316 biophysical_formula: "Runions Space Colonization: v_grow = sum((p_attr - v_node) / ||p_attr - v_node||); Cantilever Bending Moment M_b = rho_wood * g * int(x * A(x) dx)",
317 educational_summary: "The upper scaffold branches deploy via competitive space colonization toward canopy gaps. Snow Gums (*Eucalyptus pauciflora*) exhibit thick, gnarled, twisted branches that tolerate extreme snowpack loading and rime ice buildup without brittle trunk failure.",
318 indigenous_custodial_context: "High-country elders read the angle of scaffold growth to predict alpine storm vectors and snowfall weight, guiding seasonal movements between mountain peaks and valley river camps.",
319 },
320
321 AnatomicalCalloutPin {
325 pin_id: "pin_s2_rhytidome_cork",
326 scale: 2,
327 ontology_curie: "PO:0005513",
328 scientific_term: "Decorticating Periderm & Outer Rhytidome",
329 anchor_local_xyz: [0.18, 0.65, 0.0],
330 normal_xyz: [1.0, 0.0, 0.0],
331 camera_focus_offset: [0.45, 0.70, 0.90],
332 biophysical_formula: "Fourier Thermal Insulation: q_heat = -k_bark * (T_flame - T_cambium) / delta_x; Thermal Diffusivity alpha_t = k / (rho * c_p) = 1.3e-7 m^2/s",
333 educational_summary: "The outermost dead tissue layers composed of alternated phellem and collapsed phloem. Smooth-barked gums periodically decorticate (shed) outer strips in ribbons, shedding combustible epiphyte loads and reducing fuel accumulation on the trunk while reflecting solar radiation.",
334 indigenous_custodial_context: "Shed bark strips ('durra') served as instant kindling for fire drills, torches for night fishing, and insulating floor mats inside shelter huts. Paperbark and stringybark varieties provided twine, bandages, and cooking wrappers.",
335 },
336 AnatomicalCalloutPin {
337 pin_id: "pin_s2_phellogen",
338 scale: 2,
339 ontology_curie: "PO:0005509",
340 scientific_term: "Phellogen (Cork Cambium) Meristematic Ring",
341 anchor_local_xyz: [0.165, 0.65, 0.0],
342 normal_xyz: [1.0, 0.0, 0.0],
343 camera_focus_offset: [0.35, 0.68, 0.75],
344 biophysical_formula: "Periclinal Cell Division Rate: dn/dt = mu_phellogen * (1.0 - exp(-T_eff / T_base)); Suberin Deposition: lambda_sub = f(w_phenol, w_aliphatic)",
345 educational_summary: "A lateral meristem that produces suberized, impermeable cork (phellem) toward the exterior and living phelloderm parenchyma inward. Suberin lamellae deposited in cell walls prevent desiccating moisture loss and microbial pathogen invasion.",
346 indigenous_custodial_context: "Knowledge of bark cambium depth was essential when carving shields or harvesting bark; harvesters scored shallowly above the phellogen during wet spring sap flows so the tree would rapidly form wound periderm and heal.",
347 },
348 AnatomicalCalloutPin {
349 pin_id: "pin_s2_secondary_phloem_kino",
350 scale: 2,
351 ontology_curie: "PO:0005417",
352 scientific_term: "Secondary Phloem & Polyphenolic Kino Ducts",
353 anchor_local_xyz: [0.15, 0.65, 0.0],
354 normal_xyz: [1.0, 0.0, 0.0],
355 camera_focus_offset: [0.32, 0.68, 0.70],
356 biophysical_formula: "Münch Pressure-Flow Phloem Flux: J_s = (k_phloem / eta_sap) * grad(P_turgor); Kino Exudation Pressure P_kino = P_osmo - P_tissue",
357 educational_summary: "The inner living bark containing sieve tube elements and companion cells conducting sucrose downward from leaves. Embedded within are traumatic resin/kino ducts that synthesize dense polyphenolic tannins that polymerize on exposure to air, sealing mechanical insect borings.",
358 indigenous_custodial_context: "Red gum resin ('kino' or 'yandhirra') is a cornerstone bush medicine. Dissolved in water or applied as dried powder, its powerful astringent tannins arrest dysentery, stop bleeding, soothe burns, and seal woodworking joints.",
359 },
360 AnatomicalCalloutPin {
361 pin_id: "pin_s2_vascular_cambium",
362 scale: 2,
363 ontology_curie: "PO:0005511",
364 scientific_term: "Vascular Cambium (Bifacial Lateral Meristem)",
365 anchor_local_xyz: [0.138, 0.65, 0.0],
366 normal_xyz: [1.0, 0.0, 0.0],
367 camera_focus_offset: [0.30, 0.68, 0.65],
368 biophysical_formula: "Auxin-Driven Radial Growth: dR/dt = k_camb * [IAA] * (psi_turgor - psi_yield); Ray Cell Ratio: f_ray = N_ray / (N_fusiform + N_ray)",
369 educational_summary: "The microscopic single-cell layer of undifferentiated meristematic cells responsible for all radial growth in tree diameter. It divides bifacially, producing secondary xylem (wood) toward the interior and secondary phloem (inner bark) toward the exterior.",
370 indigenous_custodial_context: "Custodial seasonal calendars linked the swelling of the vascular cambium in late spring (marked by the rising of the Pleiades and blooming of silver wattles) to the prime season for stripping bark without tearing wood fibres.",
371 },
372 AnatomicalCalloutPin {
373 pin_id: "pin_s2_sapwood_xylem",
374 scale: 2,
375 ontology_curie: "PO:0005352",
376 scientific_term: "Active Secondary Xylem (Sapwood) & Vessel Elements",
377 anchor_local_xyz: [0.10, 0.65, 0.0],
378 normal_xyz: [1.0, 0.0, 0.0],
379 camera_focus_offset: [0.28, 0.68, 0.60],
380 biophysical_formula: "Hagen-Poiseuille Axial Conductance: K_ax = (pi * sum(r_vessel_i^4)) / (8.0 * eta_water); Cavitation Vulnerability P50: PLC = 100.0 / (1.0 + exp(s * (psi - psi_50)))",
381 educational_summary: "The active sapwood conducts tens of liters of water per day upward from roots to the canopy under negative hydrostatic tension (-1.5 to -3.0 MPa). Wide vessel elements maximize hydraulic efficiency while bordered pits limit the spread of cavitation embolisms.",
382 indigenous_custodial_context: "Sapwood from young branches was split to make flexible tool handles, fishing spears, and digging sticks ('kutti'), heat-tempered over coals to harden outer fibres without charring the inner core.",
383 },
384 AnatomicalCalloutPin {
385 pin_id: "pin_s2_heartwood_tyloses",
386 scale: 2,
387 ontology_curie: "PO:0005353",
388 scientific_term: "Heartwood (Duramen) & Polyphenolic Tyloses Matrix",
389 anchor_local_xyz: [0.03, 0.65, 0.0],
390 normal_xyz: [1.0, 0.0, 0.0],
391 camera_focus_offset: [0.22, 0.68, 0.55],
392 biophysical_formula: "Tyloses Vessel Occlusion Ratio: phi_occ = V_balloon / V_lumen; Phenolic Extractives Concentration: C_extract = C_0 * exp(-r / r_hw)",
393 educational_summary: "The non-conducting central core of the tree where xylem parenchyma cells balloon into vessel lumens through pit membranes (tyloses), completely sealing the tubes. Heavy impregnation with tannins and polyphenols gives heartwood exceptional durability against termites and fungal rot.",
394 indigenous_custodial_context: "Hard, dense heartwood from dead standing trees was chosen for crafting boomerangs ('kali'), woomeras, and clapsticks, valued for its resonant acoustic tone and centuries-long resistance to ground termites.",
395 },
396 AnatomicalCalloutPin {
397 pin_id: "pin_s2_pendulous_falcate_leaf",
398 scale: 2,
399 ontology_curie: "PO:0025034",
400 scientific_term: "Pendulous Isobilateral Falcate Leaf Lamina",
401 anchor_local_xyz: [0.32, 0.20, 0.15],
402 normal_xyz: [0.0, -1.0, 0.0],
403 camera_focus_offset: [0.35, 0.25, 0.45],
404 biophysical_formula: "Cos-Zenith Light Interception: I_eff = I_0 * sin(theta_sun) * cos(theta_leaf); Photoinhibition Mitigation: F_v / F_m >= 0.80 at solar noon",
405 educational_summary: "Adult eucalypt foliage hangs vertically on flexible petioles, an adaptation called pendulous falcate phyllotaxis. By presenting leaf edges to the scorching overhead sun at solar noon and leaf faces to gentle morning/afternoon light, the tree minimizes photoinhibition and heat load while maintaining carbon fixation.",
406 indigenous_custodial_context: "Fresh falcate leaves placed on hot coals created aromatic healing steam ('marridha') inhaled for coughs and colds. Leaves scattered in waterways released cineole and saponins to stun fish for harvest without poisoning the creek.",
407 },
408
409 AnatomicalCalloutPin {
413 pin_id: "pin_s3_umbellaster",
414 scale: 3,
415 ontology_curie: "PO:0006322",
416 scientific_term: "Compound Corymbose Panicle of Umbellasters",
417 anchor_local_xyz: [0.0, 0.08, 0.0],
418 normal_xyz: [0.0, 1.0, 0.0],
419 camera_focus_offset: [0.0, 0.10, 0.22],
420 biophysical_formula: "Floral Aggregation Index: N_buds = 3..7 per umbel; Total Sugar Flux: Q_nectar = sum(V_nectar_i * C_sugar_i * rho_sol)",
421 educational_summary: "An inflorescence consisting of clustered umbels (umbellasters) borne on flattened peduncles. In *Corymbia aparrerinja* and related bloodwoods, terminal corymbose panicles produce dense masses of blossom outside the foliage canopy, maximizing visibility to nectar-feeding birds and bats.",
422 indigenous_custodial_context: "Prolific flowering of corymbose blossoms signaled the arrival of nectar-feeding lorikeets ('bilany') and flying-foxes, marking gatherings where clans shared blossom-sweetened water and harvested fresh wild honey ('mayi').",
423 },
424 AnatomicalCalloutPin {
425 pin_id: "pin_s3_operculum_cap",
426 scale: 3,
427 ontology_curie: "PO:0009084",
428 scientific_term: "Operculum (Calyptriform Cap) Abscission Zone",
429 anchor_local_xyz: [0.0, 0.035, 0.0],
430 normal_xyz: [0.0, 1.0, 0.0],
431 camera_focus_offset: [0.0, 0.05, 0.12],
432 biophysical_formula: "Turgor Abscission Threshold: sigma_abs = E_hyd * epsilon_cell >= sigma_crit; Operculum Separation Force F_sep = 2.0 * pi * r_rim * gamma_wall",
433 educational_summary: "The hallmark organ of the genus *Eucalyptus* (from Greek 'eu-kalyptos', well-covered). Fused sepals and petals form a conical or hemispherical cap enclosing stamens. As stamens hydrate and expand at anthesis, enzymatic dissolution of middle lamellae along the circumscissile rim pops the operculum off.",
434 indigenous_custodial_context: "Children collected freshly shed opercula to use as miniature play cups, whistles, and pipe beads strung on kangaroo sinew. The pop of shedding opercula in late spring signified that native bees were filling tree-hollow hives with honey.",
435 },
436 AnatomicalCalloutPin {
437 pin_id: "pin_s3_hypanthium_cup",
438 scale: 3,
439 ontology_curie: "PO:0009064",
440 scientific_term: "Hypanthium (Fused Floral Cup & Nectariferous Disc)",
441 anchor_local_xyz: [0.0, 0.012, 0.0],
442 normal_xyz: [0.0, 0.0, 1.0],
443 camera_focus_offset: [0.0, 0.02, 0.10],
444 biophysical_formula: "Nectary Secretion Rate: dV_nectar/dt = k_sec * A_disc * (psi_osm - psi_ext); Sugar Concentration: Bx = [Sucrose] + [Glucose] + [Fructose] (35-65%)",
445 educational_summary: "A cup-like structure formed by the fusion of the basal parts of the sepals, petals, and stamens with the inferior ovary. The upper rim bears a prominent ring of nectariferous tissue that secretes concentrated sucrose, glucose, and fructose solutions.",
446 indigenous_custodial_context: "Blossom heads were plucked and steeped in cool bark vessels of mountain water to create a delicate, sweet nectar cordial ('ngarru'). Elders taught children to shake morning blossoms over their palms to taste the first nectar drops.",
447 },
448 AnatomicalCalloutPin {
449 pin_id: "pin_s3_staminal_ring_anthers",
450 scale: 3,
451 ontology_curie: "PO:0009066",
452 scientific_term: "Staminal Ring (Androecium) & Versatile Anthers",
453 anchor_local_xyz: [0.018, 0.028, 0.0],
454 normal_xyz: [0.85, 0.52, 0.0],
455 camera_focus_offset: [0.03, 0.035, 0.08],
456 biophysical_formula: "Filament Elastic Snap: F_spring = -k_fil * delta_x; Pollen Dehiscence: RH_crit <= 45% triggers endothecium shrinkage and slit rupture",
457 educational_summary: "Hundreds of slender cream-white filaments bent inward in bud that spring outward upon operculum detachment. Each filament terminates in a versatile, dorsifixed anther opening via longitudinal slits, dusted with tricolporate pollen grains adapted for bird, mammal, and insect vectors.",
458 indigenous_custodial_context: "Pollen dusting on foraging honeyeaters and sugar gliders was observed by custodial naturalists as part of 'Kurrumbene' (ecological balance)—recognizing the reciprocal relationship between bird pollination and seed set.",
459 },
460 AnatomicalCalloutPin {
461 pin_id: "pin_s3_style_stigma",
462 scale: 3,
463 ontology_curie: "PO:0009072",
464 scientific_term: "Gynoecium Central Terete Style & Glandular Stigma",
465 anchor_local_xyz: [0.0, 0.032, 0.0],
466 normal_xyz: [0.0, 1.0, 0.0],
467 camera_focus_offset: [0.0, 0.04, 0.08],
468 biophysical_formula: "Pollen Tube Growth Rate: v_tube = k_chem * [Ca2+] * exp(-E_act / (R * T)); Gametophytic Self-Incompatibility: S_allele match arrests tube",
469 educational_summary: "A single central, terete style rising above the staminal ring topped with a glandular, papillar stigma. The stigma secretes a sticky exudate when receptive, capturing pollen and guiding tube growth down the transmitting tissue to ovules in the ovary.",
470 indigenous_custodial_context: "Women elders held custodial knowledge of plant reproductive cycles, identifying the precise post-anthesis stage when style receptivity ended and medicinal alkaloids concentrated in developing ovary walls.",
471 },
472 AnatomicalCalloutPin {
473 pin_id: "pin_s3_ovary_locules",
474 scale: 3,
475 ontology_curie: "PO:0009063",
476 scientific_term: "Inferior Ovary with 3-4 Locules & Axile Placentation",
477 anchor_local_xyz: [0.0, 0.005, 0.0],
478 normal_xyz: [0.0, 0.0, 1.0],
479 camera_focus_offset: [0.0, 0.015, 0.08],
480 biophysical_formula: "Ovule Packaging: N_ovules = 15..45 per locule; Placentation Efficiency: eta_fert = N_viable / (N_viable + N_chaff)",
481 educational_summary: "The ovary is completely inferior, embedded within and fused to the thick woody hypanthium. A transverse cutaway reveals 3 to 4 distinct locular chambers containing two rows of anatropous ovules attached to central axile placentas.",
482 indigenous_custodial_context: "The seed chambers of green gumnuts were ground with river stone pestles into a cooling poultice applied to insect bites, stings, and skin sores to reduce swelling.",
483 },
484 AnatomicalCalloutPin {
485 pin_id: "pin_s3_gumnut_valves",
486 scale: 3,
487 ontology_curie: "PO:0009084",
488 scientific_term: "Woody Capsule (Gumnut) Enclosed Dehiscent Valves",
489 anchor_local_xyz: [0.0, -0.02, 0.0],
490 normal_xyz: [0.0, -1.0, 0.0],
491 camera_focus_offset: [0.0, -0.01, 0.12],
492 biophysical_formula: "Hydro-Elastic Bilayer Curvature: kappa = (6.0 * (alpha_out - alpha_in) * delta_RH) / (h * (5.0 + (E_out / E_in))); Valve Opening T_crit >= 60 C",
493 educational_summary: "A hard woody capsule (gumnut) protecting fertile seeds. The internal valves remain sunken and enclosed under ambient conditions, but desiccation following fire heat causes differential shrinkage between inner and outer sclerenchyma layers, curling the valves outward to release seeds into ash beds.",
494 indigenous_custodial_context: "Dry gumnuts ('wirra') were used by children for spinning tops, musical rattles tied around ankles during dance, and whistles hollowed out to mimic parrot warning calls.",
495 },
496 AnatomicalCalloutPin {
497 pin_id: "pin_s3_seed_chaff",
498 scale: 3,
499 ontology_curie: "PO:0009010",
500 scientific_term: "Saucer-Shaped Fertile Seeds & Sterile Chaff",
501 anchor_local_xyz: [0.004, -0.018, 0.0],
502 normal_xyz: [0.0, 1.0, 0.0],
503 camera_focus_offset: [0.01, -0.01, 0.06],
504 biophysical_formula: "Seed Dispersal Terminal Velocity: v_t = sqrt((2.0 * m_seed * g) / (rho_air * C_D * A_wing)); Smoke Karrikin Germination: [KAR1] >= 1e-9 M",
505 educational_summary: "Each capsule contains a few fertile, saucer-shaped or narrowly winged seeds surrounded by numerous reddish-brown sterile chaff particles. Seed germination is stimulated by butenolide karrikins present in bushfire smoke, timing seedling emergence to nutrient-rich post-fire ash beds.",
506 indigenous_custodial_context: "Women harvested fertile eucalypt seeds by shaking branches over bark dishes ('coolamons'), winnowing chaff in the wind, and grinding the nutritious seeds into flour to bake damper on hot river stones.",
507 },
508
509 AnatomicalCalloutPin {
513 pin_id: "pin_s4_cuticle_wax",
514 scale: 4,
515 ontology_curie: "PO:0000014",
516 scientific_term: "Epicuticular Waxy Cuticle & Crystalline Platelets",
517 anchor_local_xyz: [0.0, 0.004, 0.0],
518 normal_xyz: [0.0, 1.0, 0.0],
519 camera_focus_offset: [0.0, 0.006, 0.025],
520 biophysical_formula: "Cuticular Transpiration Resistance: r_c = delta_x / (D_wax * S_sol) >= 15000 s/m; Contact Angle: theta_contact >= 115 deg (Superhydrophobic)",
521 educational_summary: "The outermost protective layer consisting of a cutin polymer matrix embedded with crystalline triterpenoid and diketone wax platelets. Gives glaucous Snow Gum and Ghost Gum leaves their chalky-white hue, reflecting high UV-B radiation and preventing non-stomatal water loss.",
522 indigenous_custodial_context: "The thick glaucous wax was scraped from leaves with bone scrapers to mix with ochre pigments, producing water-resistant ceremonial body paints and rock shelter art that lasted through torrential storms.",
523 },
524 AnatomicalCalloutPin {
525 pin_id: "pin_s4_amphistomatic_stomata",
526 scale: 4,
527 ontology_curie: "PO:0000032",
528 scientific_term: "Amphistomatic Stomatal Complex & Guard Cell Crypt",
529 anchor_local_xyz: [0.002, 0.0035, 0.0],
530 normal_xyz: [0.0, 1.0, 0.0],
531 camera_focus_offset: [0.003, 0.005, 0.015],
532 biophysical_formula: "Fick's Stomatal Diffusion: J_v = g_s * (e_i - e_a) / P; Stomatal Conductance g_s = (d_stoma * A_pore) / (l_channel + 0.5 * pi * r_pore)",
533 educational_summary: "Unlike most Northern Hemisphere broadleaf trees with stomata only beneath the leaf (hypostomatic), eucalypts possess stomata on both upper and lower leaf faces (amphistomatic). Paired guard cells modulate pore diameter based on potassium and ABA gradients, operating within sunken epistomatal crypts to reduce boundary layer wind stripping.",
534 indigenous_custodial_context: "Custodial observers noted that leaf cooling via transpiration occurred symmetrically on both sides of vertically hanging leaves, correlating leaf wilting angles with river drought severity.",
535 },
536 AnatomicalCalloutPin {
537 pin_id: "pin_s4_isobilateral_palisade",
538 scale: 4,
539 ontology_curie: "PO:0005679",
540 scientific_term: "Isobilateral Palisade Mesophyll (Dual Columnar Layers)",
541 anchor_local_xyz: [0.0, 0.002, 0.0],
542 normal_xyz: [0.0, 1.0, 0.0],
543 camera_focus_offset: [0.0, 0.004, 0.018],
544 biophysical_formula: "Farquhar-von Caemmerer C3 Photosynthesis: A = min(W_c, W_j, W_p) - R_d; Quantum Yield Phi = (1.0 - 0.5 * O / (S_c/o * C)) / (4.0 + 8.0 * O / (S_c/o * C))",
545 educational_summary: "A diagnostic anatomical adaptation to vertical leaf orientation: dense, columnar palisade chlorenchyma cells packed with chloroplasts flank both adaxial and abaxial leaf surfaces, enclosing only a thin central band of spongy parenchyma. This doubles photosynthetic light harvesting efficiency under changing sun angles.",
546 indigenous_custodial_context: "The dense green flesh of crushed leaves released high concentrations of active chlorophyll and cineole, utilized as an antiseptic compress for skin infections and abrasions.",
547 },
548 AnatomicalCalloutPin {
549 pin_id: "pin_s4_intramarginal_vein",
550 scale: 4,
551 ontology_curie: "PO:0005023",
552 scientific_term: "Intramarginal Peripheral Vein & Murray's Law Anastomosis",
553 anchor_local_xyz: [0.008, 0.0015, 0.0],
554 normal_xyz: [1.0, 0.0, 0.0],
555 camera_focus_offset: [0.012, 0.003, 0.020],
556 biophysical_formula: "Murray's Law Vein Branching: r_parent^3 = r_1^3 + r_2^3; Intramarginal Loop Pressure: P_margin = P_midrib - (8.0 * eta * L * Q) / (pi * r_intra^4)",
557 educational_summary: "The continuous intramarginal vein running just inside the blade margin is the hallmark taxonomic signature of Myrtaceae foliar venation. Secondary lateral veins merge into this loop, providing redundant hydraulic bypass circuits that keep leaf edges hydrated even if insect herbivores chew through primary lateral veins.",
558 indigenous_custodial_context: "The intramarginal vein's clear outline was used by trackers as a diagnostic key to distinguish medicinal cineole-rich eucalypts from toxic or bitter lookalike species.",
559 },
560 AnatomicalCalloutPin {
561 pin_id: "pin_s4_schizogenous_oil_gland",
562 scale: 4,
563 ontology_curie: "PO:0005018",
564 scientific_term: "Schizogenous Essential Oil Cavity (1,8-Cineole / Pinene)",
565 anchor_local_xyz: [0.004, 0.0018, 0.0],
566 normal_xyz: [0.0, 1.0, 0.0],
567 camera_focus_offset: [0.006, 0.003, 0.012],
568 biophysical_formula: "Terpenoid Synthesis Flux: J_terp = k_DXP * [IPP] * [DMAPP]; Cavity Expansion Energy: delta_G_schizo = gamma_surf * delta_A_cavity",
569 educational_summary: "Spherical sub-epidermal cavities lined with secretory epithelial cells that synthesize and store volatile monoterpenes and sesquiterpenes (1,8-cineole, alpha-pinene, p-cymene). The glands appear as translucent dots when held to the sun, providing potent defense against phytophagous insects and fungal hyphae.",
570 indigenous_custodial_context: "Smoking ceremonies ('dhaagun') burned oil-rich green leaves over glowing coals, releasing cineole vapors that purified meeting grounds, cleansed spiritual pathways, and acted as an effective airborne insect repellent.",
571 },
572 AnatomicalCalloutPin {
573 pin_id: "pin_s4_sclerenchyma_bundle_sheath",
574 scale: 4,
575 ontology_curie: "PO:0005020",
576 scientific_term: "Collateral Vascular Bundle & Sclerenchyma Sheath Girders",
577 anchor_local_xyz: [0.0, 0.001, 0.0],
578 normal_xyz: [0.0, 1.0, 0.0],
579 camera_focus_offset: [0.0, 0.002, 0.015],
580 biophysical_formula: "Leaf Elastic Modulus: E_blade = f_scler * E_scler + (1.0 - f_scler) * E_paren; Lignin Cross-Linking Stress: sigma_yield >= 22.5 MPa",
581 educational_summary: "Each foliar vein is wrapped in a robust sheath of thick-walled sclerenchyma fibres that extend as vertical I-beam girders reaching all the way to both upper and lower epidermises. This architecture endows the leaf with extreme sclerophylly—resisting mechanical wilting collapse under negative turgor pressure.",
582 indigenous_custodial_context: "Tough sclerophyllous leaf skeletons that persisted in creek beds after soft tissues decayed were gathered and tied into delicate filter strainers for sifting river gravels and panning native seed.",
583 },
584
585 AnatomicalCalloutPin {
589 pin_id: "pin_s5_epipubic_bone",
590 scale: 5,
591 ontology_curie: "UBERON:0003661",
592 scientific_term: "Epipubic Bone (Os Epipubicum) & Pouch Support",
593 anchor_local_xyz: [-0.08, 0.72, 0.12],
594 normal_xyz: [-0.45, 0.72, 0.52],
595 camera_focus_offset: [-0.15, 0.85, 0.65],
596 biophysical_formula: "Cantilever Bending Moment: M_b = F_pouch_young * L_epipubic; Muscle Anchor Strain: sigma_rectus = E_tendon * (delta_L / L_0)",
597 educational_summary: "A pair of forward-projecting pelvic bones articulating with the pubis, unique to Marsupialia and Monotremata. Contrary to early hypotheses of passive pouch support, epipubic bones function as dynamic muscular levers that anchor the pectineus, pyramidalis, and rectus abdominis muscles, stiffening the torso during saltatorial locomotion.",
598 indigenous_custodial_context: "Aboriginal hunters and butchers possessed deep anatomical familiarity with epipubic bones ('mimi'), which were carefully separated during preparation of kangaroo carcases ('marloo') and carved into fine awls for piercing possum skin cloaks.",
599 },
600 AnatomicalCalloutPin {
601 pin_id: "pin_s5_achilles_tendon",
602 scale: 5,
603 ontology_curie: "UBERON:0001434",
604 scientific_term: "Elastic Achilles Tendon Energy-Recovery Spring",
605 anchor_local_xyz: [-0.14, 0.28, -0.08],
606 normal_xyz: [-0.55, 0.0, -0.83],
607 camera_focus_offset: [-0.25, 0.35, 0.55],
608 biophysical_formula: "Hookean Tendon Strain Energy: U = 0.5 * k_t * delta_L^2; Energy Recovery: eta_rebound = 0.65 (recovers 65% of mechanical hopping work per stride)",
609 educational_summary: "The hypertrophied calcaneal tendon of macropods acts as an biological pogo stick. At high speeds (above 15 km/h), the tendon stretches upon impact and recoils elastically, dramatically reducing the metabolic cost of transport so that kangaroos expend less oxygen at high hopping speeds than at slow speeds.",
610 indigenous_custodial_context: "Kangaroo leg sinew ('ngulu' or 'moeyan') was extracted intact, dried in the sun, and chewed until supple. It was the premier binding material across Australia for securing spear points to shafts, hafting stone axes, and repairing wooden tools.",
611 },
612 AnatomicalCalloutPin {
613 pin_id: "pin_s5_diprotodont_incisors",
614 scale: 5,
615 ontology_curie: "UBERON:0001759",
616 scientific_term: "Diprotodont Dentition & Procumbent Lower Incisors",
617 anchor_local_xyz: [0.0, 0.95, 0.42],
618 normal_xyz: [0.0, 0.25, 0.97],
619 camera_focus_offset: [0.0, 1.05, 0.55],
620 biophysical_formula: "Masticatory Lever Law: F_bite = F_masseter * (L_in / L_out); Shearing Mechanical Advantage MA = 0.62",
621 educational_summary: "The diagnostic trait of Order Diprotodontia (kangaroos, wombats, koalas, possums): a single pair of elongated, forward-pointing (procumbent) lower incisors that scissor against upper incisors across a wide diastema. In kangaroos, horizontal molar progression continuously replaces worn teeth.",
622 indigenous_custodial_context: "The razor-sharp, enamel-coated lower incisors of kangaroos were embedded in grass-tree resin on hardwood handles to create precision carving chisels ('koondi') used to carve fluting on boomerangs and shields.",
623 },
624 AnatomicalCalloutPin {
625 pin_id: "pin_s5_syndactyl_grooming_pes",
626 scale: 5,
627 ontology_curie: "UBERON:0001452",
628 scientific_term: "Syndactyl Grooming Digits II & III and Hopping Digit IV",
629 anchor_local_xyz: [-0.12, 0.02, 0.16],
630 normal_xyz: [0.0, 1.0, 0.0],
631 camera_focus_offset: [-0.18, 0.15, 0.40],
632 biophysical_formula: "Digit IV Ground Reaction Force: F_GRF = m_body * (g + a_hop); Syndactyly Fusion Index: W_skin_sheath = 2 * r_digit",
633 educational_summary: "The macropod hindfoot exhibits extreme morphological specialization: digits II and III are fused inside a single skin sheath (syndactyly) with dual twin claws used exclusively for combing fur and grooming ectoparasites, while digit IV is hyper-elongated into the primary hopping propulsion column.",
634 indigenous_custodial_context: "Traditional trackers read the unique footprint of the single prominent 4th toe claw print to identify species, age, speed, carrying weight, and whether a kangaroo was foraging, resting, or fleeing.",
635 },
636 AnatomicalCalloutPin {
637 pin_id: "pin_s5_keeled_carina",
638 scale: 5,
639 ontology_curie: "UBERON:0001006",
640 scientific_term: "Avian Keeled Carina Sternum & Furcula Wishbone",
641 anchor_local_xyz: [0.0, 0.55, 0.22],
642 normal_xyz: [0.0, -1.0, 0.0],
643 camera_focus_offset: [0.0, 0.45, 0.50],
644 biophysical_formula: "Flight Aerodynamic Power: P_aero = 0.5 * rho_air * V^3 * C_D * S + (2.0 * (m * g)^2) / (pi * rho_air * V * b^2); Carina Area A_carina = f(m_pectoralis)",
645 educational_summary: "In soaring raptors (*Aquila audax* Wedge-Tailed Eagle) and flying birds, the sternum projects a deep, blade-like keel (carina) providing expansive surface area for the massive pectoralis major (downstroke power) and supracoracoideus (upstroke pulley). In ratites (emus/cassowaries), the carina is lost.",
646 indigenous_custodial_context: "The Wedge-Tailed Eagle ('Maliyan' or 'Bunjil') holds supreme ancestral significance across southeastern Australia as an eagle-hawk creator entity; eagle breastbones and flight feathers are sacred ceremonial regalia.",
647 },
648 AnatomicalCalloutPin {
649 pin_id: "pin_s5_caudal_counterbalance",
650 scale: 5,
651 ontology_curie: "UBERON:0002415",
652 scientific_term: "Caudal Vertebrae & Ventral Chevron Bones (Pentapedal Limb)",
653 anchor_local_xyz: [0.0, 0.45, -0.65],
654 normal_xyz: [0.0, 0.35, -0.94],
655 camera_focus_offset: [0.0, 0.55, -0.30],
656 biophysical_formula: "Caudal Angular Momentum Balance: I_tail * d_omega_tail/dt = -I_body * d_omega_body/dt; Pentapedal Ground Reaction: F_tail >= 0.15 * m_body * g",
657 educational_summary: "In macropods, the tail is not merely a passive counterbalance; robust articulated caudal vertebrae with heavy ventral chevron bones (haemal arches) provide muscular lever arms that generate vertical ground reaction forces exceeding 15% of body weight, acting as a genuine fifth limb during pentapedal crawling.",
658 indigenous_custodial_context: "Tail meat ('marloo wipu') with its rich gelatinous connective tissue was slow-roasted in earth pits ('murnong' ovens) over fragrant eucalypt coals, producing a highly prized tender feast shared communally.",
659 },
660];
661
662pub fn find_pin_by_id(pin_id: &str) -> Option<&'static AnatomicalCalloutPin> {
666 CANONICAL_ANATOMICAL_PINS.iter().find(|p| p.pin_id == pin_id)
667}
668
669pub fn find_pins_by_scale(scale: u8) -> impl Iterator<Item = &'static AnatomicalCalloutPin> {
671 CANONICAL_ANATOMICAL_PINS.iter().filter(move |p| p.scale == scale)
672}
673
674pub fn query_closest_anatomical_pin_zero_heap(
684 scale: u8,
685 ray_origin: [f32; 3],
686 ray_dir: [f32; 3],
687 max_dist: f32,
688) -> Option<&'static AnatomicalCalloutPin> {
689 let dir_len_sq = ray_dir[0] * ray_dir[0] + ray_dir[1] * ray_dir[1] + ray_dir[2] * ray_dir[2];
690 if dir_len_sq < 1e-12 {
691 return None;
692 }
693 let inv_len = 1.0 / dir_len_sq.sqrt();
694 let d = [ray_dir[0] * inv_len, ray_dir[1] * inv_len, ray_dir[2] * inv_len];
695
696 let mut best_pin: Option<&'static AnatomicalCalloutPin> = None;
697 let mut min_t = f32::INFINITY;
698 let max_dist_sq = max_dist * max_dist;
699
700 for pin in CANONICAL_ANATOMICAL_PINS {
701 if scale != 0 && pin.scale != scale {
702 continue;
703 }
704
705 let p = pin.anchor_local_xyz;
706 let v = [p[0] - ray_origin[0], p[1] - ray_origin[1], p[2] - ray_origin[2]];
707 let t = v[0] * d[0] + v[1] * d[1] + v[2] * d[2];
708 if t < 0.0 {
709 continue;
711 }
712
713 let c = [
715 ray_origin[0] + t * d[0],
716 ray_origin[1] + t * d[1],
717 ray_origin[2] + t * d[2],
718 ];
719
720 let dist_sq = (p[0] - c[0]) * (p[0] - c[0])
721 + (p[1] - c[1]) * (p[1] - c[1])
722 + (p[2] - c[2]) * (p[2] - c[2]);
723
724 if dist_sq <= max_dist_sq && t < min_t {
725 min_t = t;
726 best_pin = Some(pin);
727 }
728 }
729
730 best_pin
731}
732
733pub fn build_anatomical_ontology_lexicon() -> HashMap<u64, String> {
737 let mut lex = HashMap::with_capacity(CANONICAL_ANATOMICAL_PINS.len() * 10 + 32);
738
739 let base_strings = [
740 "http://www.w3.org/1999/02/22-rdf-syntax-ns#type",
741 "urn:qualia:bio:AnatomicalCalloutPin",
742 "urn:qualia:bio:hasScale",
743 "urn:qualia:bio:hasOntologyCurie",
744 "urn:qualia:bio:scientificTerm",
745 "urn:qualia:bio:biophysicalFormula",
746 "urn:qualia:bio:educationalSummary",
747 "urn:qualia:bio:indigenousCustodialContext",
748 "http://purl.obolibrary.org/obo/BFO_0000050", "urn:qualia:bio:anchorLocalX",
750 "urn:qualia:bio:anchorLocalY",
751 "urn:qualia:bio:anchorLocalZ",
752 ];
753
754 for s in &base_strings {
755 lex.insert(q_hash(s), (*s).to_string());
756 }
757
758 for pin in CANONICAL_ANATOMICAL_PINS {
759 let pin_uri = format!("urn:qualia:bio:pin:{}", pin.pin_id);
760 lex.insert(q_hash(&pin_uri), pin_uri);
761
762 let curie = pin.ontology_curie;
763 lex.insert(q_hash(curie), curie.to_string());
764
765 let iri = pin.full_ontology_iri();
766 lex.insert(q_hash(&iri), iri);
767
768 let term = pin.scientific_term;
769 lex.insert(q_hash(term), term.to_string());
770
771 let formula = pin.biophysical_formula;
772 lex.insert(q_hash(formula), formula.to_string());
773
774 let summary = pin.educational_summary;
775 lex.insert(q_hash(summary), summary.to_string());
776
777 let context = pin.indigenous_custodial_context;
778 lex.insert(q_hash(context), context.to_string());
779 }
780
781 lex
782}
783
784pub fn build_anatomical_ontology_nquins() -> Vec<NQuin> {
787 let p_type = q_hash("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
788 let o_pin_type = q_hash("urn:qualia:bio:AnatomicalCalloutPin");
789 let p_scale = q_hash("urn:qualia:bio:hasScale");
790 let p_curie = q_hash("urn:qualia:bio:hasOntologyCurie");
791 let p_term = q_hash("urn:qualia:bio:scientificTerm");
792 let p_formula = q_hash("urn:qualia:bio:biophysicalFormula");
793 let p_summary = q_hash("urn:qualia:bio:educationalSummary");
794 let p_context = q_hash("urn:qualia:bio:indigenousCustodialContext");
795 let p_part_of = q_hash("http://purl.obolibrary.org/obo/BFO_0000050");
796
797 let mut quins: Vec<NQuin> = Vec::with_capacity(CANONICAL_ANATOMICAL_PINS.len() * 8);
798
799 for pin in CANONICAL_ANATOMICAL_PINS {
800 let pin_s = q_hash(&format!("urn:qualia:bio:pin:{}", pin.pin_id));
801
802 quins.push(NQuin {
804 subject: pin_s,
805 predicate: p_type,
806 object: o_pin_type,
807 context: 0,
808 metadata: 0,
809 parity: 0,
810 });
811
812 quins.push(NQuin {
814 subject: pin_s,
815 predicate: p_scale,
816 object: pin.scale as u64,
817 context: 0,
818 metadata: 0,
819 parity: 0,
820 });
821
822 quins.push(NQuin {
824 subject: pin_s,
825 predicate: p_curie,
826 object: q_hash(pin.ontology_curie),
827 context: 0,
828 metadata: 0,
829 parity: 0,
830 });
831
832 quins.push(NQuin {
834 subject: pin_s,
835 predicate: p_part_of,
836 object: q_hash(&pin.full_ontology_iri()),
837 context: 0,
838 metadata: 0,
839 parity: 0,
840 });
841
842 quins.push(NQuin {
844 subject: pin_s,
845 predicate: p_term,
846 object: q_hash(pin.scientific_term),
847 context: 0,
848 metadata: 0,
849 parity: 0,
850 });
851
852 quins.push(NQuin {
854 subject: pin_s,
855 predicate: p_formula,
856 object: q_hash(pin.biophysical_formula),
857 context: 0,
858 metadata: 0,
859 parity: 0,
860 });
861
862 quins.push(NQuin {
864 subject: pin_s,
865 predicate: p_summary,
866 object: q_hash(pin.educational_summary),
867 context: 0,
868 metadata: 0,
869 parity: 0,
870 });
871
872 quins.push(NQuin {
874 subject: pin_s,
875 predicate: p_context,
876 object: q_hash(pin.indigenous_custodial_context),
877 context: 0,
878 metadata: 0,
879 parity: 0,
880 });
881 }
882
883 quins.sort_by_key(|q| q.object);
885 quins
886}
887
888#[cfg(not(target_arch = "wasm32"))]
893pub fn emit_anatomical_ontology_nquins_to_writer(
894 writer: &mut StreamingQ42VolumeWriter,
895) -> io::Result<usize> {
896 let quins = build_anatomical_ontology_nquins();
897 let total_quins = quins.len();
898 let mut seq_id = 0u64;
899
900 for chunk in quins.chunks(QUINS_PER_BLOCK) {
901 writer.push_block(seq_id, chunk)?;
902 seq_id += 1;
903 }
904
905 Ok(total_quins)
906}
907
908#[cfg(test)]
911mod tests {
912 use super::*;
913
914 #[test]
915 fn test_canonical_pins_catalog() {
916 assert!(
918 CANONICAL_ANATOMICAL_PINS.len() >= 24,
919 "Expected at least 24 pins, got {}",
920 CANONICAL_ANATOMICAL_PINS.len()
921 );
922
923 for scale in 1..=5 {
925 let count = CANONICAL_ANATOMICAL_PINS.iter().filter(|p| p.scale == scale).count();
926 assert!(count >= 3, "Scale {} has {} pins, expected at least 3", scale, count);
927 }
928
929 for pin in CANONICAL_ANATOMICAL_PINS {
931 assert!(!pin.pin_id.is_empty());
932 assert!(pin.scale >= 1 && pin.scale <= 5);
933 assert!(pin.ontology_curie.starts_with("PO:") || pin.ontology_curie.starts_with("UBERON:"));
934 assert!(!pin.scientific_term.is_empty());
935 assert!(!pin.biophysical_formula.is_empty());
936 assert!(!pin.educational_summary.is_empty());
937 assert!(!pin.indigenous_custodial_context.is_empty());
938
939 let iri = pin.full_ontology_iri();
941 assert!(iri.starts_with("http://purl.obolibrary.org/obo/"));
942
943 let n_len = (pin.normal_xyz[0].powi(2) + pin.normal_xyz[1].powi(2) + pin.normal_xyz[2].powi(2)).sqrt();
945 assert!(n_len > 0.8 && n_len < 1.2, "Pin {} normal not unit length: {}", pin.pin_id, n_len);
946 }
947 }
948
949 #[test]
950 fn test_pin_lookups() {
951 let pin_ligno = find_pin_by_id("pin_s1_lignotuber").expect("Must find lignotuber pin");
952 assert_eq!(pin_ligno.ontology_curie, "PO:0025531");
953 assert_eq!(pin_ligno.scale, 1);
954
955 let pin_achilles = find_pin_by_id("pin_s5_achilles_tendon").expect("Must find Achilles tendon pin");
956 assert_eq!(pin_achilles.ontology_curie, "UBERON:0001434");
957 assert_eq!(pin_achilles.scale, 5);
958
959 let pin_epipubic = find_pin_by_id("pin_s5_epipubic_bone").expect("Must find epipubic bone pin");
960 assert_eq!(pin_epipubic.ontology_curie, "UBERON:0003661");
961 assert_eq!(pin_epipubic.scale, 5);
962
963 let scale4_count = find_pins_by_scale(4).count();
964 assert!(scale4_count >= 5, "Expected at least 5 Scale 4 histology pins, got {}", scale4_count);
965 }
966
967 #[test]
968 fn test_ray_picking_zero_heap() {
969 let ray_origin = [0.0, 0.25, 0.0];
971 let ray_dir = [0.0, -1.0, 0.0]; let picked = query_closest_anatomical_pin_zero_heap(1, ray_origin, ray_dir, 0.5);
974 assert!(picked.is_some(), "Ray directed at lignotuber must hit");
975 assert_eq!(picked.unwrap().pin_id, "pin_s1_lignotuber");
976
977 let away_ray_origin = [100.0, 100.0, 100.0];
979 let away_ray_dir = [1.0, 0.0, 0.0];
980 let no_hit = query_closest_anatomical_pin_zero_heap(0, away_ray_origin, away_ray_dir, 1.0);
981 assert!(no_hit.is_none(), "Ray pointing into empty space must not hit");
982
983 let scale2_query = query_closest_anatomical_pin_zero_heap(2, ray_origin, ray_dir, 0.1);
985 assert!(scale2_query.is_none() || scale2_query.unwrap().scale == 2);
986 }
987
988 #[test]
989 fn test_loupe_dissection_state_controls() {
990 let mut loupe = LoupeDissectionState::new();
991 assert_eq!(loupe.active_scale, 1);
992 loupe.select_scale(4);
993 assert_eq!(loupe.active_scale, 4);
994 assert_eq!(loupe.selected_ontology_curie, "po:0000032");
995
996 loupe.set_layer_peel(0.75);
997 assert_eq!(loupe.cutaway_plane_01, 0.75);
998 loupe.set_anthesis_progress(0.9);
999 assert_eq!(loupe.ontogenetic_progress_01, 0.9);
1000 loupe.set_explode_layer(0.5);
1001 assert_eq!(loupe.explode_layers_01, 0.5);
1002 loupe.set_vertebrate_layer_visibility(1.0, 0.5, 0.0);
1003 assert_eq!(loupe.osteology_vis_01, 1.0);
1004 assert_eq!(loupe.myology_vis_01, 0.5);
1005 assert_eq!(loupe.integument_vis_01, 0.0);
1006
1007 loupe.select_scale(1);
1008 let picked = loupe.pick_callout_pin([0.0, 0.25, 0.0], [0.0, -1.0, 0.0], 0.5);
1009 assert!(picked.is_some());
1010 assert_eq!(loupe.selected_ontology_curie, "PO:0025531");
1011 }
1012
1013 #[test]
1014 #[cfg(not(target_arch = "wasm32"))]
1015 fn test_q42_emission() {
1016 let lex = build_anatomical_ontology_lexicon();
1017 assert!(lex.len() >= 100, "Lexicon should contain >= 100 entries, got {}", lex.len());
1018
1019 let mut writer = StreamingQ42VolumeWriter::new(&lex).expect("Writer creation must succeed");
1020 let count = emit_anatomical_ontology_nquins_to_writer(&mut writer)
1021 .expect("Quin emission must succeed");
1022
1023 assert!(count >= CANONICAL_ANATOMICAL_PINS.len() * 6);
1024
1025 let temp_path = std::env::temp_dir().join(format!(
1026 "test_botanical_ontology_{}.q42",
1027 std::time::SystemTime::now()
1028 .duration_since(std::time::UNIX_EPOCH)
1029 .unwrap()
1030 .as_nanos()
1031 ));
1032
1033 writer.finish(&temp_path).expect("Q42 volume finish must succeed");
1034
1035 let volume = crate::q42::q42_volume::Q42Volume::open(&temp_path)
1036 .expect("Q42 volume open must succeed");
1037 assert!(volume.block_count() > 0);
1038
1039 let _ = std::fs::remove_file(&temp_path);
1040 }
1041}