rexafs 0.2.5

Rust-powered X-ray absorption spectroscopy analysis and EXAFS fitting
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
//! Spherical cluster of atoms around an absorber, FEFF potential
//! assignment and neighbour-shell summary.

use serde::{Deserialize, Serialize};

use super::element::Element;
use super::model::Structure;
use super::StructureError;

/// Which site is the absorber.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum AbsorberSelection {
    /// A site index of `Structure::sites`.
    SiteIndex(usize),
    /// The first site whose majority species is this element.
    Element(String),
    /// The `nth` (0-based) crystallographically distinct site of the element,
    /// counted over the asymmetric unit.
    ElementSite {
        /// Element that must be the selected site's majority species.
        symbol: String,
        /// Zero-based index among that element's distinct absorber sites.
        nth: usize,
    },
}

/// How mixed-occupancy sites are resolved into single atoms.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum OccupancyPolicy {
    /// Highest-occupancy listed species on every site; deterministic and default.
    /// Minority species are omitted with warnings. Partial occupancy does not
    /// reduce atom counts or create vacancies.
    #[default]
    Majority,
    /// Draw a species per atom proportional to the listed occupancies, seeded.
    /// Probabilities are normalized by the total listed occupancy: missing
    /// occupancy does not create vacancies. The absorber remains its majority
    /// species. This is one disorder realization, not an ensemble average.
    Random {
        /// Seed for repeatable atom-by-atom species choices on the same geometry.
        seed: u64,
    },
}

/// Spherical cluster settings; defaults are 8 Å, no hydrogen, and majority species.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ClusterOptions {
    /// Sphere radius in Å; default 8.0 and required to lie strictly between 0.5 and 50.
    pub radius: f64,
    /// Include non-absorber hydrogen atoms; false by default.
    pub include_hydrogen: bool,
    /// Resolve mixed sites into atoms; see [`OccupancyPolicy`] for vacancy limitations.
    pub occupancy: OccupancyPolicy,
}

impl Default for ClusterOptions {
    fn default() -> Self {
        Self {
            radius: 8.0,
            include_hydrogen: false,
            occupancy: OccupancyPolicy::Majority,
        }
    }
}

/// One atom of the cluster, absorber at the origin.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ClusterAtom {
    /// Cartesian position relative to the absorber (Å).
    pub cart: [f64; 3],
    /// Distance from the calculation absorber in Å.
    pub distance: f64,
    /// Resolved element symbol for this atom.
    pub symbol: String,
    /// Atomic number used to assign the scattering potential.
    pub z: u8,
    /// Index into `Structure::sites`.
    pub site_index: usize,
    /// Lattice translation of the periodic image.
    pub image: [i32; 3],
    /// FEFF potential index (0 = absorber).
    pub ipot: u16,
    /// `Ru_1`, `(Fe0.7Ni0.3)_3` — site species + site number, as Larch tags.
    pub label: String,
}

impl ClusterAtom {
    /// Borrow static element metadata; panics if a manually constructed atom has an invalid atomic number.
    pub fn element(&self) -> &'static Element {
        Element::from_z(self.z).expect("cluster atoms carry a valid Z")
    }
}

/// A FEFF potential.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Potential {
    /// FEFF potential index; zero is reserved for the absorber.
    pub ipot: u16,
    /// Element represented by this potential.
    pub symbol: String,
    /// Atomic number of the represented element.
    pub z: u8,
    /// Number of cluster atoms using it.
    pub count: usize,
}

/// A neighbour shell: atoms of one element at one distance.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Shell {
    /// Mean absorber–neighbor distance of this grouped shell in Å.
    pub distance: f64,
    /// Common element symbol of the grouped neighbors.
    pub symbol: String,
    /// Number of explicit cluster atoms in the shell, not an occupancy-weighted coordination number.
    pub count: usize,
    /// Indices into `Cluster::atoms`.
    pub atoms: Vec<usize>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
/// Owned atoms and scattering potentials centered on one calculation absorber.
/// Construct with build_cluster or Xyz::to_cluster to establish absorber-first
/// ordering and potential indices; direct field construction does not validate them.
pub struct Cluster {
    /// Index of the selected site in the source structure, or atom in an XYZ input.
    pub absorber_site: usize,
    /// Atoms sorted by distance; `atoms[0]` is the absorber.
    pub atoms: Vec<ClusterAtom>,
    /// Absorber potential followed by distinct scatterer-element potentials.
    pub potentials: Vec<Potential>,
    /// Requested sphere radius in Å, or the retained extent for an unbounded XYZ input.
    pub radius: f64,
    /// Messages about omitted, unresolved, or simplified source information.
    pub warnings: Vec<String>,
    /// Formula/title of the parent structure, for feff.inp titles.
    pub structure_title: String,
    /// Formula associated with the parent structure, retained for input-file provenance.
    pub formula: String,
    /// Parent space-group symbol when known; None for nonperiodic input.
    pub space_group: Option<String>,
}

impl Cluster {
    /// Borrow the first cluster atom, the calculation absorber; requires a nonempty cluster.
    pub fn absorber(&self) -> &ClusterAtom {
        &self.atoms[0]
    }

    /// Group neighbours (excluding the absorber) by element and distance
    /// within `tol` Å.
    pub fn shells(&self, tol: f64) -> Vec<Shell> {
        let mut shells: Vec<Shell> = Vec::new();
        for (i, atom) in self.atoms.iter().enumerate().skip(1) {
            if let Some(shell) = shells
                .iter_mut()
                .find(|s| s.symbol == atom.symbol && (s.distance - atom.distance).abs() <= tol)
            {
                // Running mean keeps the shell centred.
                shell.distance = (shell.distance * shell.count as f64 + atom.distance)
                    / (shell.count as f64 + 1.0);
                shell.count += 1;
                shell.atoms.push(i);
            } else {
                shells.push(Shell {
                    distance: atom.distance,
                    symbol: atom.symbol.clone(),
                    count: 1,
                    atoms: vec![i],
                });
            }
        }
        shells.sort_by(|a, b| a.distance.total_cmp(&b.distance));
        shells
    }

    /// Nearest cluster atom to a Cartesian point, with its distance.
    pub fn nearest(&self, cart: [f64; 3]) -> Option<(usize, f64)> {
        self.atoms
            .iter()
            .enumerate()
            .map(|(i, a)| {
                let d = ((a.cart[0] - cart[0]).powi(2)
                    + (a.cart[1] - cart[1]).powi(2)
                    + (a.cart[2] - cart[2]).powi(2))
                .sqrt();
                (i, d)
            })
            .min_by(|a, b| a.1.total_cmp(&b.1))
    }
}

/// Indices of every site of the structure that can host `symbol` as its
/// majority species, grouped by crystallographic equivalence (one
/// representative per asymmetric site, in order).
pub fn absorber_sites(structure: &Structure, symbol: &str) -> Vec<usize> {
    let mut seen_asym = Vec::new();
    let mut out = Vec::new();
    for (i, site) in structure.sites.iter().enumerate() {
        let is_host = site
            .majority()
            .is_some_and(|sp| sp.symbol.eq_ignore_ascii_case(symbol));
        if !is_host {
            continue;
        }
        match site.asym_index {
            Some(a) if seen_asym.contains(&a) => continue,
            Some(a) => seen_asym.push(a),
            None => {}
        }
        out.push(i);
    }
    out
}

/// Build an owned spherical cluster from periodic images of an expanded structure.
///
/// Positions are in Å relative to the selected absorber, which is placed first
/// with potential index zero. Other potentials are assigned by element. Input
/// structures are borrowed and unchanged. Radius violations, missing sites, and
/// an invalid absorber selection return [`StructureError`]; omitted minority or
/// unrecognized species are recorded in `Cluster::warnings` where applicable.
/// Converge cluster radius and scattering-path cutoffs for the analysis rather
/// than treating the default radius as a physical completeness guarantee.
pub fn build_cluster(
    structure: &Structure,
    absorber: &AbsorberSelection,
    opts: &ClusterOptions,
) -> Result<Cluster, StructureError> {
    if !(opts.radius > 0.5 && opts.radius < 50.0) {
        return Err(StructureError::InvalidCluster {
            reason: format!("radius {} Å out of range", opts.radius),
        });
    }
    if structure.sites.is_empty() {
        return Err(StructureError::InvalidCluster {
            reason: "structure has no sites".into(),
        });
    }
    let absorber_site = match absorber {
        AbsorberSelection::SiteIndex(i) => {
            if *i >= structure.sites.len() {
                return Err(StructureError::AbsorberNotFound {
                    reason: format!("site index {i} ≥ {}", structure.sites.len()),
                });
            }
            *i
        }
        AbsorberSelection::Element(symbol) => *absorber_sites(structure, symbol)
            .first()
            .ok_or_else(|| StructureError::AbsorberNotFound {
                reason: format!("no site with majority species {symbol}"),
            })?,
        AbsorberSelection::ElementSite { symbol, nth } => {
            let sites = absorber_sites(structure, symbol);
            *sites
                .get(*nth)
                .ok_or_else(|| StructureError::AbsorberNotFound {
                    reason: format!(
                        "{symbol} has {} distinct sites, asked for #{nth}",
                        sites.len()
                    ),
                })?
        }
    };
    let mut warnings = Vec::new();
    let absorber_element = structure.sites[absorber_site].element().ok_or_else(|| {
        StructureError::AbsorberNotFound {
            reason: "absorber site has no species".into(),
        }
    })?;

    // Species per site under the occupancy policy.
    let mut rng_state = match opts.occupancy {
        OccupancyPolicy::Random { seed } => seed.wrapping_mul(6364136223846793005).wrapping_add(1),
        OccupancyPolicy::Majority => 0,
    };
    let mut next_random = || {
        rng_state ^= rng_state << 13;
        rng_state ^= rng_state >> 7;
        rng_state ^= rng_state << 17;
        (rng_state >> 11) as f64 / (1u64 << 53) as f64
    };
    for site in &structure.sites {
        if site.species.len() > 1 && matches!(opts.occupancy, OccupancyPolicy::Majority) {
            let maj = site
                .majority()
                .map(|s| s.symbol.clone())
                .unwrap_or_default();
            let dropped: Vec<String> = site
                .species
                .iter()
                .filter(|s| s.symbol != maj)
                .map(|s| format!("{}({:.2})", s.symbol, s.occupancy))
                .collect();
            let msg = format!(
                "site {} uses majority species {maj}; dropped {}",
                site.label,
                dropped.join(", ")
            );
            if !warnings.contains(&msg) {
                warnings.push(msg);
            }
        }
    }

    let lattice = &structure.lattice;
    let center = structure.cart(absorber_site);
    let r2 = opts.radius * opts.radius;
    let ranges: Vec<i32> = (0..3)
        .map(|i| (opts.radius / lattice.interplanar_spacing(i)).ceil() as i32 + 1)
        .collect();

    let mut atoms: Vec<ClusterAtom> = Vec::new();
    for (si, site) in structure.sites.iter().enumerate() {
        let species = match opts.occupancy {
            OccupancyPolicy::Majority => site.majority().cloned(),
            OccupancyPolicy::Random { .. } => None,
        };
        let base = lattice.to_cart(site.frac);
        for na in -ranges[0]..=ranges[0] {
            for nb in -ranges[1]..=ranges[1] {
                for nc in -ranges[2]..=ranges[2] {
                    let shift = lattice.to_cart([na as f64, nb as f64, nc as f64]);
                    let cart = [
                        base[0] + shift[0] - center[0],
                        base[1] + shift[1] - center[1],
                        base[2] + shift[2] - center[2],
                    ];
                    let d2 = cart[0] * cart[0] + cart[1] * cart[1] + cart[2] * cart[2];
                    if d2 > r2 {
                        continue;
                    }
                    let is_absorber = si == absorber_site && na == 0 && nb == 0 && nc == 0;
                    let sp = match (&species, opts.occupancy) {
                        (Some(sp), _) => sp.clone(),
                        (None, OccupancyPolicy::Random { .. }) => {
                            let u = next_random() * site.total_occupancy().max(1e-9);
                            let mut acc = 0.0;
                            let mut chosen = None;
                            for s in &site.species {
                                acc += s.occupancy;
                                if u <= acc {
                                    chosen = Some(s.clone());
                                    break;
                                }
                            }
                            match chosen.or_else(|| site.species.last().cloned()) {
                                Some(s) => s,
                                None => continue,
                            }
                        }
                        (None, OccupancyPolicy::Majority) => continue,
                    };
                    let element = if is_absorber {
                        absorber_element
                    } else {
                        match sp.element() {
                            Some(e) => e,
                            None => {
                                let msg = format!(
                                    "site {} has unknown species symbol {:?}; skipped",
                                    site.label, sp.symbol
                                );
                                if !warnings.contains(&msg) {
                                    warnings.push(msg);
                                }
                                continue;
                            }
                        }
                    };
                    if !opts.include_hydrogen && element.z == 1 && !is_absorber {
                        continue;
                    }
                    atoms.push(ClusterAtom {
                        cart,
                        distance: d2.sqrt(),
                        symbol: element.symbol.to_string(),
                        z: element.z,
                        site_index: si,
                        image: [na, nb, nc],
                        ipot: u16::MAX,
                        label: format!("{}_{}", site.species_string(), si + 1),
                    });
                }
            }
        }
    }
    atoms.sort_by(|a, b| {
        a.distance
            .total_cmp(&b.distance)
            .then_with(|| a.site_index.cmp(&b.site_index))
            .then_with(|| a.image.cmp(&b.image))
    });
    // The absorber (distance 0) must be first.
    if let Some(pos) = atoms
        .iter()
        .position(|a| a.site_index == absorber_site && a.image == [0, 0, 0])
    {
        let abs = atoms.remove(pos);
        atoms.insert(0, abs);
    } else {
        return Err(StructureError::AbsorberNotFound {
            reason: "absorber not inside its own cluster".into(),
        });
    }
    // Potentials: 0 = absorber, then one per species in order of first
    // appearance by distance (Larch convention: every listed ipot is used).
    let mut potentials: Vec<Potential> = vec![Potential {
        ipot: 0,
        symbol: absorber_element.symbol.to_string(),
        z: absorber_element.z,
        count: 1,
    }];
    atoms[0].ipot = 0;
    for atom in atoms.iter_mut().skip(1) {
        let ipot = match potentials.iter_mut().skip(1).find(|p| p.z == atom.z) {
            Some(p) => {
                p.count += 1;
                p.ipot
            }
            None => {
                let ipot = potentials.len() as u16;
                potentials.push(Potential {
                    ipot,
                    symbol: atom.symbol.clone(),
                    z: atom.z,
                    count: 1,
                });
                ipot
            }
        };
        atom.ipot = ipot;
    }
    Ok(Cluster {
        absorber_site,
        atoms,
        potentials,
        radius: opts.radius,
        warnings,
        structure_title: structure.title.clone(),
        formula: structure.formula(),
        space_group: structure
            .space_group
            .hm_symbol
            .clone()
            .or_else(|| structure.space_group.number.map(|n| format!("#{n}"))),
    })
}