Skip to main content

gondola_core/geometry/
column_density.rs

1//! Column density along a straight track through the
2//! geometry, by ray casting the placed volumes.
3//!
4//! The volumes crossed by a segment A -> B are found with a
5//! BVH over the world bounding boxes of all placements. For
6//! each of them, the path length inside it is calculated
7//! exactly (see raycast). Since a daughter volume replaces
8//! the material of its mother, the column density is
9//!
10//!   X = rho_world * L_world + sum_v (rho_v - rho_mother(v)) * L_v
11//!
12//! with L_world the path length inside the world volume and
13//! L_v the one inside volume v. Lengths are in mm, densities
14//! in g/cm3 and column densities in g/cm2.
15// This file is part of gaps-online-software and published
16// under the GPLv3 license
17
18use crate::prelude::*;
19
20use std::sync::OnceLock;
21
22use glam::DVec3;
23
24use crate::geometry::bvh::{
25  Aabb,
26  Bvh,
27};
28use crate::geometry::model::{
29  Geometry,
30  VolumeId,
31  WorldPlacement,
32};
33use crate::geometry::raycast::SolidRaycaster;
34use crate::physics::Tracklet;
35
36/// Crossings of the same volume closer than this (in mm)
37/// do not count as overlaps
38const OVERLAP_TOLERANCE : f64 = 1e-6;
39
40//------------------------------------------------------------
41
42/// Acceleration structures to cast rays through the placed
43/// volumes of a geometry
44#[derive(Debug, Clone)]
45pub struct Raycaster {
46  solids     : SolidRaycaster,
47  /// all placements, the world is the first one
48  placements : Vec<WorldPlacement>,
49  /// world bounding box of every placement
50  bounds     : Vec<Aabb>,
51  /// BVH over the placements except the world. Its
52  /// primitive i is the placement i + 1.
53  bvh        : Bvh,
54}
55
56impl Raycaster {
57  pub fn new(geo : &Geometry) -> Self {
58    let solids     = SolidRaycaster::new(geo);
59    let placements = geo.world_placements();
60    let bounds : Vec<Aabb> = placements.iter()
61      .map(|p| solids.bounds(geo.volumes[p.volume].solid).transformed(&p.transform))
62      .collect();
63    let bvh = Bvh::build(&bounds[1..]);
64    Self { solids, placements, bounds, bvh }
65  }
66
67  /// The parts of the segment a -> b inside each volume
68  pub fn trace(&self, geo : &Geometry, a : DVec3, b : DVec3) -> TrackPath {
69    let length = (b - a).length();
70    let mut path = TrackPath {
71      length,
72      crossings : Vec::new(),
73      rejected  : Vec::new(),
74    };
75    if length == 0.0 {
76      return path;
77    }
78    let dir = (b - a)/length;
79    let mut add = |k : usize, placement : &WorldPlacement| {
80      if self.bounds[k].clip_line(a, dir, 0.0, length).is_none() {
81        return;
82      }
83      let t = &placement.transform;
84      let solid = geo.volumes[placement.volume].solid;
85      match self.solids.intervals(geo, solid, t.inverse_apply_point(a), t.inverse_apply_vector(dir), 0.0, length) {
86        Some(iv) => {
87          for (t0, t1) in iv {
88            path.crossings.push(Crossing {
89              copynumber : placement.copynumber,
90              volume     : placement.volume,
91              mother     : placement.mother,
92              start      : t0,
93              stop       : t1,
94              density    : geo.density(placement.volume),
95            });
96          }
97        }
98        None => path.rejected.push(placement.copynumber),
99      }
100    };
101    add(0, &self.placements[0]);
102    self.bvh.traverse(a, dir, 0.0, length, |i| {
103      let k = i as usize + 1;
104      add(k, &self.placements[k]);
105    });
106    path.crossings.sort_by(|x, y| x.start.total_cmp(&y.start).then(x.stop.total_cmp(&y.stop)));
107    path
108  }
109}
110
111/// The raycaster of a geometry is built when it is first
112/// needed. It does not take part in comparisons.
113#[derive(Debug, Clone, Default)]
114pub struct LazyRaycaster(OnceLock<Raycaster>);
115
116impl PartialEq for LazyRaycaster {
117  fn eq(&self, _other : &Self) -> bool {
118    true
119  }
120}
121
122//------------------------------------------------------------
123
124/// The part of a track inside one placed volume
125#[derive(Debug, Clone, PartialEq)]
126#[cfg_attr(feature="pybindings", pyclass)]
127pub struct Crossing {
128  /// Geant4 copy number of the placement, None for the world
129  pub copynumber : Option<i64>,
130  /// the placed logical volume (index in Geometry.volumes)
131  pub volume     : VolumeId,
132  /// the logical volume it is placed in, None for the world
133  pub mother     : Option<VolumeId>,
134  /// distance from the start of the track where it enters
135  /// the volume in mm
136  pub start      : f64,
137  /// distance from the start of the track where it leaves
138  /// the volume in mm
139  pub stop       : f64,
140  /// density of the material of the volume in g/cm3
141  pub density    : f64,
142}
143
144impl Crossing {
145  /// Path length inside the volume in mm
146  pub fn length(&self) -> f64 {
147    self.stop - self.start
148  }
149
150  /// Column density inside the volume in g/cm2
151  pub fn column_density(&self) -> f64 {
152    self.density*self.length()/10.0
153  }
154}
155
156impl fmt::Display for Crossing {
157  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
158    write!(f, "<Crossing volume {} (copynumber {:?}) from {:.3} to {:.3} mm, {:.4} g/cm2>",
159           self.volume, self.copynumber, self.start, self.stop, self.column_density())
160  }
161}
162
163#[cfg(feature="pybindings")]
164#[pymethods]
165impl Crossing {
166  /// Geant4 copy number of the placement, None for the world
167  #[getter]
168  fn get_copynumber(&self) -> Option<i64> {
169    self.copynumber
170  }
171
172  /// The placed logical volume (index in Geometry.volumes)
173  #[getter]
174  fn get_volume(&self) -> VolumeId {
175    self.volume
176  }
177
178  /// The logical volume it is placed in (index in
179  /// Geometry.volumes), None for the world
180  #[getter]
181  fn get_mother(&self) -> Option<VolumeId> {
182    self.mother
183  }
184
185  /// Distance from the start of the track where it enters
186  /// the volume in mm
187  #[getter]
188  fn get_start(&self) -> f64 {
189    self.start
190  }
191
192  /// Distance from the start of the track where it leaves
193  /// the volume in mm
194  #[getter]
195  fn get_stop(&self) -> f64 {
196    self.stop
197  }
198
199  /// Density of the material of the volume in g/cm3
200  #[getter]
201  fn get_density(&self) -> f64 {
202    self.density
203  }
204
205  /// Path length inside the volume in mm
206  #[getter]
207  #[pyo3(name="length")]
208  fn get_length_py(&self) -> f64 {
209    self.length()
210  }
211
212  /// Column density inside the volume in g/cm2
213  #[getter]
214  #[pyo3(name="column_density")]
215  fn get_column_density_py(&self) -> f64 {
216    self.column_density()
217  }
218}
219
220#[cfg(feature="pybindings")]
221pythonize_display!(Crossing);
222
223//------------------------------------------------------------
224
225/// The volumes along a straight track
226#[derive(Debug, Clone, PartialEq)]
227#[cfg_attr(feature="pybindings", pyclass)]
228pub struct TrackPath {
229  /// length of the track in mm
230  pub length    : f64,
231  /// all parts of the track inside a volume (including the
232  /// world), sorted by where they start
233  pub crossings : Vec<Crossing>,
234  /// copy numbers of volumes which have been left out,
235  /// because the track crosses their (not closed) mesh
236  /// an unequal number of times inwards and outwards
237  pub rejected  : Vec<Option<i64>>,
238}
239
240impl TrackPath {
241  /// Column density along the track in g/cm2
242  pub fn column_density(&self) -> f64 {
243    self.column_density_until(f64::INFINITY)
244  }
245
246  /// Column density from the start of the track up to a
247  /// distance (in mm) along it in g/cm2
248  pub fn column_density_until(&self, distance : f64) -> f64 {
249    let mut x = 0.0;
250    for c in &self.crossings {
251      if c.start >= distance {
252        break;
253      }
254      let mother_density = match c.mother {
255        Some(m) => self.mother_density(m),
256        None    => 0.0,
257      };
258      x += (c.density - mother_density)*(c.stop.min(distance) - c.start)/10.0;
259    }
260    x
261  }
262
263  fn mother_density(&self, mother : VolumeId) -> f64 {
264    self.crossings.iter()
265      .find(|c| c.volume == mother)
266      .map(|c| c.density)
267      .unwrap_or(0.0)
268  }
269
270  /// Pairs of crossings of volumes with the same mother
271  /// which overlap along the track, as
272  /// (copynumber, copynumber, overlap in mm). Overlapping
273  /// volumes are an error in the geometry.
274  pub fn overlaps(&self) -> Vec<(Option<i64>, Option<i64>, f64)> {
275    let mut overlaps = Vec::new();
276    for (i, a) in self.crossings.iter().enumerate() {
277      for b in &self.crossings[i + 1..] {
278        if b.start >= a.stop - OVERLAP_TOLERANCE {
279          break;
280        }
281        if a.mother == b.mother && a.mother.is_some() {
282          overlaps.push((a.copynumber, b.copynumber, a.stop.min(b.stop) - b.start));
283        }
284      }
285    }
286    overlaps
287  }
288}
289
290impl fmt::Display for TrackPath {
291  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
292    write!(f, "<TrackPath {:.3} mm, {} crossings, {} rejected, {:.4} g/cm2>",
293           self.length, self.crossings.len(), self.rejected.len(), self.column_density())
294  }
295}
296
297#[cfg(feature="pybindings")]
298#[pymethods]
299impl TrackPath {
300  /// Length of the track in mm
301  #[getter]
302  fn get_length(&self) -> f64 {
303    self.length
304  }
305
306  /// All parts of the track inside a volume (including the
307  /// world), sorted by where they start
308  #[getter]
309  fn get_crossings(&self) -> Vec<Crossing> {
310    self.crossings.clone()
311  }
312
313  /// Copy numbers of volumes which have been left out,
314  /// because the track crosses their (not closed) mesh an
315  /// unequal number of times inwards and outwards
316  #[getter]
317  fn get_rejected(&self) -> Vec<Option<i64>> {
318    self.rejected.clone()
319  }
320
321  /// Column density along the track in g/cm2
322  #[getter]
323  #[pyo3(name="column_density")]
324  fn get_column_density_py(&self) -> f64 {
325    self.column_density()
326  }
327
328  /// Column density from the start of the track up to a
329  /// distance (in mm) along it in g/cm2
330  #[pyo3(name="column_density_until")]
331  fn column_density_until_py(&self, distance : f64) -> f64 {
332    self.column_density_until(distance)
333  }
334
335  /// Pairs of crossings of volumes with the same mother
336  /// which overlap along the track, as
337  /// (copynumber, copynumber, overlap in mm)
338  #[pyo3(name="overlaps")]
339  fn overlaps_py(&self) -> Vec<(Option<i64>, Option<i64>, f64)> {
340    self.overlaps()
341  }
342}
343
344#[cfg(feature="pybindings")]
345pythonize_display!(TrackPath);
346
347//------------------------------------------------------------
348
349impl Geometry {
350  /// The raycaster for this geometry, it is built the first
351  /// time it is needed (this takes about half a second for
352  /// the GAPS geometry)
353  pub fn raycaster(&self) -> &Raycaster {
354    self.raycaster.0.get_or_init(|| Raycaster::new(self))
355  }
356
357  /// The volumes along the straight track a -> b (in mm)
358  pub fn trace(&self, a : DVec3, b : DVec3) -> TrackPath {
359    self.raycaster().trace(self, a, b)
360  }
361
362  /// Column density along the straight track a -> b (in mm)
363  /// in g/cm2, including the air of the world volume
364  pub fn column_density(&self, a : DVec3, b : DVec3) -> f64 {
365    self.trace(a, b).column_density()
366  }
367
368  /// Cumulative column density in g/cm2 at each point of a
369  /// track made of straight segments between the points.
370  /// The first value is always 0.
371  pub fn depths(&self, points : &[DVec3]) -> Vec<f64> {
372    let mut depths = Vec::with_capacity(points.len());
373    let mut x = 0.0;
374    for (k, p) in points.iter().enumerate() {
375      if k > 0 {
376        x += self.column_density(points[k - 1], *p);
377      }
378      depths.push(x);
379    }
380    depths
381  }
382
383  /// The start and stop point of a tracklet (in mm). For an
384  /// infinite tracklet, the track goes from the start along
385  /// the vertex momentum until it leaves the world volume.
386  pub fn tracklet_endpoints(&self, tracklet : &Tracklet) -> Result<(DVec3, DVec3), GeometryError> {
387    let start = DVec3::new(tracklet.start.x as f64, tracklet.start.y as f64, tracklet.start.z as f64);
388    if !tracklet.is_infinite {
389      let stop = DVec3::new(tracklet.stop.x as f64, tracklet.stop.y as f64, tracklet.stop.z as f64);
390      return Ok((start, stop));
391    }
392    let mom = DVec3::new(tracklet.vertex_mom_x as f64, tracklet.vertex_mom_y as f64, tracklet.vertex_mom_z as f64);
393    if mom.length() == 0.0 {
394      return Err(GeometryError::InvalidTrack(String::from("Infinite tracklet without vertex momentum")));
395    }
396    let dir   = mom.normalize();
397    let world = self.raycaster().bounds[0];
398    let stop  = match world.clip_line(start, dir, 0.0, f64::INFINITY) {
399      Some((_, t1)) => start + t1*dir,
400      None          => start,
401    };
402    Ok((start, stop))
403  }
404
405  /// The volumes along a tracklet, see tracklet_endpoints
406  pub fn trace_tracklet(&self, tracklet : &Tracklet) -> Result<TrackPath, GeometryError> {
407    let (start, stop) = self.tracklet_endpoints(tracklet)?;
408    Ok(self.trace(start, stop))
409  }
410
411  /// Column density along a tracklet in g/cm2, see
412  /// tracklet_endpoints
413  pub fn tracklet_column_density(&self, tracklet : &Tracklet) -> Result<f64, GeometryError> {
414    Ok(self.trace_tracklet(tracklet)?.column_density())
415  }
416}
417
418//------------------------------------------------------------
419
420#[cfg(test)]
421mod tests {
422  use super::*;
423  use crate::geometry::gdml::parse_gdml_str;
424
425  /// A 100 mm aluminium cube at the origin and an aluminium
426  /// ring at z = 200 mm, in an air world
427  const GDML : &str = r#"<?xml version="1.0" encoding="UTF-8"?>
428<gdml>
429  <materials>
430    <material name="Air"><D unit="g/cm3" value="0.001"/></material>
431    <material name="Alu"><D unit="g/cm3" value="2.7"/></material>
432  </materials>
433  <solids>
434    <box lunit="mm" name="World" x="1000" y="1000" z="1000"/>
435    <box lunit="mm" name="Cube" x="100" y="100" z="100"/>
436    <tube aunit="deg" deltaphi="360" lunit="mm" name="Ring" rmax="50" rmin="40" startphi="0" z="10"/>
437  </solids>
438  <structure>
439    <volume name="CubeVol">
440      <materialref ref="Alu"/>
441      <solidref ref="Cube"/>
442    </volume>
443    <volume name="RingVol">
444      <materialref ref="Alu"/>
445      <solidref ref="Ring"/>
446    </volume>
447    <volume name="WorldVol">
448      <materialref ref="Air"/>
449      <solidref ref="World"/>
450      <physvol copynumber="1" name="cube">
451        <volumeref ref="CubeVol"/>
452      </physvol>
453      <physvol copynumber="2" name="ring">
454        <volumeref ref="RingVol"/>
455        <position name="ring_pos" unit="mm" x="0" y="0" z="200"/>
456      </physvol>
457    </volume>
458  </structure>
459  <setup name="Default" version="1.0">
460    <world ref="WorldVol"/>
461  </setup>
462</gdml>
463"#;
464
465  #[test]
466  fn column_density_through_boxes_and_tubes() {
467    let geo = parse_gdml_str(GDML).unwrap();
468    // along x through the cube: 100 mm alu, 300 mm air
469    let a = DVec3::new(-200.0, 0.0, 0.0);
470    let b = DVec3::new( 200.0, 0.0, 0.0);
471    let path = geo.trace(a, b);
472    assert_eq!(path.crossings.len(), 2);
473    assert_eq!(path.crossings[1].copynumber, Some(1));
474    assert!((path.crossings[1].length() - 100.0).abs() < 1e-9);
475    let expected = (2.7*100.0 + 0.001*300.0)/10.0;
476    assert!((geo.column_density(a, b) - expected).abs() < 1e-12);
477    // along y through the ring at z = 200: 2 x 10 mm alu
478    let a = DVec3::new(0.0, -200.0, 200.0);
479    let b = DVec3::new(0.0,  200.0, 200.0);
480    let path = geo.trace(a, b);
481    assert_eq!(path.crossings.iter().filter(|c| c.copynumber == Some(2)).count(), 2);
482    let expected = (2.7*20.0 + 0.001*380.0)/10.0;
483    assert!((path.column_density() - expected).abs() < 1e-12);
484    assert!((path.column_density_until(200.0) - expected/2.0).abs() < 1e-12);
485    assert!(path.overlaps().is_empty());
486  }
487
488  #[test]
489  fn tracks_leaving_the_world_and_depths() {
490    let geo = parse_gdml_str(GDML).unwrap();
491    // the world ends at |x| = 500, there is nothing beyond
492    let a = DVec3::new(-2000.0, 0.0, 0.0);
493    let b = DVec3::new( 2000.0, 0.0, 0.0);
494    let expected = (2.7*100.0 + 0.001*900.0)/10.0;
495    assert!((geo.column_density(a, b) - expected).abs() < 1e-12);
496    // depths along a polyline
497    let points = [DVec3::new(-200.0, 0.0, 0.0), DVec3::ZERO, DVec3::new(0.0, 0.0, 200.0)];
498    let depths = geo.depths(&points);
499    assert_eq!(depths[0], 0.0);
500    assert!((depths[1] - (2.7*50.0 + 0.001*150.0)/10.0).abs() < 1e-12);
501    // along the axis of the ring, through its hole
502    assert!((depths[2] - depths[1] - (2.7*50.0 + 0.001*150.0)/10.0).abs() < 1e-12);
503  }
504
505  #[test]
506  fn tracklets() {
507    let geo = parse_gdml_str(GDML).unwrap();
508    let mut t = Tracklet::new();
509    t.start.x = -200.0;
510    t.is_infinite = false;
511    t.stop.x = 200.0;
512    let expected = (2.7*100.0 + 0.001*300.0)/10.0;
513    assert!((geo.tracklet_column_density(&t).unwrap() - expected).abs() < 1e-9);
514    // an infinite tracklet goes until the end of the world
515    t.is_infinite  = true;
516    t.vertex_mom_x = 3.0;
517    let (_, stop) = geo.tracklet_endpoints(&t).unwrap();
518    assert!((stop - DVec3::new(500.0, 0.0, 0.0)).length() < 1e-9);
519    let expected = (2.7*100.0 + 0.001*600.0)/10.0;
520    assert!((geo.tracklet_column_density(&t).unwrap() - expected).abs() < 1e-9);
521    t.vertex_mom_x = 0.0;
522    assert!(matches!(geo.tracklet_column_density(&t), Err(GeometryError::InvalidTrack(_))));
523  }
524}