Skip to main content

section_properties/io/
csv.rs

1//! CSV export for section properties and geometry.
2//!
3//! Exports section properties in tabular format for spreadsheets
4//! and engineering reports.
5
6use crate::geometry::{Point, Polygon};
7use crate::section::Section;
8use crate::section_properties::SectionProperties;
9
10/// CSV export options.
11#[derive(Debug, Clone)]
12pub struct CsvExportOptions {
13    /// Include header row
14    pub include_header: bool,
15    /// Decimal separator
16    pub decimal_separator: char,
17    /// Field delimiter
18    pub delimiter: char,
19    /// Include geometry vertices
20    pub include_vertices: bool,
21    /// Include principal properties
22    pub include_principal: bool,
23    /// Include gyration properties
24    pub include_gyration: bool,
25    /// Units for output (m, mm, cm, in)
26    pub units: String,
27    /// Precision for numeric values
28    pub precision: usize,
29}
30
31impl Default for CsvExportOptions {
32    fn default() -> Self {
33        Self {
34            include_header: true,
35            decimal_separator: '.',
36            delimiter: ',',
37            include_vertices: true,
38            include_principal: true,
39            include_gyration: true,
40            units: "m".to_string(),
41            precision: 6,
42        }
43    }
44}
45
46/// Export section properties to CSV.
47pub fn to_csv(section: &Section, options: CsvExportOptions) -> String {
48    let props = SectionProperties::from_section(section);
49    let mut csv = String::new();
50    let fmt_val = |v: f64| format!("{:.p$e}", v, p = options.precision);
51
52    // Unit conversion factor
53    let unit_factor: f64 = match options.units.as_str() {
54        "mm" => 1000.0,
55        "cm" => 100.0,
56        "in" => 39.3701,
57        _ => 1.0,
58    };
59    let area_factor = unit_factor * unit_factor;
60    let inertia_factor = unit_factor.powi(4);
61
62    // Header
63    if options.include_header {
64        csv.push_str("Property,Value,Unit\n");
65    }
66
67    // Basic properties
68    csv.push_str(&format!(
69        "Area,{},{}^2\n",
70        fmt_val(props.area * area_factor),
71        options.units
72    ));
73    csv.push_str(&format!(
74        "CentroidX,{},{}\n",
75        fmt_val(props.centroid.x * unit_factor),
76        options.units
77    ));
78    csv.push_str(&format!(
79        "CentroidY,{},{}\n",
80        fmt_val(props.centroid.y * unit_factor),
81        options.units
82    ));
83    csv.push_str(&format!(
84        "Ix,{},{}^4\n",
85        fmt_val(props.ix * inertia_factor),
86        options.units
87    ));
88    csv.push_str(&format!(
89        "Iy,{},{}^4\n",
90        fmt_val(props.iy * inertia_factor),
91        options.units
92    ));
93    csv.push_str(&format!(
94        "Ixy,{},{}^4\n",
95        fmt_val(props.ixy * inertia_factor),
96        options.units
97    ));
98
99    // Principal properties
100    if options.include_principal {
101        let (i1, i2, angle) = props.principal_moments();
102        csv.push_str(&format!(
103            "I1 (Major),,{},{}^4\n",
104            fmt_val(i1 * inertia_factor),
105            options.units
106        ));
107        csv.push_str(&format!(
108            "I2 (Minor),,{},{}^4\n",
109            fmt_val(i2 * inertia_factor),
110            options.units
111        ));
112        csv.push_str(&format!("PrincipalAngle,{},rad\n", fmt_val(angle)));
113        csv.push_str(&format!(
114            "PrincipalAngleDeg,{},deg\n",
115            fmt_val(angle.to_degrees())
116        ));
117    }
118
119    // Gyration properties
120    if options.include_gyration {
121        let (rx, ry, rp) = props.radius_of_gyration();
122        csv.push_str(&format!(
123            "rx,{},{}\n",
124            fmt_val(rx * unit_factor),
125            options.units
126        ));
127        csv.push_str(&format!(
128            "ry,{},{}\n",
129            fmt_val(ry * unit_factor),
130            options.units
131        ));
132        csv.push_str(&format!(
133            "rp (polar),,{},{}\n",
134            fmt_val(rp * unit_factor),
135            options.units
136        ));
137    }
138
139    // Geometry vertices
140    if options.include_vertices {
141        csv.push_str("\n# Geometry Vertices\n");
142        if options.include_header {
143            csv.push_str("Type,Index,X,Y\n");
144        }
145
146        for (i, v) in section.outer.vertices.iter().enumerate() {
147            csv.push_str(&format!(
148                "Outer,{},{},{}\n",
149                i,
150                fmt_val(v.x * unit_factor),
151                fmt_val(v.y * unit_factor)
152            ));
153        }
154
155        for (h_idx, hole) in section.holes.iter().enumerate() {
156            for (_i, v) in hole.vertices.iter().enumerate() {
157                csv.push_str(&format!(
158                    "Hole{},,{},{}\n",
159                    h_idx,
160                    fmt_val(v.x * unit_factor),
161                    fmt_val(v.y * unit_factor)
162                ));
163            }
164        }
165    }
166
167    // Replace delimiter if not comma (must do before decimal separator
168    // to avoid replacing decimal commas with the delimiter)
169    if options.delimiter != ',' {
170        csv = csv.replace(',', &options.delimiter.to_string());
171    }
172
173    // Replace decimal separator if needed
174    if options.decimal_separator != '.' {
175        csv = csv.replace('.', &options.decimal_separator.to_string());
176    }
177
178    csv
179}
180
181/// Export multiple sections to CSV (one row per section).
182pub fn to_csv_catalog(sections: &[(String, Section)], options: CsvExportOptions) -> String {
183    let mut csv = String::new();
184    let fmt_val = |v: f64| format!("{:.p$e}", v, p = options.precision);
185    let unit_factor: f64 = match options.units.as_str() {
186        "mm" => 1000.0,
187        "cm" => 100.0,
188        "in" => 39.3701,
189        _ => 1.0,
190    };
191    let area_factor = unit_factor * unit_factor;
192    let inertia_factor = unit_factor.powi(4);
193
194    if options.include_header {
195        csv.push_str("Designation,Area,Ix,Iy,Ixy,rx,ry,Angle,AngleDeg\n");
196    }
197
198    for (name, section) in sections {
199        let props = SectionProperties::from_section(section);
200        let (_i1, _i2, angle) = props.principal_moments();
201        let (rx, ry, _) = props.radius_of_gyration();
202
203        csv.push_str(&format!(
204            "{},{},{},{},{},{},{},{},{}\n",
205            name,
206            fmt_val(props.area * area_factor),
207            fmt_val(props.ix * inertia_factor),
208            fmt_val(props.iy * inertia_factor),
209            fmt_val(props.ixy * inertia_factor),
210            fmt_val(rx * unit_factor),
211            fmt_val(ry * unit_factor),
212            fmt_val(angle),
213            fmt_val(angle.to_degrees()),
214        ));
215    }
216
217    if options.decimal_separator != '.' {
218        csv = csv.replace('.', &options.decimal_separator.to_string());
219    }
220    if options.delimiter != ',' {
221        csv = csv.replace(',', &options.delimiter.to_string());
222    }
223
224    csv
225}
226
227/// Import section from CSV (geometry only).
228pub fn from_csv(csv_str: &str) -> Result<Section, Box<dyn std::error::Error>> {
229    let mut rdr = csv::ReaderBuilder::new()
230        .has_headers(true)
231        .flexible(true)
232        .from_reader(csv_str.as_bytes());
233
234    let mut outer_vertices = Vec::new();
235    let mut holes: Vec<Vec<Point>> = Vec::new();
236
237    for result in rdr.records() {
238        let record = result?;
239
240        // Expected columns: Type,Index,X,Y
241        let type_ = record.get(0).unwrap_or("");
242        let _idx = record.get(1).unwrap_or("");
243        let x_str = record.get(2).unwrap_or("");
244        let y_str = record.get(3).unwrap_or("");
245
246        let x = x_str.parse::<f64>().unwrap_or(0.0);
247        let y = y_str.parse::<f64>().unwrap_or(0.0);
248
249        match type_ {
250            "Outer" => outer_vertices.push(Point::new(x, y)),
251            t if t.starts_with("Hole") => {
252                let hole_idx = t
253                    .strip_prefix("Hole")
254                    .unwrap_or("0")
255                    .parse::<usize>()
256                    .unwrap_or(0);
257                while holes.len() <= hole_idx {
258                    holes.push(Vec::new());
259                }
260                holes[hole_idx].push(Point::new(x, y));
261            }
262            _ => {}
263        }
264    }
265
266    let outer = Polygon::new(outer_vertices);
267    let hole_polys: Vec<Polygon> = holes.into_iter().map(Polygon::new).collect();
268
269    Ok(Section::new(outer, hole_polys))
270}
271
272#[cfg(test)]
273mod tests {
274    use super::*;
275    use crate::geometry::{Point, Polygon};
276    use crate::section::Section;
277    use crate::section_library::ParametricSection;
278    use crate::section_library::steel::ISection;
279
280    #[test]
281    fn csv_export_properties() {
282        let i = ISection::from_designation("IPE300").unwrap();
283        let section = i.build();
284
285        let csv = to_csv(&section, CsvExportOptions::default());
286
287        assert!(csv.contains("Area"));
288        assert!(csv.contains("Ix"));
289        assert!(csv.contains("Iy"));
290        assert!(csv.contains("PrincipalAngle"));
291        assert!(csv.contains("rx"));
292    }
293
294    #[test]
295    fn csv_catalog() {
296        let i1 = ISection::from_designation("IPE300").unwrap();
297        let i2 = ISection::from_designation("HEB200").unwrap();
298
299        let sections = vec![
300            ("IPE300".to_string(), i1.build()),
301            ("HEB200".to_string(), i2.build()),
302        ];
303
304        let csv = to_csv_catalog(&sections, CsvExportOptions::default());
305
306        assert!(csv.contains("IPE300"));
307        assert!(csv.contains("HEB200"));
308        assert!(csv.contains("Designation"));
309    }
310
311    #[test]
312    fn csv_custom_options() {
313        let i = ISection::from_designation("IPE300").unwrap();
314        let section = i.build();
315
316        let options = CsvExportOptions {
317            delimiter: ';',
318            decimal_separator: ',',
319            units: "mm".to_string(),
320            precision: 3,
321            ..Default::default()
322        };
323
324        let csv = to_csv(&section, options);
325
326        assert!(csv.contains(";"));
327        assert!(csv.contains(",")); // decimal comma
328        assert!(csv.contains("mm"));
329    }
330
331    #[test]
332    fn csv_import_geometry() {
333        let outer = Polygon::new(vec![
334            Point::new(0.0, 0.0),
335            Point::new(1.0, 0.0),
336            Point::new(1.0, 1.0),
337            Point::new(0.0, 1.0),
338        ]);
339        let hole = Polygon::new(vec![
340            Point::new(0.3, 0.3),
341            Point::new(0.3, 0.7),
342            Point::new(0.7, 0.7),
343            Point::new(0.7, 0.3),
344        ]);
345        let section = Section::new(outer, vec![hole]);
346
347        let csv = to_csv(&section, CsvExportOptions::default());
348        let imported = from_csv(&csv).unwrap();
349
350        assert_eq!(imported.outer.vertices.len(), 4);
351        assert_eq!(imported.holes.len(), 1);
352        assert_eq!(imported.holes[0].vertices.len(), 4);
353    }
354}