Skip to main content

gondola_core/geometry/
model.rs

1//! The data model of the parsed geometry. All lengths are
2//! in mm, all angles in rad and densities in g/cm3.
3// This file is part of gaps-online-software and published
4// under the GPLv3 license
5
6use crate::prelude::*;
7
8use std::io::BufWriter;
9
10use glam::{
11  DMat3,
12  DVec3,
13};
14use serde::{
15  Deserialize,
16  Serialize,
17};
18
19#[cfg(feature="pybindings")]
20use numpy::{
21  IntoPyArray,
22  ndarray::Array2,
23};
24
25use crate::geometry::gdml::parse_gdml_file;
26use crate::geometry::column_density::LazyRaycaster;
27#[cfg(feature="pybindings")]
28use crate::geometry::column_density::TrackPath;
29#[cfg(feature="pybindings")]
30use crate::physics::Tracklet;
31
32/// Identifies the cache file and its layout. Bump the
33/// version whenever the data model changes.
34const CACHE_MAGIC   : &[u8; 8] = b"GAPSGEO\0";
35const CACHE_VERSION : u32      = 1;
36
37/// Index of a material in Geometry.materials
38pub type MaterialId = usize;
39/// Index of a solid in Geometry.solids
40pub type SolidId    = usize;
41/// Index of a logical volume in Geometry.volumes, in the
42/// order the volumes are defined in the GDML file. It is
43/// assigned by the parser and is not a Geant4 number.
44pub type VolumeId   = usize;
45
46//------------------------------------------------------------
47
48/// Rigid transformation from a local (daughter) frame into
49/// the frame of its parent
50///
51/// p_parent = rotation * p_local + translation
52#[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize)]
53#[cfg_attr(feature="pybindings", pyclass)]
54pub struct Transform {
55  pub rotation    : DMat3,
56  pub translation : DVec3,
57}
58
59impl Transform {
60  pub const IDENTITY : Self = Self {
61    rotation    : DMat3::IDENTITY,
62    translation : DVec3::ZERO,
63  };
64
65  /// Transform as built by Geant4 from a GDML position and
66  /// rotation (G4GDMLReadStructure::PhysvolRead and
67  /// G4GDMLReadSolids::BooleanRead).
68  ///
69  /// Geant4 builds the rotation matrix R by rotating about
70  /// x, then y, then z (R = Rz * Ry * Rx) and places the
71  /// daughter with the inverse of that matrix.
72  ///
73  /// # Arguments:
74  ///   * position : in mm
75  ///   * angles   : rotation angles about x, y, z in rad
76  pub fn from_gdml(position : DVec3, angles : DVec3) -> Self {
77    let r = DMat3::from_rotation_z(angles.z)
78          * DMat3::from_rotation_y(angles.y)
79          * DMat3::from_rotation_x(angles.x);
80    Self {
81      rotation    : r.transpose(),
82      translation : position,
83    }
84  }
85
86  /// local -> parent
87  pub fn apply_point(&self, p : DVec3) -> DVec3 {
88    self.rotation * p + self.translation
89  }
90
91  /// local -> parent (directions are only rotated)
92  pub fn apply_vector(&self, v : DVec3) -> DVec3 {
93    self.rotation * v
94  }
95
96  /// parent -> local
97  pub fn inverse_apply_point(&self, p : DVec3) -> DVec3 {
98    self.rotation.transpose() * (p - self.translation)
99  }
100
101  /// parent -> local
102  pub fn inverse_apply_vector(&self, v : DVec3) -> DVec3 {
103    self.rotation.transpose() * v
104  }
105}
106
107impl fmt::Display for Transform {
108  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
109    let mut repr = String::from("<Transform");
110    for k in 0..3 {
111      let row = self.rotation.row(k);
112      repr += &(format!("\n  | {:8.4} {:8.4} {:8.4} |", row.x, row.y, row.z));
113    }
114    repr += &(format!("\n  translation {:.2} {:.2} {:.2}>",
115                      self.translation.x, self.translation.y, self.translation.z));
116    write!(f, "{}", repr)
117  }
118}
119
120#[cfg(feature="pybindings")]
121#[pymethods]
122impl Transform {
123  /// The rotation matrix, as a list of rows
124  #[getter]
125  fn get_rotation(&self) -> [[f64; 3]; 3] {
126    [self.rotation.row(0).to_array(),
127     self.rotation.row(1).to_array(),
128     self.rotation.row(2).to_array()]
129  }
130
131  /// Translation in mm
132  #[getter]
133  fn get_translation(&self) -> (f64, f64, f64) {
134    self.translation.into()
135  }
136
137  /// Transform a point from the local into the parent frame
138  #[pyo3(name="apply_point")]
139  fn apply_point_py(&self, p : (f64, f64, f64)) -> (f64, f64, f64) {
140    self.apply_point(p.into()).into()
141  }
142
143  /// Transform a direction from the local into the parent frame
144  #[pyo3(name="apply_vector")]
145  fn apply_vector_py(&self, v : (f64, f64, f64)) -> (f64, f64, f64) {
146    self.apply_vector(v.into()).into()
147  }
148
149  /// Transform a point from the parent into the local frame
150  #[pyo3(name="inverse_apply_point")]
151  fn inverse_apply_point_py(&self, p : (f64, f64, f64)) -> (f64, f64, f64) {
152    self.inverse_apply_point(p.into()).into()
153  }
154
155  /// Transform a direction from the parent into the local frame
156  #[pyo3(name="inverse_apply_vector")]
157  fn inverse_apply_vector_py(&self, v : (f64, f64, f64)) -> (f64, f64, f64) {
158    self.inverse_apply_vector(v.into()).into()
159  }
160}
161
162#[cfg(feature="pybindings")]
163pythonize_display!(Transform);
164
165//------------------------------------------------------------
166
167#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
168#[cfg_attr(feature="pybindings", pyclass)]
169pub struct Material {
170  pub name    : String,
171  /// g/cm3
172  pub density : f64,
173}
174
175impl fmt::Display for Material {
176  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
177    write!(f, "<Material {} : {:.6e} g/cm3>", self.name, self.density)
178  }
179}
180
181#[cfg(feature="pybindings")]
182#[pymethods]
183impl Material {
184  #[getter]
185  fn get_name(&self) -> String {
186    self.name.clone()
187  }
188
189  /// Density in g/cm3
190  #[getter]
191  fn get_density(&self) -> f64 {
192    self.density
193  }
194}
195
196#[cfg(feature="pybindings")]
197pythonize_display!(Material);
198
199//------------------------------------------------------------
200
201#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
202pub enum BooleanOp {
203  Union,
204  Intersection,
205  Subtraction,
206}
207
208#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
209pub enum Shape {
210  /// Closed triangle mesh, vertices in the local frame
211  /// of the solid. Triangles are indices into vertices.
212  Tessellated {
213    vertices  : Vec<DVec3>,
214    triangles : Vec<[u32; 3]>,
215  },
216  /// Box centered at the origin
217  Box {
218    half_lengths : DVec3,
219  },
220  /// (Segment of a) tube along z, centered at the origin
221  Tube {
222    rmin        : f64,
223    rmax        : f64,
224    half_z      : f64,
225    start_phi   : f64,
226    delta_phi   : f64,
227  },
228  /// The second solid is placed in the frame of the first
229  /// one with second_transform
230  Boolean {
231    op               : BooleanOp,
232    first            : SolidId,
233    second           : SolidId,
234    second_transform : Transform,
235  },
236}
237
238/// The type of a solid, mainly to inspect
239/// the geometry from python
240#[derive(Debug, Copy, Clone, PartialEq, FromRepr, AsRefStr, EnumIter)]
241#[repr(u8)]
242#[cfg_attr(feature = "pybindings", pyclass(eq, eq_int))]
243pub enum SolidKind {
244  Unknown      = 0u8,
245  Tessellated  = 10u8,
246  Box          = 20u8,
247  Tube         = 30u8,
248  Union        = 40u8,
249  Intersection = 41u8,
250  Subtraction  = 42u8,
251}
252
253// expand it so that it can be used as keys 
254// in dictionaries
255#[cfg(feature = "pybindings")]
256#[pymethods]
257impl SolidKind {
258  fn __hash__(&self) -> usize {
259    (*self as u8) as usize
260  }
261}
262
263expand_and_test_enum!(SolidKind, test_solidkind_repr);
264
265#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
266#[cfg_attr(feature="pybindings", pyclass)]
267pub struct Solid {
268  pub name  : String,
269  pub shape : Shape,
270}
271
272impl Solid {
273  pub fn kind(&self) -> SolidKind {
274    match self.shape {
275      Shape::Tessellated {..} => SolidKind::Tessellated,
276      Shape::Box {..}         => SolidKind::Box,
277      Shape::Tube {..}        => SolidKind::Tube,
278      Shape::Boolean {op, ..} => match op {
279        BooleanOp::Union        => SolidKind::Union,
280        BooleanOp::Intersection => SolidKind::Intersection,
281        BooleanOp::Subtraction  => SolidKind::Subtraction,
282      }
283    }
284  }
285
286  /// Number of vertices of a tessellated solid, 0 otherwise
287  pub fn n_vertices(&self) -> usize {
288    match &self.shape {
289      Shape::Tessellated { vertices, .. } => vertices.len(),
290      _ => 0
291    }
292  }
293
294  /// Number of triangles of a tessellated solid, 0 otherwise
295  pub fn n_triangles(&self) -> usize {
296    match &self.shape {
297      Shape::Tessellated { triangles, .. } => triangles.len(),
298      _ => 0
299    }
300  }
301}
302
303impl fmt::Display for Solid {
304  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
305    let mut repr = format!("<Solid {} ({})", self.name, self.kind().as_ref());
306    match &self.shape {
307      Shape::Tessellated { vertices, triangles } => {
308        repr += &(format!("\n  {} vertices, {} triangles", vertices.len(), triangles.len()));
309      }
310      Shape::Box { half_lengths } => {
311        repr += &(format!("\n  half lengths {:.2} {:.2} {:.2}", half_lengths.x, half_lengths.y, half_lengths.z));
312      }
313      Shape::Tube { rmin, rmax, half_z, start_phi, delta_phi } => {
314        repr += &(format!("\n  rmin {:.2} rmax {:.2} half z {:.2} phi {:.4} + {:.4}",
315                          rmin, rmax, half_z, start_phi, delta_phi));
316      }
317      Shape::Boolean { first, second, .. } => {
318        repr += &(format!("\n  first {} second {}", first, second));
319      }
320    }
321    write!(f, "{}>", repr)
322  }
323}
324
325#[cfg(feature="pybindings")]
326#[pymethods]
327impl Solid {
328  #[getter]
329  fn get_name(&self) -> String {
330    self.name.clone()
331  }
332
333  #[getter]
334  #[pyo3(name="kind")]
335  fn get_kind_py(&self) -> SolidKind {
336    self.kind()
337  }
338
339  #[getter]
340  #[pyo3(name="n_vertices")]
341  fn get_n_vertices_py(&self) -> usize {
342    self.n_vertices()
343  }
344
345  #[getter]
346  #[pyo3(name="n_triangles")]
347  fn get_n_triangles_py(&self) -> usize {
348    self.n_triangles()
349  }
350
351  /// Vertices of a tessellated solid in its local frame
352  /// as an (N,3) array in mm. Empty for other solids.
353  #[getter]
354  fn get_vertices<'py>(&self, py : Python<'py>) -> Bound<'py, PyArray2<f64>> {
355    let flat : Vec<f64> = match &self.shape {
356      Shape::Tessellated { vertices, .. } => vertices.iter().flat_map(|v| v.to_array()).collect(),
357      _ => Vec::new()
358    };
359    let n = flat.len()/3;
360    Array2::from_shape_vec((n, 3), flat).unwrap().into_pyarray(py)
361  }
362
363  /// Triangles of a tessellated solid as an (N,3) array
364  /// of indices into vertices. Empty for other solids.
365  #[getter]
366  fn get_triangles<'py>(&self, py : Python<'py>) -> Bound<'py, PyArray2<u32>> {
367    let flat : Vec<u32> = match &self.shape {
368      Shape::Tessellated { triangles, .. } => triangles.iter().flatten().copied().collect(),
369      _ => Vec::new()
370    };
371    let n = flat.len()/3;
372    Array2::from_shape_vec((n, 3), flat).unwrap().into_pyarray(py)
373  }
374
375  /// Half lengths in mm of a box, None for other solids
376  #[getter]
377  fn get_half_lengths(&self) -> Option<(f64, f64, f64)> {
378    match self.shape {
379      Shape::Box { half_lengths } => Some(half_lengths.into()),
380      _ => None
381    }
382  }
383
384  /// (rmin, rmax, half_z, start_phi, delta_phi) of a tube
385  /// in mm and rad, None for other solids
386  #[getter]
387  fn get_tube(&self) -> Option<(f64, f64, f64, f64, f64)> {
388    match self.shape {
389      Shape::Tube { rmin, rmax, half_z, start_phi, delta_phi } => Some((rmin, rmax, half_z, start_phi, delta_phi)),
390      _ => None
391    }
392  }
393
394  /// Indices of the first and second solid of a boolean
395  /// solid, None for other solids
396  #[getter]
397  fn get_operands(&self) -> Option<(SolidId, SolidId)> {
398    match self.shape {
399      Shape::Boolean { first, second, .. } => Some((first, second)),
400      _ => None
401    }
402  }
403
404  /// Placement of the second solid in the frame of the first
405  /// one for a boolean solid, None for other solids
406  #[getter]
407  fn get_second_transform(&self) -> Option<Transform> {
408    match self.shape {
409      Shape::Boolean { second_transform, .. } => Some(second_transform),
410      _ => None
411    }
412  }
413}
414
415#[cfg(feature="pybindings")]
416pythonize_display!(Solid);
417
418//------------------------------------------------------------
419
420/// A placement of a (logical) volume inside its mother volume
421#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
422#[cfg_attr(feature="pybindings", pyclass)]
423pub struct Placement {
424  pub name       : String,
425  /// The Geant4 copy number of the placement (copynumber
426  /// attribute of the physvol, 0 if not given)
427  pub copynumber : i64,
428  /// the placed logical volume (index in Geometry.volumes)
429  pub volume     : VolumeId,
430  /// daughter -> mother frame
431  pub transform  : Transform,
432}
433
434impl fmt::Display for Placement {
435  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
436    write!(f, "<Placement {} (copynumber {}, volume {})>", self.name, self.copynumber, self.volume)
437  }
438}
439
440#[cfg(feature="pybindings")]
441#[pymethods]
442impl Placement {
443  #[getter]
444  fn get_name(&self) -> String {
445    self.name.clone()
446  }
447
448  /// The Geant4 copy number of the placement (copynumber
449  /// attribute of the physvol, 0 if not given)
450  #[getter]
451  fn get_copynumber(&self) -> i64 {
452    self.copynumber
453  }
454
455  /// Index of the placed logical volume in Geometry.volumes,
456  /// i.e. geo.volumes[p.volume] is the volume which is placed.
457  /// The index follows the order of the volumes in the GDML
458  /// file and is not a Geant4 number. A logical volume can be
459  /// placed many times, so this does not identify the placement
460  /// (use the copynumber for that).
461  #[getter]
462  fn get_volume(&self) -> VolumeId {
463    self.volume
464  }
465
466  /// daughter -> mother frame
467  #[getter]
468  fn get_transform(&self) -> Transform {
469    self.transform
470  }
471}
472
473#[cfg(feature="pybindings")]
474pythonize_display!(Placement);
475
476//------------------------------------------------------------
477
478#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
479#[cfg_attr(feature="pybindings", pyclass)]
480pub struct Volume {
481  pub name      : String,
482  pub material  : MaterialId,
483  pub solid     : SolidId,
484  pub daughters : Vec<Placement>,
485  /// GDML auxiliary information as (auxtype, auxvalue),
486  /// e.g. ("SensDet", "SimpleDet/ActiveDetectorSD")
487  pub auxiliary : Vec<(String, String)>,
488}
489
490impl fmt::Display for Volume {
491  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
492    write!(f, "<Volume {} (material {}, solid {}, {} daughters)>",
493           self.name, self.material, self.solid, self.daughters.len())
494  }
495}
496
497#[cfg(feature="pybindings")]
498#[pymethods]
499impl Volume {
500  #[getter]
501  fn get_name(&self) -> String {
502    self.name.clone()
503  }
504
505  /// Index of the material in Geometry.materials
506  #[getter]
507  fn get_material(&self) -> MaterialId {
508    self.material
509  }
510
511  /// Index of the solid in Geometry.solids
512  #[getter]
513  fn get_solid(&self) -> SolidId {
514    self.solid
515  }
516
517  #[getter]
518  fn get_daughters(&self) -> Vec<Placement> {
519    self.daughters.clone()
520  }
521
522  /// GDML auxiliary information as (auxtype, auxvalue)
523  #[getter]
524  fn get_auxiliary(&self) -> Vec<(String, String)> {
525    self.auxiliary.clone()
526  }
527}
528
529#[cfg(feature="pybindings")]
530pythonize_display!(Volume);
531
532//------------------------------------------------------------
533
534/// A placed volume with its transformation into the
535/// world frame
536#[derive(Debug, Clone, PartialEq)]
537#[cfg_attr(feature="pybindings", pyclass)]
538pub struct WorldPlacement {
539  /// the placed logical volume (index in Geometry.volumes)
540  pub volume     : VolumeId,
541  /// the Geant4 copy number of the placement, None for
542  /// the world
543  pub copynumber : Option<i64>,
544  /// the logical volume this one is placed in (index in
545  /// Geometry.volumes), None for the world
546  pub mother     : Option<VolumeId>,
547  /// local -> world frame
548  pub transform : Transform,
549  /// nesting depth, 0 for the world volume
550  pub depth     : usize,
551}
552
553impl fmt::Display for WorldPlacement {
554  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
555    write!(f, "<WorldPlacement volume {} (copynumber {:?}, mother {:?}, depth {})>",
556           self.volume, self.copynumber, self.mother, self.depth)
557  }
558}
559
560#[cfg(feature="pybindings")]
561#[pymethods]
562impl WorldPlacement {
563  /// Index of the placed logical volume in Geometry.volumes,
564  /// i.e. geo.volumes[p.volume] is the volume which is placed.
565  /// The index follows the order of the volumes in the GDML
566  /// file and is not a Geant4 number. A logical volume can be
567  /// placed many times, so this does not identify the placement
568  /// (use the copynumber for that).
569  #[getter]
570  fn get_volume(&self) -> VolumeId {
571    self.volume
572  }
573
574  /// The Geant4 copy number of the placement, None for
575  /// the world
576  #[getter]
577  fn get_copynumber(&self) -> Option<i64> {
578    self.copynumber
579  }
580
581  /// Index of the logical volume this one is placed in
582  /// (in Geometry.volumes), None for the world
583  #[getter]
584  fn get_mother(&self) -> Option<VolumeId> {
585    self.mother
586  }
587
588  /// local -> world frame
589  #[getter]
590  fn get_transform(&self) -> Transform {
591    self.transform
592  }
593
594  /// Nesting depth, 0 for the world volume
595  #[getter]
596  fn get_depth(&self) -> usize {
597    self.depth
598  }
599}
600
601#[cfg(feature="pybindings")]
602pythonize_display!(WorldPlacement);
603
604//------------------------------------------------------------
605
606#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
607#[cfg_attr(feature="pybindings", pyclass)]
608pub struct Geometry {
609  pub materials : Vec<Material>,
610  pub solids    : Vec<Solid>,
611  pub volumes   : Vec<Volume>,
612  /// the world volume (index in volumes)
613  pub world     : VolumeId,
614  /// All placements (except the world) by their Geant4
615  /// copy number. It is not stored in the cache, but
616  /// rebuilt when the geometry is created.
617  #[serde(skip)]
618  pub placements_by_copynumber : HashMap<i64, WorldPlacement>,
619  /// for the column density, built when first needed
620  #[serde(skip)]
621  pub(crate) raycaster : LazyRaycaster,
622}
623
624impl Geometry {
625  /// Create the geometry and index its placements by their
626  /// Geant4 copy number, which have to be unique
627  pub fn new(materials : Vec<Material>,
628             solids    : Vec<Solid>,
629             volumes   : Vec<Volume>,
630             world     : VolumeId) -> Result<Self, GeometryError> {
631    let mut geo = Self {
632      materials,
633      solids,
634      volumes,
635      world,
636      placements_by_copynumber : HashMap::new(),
637      raycaster                : LazyRaycaster::default(),
638    };
639    geo.index_copynumbers()?;
640    Ok(geo)
641  }
642
643  fn index_copynumbers(&mut self) -> Result<(), GeometryError> {
644    let mut index = HashMap::new();
645    for p in self.world_placements() {
646      let Some(copynumber) = p.copynumber else { continue };
647      if index.insert(copynumber, p).is_some() {
648        return Err(GeometryError::DuplicateCopynumber(copynumber));
649      }
650    }
651    self.placements_by_copynumber = index;
652    Ok(())
653  }
654
655  /// Load the geometry, either from a GDML file or from a
656  /// binary cache. If cache is given, it will be used if it
657  /// is newer than the GDML file, otherwise the GDML file is
658  /// parsed and the cache (re)written.
659  pub fn load(gdml : &Path, cache : Option<&Path>) -> Result<Self, GeometryError> {
660    let Some(cache) = cache else {
661      return parse_gdml_file(gdml);
662    };
663    let modified = |p : &Path| fs::metadata(p).and_then(|m| m.modified()).ok();
664    if let (Some(t_cache), Some(t_gdml)) = (modified(cache), modified(gdml)) {
665      if t_cache >= t_gdml {
666        return Self::read_cache(cache);
667      }
668    }
669    let geo = parse_gdml_file(gdml)?;
670    geo.write_cache(cache)?;
671    Ok(geo)
672  }
673
674  pub fn write_cache(&self, path : &Path) -> Result<(), GeometryError> {
675    let mut f = BufWriter::new(File::create(path)?);
676    f.write_all(CACHE_MAGIC)?;
677    f.write_all(&CACHE_VERSION.to_le_bytes())?;
678    postcard::to_io(self, &mut f)?;
679    f.flush()?;
680    Ok(())
681  }
682
683  pub fn read_cache(path : &Path) -> Result<Self, GeometryError> {
684    let mut bytes = Vec::new();
685    BufReader::new(File::open(path)?).read_to_end(&mut bytes)?;
686    let header = CACHE_MAGIC.len() + 4;
687    if bytes.len() < header || &bytes[..CACHE_MAGIC.len()] != CACHE_MAGIC {
688      return Err(GeometryError::Cache(format!("{} is not a geometry cache file", path.display())));
689    }
690    let version = u32::from_le_bytes(bytes[CACHE_MAGIC.len()..header].try_into().unwrap());
691    if version != CACHE_VERSION {
692      return Err(GeometryError::Cache(format!("Cache version {} is not supported (expected {})", version, CACHE_VERSION)));
693    }
694    let mut geo : Self = postcard::from_bytes(&bytes[header..])?;
695    geo.index_copynumbers()?;
696    Ok(geo)
697  }
698
699  pub fn world_volume(&self) -> &Volume {
700    &self.volumes[self.world]
701  }
702
703  /// Density of the material of a volume in g/cm3
704  pub fn density(&self, volume : VolumeId) -> f64 {
705    self.materials[self.volumes[volume].material].density
706  }
707
708  /// The placement with the given Geant4 copy number
709  pub fn placement(&self, copynumber : i64) -> Option<&WorldPlacement> {
710    self.placements_by_copynumber.get(&copynumber)
711  }
712
713  /// All placed volumes (including the world volume itself)
714  /// with their transformation into the world frame
715  pub fn world_placements(&self) -> Vec<WorldPlacement> {
716    let mut placements = vec![WorldPlacement {
717      volume     : self.world,
718      copynumber : None,
719      mother     : None,
720      transform  : Transform::IDENTITY,
721      depth      : 0,
722    }];
723    // the list grows while we walk it, which makes
724    // this a breadth first traversal
725    let mut k = 0;
726    while k < placements.len() {
727      let mother = placements[k].clone();
728      for d in &self.volumes[mother.volume].daughters {
729        placements.push(WorldPlacement {
730          volume     : d.volume,
731          copynumber : Some(d.copynumber),
732          mother     : Some(mother.volume),
733          transform  : Transform {
734            rotation    : mother.transform.rotation * d.transform.rotation,
735            translation : mother.transform.apply_point(d.transform.translation),
736          },
737          depth      : mother.depth + 1,
738        });
739      }
740      k += 1;
741    }
742    placements
743  }
744}
745
746impl fmt::Display for Geometry {
747  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
748    let mut repr = String::from("<Geometry");
749    repr += &(format!("\n  {} materials, {} solids, {} volumes",
750                      self.materials.len(), self.solids.len(), self.volumes.len()));
751    repr += &(format!("\n  world {} ({} placements)>",
752                      self.world_volume().name, self.world_volume().daughters.len()));
753    write!(f, "{}", repr)
754  }
755}
756
757#[cfg(feature="pybindings")]
758#[pymethods]
759impl Geometry {
760  /// Load the geometry, either from a GDML file or from a
761  /// binary cache. If cache is given, it will be used if it
762  /// is newer than the GDML file, otherwise the GDML file is
763  /// parsed and the cache (re)written.
764  ///
765  /// # Arguments:
766  ///   * gdml  : path to the GDML file
767  ///   * cache : path to the binary cache file
768  #[staticmethod]
769  #[pyo3(name="load", signature = (gdml, cache=None))]
770  fn load_py(gdml : String, cache : Option<String>) -> PyResult<Self> {
771    Ok(Self::load(Path::new(&gdml), cache.as_deref().map(Path::new))?)
772  }
773
774  /// Parse a GDML file
775  #[staticmethod]
776  fn from_gdml(path : String) -> PyResult<Self> {
777    Ok(parse_gdml_file(Path::new(&path))?)
778  }
779
780  /// Read the geometry from a binary cache file
781  #[staticmethod]
782  fn from_cache(path : String) -> PyResult<Self> {
783    Ok(Self::read_cache(Path::new(&path))?)
784  }
785
786  /// Write the geometry to a binary cache file
787  #[pyo3(name="write_cache")]
788  fn write_cache_py(&self, path : String) -> PyResult<()> {
789    Ok(self.write_cache(Path::new(&path))?)
790  }
791
792  #[getter]
793  fn get_materials(&self) -> Vec<Material> {
794    self.materials.clone()
795  }
796
797  #[getter]
798  fn get_solids(&self) -> Vec<Solid> {
799    self.solids.clone()
800  }
801
802  #[getter]
803  fn get_volumes(&self) -> Vec<Volume> {
804    self.volumes.clone()
805  }
806
807  /// Index of the world volume in volumes
808  #[getter]
809  fn get_world(&self) -> VolumeId {
810    self.world
811  }
812
813  #[getter]
814  #[pyo3(name="world_volume")]
815  fn get_world_volume_py(&self) -> Volume {
816    self.world_volume().clone()
817  }
818
819  /// Density of the material of a volume in g/cm3
820  #[pyo3(name="density")]
821  fn density_py(&self, volume : VolumeId) -> PyResult<f64> {
822    if volume >= self.volumes.len() {
823      return Err(PyValueError::new_err(format!("No volume with index {volume}")));
824    }
825    Ok(self.density(volume))
826  }
827
828  /// All placements (except the world) by their Geant4
829  /// copy number. This copies all placements, for a single
830  /// lookup use placement(copynumber)
831  #[getter]
832  #[pyo3(name="placements_by_copynumber")]
833  fn get_placements_by_copynumber_py(&self) -> HashMap<i64, WorldPlacement> {
834    self.placements_by_copynumber.clone()
835  }
836
837  /// The placement with the given Geant4 copy number,
838  /// None if there is no such placement
839  #[pyo3(name="placement")]
840  fn placement_py(&self, copynumber : i64) -> Option<WorldPlacement> {
841    self.placement(copynumber).cloned()
842  }
843
844  /// All placed volumes (including the world volume itself)
845  /// with their transformation into the world frame
846  #[pyo3(name="world_placements")]
847  fn world_placements_py(&self) -> Vec<WorldPlacement> {
848    self.world_placements()
849  }
850
851  /// The volumes along the straight track a -> b
852  ///
853  /// # Arguments:
854  ///   * a, b : start and stop point (x, y, z) in mm
855  #[pyo3(name="trace")]
856  fn trace_py(&self, a : (f64, f64, f64), b : (f64, f64, f64)) -> TrackPath {
857    self.trace(a.into(), b.into())
858  }
859
860  /// Column density along the straight track a -> b in
861  /// g/cm2, including the air of the world volume
862  ///
863  /// # Arguments:
864  ///   * a, b : start and stop point (x, y, z) in mm
865  #[pyo3(name="column_density")]
866  fn column_density_py(&self, a : (f64, f64, f64), b : (f64, f64, f64)) -> f64 {
867    self.column_density(a.into(), b.into())
868  }
869
870  /// Cumulative column density in g/cm2 at each point of a
871  /// track made of straight segments between the points.
872  /// The first value is always 0.
873  ///
874  /// # Arguments:
875  ///   * points : list of (x, y, z) in mm
876  #[pyo3(name="depths")]
877  fn depths_py(&self, points : Vec<(f64, f64, f64)>) -> Vec<f64> {
878    let points : Vec<DVec3> = points.into_iter().map(DVec3::from).collect();
879    self.depths(&points)
880  }
881
882  /// The start and stop point of a tracklet in mm. For an
883  /// infinite tracklet, the track goes from the start along
884  /// the vertex momentum until it leaves the world volume.
885  #[pyo3(name="tracklet_endpoints")]
886  fn tracklet_endpoints_py(&self, tracklet : &Tracklet) -> PyResult<((f64, f64, f64), (f64, f64, f64))> {
887    let (start, stop) = self.tracklet_endpoints(tracklet)?;
888    Ok((start.into(), stop.into()))
889  }
890
891  /// The volumes along a tracklet, see tracklet_endpoints
892  #[pyo3(name="trace_tracklet")]
893  fn trace_tracklet_py(&self, tracklet : &Tracklet) -> PyResult<TrackPath> {
894    Ok(self.trace_tracklet(tracklet)?)
895  }
896
897  /// Column density along a tracklet in g/cm2, including
898  /// the air of the world volume, see tracklet_endpoints
899  #[pyo3(name="tracklet_column_density")]
900  fn tracklet_column_density_py(&self, tracklet : &Tracklet) -> PyResult<f64> {
901    Ok(self.tracklet_column_density(tracklet)?)
902  }
903}
904
905#[cfg(feature="pybindings")]
906pythonize_display!(Geometry);
907
908//------------------------------------------------------------
909
910#[cfg(test)]
911mod tests {
912  use super::*;
913  use std::f64::consts::FRAC_PI_2;
914
915  #[test]
916  fn transform_roundtrip() {
917    let t = Transform::from_gdml(DVec3::new(1.0, 2.0, 3.0), DVec3::new(0.3, -1.1, 2.0));
918    let p = DVec3::new(-4.0, 5.0, 0.5);
919    assert!((t.inverse_apply_point(t.apply_point(p)) - p).length() < 1e-12);
920  }
921
922  #[test]
923  fn transform_g4_convention() {
924    // a GDML rotation of +90 deg about z places the
925    // daughter rotated by -90 deg, so the local x axis
926    // ends up along -y in the mother
927    let t = Transform::from_gdml(DVec3::ZERO, DVec3::new(0.0, 0.0, FRAC_PI_2));
928    assert!((t.apply_vector(DVec3::X) - DVec3::NEG_Y).length() < 1e-12);
929  }
930}