1use crate::material::Material;
7use crate::section::Section;
8use crate::section_library::ParametricSection;
9use crate::section_properties::SectionProperties;
10use std::rc::Rc;
11
12#[derive(Debug, Clone)]
14pub struct SectionEntry {
15 pub name: String,
16 pub designation: String,
17 pub section: Section,
18 pub parametric: Option<Rc<dyn ParametricSection>>,
19 pub material: Option<Material>,
20 pub properties: Option<SectionProperties>,
21 pub tags: Vec<String>,
22 pub source: String,
23 pub metadata: std::collections::HashMap<String, String>,
24}
25
26impl SectionEntry {
27 pub fn new<S: ParametricSection + 'static>(parametric: S, material: Option<Material>) -> Self {
28 let designation = parametric.designation();
29 let section = parametric.build();
30 let properties = SectionProperties::from_section(§ion);
31
32 Self {
33 name: designation.clone(),
34 designation,
35 section,
36 parametric: Some(Rc::new(parametric)),
37 material,
38 properties: Some(properties),
39 tags: Vec::new(),
40 source: "parametric".to_string(),
41 metadata: std::collections::HashMap::new(),
42 }
43 }
44
45 pub fn from_section(section: Section, name: String, source: String) -> Self {
46 let properties = SectionProperties::from_section(§ion);
47 Self {
48 name: name.clone(),
49 designation: name,
50 section,
51 parametric: None,
52 material: None,
53 properties: Some(properties),
54 tags: Vec::new(),
55 source,
56 metadata: std::collections::HashMap::new(),
57 }
58 }
59
60 pub fn with_tags(mut self, tags: Vec<String>) -> Self {
61 self.tags = tags;
62 self
63 }
64
65 pub fn with_metadata(mut self, key: String, value: String) -> Self {
66 self.metadata.insert(key, value);
67 self
68 }
69
70 pub fn area(&self) -> f64 {
71 self.properties.as_ref().map(|p| p.area).unwrap_or(0.0)
72 }
73
74 pub fn ix(&self) -> f64 {
75 self.properties.as_ref().map(|p| p.ix).unwrap_or(0.0)
76 }
77
78 pub fn iy(&self) -> f64 {
79 self.properties.as_ref().map(|p| p.iy).unwrap_or(0.0)
80 }
81
82 pub fn weight_per_meter(&self, density: f64) -> f64 {
83 self.area() * density
84 }
85}
86
87#[derive(Debug, Clone, Default)]
89pub struct SearchFilter {
90 pub name_contains: Option<String>,
91 pub designation_contains: Option<String>,
92 pub min_area: Option<f64>,
93 pub max_area: Option<f64>,
94 pub min_ix: Option<f64>,
95 pub max_ix: Option<f64>,
96 pub min_iy: Option<f64>,
97 pub max_iy: Option<f64>,
98 pub min_depth: Option<f64>,
99 pub max_depth: Option<f64>,
100 pub min_width: Option<f64>,
101 pub max_width: Option<f64>,
102 pub section_type: Option<String>,
103 pub material: Option<String>,
104 pub tags: Vec<String>,
105 pub shape_factor_min: Option<f64>,
107 pub shape_factor_max: Option<f64>,
108}
109
110#[derive(Debug, Clone)]
112pub struct SearchResult {
113 pub entry: SectionEntry,
114 pub score: f64,
115 pub matched_fields: Vec<String>,
116}
117
118#[derive(Debug, Default)]
120pub struct SectionDatabase {
121 entries: Vec<SectionEntry>,
122 name_index: std::collections::HashMap<String, usize>,
123 designation_index: std::collections::HashMap<String, usize>,
124 tag_index: std::collections::HashMap<String, Vec<usize>>,
125}
126
127impl SectionDatabase {
128 pub fn new() -> Self {
129 Self::default()
130 }
131
132 pub fn add(&mut self, entry: SectionEntry) {
134 let idx = self.entries.len();
135 let name = entry.name.clone();
136 let designation = entry.designation.clone();
137 let tags = entry.tags.clone();
138
139 self.name_index.insert(name, idx);
140 self.designation_index.insert(designation, idx);
141
142 for tag in tags {
143 self.tag_index.entry(tag).or_default().push(idx);
144 }
145
146 self.entries.push(entry);
147 }
148
149 pub fn add_many(&mut self, entries: Vec<SectionEntry>) {
151 for entry in entries {
152 self.add(entry);
153 }
154 }
155
156 pub fn get_by_name(&self, name: &str) -> Option<&SectionEntry> {
158 self.name_index.get(name).map(|&i| &self.entries[i])
159 }
160
161 pub fn get_by_designation(&self, designation: &str) -> Option<&SectionEntry> {
163 self.designation_index
164 .get(designation)
165 .map(|&i| &self.entries[i])
166 }
167
168 pub fn get_by_tag(&self, tag: &str) -> Vec<&SectionEntry> {
170 self.tag_index
171 .get(tag)
172 .map(|indices| indices.iter().map(|&i| &self.entries[i]).collect())
173 .unwrap_or_default()
174 }
175
176 pub fn search(&self, filter: &SearchFilter) -> Vec<SearchResult> {
178 let mut results = Vec::new();
179
180 for entry in &self.entries {
181 let mut score = 0.0;
182 let mut matched = Vec::new();
183 let mut ok = true;
184
185 if let Some(ref pattern) = filter.name_contains {
187 if entry.name.to_lowercase().contains(&pattern.to_lowercase()) {
188 score += 10.0;
189 matched.push("name".to_string());
190 } else {
191 ok = false;
192 }
193 }
194 if let Some(ref pattern) = filter.designation_contains {
195 if entry
196 .designation
197 .to_lowercase()
198 .contains(&pattern.to_lowercase())
199 {
200 score += 10.0;
201 matched.push("designation".to_string());
202 } else {
203 ok = false;
204 }
205 }
206
207 if let Some(props) = &entry.properties {
209 if let Some(min) = filter.min_area {
210 if props.area >= min {
211 score += 1.0;
212 matched.push("area_min".to_string());
213 } else {
214 ok = false;
215 }
216 }
217 if let Some(max) = filter.max_area {
218 if props.area <= max {
219 score += 1.0;
220 matched.push("area_max".to_string());
221 } else {
222 ok = false;
223 }
224 }
225 if let Some(min) = filter.min_ix {
226 if props.ix >= min {
227 score += 1.0;
228 matched.push("ix_min".to_string());
229 } else {
230 ok = false;
231 }
232 }
233 if let Some(max) = filter.max_ix {
234 if props.ix <= max {
235 score += 1.0;
236 matched.push("ix_max".to_string());
237 } else {
238 ok = false;
239 }
240 }
241 if let Some(min) = filter.min_iy {
242 if props.iy >= min {
243 score += 1.0;
244 matched.push("iy_min".to_string());
245 } else {
246 ok = false;
247 }
248 }
249 if let Some(max) = filter.max_iy {
250 if props.iy <= max {
251 score += 1.0;
252 matched.push("iy_max".to_string());
253 } else {
254 ok = false;
255 }
256 }
257 }
258
259 if let Some(ref typ) = filter.section_type {
261 if entry.tags.iter().any(|t| t.contains(typ)) {
262 score += 5.0;
263 matched.push("type".to_string());
264 } else {
265 ok = false;
266 }
267 }
268
269 if let Some(ref mat) = filter.material {
271 if entry
272 .material
273 .as_ref()
274 .map(|m| m.name.contains(mat))
275 .unwrap_or(false)
276 {
277 score += 5.0;
278 matched.push("material".to_string());
279 } else {
280 ok = false;
281 }
282 }
283
284 for tag in &filter.tags {
286 if entry.tags.contains(tag) {
287 score += 2.0;
288 matched.push(format!("tag:{}", tag));
289 } else {
290 ok = false;
291 }
292 }
293
294 let bounds = entry.section.bounds();
296 let depth = bounds.3 - bounds.2;
297 let width = bounds.1 - bounds.0;
298
299 if let Some(min) = filter.min_depth {
300 if depth >= min {
301 score += 1.0;
302 } else {
303 ok = false;
304 }
305 }
306 if let Some(max) = filter.max_depth {
307 if depth <= max {
308 score += 1.0;
309 } else {
310 ok = false;
311 }
312 }
313 if let Some(min) = filter.min_width {
314 if width >= min {
315 score += 1.0;
316 } else {
317 ok = false;
318 }
319 }
320 if let Some(max) = filter.max_width {
321 if width <= max {
322 score += 1.0;
323 } else {
324 ok = false;
325 }
326 }
327
328 if ok && score > 0.0 {
329 results.push(SearchResult {
330 entry: entry.clone(),
331 score,
332 matched_fields: matched,
333 });
334 }
335 }
336
337 results.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap());
339 results
340 }
341
342 pub fn find_similar(&self, reference: &Section, tolerance: f64) -> Vec<SearchResult> {
344 let ref_props = crate::section_properties::SectionProperties::from_section(reference);
345 let ref_area = ref_props.area;
346 let ref_ix = ref_props.ix;
347 let ref_iy = ref_props.iy;
348
349 let mut filter = SearchFilter::default();
350 filter.min_area = Some(ref_area * (1.0 - tolerance));
351 filter.max_area = Some(ref_area * (1.0 + tolerance));
352 filter.min_ix = Some(ref_ix * (1.0 - tolerance));
353 filter.max_ix = Some(ref_ix * (1.0 + tolerance));
354 filter.min_iy = Some(ref_iy * (1.0 - tolerance));
355 filter.max_iy = Some(ref_iy * (1.0 + tolerance));
356
357 self.search(&filter)
358 }
359
360 pub fn all(&self) -> &[SectionEntry] {
362 &self.entries
363 }
364
365 pub fn len(&self) -> usize {
367 self.entries.len()
368 }
369
370 pub fn is_empty(&self) -> bool {
372 self.entries.is_empty()
373 }
374
375 pub fn clear(&mut self) {
377 self.entries.clear();
378 self.name_index.clear();
379 self.designation_index.clear();
380 self.tag_index.clear();
381 }
382
383 pub fn to_json(&self, pretty: bool) -> String {
385 #[derive(serde::Serialize)]
386 struct DbExport {
387 version: String,
388 count: usize,
389 entries: Vec<DbEntry>,
390 }
391
392 #[derive(serde::Serialize)]
393 struct DbEntry {
394 name: String,
395 designation: String,
396 area: f64,
397 ix: f64,
398 iy: f64,
399 tags: Vec<String>,
400 source: String,
401 }
402
403 let export = DbExport {
404 version: "1.0".to_string(),
405 count: self.entries.len(),
406 entries: self
407 .entries
408 .iter()
409 .map(|e| DbEntry {
410 name: e.name.clone(),
411 designation: e.designation.clone(),
412 area: e.area(),
413 ix: e.ix(),
414 iy: e.iy(),
415 tags: e.tags.clone(),
416 source: e.source.clone(),
417 })
418 .collect(),
419 };
420
421 if pretty {
422 serde_json::to_string_pretty(&export).unwrap()
423 } else {
424 serde_json::to_string(&export).unwrap()
425 }
426 }
427}
428
429pub fn build_standard_database() -> SectionDatabase {
431 let mut db = SectionDatabase::new();
432
433 use crate::material::presets::STEEL_S355;
435 use crate::section_library::steel::*;
436
437 for des in [
439 "IPE160", "IPE200", "IPE240", "IPE300", "IPE360", "IPE400", "IPE450", "IPE500", "IPE600",
440 ] {
441 if let Some(i) = ISection::from_designation(des) {
442 let entry = SectionEntry::new(i, Some(STEEL_S355)).with_tags(vec![
443 "steel".to_string(),
444 "i-section".to_string(),
445 "hot-rolled".to_string(),
446 ]);
447 db.add(entry);
448 }
449 }
450
451 for des in ["HEA200", "HEA300", "HEB200", "HEB300", "HEB400"] {
453 if let Some(i) = ISection::from_designation(des) {
454 let entry = SectionEntry::new(i, Some(STEEL_S355)).with_tags(vec![
455 "steel".to_string(),
456 "h-section".to_string(),
457 "hot-rolled".to_string(),
458 ]);
459 db.add(entry);
460 }
461 }
462
463 for des in ["UPN100", "UPN160", "UPN200", "UPN240", "UPN300"] {
465 if let Some(c) = crate::section_library::steel::ChannelSection::from_designation(des) {
466 let entry = SectionEntry::new(c, Some(STEEL_S355)).with_tags(vec![
467 "steel".to_string(),
468 "channel".to_string(),
469 "hot-rolled".to_string(),
470 ]);
471 db.add(entry);
472 }
473 }
474
475 for des in ["L50X50X5", "L75X75X8", "L100X100X10", "L150X150X12"] {
477 if let Some(a) = crate::section_library::steel::AngleSection::from_designation(des) {
478 let entry = SectionEntry::new(a, Some(STEEL_S355)).with_tags(vec![
479 "steel".to_string(),
480 "angle".to_string(),
481 "hot-rolled".to_string(),
482 ]);
483 db.add(entry);
484 }
485 }
486
487 for des in [
489 "SHS100X5",
490 "SHS150X8",
491 "SHS200X8",
492 "SHS250X10",
493 "RHS200X100X8",
494 "RHS300X200X10",
495 ] {
496 if let Some(h) =
497 crate::section_library::steel::RectangularHollowSection::from_designation(des)
498 {
499 let entry = SectionEntry::new(h, Some(STEEL_S355)).with_tags(vec![
500 "steel".to_string(),
501 "hollow".to_string(),
502 "cold-formed".to_string(),
503 ]);
504 db.add(entry);
505 }
506 }
507
508 for des in ["CHS60X3", "CHS89X4", "CHS114X5", "CHS168X6", "CHS219X8"] {
509 if let Some(h) =
510 crate::section_library::steel::CircularHollowSectionLib::from_designation(des)
511 {
512 let entry = SectionEntry::new(h, Some(STEEL_S355)).with_tags(vec![
513 "steel".to_string(),
514 "chs".to_string(),
515 "cold-formed".to_string(),
516 ]);
517 db.add(entry);
518 }
519 }
520
521 db
522}
523
524#[cfg(test)]
525mod tests {
526 use super::*;
527
528 use crate::material::presets::STEEL_S355;
529
530 use crate::section_library::ParametricSection;
531 use crate::section_library::steel::ISection;
532
533 #[test]
534 fn database_basic() {
535 let mut db = SectionDatabase::new();
536
537 let i = ISection::from_designation("IPE300").unwrap();
538 let entry = SectionEntry::new(i, Some(STEEL_S355))
539 .with_tags(vec!["steel".to_string(), "i-section".to_string()]);
540
541 db.add(entry);
542
543 assert_eq!(db.len(), 1);
544 assert!(db.get_by_name("IPE300").is_some());
545 assert!(db.get_by_designation("IPE300").is_some());
546 }
547
548 #[test]
549 fn database_search() {
550 let mut db = SectionDatabase::new();
551
552 let i1 = ISection::from_designation("IPE300").unwrap();
553 let i2 = ISection::from_designation("HEB200").unwrap();
554
555 db.add(SectionEntry::new(i1, Some(STEEL_S355)).with_tags(vec!["steel".to_string()]));
556 db.add(SectionEntry::new(i2, Some(STEEL_S355)).with_tags(vec!["steel".to_string()]));
557
558 let mut filter = SearchFilter::default();
559 filter.name_contains = Some("IPE".to_string());
560
561 let results = db.search(&filter);
562 assert_eq!(results.len(), 1);
563 assert!(results[0].entry.name.contains("IPE"));
564 }
565
566 #[test]
567 fn database_property_filter() {
568 let db = build_standard_database();
569
570 let mut filter = SearchFilter::default();
571 filter.min_area = Some(5e-3); filter.max_area = Some(15e-3); let results = db.search(&filter);
575 assert!(!results.is_empty());
576
577 for r in &results {
578 assert!(r.entry.area() >= 5e-3);
579 assert!(r.entry.area() <= 15e-3);
580 }
581 }
582
583 #[test]
584 fn database_find_similar() {
585 let db = build_standard_database();
586
587 let i = ISection::from_designation("IPE300").unwrap();
588 let section = i.build();
589
590 let similar = db.find_similar(§ion, 0.2); assert!(!similar.is_empty());
593 }
595
596 #[test]
597 fn standard_database() {
598 let db = build_standard_database();
599 assert!(db.len() > 20);
600
601 let tags: std::collections::HashSet<_> = db
603 .all()
604 .into_iter()
605 .flat_map(|e| e.tags.iter().cloned())
606 .collect();
607
608 assert!(tags.contains("i-section"));
609 assert!(tags.contains("channel"));
610 assert!(tags.contains("angle"));
611 assert!(tags.contains("hollow"));
612 }
613}