laddu 0.20.0

Amplitude analysis tools for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
use std::collections::HashSet;

use laddu_physics::{channel::Channel, vectors::Vec4};
use pyo3::{exceptions::PyValueError, prelude::*};

#[cfg(feature = "generation")]
use super::generation::{PyInitialMomentum, PyMassProposal, PyVertexProposal};
use super::{
    angular::PyVec3, error::to_py_err, expr::PyExpr, particle::PyParticle,
    quantum::PyMandelstamChannel,
};

#[pyclass(name = "Edge", module = "laddu", frozen, skip_from_py_object)]
#[derive(Clone)]
/// An edge (particle line) in a reaction channel.
///
/// Parameters
/// ----------
/// name : str
///     Unique edge name.
/// p4 : str, optional
///     Dataset four-vector column used for observed events.
/// particle : Particle, optional
///     Particle properties such as mass and quantum numbers.
/// output : bool, default=False
///     Include this edge as a four-vector column in generated datasets.
/// mass_proposal : MassProposal, optional
///     Mass distribution for generation.
/// initial_momentum : InitialMomentum, optional
///     Momentum prescription for an initial-state edge.
pub struct PyEdge {
    name: String,
    p4: Option<String>,
    particle: Option<PyParticle>,
    output: bool,
    #[cfg(feature = "generation")]
    mass_proposal: Option<PyMassProposal>,
    #[cfg(feature = "generation")]
    initial_momentum: Option<PyInitialMomentum>,
}

#[pymethods]
impl PyEdge {
    /// Define a channel edge.
    ///
    /// Raises
    /// ------
    /// ValueError
    ///     If ``name`` is empty.
    #[new]
    #[cfg(feature = "generation")]
    #[pyo3(signature = (name, *, p4=None, particle=None, output=false, mass_proposal=None, initial_momentum=None))]
    fn new(
        name: String,
        p4: Option<String>,
        particle: Option<PyRef<'_, PyParticle>>,
        output: bool,
        mass_proposal: Option<PyRef<'_, PyMassProposal>>,
        initial_momentum: Option<PyRef<'_, PyInitialMomentum>>,
    ) -> PyResult<Self> {
        if name.is_empty() {
            return Err(PyValueError::new_err("edge name cannot be empty"));
        }
        Ok(Self {
            name,
            p4,
            particle: particle.map(|particle| particle.clone()),
            output,
            mass_proposal: mass_proposal.map(|proposal| proposal.clone()),
            initial_momentum: initial_momentum.map(|momentum| momentum.clone()),
        })
    }

    fn __repr__(&self) -> String {
        format!("Edge({:?})", self.name)
    }

    #[getter]
    /// str: Unique edge name.
    fn name(&self) -> &str {
        &self.name
    }
    #[getter]
    /// str or None: Dataset four-vector column.
    fn p4(&self) -> Option<&str> {
        self.p4.as_deref()
    }
    #[getter]
    /// Particle or None: Particle properties assigned to the edge.
    fn particle(&self) -> Option<PyParticle> {
        self.particle.clone()
    }
    #[getter]
    /// bool: Whether generated datasets include this edge.
    fn output(&self) -> bool {
        self.output
    }
}

#[pyclass(name = "Vertex", module = "laddu", frozen, skip_from_py_object)]
#[derive(Clone)]
/// A directed interaction or decay vertex.
///
/// Parameters
/// ----------
/// name : str
///     Unique vertex name.
/// incoming, outgoing : sequence of str
///     Edge names on each side of the vertex.
/// generation : VertexProposal, optional
///     Phase-space proposal used when generating this vertex.
pub struct PyVertex {
    name: String,
    incoming: Vec<String>,
    outgoing: Vec<String>,
    #[cfg(feature = "generation")]
    generation: Option<PyVertexProposal>,
}

#[pymethods]
impl PyVertex {
    /// Define a channel vertex.
    ///
    /// Raises
    /// ------
    /// ValueError
    ///     If the name is empty, either side is empty, or an edge is repeated.
    #[new]
    #[cfg(feature = "generation")]
    #[pyo3(signature = (name, *, incoming, outgoing, generation=None))]
    fn new(
        name: String,
        incoming: Vec<String>,
        outgoing: Vec<String>,
        generation: Option<PyRef<'_, PyVertexProposal>>,
    ) -> PyResult<Self> {
        validate_vertex_input(&name, &incoming, &outgoing)?;
        Ok(Self {
            name,
            incoming,
            outgoing,
            generation: generation.map(|proposal| proposal.clone()),
        })
    }

    fn __repr__(&self) -> String {
        format!("Vertex({:?})", self.name)
    }
    #[getter]
    /// str: Unique vertex name.
    fn name(&self) -> &str {
        &self.name
    }
    #[getter]
    /// list of str: Incoming edge names.
    fn incoming(&self) -> Vec<String> {
        self.incoming.clone()
    }
    #[getter]
    /// list of str: Outgoing edge names.
    fn outgoing(&self) -> Vec<String> {
        self.outgoing.clone()
    }
}

fn validate_vertex_input(name: &str, incoming: &[String], outgoing: &[String]) -> PyResult<()> {
    if name.is_empty() {
        return Err(PyValueError::new_err("vertex name cannot be empty"));
    }
    if incoming.is_empty() || outgoing.is_empty() {
        return Err(PyValueError::new_err(
            "a vertex requires at least one incoming and one outgoing edge",
        ));
    }
    let mut seen = HashSet::new();
    if incoming
        .iter()
        .chain(outgoing)
        .any(|edge| !seen.insert(edge))
    {
        return Err(PyValueError::new_err(
            "an edge cannot appear more than once in a vertex",
        ));
    }
    Ok(())
}

#[pyclass(name = "Channel", module = "laddu", frozen, skip_from_py_object)]
#[derive(Clone)]
/// A validated reaction topology used to build kinematics and generators.
///
/// Parameters
/// ----------
/// name : str
///     Channel name.
/// edges : sequence of Edge
///     Particle lines with unique names.
/// vertices : sequence of Vertex
///     Directed interactions connecting the edges.
///
/// Examples
/// --------
/// >>> import laddu as ld
/// >>> beam = ld.Edge("beam", p4="beam", particle=ld.particles.PHOTON)
/// >>> target = ld.Edge("target", p4="target", particle=ld.particles.PROTON)
/// >>> recoil = ld.Edge("recoil", p4="recoil", particle=ld.particles.PROTON)
/// >>> production = ld.Vertex(
/// ...     "production", incoming=["beam", "target"], outgoing=["recoil"]
/// ... )
/// >>> channel = ld.Channel("gamma p", edges=\[beam, target, recoil\], vertices=\[production\])
pub struct PyChannel {
    pub(crate) inner: Channel,
}

#[pyclass(name = "VertexFrame", module = "laddu", frozen, skip_from_py_object)]
#[derive(Clone)]
/// Kinematic expressions evaluated in a vertex center-of-momentum frame.
///
/// Obtain a frame from :meth:`Channel.vertex`; instances cannot be constructed
/// directly.
pub struct PyVertexFrame {
    channel: Channel,
    name: String,
}

#[pymethods]
impl PyVertexFrame {
    #[getter]
    /// str: Name of the represented vertex.
    fn name(&self) -> &str {
        &self.name
    }

    /// Return an edge's three-momentum in this vertex frame.
    ///
    /// Parameters
    /// ----------
    /// edge : str
    ///     Edge incident on the vertex.
    ///
    /// Returns
    /// -------
    /// Vec3
    ///     Symbolic three-vector expression.
    fn vec3(&self, edge: &str) -> PyResult<PyVec3> {
        Ok(PyVec3 {
            inner: self
                .channel
                .get_vertex(&self.name)
                .map_err(to_py_err)?
                .vec3(edge)
                .map_err(to_py_err)?,
        })
    }

    /// Return the polar-angle expression for an edge.
    ///
    /// ``z_axis`` defines the polar axis and ``y_hint`` fixes the azimuthal
    /// orientation after orthogonalization.
    fn theta(&self, edge: &str, z_axis: &PyVec3, y_hint: &PyVec3) -> PyResult<PyExpr> {
        self.channel
            .get_vertex(&self.name)
            .map_err(to_py_err)?
            .theta(edge, z_axis.inner.clone(), y_hint.inner.clone())
            .map(PyExpr::from)
            .map_err(to_py_err)
    }

    /// Return the cosine of an edge's polar angle.
    fn costheta(&self, edge: &str, z_axis: &PyVec3, y_hint: &PyVec3) -> PyResult<PyExpr> {
        self.channel
            .get_vertex(&self.name)
            .map_err(to_py_err)?
            .costheta(edge, z_axis.inner.clone(), y_hint.inner.clone())
            .map(PyExpr::from)
            .map_err(to_py_err)
    }

    /// Return an edge's azimuthal-angle expression.
    fn phi(&self, edge: &str, z_axis: &PyVec3, y_hint: &PyVec3) -> PyResult<PyExpr> {
        self.channel
            .get_vertex(&self.name)
            .map_err(to_py_err)?
            .phi(edge, z_axis.inner.clone(), y_hint.inner.clone())
            .map(PyExpr::from)
            .map_err(to_py_err)
    }

    /// Return a Mandelstam invariant for this vertex.
    ///
    /// Parameters
    /// ----------
    /// channel : MandelstamChannel
    ///     One of the ``S``, ``T``, or ``U`` channels.
    fn mandelstam(&self, channel: &PyMandelstamChannel) -> PyResult<PyExpr> {
        self.channel
            .get_vertex(&self.name)
            .map_err(to_py_err)?
            .mandelstam(channel.inner)
            .map(PyExpr::from)
            .map_err(to_py_err)
    }

    /// Return the Mandelstam-s invariant.
    fn s(&self) -> PyResult<PyExpr> {
        self.channel
            .get_vertex(&self.name)
            .map_err(to_py_err)?
            .s()
            .map(PyExpr::from)
            .map_err(to_py_err)
    }

    /// Return the Mandelstam-t invariant.
    fn t(&self) -> PyResult<PyExpr> {
        self.channel
            .get_vertex(&self.name)
            .map_err(to_py_err)?
            .t()
            .map(PyExpr::from)
            .map_err(to_py_err)
    }

    /// Return the Mandelstam-u invariant.
    fn u(&self) -> PyResult<PyExpr> {
        self.channel
            .get_vertex(&self.name)
            .map_err(to_py_err)?
            .u()
            .map(PyExpr::from)
            .map_err(to_py_err)
    }
}

#[pymethods]
impl PyChannel {
    /// Construct and validate a reaction channel.
    ///
    /// Raises
    /// ------
    /// ValueError
    ///     If an edge or vertex name is duplicated.
    /// LadduError
    ///     If a vertex references invalid edges or violates topology rules.
    #[new]
    #[pyo3(signature = (name, *, edges, vertices))]
    fn new(
        name: String,
        edges: Vec<PyRef<'_, PyEdge>>,
        vertices: Vec<PyRef<'_, PyVertex>>,
    ) -> PyResult<Self> {
        let mut channel = Channel::new(name);
        let mut names = HashSet::new();
        for edge in edges {
            if !names.insert(edge.name.clone()) {
                return Err(PyValueError::new_err(format!(
                    "duplicate edge name {:?}",
                    edge.name
                )));
            }
            let mut handle = channel.edge(edge.name.clone());
            if let Some(p4) = &edge.p4 {
                handle.p4(Vec4::event(p4));
            }
            if let Some(particle) = &edge.particle {
                handle.properties(&particle.inner);
            }
            if edge.output {
                handle.output();
            } else {
                handle.generated_only();
            }
            #[cfg(feature = "generation")]
            {
                if let Some(proposal) = &edge.mass_proposal {
                    handle.mass_proposal(proposal.inner);
                }
                if let Some(momentum) = &edge.initial_momentum {
                    handle.initial(momentum.inner.clone());
                }
            }
        }
        let mut vertex_names = HashSet::new();
        for vertex in vertices {
            if !vertex_names.insert(vertex.name.clone()) {
                return Err(PyValueError::new_err(format!(
                    "duplicate vertex name {:?}",
                    vertex.name
                )));
            }
            let mut handle = channel.vertex(vertex.name.clone());
            handle.incoming(&vertex.incoming).outgoing(&vertex.outgoing);
            #[cfg(feature = "generation")]
            if let Some(proposal) = &vertex.generation {
                handle.generation(proposal.inner.clone());
            }
            handle.validate().map_err(to_py_err)?;
        }
        Ok(Self { inner: channel })
    }

    fn __repr__(&self) -> String {
        format!(
            "Channel({:?}, edges={}, vertices={})",
            self.inner.name(),
            self.inner.edges().count(),
            self.inner.vertices().count()
        )
    }

    #[getter]
    /// str: Channel name.
    fn name(&self) -> &str {
        self.inner.name()
    }
    #[getter]
    /// list of str: Edge names in channel order.
    fn edge_names(&self) -> Vec<String> {
        self.inner
            .edges()
            .map(|edge| edge.name().to_owned())
            .collect()
    }
    #[getter]
    /// list of str: Vertex names in channel order.
    fn vertex_names(&self) -> Vec<String> {
        self.inner
            .vertices()
            .map(|vertex| vertex.name().to_owned())
            .collect()
    }

    /// Return particle properties assigned to an edge.
    ///
    /// Raises
    /// ------
    /// LadduError
    ///     If the edge is unknown or has no particle properties.
    fn particle(&self, edge: &str) -> PyResult<PyParticle> {
        self.inner
            .particle(edge)
            .cloned()
            .map(PyParticle::from)
            .map_err(to_py_err)
    }

    /// Return the center-of-momentum frame for a named vertex.
    ///
    /// Raises
    /// ------
    /// LadduError
    ///     If the vertex is unknown.
    fn vertex(&self, name: &str) -> PyResult<PyVertexFrame> {
        self.inner.get_vertex(name).map_err(to_py_err)?;
        Ok(PyVertexFrame {
            channel: self.inner.clone(),
            name: name.to_owned(),
        })
    }

    /// Return the invariant-mass expression for an edge.
    fn mass(&self, edge: &str) -> PyResult<PyExpr> {
        self.inner.mass(edge).map(PyExpr::from).map_err(to_py_err)
    }

    /// Return the squared invariant-mass expression for an edge.
    fn s(&self, edge: &str) -> PyResult<PyExpr> {
        self.inner.s(edge).map(PyExpr::from).map_err(to_py_err)
    }

    /// Validate all information required for event generation.
    ///
    /// Raises
    /// ------
    /// LadduError
    ///     If initial states, masses, outputs, or vertex proposals are invalid.
    fn validate_generation(&self) -> PyResult<()> {
        self.inner.validate().map_err(to_py_err)
    }
}