beamdpr 1.4.0

Combine and transform egsphsp (EGS phase space) files for use with BEAMnrc
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
use std::f32;
use std::fs::File;
use std::path::Path;
use std::process::exit;

use clap::{value_parser, Arg, Command};

use egsphsp::PHSPReader;
use egsphsp::{
    combine, compare, randomize, reweight, sample_combine, transform, translate, Transform,
};

fn main() {
    let matches = Command::new("beamdpr")
        .version(env!("CARGO_PKG_VERSION"))
        .author("Henry B. <henry.baxter@gmail.com>")
        .about("Combine and transform egsphsp (EGS phase space) \
                files")
        .subcommand_required(true)
        .arg_required_else_help(true)
        .subcommand(Command::new("print")
            .about("Print the specified fields in the specified order for n (or all) records")
            .arg(Arg::new("fields")
                .long("field")
                .short('f')
                .value_name("FIELDS")
                .value_parser(value_parser!(String))
                .required(true)
                .num_args(1..))
            .arg(Arg::new("number")
                .long("number")
                .short('n')
                .value_name("RECORDS")
                .value_parser(value_parser!(String))
                .default_value("10"))
            .arg(Arg::new("input")
                .value_name("FILE")
                .value_parser(value_parser!(String))
                .required(true)))
        .subcommand(Command::new("reweight")
            .about("Reweight a phase space file as a function of distance from z")
            .arg(Arg::new("input")
                .required(true)
                .value_name("INPUT")
                .value_parser(value_parser!(String)))
            .arg(Arg::new("output")
                .long("output")
                .required(false)
                .short('o')
                .value_name("OUTPUT")
                .value_parser(value_parser!(String)))
            .arg(Arg::new("r")
                .required(true)
                .short('r')
                .value_name("RADIUS")
                .value_parser(value_parser!(f32))
                .allow_hyphen_values(true))
            .arg(Arg::new("c")
                .short('c')
                .value_name("CONSTANT")
                .value_parser(value_parser!(f32))
                .allow_hyphen_values(true)
                .required(true))
            .arg(Arg::new("bins")
                .long("bins")
                .value_name("BINS")
                .value_parser(value_parser!(String))
                .default_value("100")
                .required(false)))
        .subcommand(Command::new("randomize")
            .about("Randomize the order of the particles")
            .arg(Arg::new("input").required(true))
            .arg(Arg::new("seed")
                .long("seed")
                .help("Seed as an unsigned integer")
                .default_value("0")
                .required(false)))
        .subcommand(Command::new("compare")
            .about("Compare two phase space files")
            .arg(Arg::new("first").required(true))
            .arg(Arg::new("second").required(true)))
        .subcommand(Command::new("stats")
            .about("Stats on phase space file")
            .arg(Arg::new("input").required(true))
            .arg(Arg::new("format")
                .default_value("human")
                .value_parser(["human", "json"])
                .long("format")
                .help("Output stats in json or human format")))
        .subcommand(Command::new("combine")
            .about("Combine phase space from one or more input files into outputfile - does not \
                    adjust weights")
            .arg(Arg::new("input")
                .required(true)
                .num_args(1..))
            .arg(Arg::new("output")
                .short('o')
                .long("output")
                .value_name("OUTPUT")
                .value_parser(value_parser!(String))
                .required(true))
            .arg(Arg::new("delete")
                .short('d')
                .long("delete")
                .help("Delete input files as they are used (no going back!)")
                .action(clap::ArgAction::SetTrue)))
        .subcommand(Command::new("sample-combine")
            .about("Combine samples of phase space inputs files into outputfile - does not \
                    adjust weights")
            .arg(Arg::new("input")
                .required(true)
                .num_args(1..))
            .arg(Arg::new("output")
                .short('o')
                .long("output")
                .value_parser(value_parser!(String))
                .required(true))
            .arg(Arg::new("seed")
                .long("seed")
                .help("Seed as an unsigned integer")
                .default_value("0")
                .required(false))
            .arg(Arg::new("rate")
                .default_value("10")
                .required(false)
                .long("rate")
                .value_name("RATE")
                .value_parser(value_parser!(String))
                .help("Inverse sample rate - 10 means take roughly 1 out of every 10 particles")))
        .subcommand(Command::new("translate")
            .about("Translate using X and Y in centimeters. Use parantheses around negatives.")
            .arg(Arg::new("in-place")
                .short('i')
                .long("in-place")
                .help("Transform input file in-place")
                .action(clap::ArgAction::SetTrue))
            .arg(Arg::new("x")
                .short('x')
                .value_name("X")
                .value_parser(clap::value_parser!(f32))
                .allow_hyphen_values(true)
                .required_unless_present("y")
                .default_value("0"))
            .arg(Arg::new("y")
                .short('y')
                .value_name("Y")
                .value_parser(clap::value_parser!(f32))
                .allow_hyphen_values(true)
                .required_unless_present("x")
                .default_value("0"))
            .arg(Arg::new("input")
                .help("Phase space file")
                .required(true))
            .arg(Arg::new("output")
                .help("Output file")
                .required_unless_present("in-place")))
        .subcommand(Command::new("rotate")
            .about("Rotate by --angle radians counter clockwise around z axis. Use parantheses \
                    around negatives.")
            .arg(Arg::new("in-place")
                .short('i')
                .long("in-place")
                .help("Transform input file in-place")
                .action(clap::ArgAction::SetTrue))
            .arg(Arg::new("angle")
                .short('a')
                .long("angle")
                .value_name("ANGLE")
                .value_parser(value_parser!(f32))
                .allow_hyphen_values(true)
                .required(true)
                .help("Counter clockwise angle in radians to rotate around Z axis"))
            .arg(Arg::new("input")
                .help("Phase space file")
                .required(true))
            .arg(Arg::new("output")
                .help("Output file")
                .required_unless_present("in-place")))
        .subcommand(Command::new("reflect")
            .about("Reflect in vector specified with -x and -y. Use parantheses around \
                    negatives.")
            .arg(Arg::new("in-place")
                .short('i')
                .long("in-place")
                .help("Transform input file in-place")
                .action(clap::ArgAction::SetTrue))
            .arg(Arg::new("x")
                .short('x')
                .value_name("X")
                .value_parser(clap::value_parser!(f32))
                .allow_hyphen_values(true)
                .required_unless_present("y")
                .default_value("0"))
            .arg(Arg::new("y")
                .short('y')
                .value_name("Y")
                .value_parser(clap::value_parser!(f32))
                .allow_hyphen_values(true)
                .required_unless_present("x")
                .default_value("0"))
            .arg(Arg::new("input")
                .help("Phase space file")
                .required(true))
            .arg(Arg::new("output")
                .help("Output file")
                .required_unless_present("in-place")))
        .get_matches();
    let subcommand = matches.subcommand_name().unwrap();
    let result = if subcommand == "combine" {
        // println!("combine");
        let sub_matches = matches.subcommand_matches("combine").unwrap();
        let input_paths: Vec<&Path> = sub_matches
            .get_many::<String>("input")
            .unwrap()
            .map(|s: &_| Path::new(s))
            .collect();
        let output_path = Path::new(sub_matches.get_one::<String>("output").unwrap());
        println!(
            "combine {} files into {}",
            input_paths.len(),
            output_path.display()
        );
        combine(
            &input_paths,
            output_path,
            *sub_matches.get_one::<bool>("delete").unwrap(),
        )
    } else if subcommand == "print" {
        // prints the fields specified?
        let sub_matches = matches.subcommand_matches("print").unwrap();
        let input_path = Path::new(sub_matches.get_one::<String>("input").unwrap());
        let number = sub_matches
            .get_one::<String>("number")
            .unwrap()
            .parse::<usize>()
            .unwrap();
        let fields: Vec<&str> = sub_matches
            .get_many::<String>("fields")
            .unwrap()
            .map(|s| s.as_str())
            .collect();
        let file = File::open(input_path).unwrap();
        let reader = PHSPReader::from(file).unwrap();
        for field in fields.iter() {
            print!("{:<16}", field);
        }
        println!();
        for record in reader.take(number).map(|r| r.unwrap()) {
            for field in fields.iter() {
                match *field {
                    "weight" => print!("{:<16}", record.get_weight()),
                    "energy" => print!("{:<16}", record.total_energy()),
                    "x" => print!("{:<16}", record.x_cm),
                    "y" => print!("{:<16}", record.y_cm),
                    "x_cos" => print!("{:<16}", record.x_cos),
                    "y_cos" => print!("{:<16}", record.y_cos),
                    "produced" => print!("{:<16}", record.bremsstrahlung_or_annihilation()),
                    "charged" => print!("{:<16}", record.charged()),
                    "r" => print!(
                        "{:<16}",
                        (record.x_cm * record.x_cm + record.y_cm * record.y_cm).sqrt()
                    ),
                    _ => panic!("Unknown field {}", field),
                };
            }
            println!();
        }
        Ok(())
    } else if subcommand == "reweight" {
        println!("unwrapping subcommand");
        let sub_matches = matches.subcommand_matches("reweight").unwrap();
        println!("unwrapping input_path");
        let input_path = Path::new(sub_matches.get_one::<String>("input").unwrap());
        println!("unwrapping output_path");
        let output_path = if sub_matches.contains_id("output") {
            Path::new(sub_matches.get_one::<String>("output").unwrap())
        } else {
            input_path
        };
        println!("unwrapping c");
        let c = *sub_matches.get_one::<f32>("c").unwrap();
        println!("unwrapping r");
        let r = *sub_matches.get_one::<f32>("r").unwrap();
        let bins = sub_matches
            .get_one::<String>("bins")
            .unwrap()
            .parse::<usize>()
            .unwrap();
        reweight(input_path, output_path, &|x| c * x, bins, r)
    } else if subcommand == "sample-combine" {
        let sub_matches = matches.subcommand_matches("sample-combine").unwrap();
        let input_paths: Vec<&Path> = sub_matches
            .get_many::<String>("input")
            .unwrap()
            .map(Path::new)
            .collect();
        let output_path = Path::new(sub_matches.get_one::<String>("output").unwrap());
        let rate = 1.0
            / sub_matches
                .get_one::<String>("rate")
                .unwrap()
                .parse::<f64>()
                .unwrap();
        let seed = sub_matches
            .get_one::<String>("seed")
            .unwrap()
            .parse::<u64>()
            .unwrap();
        println!(
            "sample combine {} files into {} at 1 in {}",
            input_paths.len(),
            output_path.display(),
            rate
        );
        sample_combine(&input_paths, output_path, rate, seed)
    } else if subcommand == "randomize" {
        let sub_matches = matches.subcommand_matches("randomize").unwrap();
        let path = Path::new(sub_matches.get_one::<String>("input").unwrap());
        let seed = sub_matches
            .get_one::<String>("seed")
            .unwrap()
            .parse::<u64>()
            .unwrap();
        randomize(path, seed)
    } else if subcommand == "compare" {
        // now we're going to print the header information of each
        // and then we're going to return a return code
        let sub_matches = matches.subcommand_matches("compare").unwrap();
        let path1 = Path::new(sub_matches.get_one::<String>("first").unwrap());
        let path2 = Path::new(sub_matches.get_one::<String>("second").unwrap());
        compare(path1, path2)
    } else if subcommand == "stats" {
        let sub_matches = matches.subcommand_matches("stats").unwrap();
        let path = Path::new(sub_matches.get_one::<String>("input").unwrap());
        let reader = PHSPReader::from(File::open(path).unwrap()).unwrap();
        let header = reader.header;
        // let mut max_x = f32::MIN;
        // let mut min_x = f32::MAX;
        // let mut max_y = f32::MIN;
        // let mut min_y = f32::MAX;
        // for record in reader.map(|r| r.unwrap()) {
        // max_x = max_x.max(record.x_cm);
        // min_x = min_x.min(record.x_cm);
        // max_y = max_y.max(record.y_cm);
        // min_y = min_y.min(record.y_cm);
        // }

        if sub_matches.get_one::<String>("format").unwrap() == "json" {
            // TODO use a proper serializer!
            println!("{{");
            println!("\t\"total_particles\": {},", header.total_particles);
            println!("\t\"total_photons\": {},", header.total_photons);
            println!("\t\"maximum_energy\": {},", header.max_energy);
            println!("\t\"minimum_energy\": {},", header.min_energy);
            println!(
                "\t\"total_particles_in_source\": {}",
                header.total_particles_in_source
            );
            println!("}}");
        } else {
            println!("Total particles: {}", header.total_particles);
            println!("Total photons: {}", header.total_photons);
            println!(
                "Total electrons/positrons: {}",
                header.total_particles - header.total_photons
            );
            println!("Maximum energy: {:.*} MeV", 4, header.max_energy);
            println!("Minimum energy: {:.*} MeV", 4, header.min_energy);
            println!(
                "Incident particles from source: {:.*}",
                1, header.total_particles_in_source
            );
            // println!("X position in [{}, {}], Y position in [{}, {}]",
            // min_x,
            // max_x,
            // min_y,
            // max_y);
        }
        Ok(())
    } else {
        let mut matrix = [[0.0; 3]; 3];
        match subcommand {
            "translate" => {
                // println!("translate");
                let sub_matches = matches.subcommand_matches("translate").unwrap();
                let x = *sub_matches.get_one::<f32>("x").unwrap();
                let y = *sub_matches.get_one::<f32>("y").unwrap();
                let input_path = Path::new(sub_matches.get_one::<String>("input").unwrap());
                if sub_matches.get_flag("in-place") {
                    println!("translate {} by ({}, {})", input_path.display(), x, y);
                    translate(input_path, input_path, x, y)
                } else {
                    let output_path = Path::new(sub_matches.get_one::<String>("output").unwrap());
                    println!(
                        "translate {} by ({}, {}) and write to {}",
                        input_path.display(),
                        x,
                        y,
                        output_path.display()
                    );
                    translate(input_path, output_path, x, y)
                }
            }
            "reflect" => {
                // println!("reflect");
                let sub_matches = matches.subcommand_matches("reflect").unwrap();
                let x = *sub_matches.get_one::<f32>("x").unwrap();
                let y = *sub_matches.get_one::<f32>("y").unwrap();
                Transform::reflection(&mut matrix, x, y);
                let input_path = Path::new(sub_matches.get_one::<String>("input").unwrap());
                if sub_matches.get_flag("in-place") {
                    println!("reflect {} around ({}, {})", input_path.display(), x, y);
                    transform(input_path, input_path, &matrix)
                } else {
                    let output_path = Path::new(sub_matches.get_one::<String>("output").unwrap());
                    println!(
                        "reflect {} around ({}, {}) and write to {}",
                        input_path.display(),
                        x,
                        y,
                        output_path.display()
                    );
                    transform(input_path, output_path, &matrix)
                }
            }
            "rotate" => {
                // println!("rotate");
                let sub_matches = matches.subcommand_matches("rotate").unwrap();
                let angle = *sub_matches.get_one::<f32>("angle").unwrap();
                Transform::rotation(&mut matrix, angle);
                let input_path = Path::new(sub_matches.get_one::<String>("input").unwrap());
                if *sub_matches.get_one::<bool>("in-place").unwrap() {
                    println!("rotate {} by {} radians", input_path.display(), angle);
                    transform(input_path, input_path, &matrix)
                } else {
                    let output_path = Path::new(sub_matches.get_one::<String>("output").unwrap());
                    println!(
                        "rotate {} by {} radians and write to {}",
                        input_path.display(),
                        angle,
                        output_path.display()
                    );
                    transform(input_path, output_path, &matrix)
                }
            }
            _ => panic!("Programmer error, trying to match invalid command"),
        }
    };

    match result {
        Ok(()) => exit(0),
        Err(err) => {
            println!("Error: {}", err);
            exit(1);
        }
    };
}