dirt_atom 0.1.4

Per-atom DEM data (radius, density) with pack/unpack and MaterialTable for DIRT
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
use super::*;

pub(super) fn read_csv_particles(
    insert: &InsertConfig,
    file_path: &str,
    atom: &mut Atom,
    registry: &AtomDataRegistry,
    material_table: &MaterialTable,
    domain: &Domain,
    max_tag: &mut u32,
) -> Result<(), InsertFileError> {
    let mat_name = insert
        .material
        .as_deref()
        .ok_or(InsertFileError::MissingField {
            source: "CSV",
            field: "material",
        })?;
    let mat_idx = resolve_file_material(material_table, mat_name)?;

    let type_index_map = insert
        .type_map
        .as_ref()
        .map(|tm| resolve_type_map(tm, material_table))
        .transpose()?;

    // Open before checking fields that are needed only to decode rows. This
    // reports a missing input file at the fallible boundary instead of hiding
    // it behind a later configuration omission.
    let file = File::open(file_path).map_err(|e| InsertFileError::FileOpen {
        path: file_path.to_string(),
        source: e.to_string(),
    })?;

    let density = insert.density.ok_or(InsertFileError::MissingField {
        source: "CSV",
        field: "density",
    })?;

    let cols = insert.columns.clone().unwrap_or_default();
    let col_x = cols.x.unwrap_or(0);
    let col_y = cols.y.unwrap_or(1);
    let col_z = cols.z.unwrap_or(2);
    let col_radius = cols.radius;
    let col_vx = cols.vx;
    let col_vy = cols.vy;
    let col_vz = cols.vz;
    let col_atom_type = cols.atom_type;

    let default_radius = match &insert.radius {
        Some(RadiusSpec::Fixed(r)) => Some(*r),
        _ => None,
    };

    let reader = BufReader::new(file);
    let mut count = 0u32;

    for (line_num, line) in reader.lines().enumerate() {
        let line = line.map_err(|e| InsertFileError::FileRead {
            path: file_path.to_string(),
            line: line_num + 1,
            source: e.to_string(),
        })?;
        let trimmed = line.trim();
        if trimmed.is_empty() || trimmed.starts_with('#') {
            continue;
        }
        // Skip header line if it starts with a letter
        if line_num == 0 && trimmed.chars().next().map_or(false, |c| c.is_alphabetic()) {
            continue;
        }

        let fields: Vec<&str> = trimmed.split(',').map(|s| s.trim()).collect();
        let parse = |idx: usize, name: &'static str| -> Result<f64, InsertFileError> {
            fields
                .get(idx)
                .ok_or_else(|| InsertFileError::MissingColumn {
                    path: file_path.to_string(),
                    line: line_num + 1,
                    field: name,
                })
                .and_then(|s| {
                    s.parse()
                        .map_err(|e: std::num::ParseFloatError| InsertFileError::ParseField {
                            path: file_path.to_string(),
                            line: line_num + 1,
                            field: format!("{} (column {})", name, idx),
                            value: (*s).to_string(),
                            source: e.to_string(),
                        })
                })
        };

        let x = parse(col_x, "x")?;
        let y = parse(col_y, "y")?;
        let z = parse(col_z, "z")?;
        let radius = col_radius
            .map(|c| parse(c, "radius"))
            .transpose()?
            .or(default_radius)
            .ok_or(InsertFileError::MissingDefault {
                path: file_path.to_string(),
                field: "radius",
                context: "CSV file insertion with no radius column",
            })?;
        let vx = col_vx.map(|c| parse(c, "vx")).transpose()?.unwrap_or(0.0);
        let vy = col_vy.map(|c| parse(c, "vy")).transpose()?.unwrap_or(0.0);
        let vz = col_vz.map(|c| parse(c, "vz")).transpose()?.unwrap_or(0.0);

        // Determine material: type_map lookup (if atom_type column present) → default material
        let row_mat_idx = match col_atom_type {
            Some(col) => {
                let file_type = parse(col, "atom_type")? as u32;
                lookup_material_for_type(file_type, type_index_map.as_ref(), mat_idx)
            }
            None => mat_idx,
        };
        let cutoff_padding = material_table.liquid_bridge_cutoff_padding(row_mat_idx);

        // Tag advances for every file particle (keeps tags globally consistent
        // across ranks); the atom is only stored if it lies in this subdomain.
        if owns_position(domain, &[x, y, z]) {
            insert_single_particle(
                atom,
                registry,
                DemParticle {
                    pos: [x, y, z],
                    vel: [vx, vy, vz],
                    radius,
                    cutoff_padding,
                    density,
                    mat_idx: row_mat_idx,
                    tag: *max_tag,
                },
            );
            count += 1;
        }
        *max_tag += 1;
    }

    println!(
        "DemAtomInsert: loaded {} local particles from CSV '{}'",
        count, file_path
    );
    Ok(())
}

pub(super) fn read_lammps_dump_particles(
    insert: &InsertConfig,
    file_path: &str,
    atom: &mut Atom,
    registry: &AtomDataRegistry,
    material_table: &MaterialTable,
    domain: &Domain,
    max_tag: &mut u32,
) -> Result<(), InsertFileError> {
    let mat_name = insert
        .material
        .as_deref()
        .ok_or(InsertFileError::MissingField {
            source: "lammps_dump",
            field: "material",
        })?;
    let mat_idx = resolve_file_material(material_table, mat_name)?;

    let type_index_map = insert
        .type_map
        .as_ref()
        .map(|tm| resolve_type_map(tm, material_table))
        .transpose()?;

    let density = insert.density.ok_or(InsertFileError::MissingField {
        source: "lammps_dump",
        field: "density",
    })?;

    let default_radius = match &insert.radius {
        Some(RadiusSpec::Fixed(r)) => Some(*r),
        _ => None,
    };

    let file = File::open(file_path).map_err(|e| InsertFileError::FileOpen {
        path: file_path.to_string(),
        source: e.to_string(),
    })?;
    let reader = BufReader::new(file);
    let mut lines = reader.lines();

    // Parse LAMMPS dump format
    let mut n_atoms: usize = 0;
    let mut column_names: Vec<String> = Vec::new();
    let mut reading_atoms = false;
    let mut count = 0u32;

    // Helper to find column index by name
    let find_col =
        |names: &[String], name: &str| -> Option<usize> { names.iter().position(|n| n == name) };

    let mut line_num = 0usize;
    while let Some(line) = lines.next() {
        line_num += 1;
        let line = line.map_err(|e| InsertFileError::FileRead {
            path: file_path.to_string(),
            line: line_num,
            source: e.to_string(),
        })?;
        let trimmed = line.trim();

        if trimmed == "ITEM: NUMBER OF ATOMS" {
            if let Some(next) = lines.next() {
                line_num += 1;
                let next = next.map_err(|e| InsertFileError::FileRead {
                    path: file_path.to_string(),
                    line: line_num,
                    source: e.to_string(),
                })?;
                n_atoms = next.trim().parse().map_err(|e: std::num::ParseIntError| {
                    InsertFileError::ParseField {
                        path: file_path.to_string(),
                        line: line_num,
                        field: "number of atoms".to_string(),
                        value: next.trim().to_string(),
                        source: e.to_string(),
                    }
                })?;
            }
            continue;
        }

        if trimmed.starts_with("ITEM: ATOMS") {
            // Parse column names from header: "ITEM: ATOMS id type x y z ..."
            column_names = trimmed
                .strip_prefix("ITEM: ATOMS")
                .unwrap_or("")
                .split_whitespace()
                .map(|s| s.to_string())
                .collect();
            reading_atoms = true;
            continue;
        }

        if trimmed.starts_with("ITEM:") {
            reading_atoms = false;
            continue;
        }

        if reading_atoms && !trimmed.is_empty() {
            let fields: Vec<&str> = trimmed.split_whitespace().collect();
            if fields.len() < column_names.len() {
                continue;
            }

            let parse_col = |name: &'static str| -> Result<Option<f64>, InsertFileError> {
                let Some(i) = find_col(&column_names, name) else {
                    return Ok(None);
                };
                let Some(value) = fields.get(i) else {
                    return Err(InsertFileError::MissingColumn {
                        path: file_path.to_string(),
                        line: line_num,
                        field: name,
                    });
                };
                value
                    .parse()
                    .map(Some)
                    .map_err(|e: std::num::ParseFloatError| InsertFileError::ParseField {
                        path: file_path.to_string(),
                        line: line_num,
                        field: name.to_string(),
                        value: (*value).to_string(),
                        source: e.to_string(),
                    })
            };

            let x = parse_col("x")?.ok_or(InsertFileError::MissingColumn {
                path: file_path.to_string(),
                line: line_num,
                field: "x",
            })?;
            let y = parse_col("y")?.ok_or(InsertFileError::MissingColumn {
                path: file_path.to_string(),
                line: line_num,
                field: "y",
            })?;
            let z = parse_col("z")?.ok_or(InsertFileError::MissingColumn {
                path: file_path.to_string(),
                line: line_num,
                field: "z",
            })?;
            let vx = parse_col("vx")?.unwrap_or(0.0);
            let vy = parse_col("vy")?.unwrap_or(0.0);
            let vz = parse_col("vz")?.unwrap_or(0.0);
            let radius =
                parse_col("radius")?
                    .or(default_radius)
                    .ok_or(InsertFileError::MissingDefault {
                        path: file_path.to_string(),
                        field: "radius",
                        context: "LAMMPS dump file insertion with no radius column",
                    })?;

            // Determine material: type_map override → default material
            let row_mat_idx = match parse_col("type")? {
                Some(t) => lookup_material_for_type(t as u32, type_index_map.as_ref(), mat_idx),
                None => mat_idx,
            };
            let cutoff_padding = material_table.liquid_bridge_cutoff_padding(row_mat_idx);

            if owns_position(domain, &[x, y, z]) {
                insert_single_particle(
                    atom,
                    registry,
                    DemParticle {
                        pos: [x, y, z],
                        vel: [vx, vy, vz],
                        radius,
                        cutoff_padding,
                        density,
                        mat_idx: row_mat_idx,
                        tag: *max_tag,
                    },
                );
                count += 1;
            }
            *max_tag += 1;
        }
    }

    let _ = n_atoms; // used for format validation if needed
    println!(
        "DemAtomInsert: loaded {} local particles from LAMMPS dump '{}'",
        count, file_path
    );
    Ok(())
}

/// Parse a field from a LAMMPS data file, with a user-friendly error on failure.
pub(super) fn parse_field<T: std::str::FromStr>(
    value: &str,
    field_name: &str,
    line_num: usize,
    file_path: &str,
) -> Result<T, InsertFileError>
where
    T::Err: std::fmt::Display,
{
    value.parse::<T>().map_err(|e| InsertFileError::ParseField {
        path: file_path.to_string(),
        line: line_num,
        field: field_name.to_string(),
        value: value.to_string(),
        source: e.to_string(),
    })
}

pub(super) fn read_lammps_data_particles(
    insert: &InsertConfig,
    file_path: &str,
    atom: &mut Atom,
    registry: &AtomDataRegistry,
    material_table: &MaterialTable,
    domain: &Domain,
    max_tag: &mut u32,
) -> Result<(), InsertFileError> {
    let mat_name = insert
        .material
        .as_deref()
        .ok_or(InsertFileError::MissingField {
            source: "lammps_data",
            field: "material",
        })?;
    let mat_idx = resolve_file_material(material_table, mat_name)?;

    let type_index_map = insert
        .type_map
        .as_ref()
        .map(|tm| resolve_type_map(tm, material_table))
        .transpose()?;

    let default_density = insert.density;
    let default_radius = match &insert.radius {
        Some(RadiusSpec::Fixed(r)) => Some(*r),
        _ => None,
    };

    let file = File::open(file_path).map_err(|e| InsertFileError::FileOpen {
        path: file_path.to_string(),
        source: e.to_string(),
    })?;
    let reader = BufReader::new(file);
    let lines: Vec<String> = reader
        .lines()
        .enumerate()
        .map(|(i, l)| {
            l.map_err(|e| InsertFileError::FileRead {
                path: file_path.to_string(),
                line: i + 1,
                source: e.to_string(),
            })
        })
        .collect::<Result<_, _>>()?;

    // Detect atom style from config or from "Atoms # style" header
    let config_style = insert.atom_style.as_deref();

    // Find section start indices
    let mut atoms_start = None;
    let mut atoms_style = None;
    let mut velocities_start = None;

    for (i, line) in lines.iter().enumerate() {
        let trimmed = line.trim();
        if trimmed.starts_with("Atoms") {
            atoms_start = Some(i + 1);
            // Try to detect style from "Atoms # style" comment
            if let Some(comment) = trimmed.strip_prefix("Atoms") {
                let comment = comment.trim();
                if let Some(style) = comment.strip_prefix('#') {
                    let style = style.trim();
                    if !style.is_empty() {
                        atoms_style = Some(style.to_string());
                    }
                }
            }
        } else if trimmed == "Velocities" {
            velocities_start = Some(i + 1);
        }
    }

    let atom_style = config_style
        .map(|s| s.to_string())
        .or(atoms_style)
        .unwrap_or_else(|| "atomic".to_string());

    let atoms_start = atoms_start.ok_or(InsertFileError::MissingSection {
        path: file_path.to_string(),
        section: "Atoms",
    })?;

    // Parse Atoms section
    struct ParsedAtom {
        id: u32,
        atom_type: u32,
        pos: [f64; 3],
        radius: f64,
        density: f64,
    }

    let section_headers = [
        "Atoms",
        "Velocities",
        "Bonds",
        "Angles",
        "Dihedrals",
        "Impropers",
        "Masses",
        "Pair Coeffs",
    ];
    let is_section_header = |line: &str| -> bool {
        let trimmed = line.trim();
        section_headers.iter().any(|h| trimmed.starts_with(h))
    };

    let mut parsed_atoms: Vec<ParsedAtom> = Vec::new();

    for i in atoms_start..lines.len() {
        let trimmed = lines[i].trim();
        if trimmed.is_empty() {
            continue;
        }
        if is_section_header(trimmed) {
            break;
        }
        // Skip comment lines
        if trimmed.starts_with('#') {
            continue;
        }

        let fields: Vec<&str> = trimmed.split_whitespace().collect();

        match atom_style.as_str() {
            "atomic" => {
                // id type x y z
                if fields.len() < 5 {
                    return Err(InsertFileError::RowTooShort {
                        path: file_path.to_string(),
                        line: i + 1,
                        style: "atomic".to_string(),
                        expected: 5,
                        found: fields.len(),
                    });
                }
                let id: u32 = parse_field(fields[0], "atom id", i + 1, file_path)?;
                let atype: u32 = parse_field(fields[1], "atom type", i + 1, file_path)?;
                let x: f64 = parse_field(fields[2], "x coordinate", i + 1, file_path)?;
                let y: f64 = parse_field(fields[3], "y coordinate", i + 1, file_path)?;
                let z: f64 = parse_field(fields[4], "z coordinate", i + 1, file_path)?;
                let radius = default_radius.ok_or(InsertFileError::MissingDefault {
                    path: file_path.to_string(),
                    field: "radius",
                    context: "atomic style LAMMPS data",
                })?;
                let density = default_density.ok_or(InsertFileError::MissingDefault {
                    path: file_path.to_string(),
                    field: "density",
                    context: "atomic style LAMMPS data",
                })?;
                parsed_atoms.push(ParsedAtom {
                    id,
                    atom_type: atype,
                    pos: [x, y, z],
                    radius,
                    density,
                });
            }
            "sphere" | "bpm/sphere" => {
                // id type diameter density x y z
                if fields.len() < 7 {
                    return Err(InsertFileError::RowTooShort {
                        path: file_path.to_string(),
                        line: i + 1,
                        style: atom_style.clone(),
                        expected: 7,
                        found: fields.len(),
                    });
                }
                let id: u32 = parse_field(fields[0], "atom id", i + 1, file_path)?;
                let atype: u32 = parse_field(fields[1], "atom type", i + 1, file_path)?;
                let diameter: f64 = parse_field(fields[2], "diameter", i + 1, file_path)?;
                let density: f64 = parse_field(fields[3], "density", i + 1, file_path)?;
                let x: f64 = parse_field(fields[4], "x coordinate", i + 1, file_path)?;
                let y: f64 = parse_field(fields[5], "y coordinate", i + 1, file_path)?;
                let z: f64 = parse_field(fields[6], "z coordinate", i + 1, file_path)?;
                parsed_atoms.push(ParsedAtom {
                    id,
                    atom_type: atype,
                    pos: [x, y, z],
                    radius: diameter / 2.0,
                    density,
                });
            }
            other => {
                return Err(InsertFileError::UnsupportedAtomStyle {
                    path: file_path.to_string(),
                    style: other.to_string(),
                });
            }
        }
    }

    // Parse Velocities section (optional) — build id → [vx, vy, vz] map
    let mut velocity_map: HashMap<u32, [f64; 3]> = HashMap::new();
    if let Some(vel_start) = velocities_start {
        for i in vel_start..lines.len() {
            let trimmed = lines[i].trim();
            if trimmed.is_empty() {
                continue;
            }
            if is_section_header(trimmed) {
                break;
            }
            if trimmed.starts_with('#') {
                continue;
            }
            let fields: Vec<&str> = trimmed.split_whitespace().collect();
            if fields.len() >= 4 {
                let id: u32 = parse_field(fields[0], "atom id (Velocities)", i + 1, file_path)?;
                let vx: f64 = parse_field(fields[1], "vx", i + 1, file_path)?;
                let vy: f64 = parse_field(fields[2], "vy", i + 1, file_path)?;
                let vz: f64 = parse_field(fields[3], "vz", i + 1, file_path)?;
                velocity_map.insert(id, [vx, vy, vz]);
            }
        }
    }

    // Insert all parsed atoms (only those owned by this subdomain).
    let mut count = 0usize;
    for pa in parsed_atoms {
        let vel = velocity_map.get(&pa.id).copied().unwrap_or([0.0; 3]);
        let row_mat_idx = lookup_material_for_type(pa.atom_type, type_index_map.as_ref(), mat_idx);
        let cutoff_padding = material_table.liquid_bridge_cutoff_padding(row_mat_idx);
        if owns_position(domain, &pa.pos) {
            insert_single_particle(
                atom,
                registry,
                DemParticle {
                    pos: pa.pos,
                    vel,
                    radius: pa.radius,
                    cutoff_padding,
                    density: pa.density,
                    mat_idx: row_mat_idx,
                    tag: *max_tag,
                },
            );
            count += 1;
        }
        *max_tag += 1;
    }

    println!(
        "DemAtomInsert: loaded {} local particles from LAMMPS data file '{}' (style: {})",
        count, file_path, atom_style
    );
    Ok(())
}