-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathareas.rs
1952 lines (1775 loc) · 69.8 KB
/
areas.rs
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
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2021 Miklos Vajna
*
* SPDX-License-Identifier: MIT
*/
#![deny(warnings)]
#![warn(clippy::all)]
#![warn(missing_docs)]
//! The areas module contains the Relations class and associated functionality.
use crate::area_files;
use crate::cache;
use crate::context;
use crate::i18n::translate as tr;
use crate::ranges;
use crate::stats;
use crate::util;
use crate::yattag;
use anyhow::Context;
use std::collections::HashMap;
use std::fmt::Write as _;
use std::ops::DerefMut;
/// The filters -> <street> -> ranges key from data/relation-<name>.yaml.
#[derive(Clone, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RelationRangesDict {
pub end: String,
refsettlement: Option<String>,
pub start: String,
}
/// The filters key from data/relation-<name>.yaml.
#[derive(Clone, serde::Deserialize)]
#[serde(rename_all = "kebab-case")]
#[serde(deny_unknown_fields)]
pub struct RelationFiltersDict {
pub interpolation: Option<String>,
pub invalid: Option<Vec<String>>,
pub ranges: Option<Vec<RelationRangesDict>>,
pub valid: Option<Vec<String>>,
refsettlement: Option<String>,
show_refstreet: Option<bool>,
}
impl RelationFiltersDict {
/// Determines if at least one Option is Some.
pub fn is_some(&self) -> bool {
self.interpolation.is_some()
|| self.invalid.is_some()
|| self.ranges.is_some()
|| self.valid.is_some()
|| self.refsettlement.is_some()
|| self.show_refstreet.is_some()
}
}
/// A relation from data/relation-<name>.yaml.
#[derive(Clone, serde::Deserialize)]
#[serde(rename_all = "kebab-case")]
#[serde(deny_unknown_fields)]
pub struct RelationDict {
additional_housenumbers: Option<bool>,
pub alias: Option<Vec<String>>,
pub filters: Option<HashMap<String, RelationFiltersDict>>,
housenumber_letters: Option<bool>,
inactive: Option<bool>,
missing_streets: Option<String>,
osm_street_filters: Option<Vec<String>>,
pub osmrelation: Option<u64>,
pub refcounty: Option<String>,
pub refsettlement: Option<String>,
pub refstreets: Option<HashMap<String, String>>,
pub street_filters: Option<Vec<String>>,
pub source: Option<String>,
}
impl Default for RelationDict {
fn default() -> Self {
let additional_housenumbers = None;
let alias = None;
let filters = None;
let housenumber_letters = None;
let inactive = None;
let missing_streets = None;
let osm_street_filters = None;
let osmrelation = None;
let refcounty = None;
let refsettlement = None;
let refstreets = None;
let street_filters = None;
let source = None;
RelationDict {
additional_housenumbers,
alias,
filters,
housenumber_letters,
inactive,
missing_streets,
osm_street_filters,
osmrelation,
refcounty,
refsettlement,
refstreets,
street_filters,
source,
}
}
}
/// A relation configuration comes directly from static data, not a result of some external query.
#[derive(Clone)]
pub struct RelationConfig {
parent: RelationDict,
dict: RelationDict,
}
impl RelationConfig {
pub fn new(parent_config: &RelationDict, my_config: &RelationDict) -> Self {
RelationConfig {
parent: parent_config.clone(),
dict: my_config.clone(),
}
}
/// Gets the typed value of a property transparently.
fn get_property<T: Clone>(parent_value: &Option<T>, my_value: &Option<T>) -> Option<T> {
if let Some(value) = my_value {
return Some(value.clone());
}
if let Some(value) = parent_value {
return Some(value.clone());
}
None
}
/// Sets if the relation is active.
pub fn set_active(&mut self, active: bool) {
self.dict.inactive = Some(!active);
}
/// Gets if the relation is active.
pub fn is_active(&self) -> bool {
match RelationConfig::get_property(&self.parent.inactive, &self.dict.inactive) {
Some(value) => !value,
None => true,
}
}
/// Gets the OSM relation object's ID.
pub fn get_osmrelation(&self) -> u64 {
self.parent.osmrelation.unwrap()
}
/// Gets the relation's refcounty identifier from reference.
pub fn get_refcounty(&self) -> String {
match RelationConfig::get_property(&self.parent.refcounty, &self.dict.refcounty) {
Some(value) => value,
None => "".into(),
}
}
/// Gets the relation's refsettlement identifier from reference.
pub fn get_refsettlement(&self) -> String {
RelationConfig::get_property(&self.parent.refsettlement, &self.dict.refsettlement).unwrap()
}
/// Gets the alias(es) of the relation: alternative names which are also accepted.
fn get_alias(&self) -> Vec<String> {
RelationConfig::get_property(&self.parent.alias, &self.dict.alias).unwrap_or_default()
}
/// Return value can be 'yes', 'no' and 'only'.
pub fn should_check_missing_streets(&self) -> String {
match RelationConfig::get_property(&self.parent.missing_streets, &self.dict.missing_streets)
{
Some(value) => value,
None => "yes".into(),
}
}
/// Do we care if 42/B is missing when 42/A is provided?
fn should_check_housenumber_letters(&self) -> bool {
RelationConfig::get_property(
&self.parent.housenumber_letters,
&self.dict.housenumber_letters,
)
.unwrap_or(false)
}
/// Do we care if 42 is in OSM when it's not in the ref?
pub fn should_check_additional_housenumbers(&self) -> bool {
RelationConfig::get_property(
&self.parent.additional_housenumbers,
&self.dict.additional_housenumbers,
)
.unwrap_or(false)
}
/// Returns an OSM name -> ref name map.
pub fn get_refstreets(&self) -> HashMap<String, String> {
match self.dict.refstreets {
Some(ref value) => value.clone(),
None => HashMap::new(),
}
}
/// Returns a street name -> properties map.
fn get_filters(&self) -> &Option<HashMap<String, RelationFiltersDict>> {
// The schema doesn't allow this key in parent config, no need to go via the slow
// get_property().
&self.dict.filters
}
/// Returns a street from relation filters.
fn get_filter_street(&self, street: &str) -> Option<&RelationFiltersDict> {
let filters = match self.get_filters() {
Some(value) => value,
None => {
return None;
}
};
filters.get(street)
}
/// Determines in a relation's street is interpolation=all or not.
pub fn get_street_is_even_odd(&self, street: &str) -> bool {
let mut interpolation_all = false;
if let Some(filter_for_street) = self.get_filter_street(street) {
if let Some(ref interpolation) = filter_for_street.interpolation {
if interpolation == "all" {
interpolation_all = true;
}
}
}
!interpolation_all
}
/// Decides is a ref street should be shown for an OSM street.
pub fn should_show_ref_street(&self, osm_street_name: &str) -> bool {
let mut show_ref_street = true;
if let Some(filter_for_street) = self.get_filter_street(osm_street_name) {
if let Some(value) = filter_for_street.show_refstreet {
show_ref_street = value;
}
}
show_ref_street
}
/// Returns a list of refsettlement values specific to a street.
pub fn get_street_refsettlement(&self, street: &str) -> Vec<String> {
let mut ret: Vec<String> = vec![self.get_refsettlement()];
let filters = match self.get_filters() {
Some(value) => value,
None => {
return ret;
}
};
for (filter_street, value) in filters {
if filter_street != street {
continue;
}
if let Some(ref refsettlement) = value.refsettlement {
ret = vec![refsettlement.to_string()];
}
if let Some(ref ranges) = value.ranges {
for street_range in ranges {
if let Some(ref refsettlement) = street_range.refsettlement {
ret.push(refsettlement.to_string());
}
}
}
}
ret.sort();
ret.dedup();
ret
}
/// Gets list of streets which are only in reference, but have to be filtered out.
fn get_street_filters(&self) -> Vec<String> {
RelationConfig::get_property(&self.parent.street_filters, &self.dict.street_filters)
.unwrap_or_default()
}
/// Gets list of streets which are only in OSM, but have to be filtered out.
fn get_osm_street_filters(&self) -> Vec<String> {
RelationConfig::get_property(
&self.parent.osm_street_filters,
&self.dict.osm_street_filters,
)
.unwrap_or_default()
}
/// Maps an OSM street name to a ref street name.
pub fn get_ref_street_from_osm_street(&self, osm_street_name: &str) -> String {
let refstreets = self.get_refstreets();
match refstreets.get(osm_street_name) {
Some(value) => value.into(),
None => osm_street_name.into(),
}
}
/// Maps a reference street name to an OSM street name.
fn get_osm_street_from_ref_street(&self, ref_street_name: &str) -> String {
let refstreets = self.get_refstreets();
let reverse: HashMap<String, String> = refstreets
.iter()
.map(|(key, value)| (value.clone(), key.clone()))
.collect();
match reverse.get(ref_street_name) {
Some(value) => value.into(),
None => ref_street_name.into(),
}
}
}
/// Return type of Relation::get_missing_housenumbers().
#[derive(serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct MissingHousenumbers {
pub ongoing_streets: util::NumberedStreets,
pub done_streets: util::NumberedStreets,
}
#[derive(Clone, Debug, Ord, PartialOrd, derivative::Derivative)]
#[derivative(Eq, PartialEq)]
pub struct RelationLint {
pub relation_name: String,
pub street_name: String,
/// Type, e.g. invalid or range.
pub source: RelationLintSource,
pub housenumber: String,
/// E.g. missing from reference or present in OSM
pub reason: RelationLintReason,
#[derivative(PartialEq = "ignore")]
pub id: u64,
#[derivative(PartialEq = "ignore")]
pub object_type: String,
}
#[derive(Clone, Debug, Eq, Ord, PartialOrd, PartialEq)]
pub enum RelationLintSource {
Range,
Invalid,
}
impl TryFrom<&str> for RelationLintSource {
type Error = anyhow::Error;
fn try_from(value: &str) -> Result<Self, Self::Error> {
match value {
"range" => Ok(RelationLintSource::Range),
"invalid" => Ok(RelationLintSource::Invalid),
_ => Err(anyhow::anyhow!("invalid value: {value}")),
}
}
}
impl std::fmt::Display for RelationLintSource {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
RelationLintSource::Range => write!(f, "range"),
RelationLintSource::Invalid => write!(f, "invalid"),
}
}
}
#[derive(Clone, Debug, Eq, Ord, PartialOrd, PartialEq)]
pub enum RelationLintReason {
CreatedInOsm,
DeletedFromRef,
OutOfRange,
}
impl TryFrom<&str> for RelationLintReason {
type Error = anyhow::Error;
fn try_from(value: &str) -> Result<Self, Self::Error> {
match value {
"created-in-osm" => Ok(RelationLintReason::CreatedInOsm),
"deleted-from-ref" => Ok(RelationLintReason::DeletedFromRef),
"out-of-range" => Ok(RelationLintReason::OutOfRange),
_ => Err(anyhow::anyhow!("invalid value: {value}")),
}
}
}
impl std::fmt::Display for RelationLintReason {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
RelationLintReason::CreatedInOsm => write!(f, "created-in-osm"),
RelationLintReason::DeletedFromRef => write!(f, "deleted-from-ref"),
RelationLintReason::OutOfRange => write!(f, "out-of-range"),
}
}
}
/// A relation is a closed polygon on the map.
#[derive(Clone)]
pub struct Relation<'a> {
ctx: &'a context::Context,
name: String,
file: area_files::RelationFiles,
config: RelationConfig,
osm_housenumbers: HashMap<String, Vec<util::HouseNumber>>,
lints: Vec<RelationLint>,
}
impl<'a> Relation<'a> {
fn new(
ctx: &'a context::Context,
name: &str,
parent_config: &RelationDict,
yaml_cache: &HashMap<String, serde_json::Value>,
) -> anyhow::Result<Relation<'a>> {
let mut my_config = RelationDict::default();
let file = area_files::RelationFiles::new(name);
let relation_path = format!("relation-{name}.yaml");
// Intentionally don't require this cache to be present, it's fine to omit it for simple
// relations.
if let Some(value) = yaml_cache.get(&relation_path) {
my_config = serde_json::from_value(value.clone())
.context(format!("failed to parse '{relation_path}'"))?;
}
let config = RelationConfig::new(parent_config, &my_config);
// osm street name -> house number list map, so we don't have to read the on-disk list of the
// relation again and again for each street.
let osm_housenumbers: HashMap<String, Vec<util::HouseNumber>> = HashMap::new();
let lints: Vec<RelationLint> = Vec::new();
Ok(Relation {
ctx,
name: name.into(),
file,
config,
osm_housenumbers,
lints,
})
}
pub fn get_lints(&self) -> &Vec<RelationLint> {
&self.lints
}
/// Gets the name of the relation.
pub fn get_name(&self) -> String {
self.name.clone()
}
/// Gets access to the file interface.
pub fn get_files(&self) -> &area_files::RelationFiles {
&self.file
}
/// Gets access to the config interface.
pub fn get_config(&self) -> &RelationConfig {
&self.config
}
/// Sets the config interface.
pub fn set_config(&mut self, config: &RelationConfig) {
self.config = config.clone();
}
/// Gets a street name -> ranges map, which allows silencing false positives.
fn get_street_ranges(&self) -> anyhow::Result<HashMap<String, ranges::Ranges>> {
let mut filter_dict: HashMap<String, ranges::Ranges> = HashMap::new();
let filters = match self.config.get_filters() {
Some(value) => value,
None => {
return Ok(filter_dict);
}
};
for (street, filter) in filters {
let mut interpolation = "";
if let Some(ref value) = filter.interpolation {
interpolation = value;
}
let mut i: Vec<ranges::Range> = Vec::new();
if let Some(ref value) = filter.ranges {
for range in value {
let start = range
.start
.trim()
.parse::<i64>()
.context("failed to parse() 'start'")?;
let end = range
.end
.trim()
.parse::<i64>()
.context("failed to parse() 'end'")?;
i.push(ranges::Range::new(start, end, interpolation));
}
filter_dict.insert(street.into(), ranges::Ranges::new(i));
}
}
Ok(filter_dict)
}
/// Gets a street name -> invalid map, which allows silencing individual false positives.
fn get_street_invalid(&self) -> HashMap<String, Vec<String>> {
let mut invalid_dict: HashMap<String, Vec<String>> = HashMap::new();
if let Some(filters) = self.config.get_filters() {
for (street, filter) in filters {
if let Some(ref value) = filter.invalid {
invalid_dict.insert(street.into(), value.to_vec());
}
}
}
invalid_dict
}
/// Reads list of streets for an area from OSM.
pub fn get_osm_streets(&self, sorted_result: bool) -> anyhow::Result<Vec<util::Street>> {
let mut ret: Vec<util::Street> = Vec::new();
for row in self.file.get_osm_json_streets(self.ctx)? {
let mut street = util::Street::new(
&row.name, /*ref_name=*/ "", /*show_ref_street=*/ true,
/*osm_id=*/ row.id,
);
if let Some(value) = row.object_type {
street.set_osm_type(&value);
}
street.set_source(&tr("street"));
ret.push(street)
}
if stats::has_sql_mtime(self.ctx, &format!("housenumbers/{}", self.name))? {
ret.append(
&mut util::get_street_from_housenumber(
&self.file.get_osm_json_housenumbers(self.ctx)?,
)
.context("get_street_from_housenumber() failed")?,
);
}
if sorted_result {
ret.sort();
ret.dedup();
}
Ok(ret)
}
/// Produces a query which lists streets in relation.
pub fn get_osm_streets_query(&self) -> anyhow::Result<String> {
let contents = self.ctx.get_file_system().read_to_string(&format!(
"{}/{}",
self.ctx.get_abspath("data"),
"streets-template.overpassql"
))?;
Ok(util::process_template(
&contents,
self.config.get_osmrelation(),
))
}
/// Produces a query which lists streets in relation, in JSON format.
pub fn get_osm_streets_json_query(&self) -> anyhow::Result<String> {
let query = self.get_osm_streets_query()?;
let mut i = 0;
let mut lines = Vec::new();
for line in query.lines() {
i += 1;
if i == 1 {
lines.push("[out:json];".to_string());
continue;
}
lines.push(line.to_string());
}
Ok(lines.join("\n"))
}
/// Gets streets from reference.
fn get_ref_streets(&self) -> anyhow::Result<Vec<String>> {
let conn = self.ctx.get_database_connection()?;
let mut streets: Vec<String> = Vec::new();
let mut stmt = conn.prepare(
"select street from ref_streets where county_code = ?1 and settlement_code = ?2",
)?;
let mut rows = stmt.query([
&self.config.get_refcounty(),
&self.config.get_refsettlement(),
])?;
while let Some(row) = rows.next()? {
let street: String = row.get(0).unwrap();
streets.push(street);
}
streets.sort();
streets.dedup();
Ok(streets)
}
/// Gets the OSM house number list of a street.
fn get_osm_housenumbers(
&mut self,
street_name: &str,
) -> anyhow::Result<Vec<util::HouseNumber>> {
if self.osm_housenumbers.is_empty() {
// This function gets called for each & every street, make sure we read the file only
// once.
let street_ranges = self.get_street_ranges()?;
let mut house_numbers: HashMap<String, Vec<util::HouseNumber>> = HashMap::new();
let osm_housenumbers = self.file.get_osm_json_housenumbers(self.ctx)?;
let mut lints: Vec<RelationLint> = Vec::new();
for row in osm_housenumbers {
let mut street = &row.street;
if street.is_empty() {
if let Some(ref value) = row.place {
street = value;
}
}
for house_number in row.housenumber.split(&[';', ',']) {
house_numbers
.entry(street.to_string())
.or_default()
.append(&mut normalize(
self,
house_number,
street,
&street_ranges,
&mut Some(&mut lints),
Some(&row),
)?)
}
}
self.lints.append(&mut lints);
for (key, mut value) in house_numbers {
value.sort_unstable();
value.dedup();
self.osm_housenumbers
.insert(key, util::sort_numerically(&value));
}
let streets_invalids = self.get_street_invalid();
for (street_name, housenumbers) in &self.osm_housenumbers {
let mut invalids: Vec<String> = Vec::new();
if let Some(value) = streets_invalids.get(street_name) {
invalids.clone_from(value);
invalids = self.normalize_invalids(street_name, &invalids)?;
// housenumber letters: OSM data is already in the 42/A, do the same for the
// invalid items as well, so contains() makes sense:
invalids = invalids
.iter()
.map(
|i| match util::HouseNumber::normalize_letter_suffix(i, "") {
Ok(value) => value,
Err(_) => i.to_string(),
},
)
.collect();
}
for housenumber in housenumbers {
if invalids.contains(&housenumber.get_number().to_string()) {
let relation_name = self.get_name();
let street_name = street_name.to_string();
let source = RelationLintSource::Invalid;
let reason = RelationLintReason::CreatedInOsm;
let id: u64 = housenumber.get_id().context("no osm id")?;
let object_type = housenumber.get_object_type().context("no osm type")?;
let housenumber = housenumber.get_number().to_string();
let lint = RelationLint {
relation_name,
street_name,
source,
housenumber,
reason,
id,
object_type,
};
self.lints.push(lint);
}
}
}
}
Ok(match self.osm_housenumbers.get(street_name) {
Some(value) => value.clone(),
None => {
self.osm_housenumbers.insert(street_name.into(), vec![]);
vec![]
}
})
}
/// Determines what suffix should the Nth reference use for hours numbers.
pub fn get_ref_suffix(index: usize) -> &'static str {
match index {
0 => "",
_ => "*",
}
}
/// Normalizes an 'invalid' list.
fn normalize_invalids(
&self,
osm_street_name: &str,
street_invalid: &[String],
) -> anyhow::Result<Vec<String>> {
if self.config.should_check_housenumber_letters() {
return Ok(street_invalid.into());
}
let mut normalized_invalids: Vec<String> = Vec::new();
let street_ranges = self.get_street_ranges()?;
for i in street_invalid {
let normalizeds = normalize(self, i, osm_street_name, &street_ranges, &mut None, None)?;
// normalize() may return an empty list if the number is out of range.
if !normalizeds.is_empty() {
normalized_invalids.push(normalizeds[0].get_number().into())
}
}
Ok(normalized_invalids)
}
/// Gets house numbers from reference in SQL."""
fn get_ref_housenumbers(
&mut self,
osm_street_names: &[util::Street],
) -> anyhow::Result<HashMap<String, Vec<util::HouseNumber>>> {
let mut ret: HashMap<String, Vec<util::HouseNumber>> = HashMap::new();
let mut lines: HashMap<String, Vec<String>> = HashMap::new();
let conn = self.ctx.get_database_connection()?;
let mut stmt = conn.prepare(
"select housenumber, comment from ref_housenumbers where county_code = ?1 and settlement_code = ?2 and street = ?3 order by housenumber")?;
for street in osm_street_names {
let street = self
.config
.get_ref_street_from_osm_street(street.get_osm_name());
for refsettlement in self.config.get_street_refsettlement(&street) {
let mut rows =
stmt.query([&self.config.get_refcounty(), &refsettlement, &street])?;
while let Some(row) = rows.next()? {
let housenumber: String = row.get(0).unwrap();
let mut comment: String = row.get(1).unwrap();
let suffix = Relation::get_ref_suffix(if comment.is_empty() { 0 } else { 1 });
if comment == " " {
comment = "".into();
}
let value = housenumber + suffix + "\t" + &comment;
lines.entry(street.to_string()).or_default().push(value);
}
}
}
let street_ranges = self
.get_street_ranges()
.context("get_street_ranges() failed")?;
let streets_invalid = self.get_street_invalid();
for osm_street in osm_street_names {
let osm_street_name = osm_street.get_osm_name();
let mut house_numbers: Vec<util::HouseNumber> = Vec::new();
let ref_street_name = self.config.get_ref_street_from_osm_street(osm_street_name);
let mut street_invalid: Vec<String> = Vec::new();
if let Some(value) = streets_invalid.get(osm_street_name) {
street_invalid.clone_from(value);
// Simplify invalid items by default, so the 42a markup can be used, no matter what
// is the value of housenumber-letters.
street_invalid = self.normalize_invalids(osm_street_name, &street_invalid)?;
}
let mut used_invalids: Vec<String> = Vec::new();
if let Some(value) = lines.get(&ref_street_name) {
// Find 'invalid' items which are ranges.
let invalid_ranges: Vec<String> = street_invalid
.iter()
.filter(|i| i.contains('-'))
.map(|i| i.replace("/", "").to_lowercase())
.collect();
// Filter out ref items which match such invalid items.
let hns: Vec<_> = value
.iter()
.filter(|i| {
let mut it = i.split('\t');
let i = it.next().expect("token list should not be empty");
let mut hn = i.replace("/", "").to_lowercase();
if hn.ends_with('*') {
// a-b filters out both a-b and a-b*, so ignore the trailing *.
let mut chars = hn.chars();
chars.next_back();
hn = chars.as_str().into();
}
let contains = invalid_ranges.contains(&hn);
if contains {
// Mark this 'invalid' item as used.
used_invalids.push(hn.to_string());
}
!contains
})
.collect();
for house_number in hns {
let normalized = normalize(
self,
house_number,
osm_street_name,
&street_ranges,
&mut None,
None,
)?;
house_numbers.append(
&mut normalized
.iter()
.filter(|i| {
let is_invalid = util::HouseNumber::is_invalid(
i.get_number(),
&street_invalid,
&mut used_invalids,
);
!is_invalid
})
.cloned()
.collect(),
);
}
}
if let Some(street_invalid) = streets_invalid.get(osm_street_name) {
// This is the full list of invalid items, before removing the out of range ones.
for invalid in street_invalid {
if !used_invalids.contains(invalid) {
let relation_name = self.get_name();
let street_name = osm_street.get_osm_name().to_string();
let source = RelationLintSource::Invalid;
let housenumber = invalid.to_string();
let mut reason = RelationLintReason::DeletedFromRef;
if let Some(value) = lines.get(&ref_street_name) {
// See if this is indeed deleted from the reference or it's just out of
// range, so the returned reference doesn't contain it as the range already
// filters it out.
let housenumbers: Vec<_> = value
.iter()
.map(|i| i.split('\t').next().unwrap().to_string())
.collect();
if housenumbers.contains(&housenumber) {
// Out of range, not really deleted from reference.
reason = RelationLintReason::OutOfRange;
}
}
let id: u64 = 0;
let object_type = "".to_string();
let lint = RelationLint {
relation_name,
street_name,
source,
housenumber,
reason,
id,
object_type,
};
self.lints.push(lint);
}
}
}
house_numbers.sort_unstable();
house_numbers.dedup();
ret.insert(
osm_street_name.into(),
util::sort_numerically(&house_numbers),
);
}
Ok(ret)
}
/// Compares ref and osm house numbers, prints the ones which are in ref, but not in osm.
/// Return value is a pair of ongoing and done streets.
/// Each of of these is a pair of a street name and a house number list.
pub fn get_missing_housenumbers(&mut self) -> anyhow::Result<MissingHousenumbers> {
let mut ongoing_streets = Vec::new();
let mut done_streets = Vec::new();
let osm_street_names = self.get_osm_streets(/*sorted_result=*/ true)?;
let all_ref_house_numbers = self
.get_ref_housenumbers(&osm_street_names)
.context("get_ref_housenumbers() failed")?;
for osm_street in osm_street_names {
let osm_street_name = osm_street.get_osm_name();
let ref_house_numbers = &all_ref_house_numbers[osm_street_name];
let osm_house_numbers = self.get_osm_housenumbers(osm_street_name)?;
let only_in_reference = util::get_only_in_first(ref_house_numbers, &osm_house_numbers);
let in_both = util::get_in_both(ref_house_numbers, &osm_house_numbers);
let ref_street_name = self.config.get_ref_street_from_osm_street(osm_street_name);
let street = util::Street::new(
osm_street_name,
&ref_street_name,
self.config.should_show_ref_street(osm_street_name),
/*osm_id=*/ 0,
);
if !only_in_reference.is_empty() {
ongoing_streets.push(util::NumberedStreet {
street: street.clone(),
house_numbers: only_in_reference,
})
}
if !in_both.is_empty() {
done_streets.push(util::NumberedStreet {
street,
house_numbers: in_both,
});
}
}
// Sort by length, reverse.
ongoing_streets.sort_by(|a, b| b.house_numbers.len().cmp(&a.house_numbers.len()));
Ok(MissingHousenumbers {
ongoing_streets,
done_streets,
})
}
/// Tries to find missing streets in a relation.
pub fn get_missing_streets(&self) -> anyhow::Result<(Vec<String>, Vec<String>)> {
let reference_streets: Vec<util::Street> = self
.get_ref_streets()?
.iter()
.map(|i| util::Street::from_string(i))
.collect();
let street_blacklist = self.config.get_street_filters();
let osm_streets: Vec<util::Street> = self
.get_osm_streets(/*sorted_result=*/ true)?
.iter()
.map(|street| {
util::Street::from_string(
&self
.config
.get_ref_street_from_osm_street(street.get_osm_name()),
)
})
.collect();
let only_in_reference = util::get_only_in_first(&reference_streets, &osm_streets);
let only_in_ref_names: Vec<String> = only_in_reference
.iter()
.filter(|i| !street_blacklist.contains(i.get_osm_name()))
.map(|i| i.get_osm_name())
.cloned()
.collect();
let in_both: Vec<String> = util::get_in_both(&reference_streets, &osm_streets)
.iter()
.map(|i| i.get_osm_name())
.cloned()
.collect();
Ok((only_in_ref_names, in_both))
}
/// Tries to find additional streets in a relation.
pub fn get_additional_streets(&self, sorted_result: bool) -> anyhow::Result<Vec<util::Street>> {
let ref_streets: Vec<String> = self
.get_ref_streets()?
.iter()
.map(|street| self.config.get_osm_street_from_ref_street(street))
.collect();
let ref_street_objs: Vec<_> = ref_streets
.iter()
.map(|i| util::Street::from_string(i))
.collect();
let osm_streets = self.get_osm_streets(sorted_result)?;
let osm_street_blacklist = self.config.get_osm_street_filters();
let mut only_in_osm = util::get_only_in_first(&osm_streets, &ref_street_objs);
only_in_osm.retain(|i| !osm_street_blacklist.contains(i.get_osm_name()));
Ok(only_in_osm)
}
/// Calculate and write stat for the street coverage of a relation.
pub fn write_missing_streets(&self) -> anyhow::Result<(usize, usize, f64, Vec<String>)> {
let (todo_streets, done_streets) = self.get_missing_streets()?;
let streets = todo_streets.clone();
let todo_count = todo_streets.len();
let done_count = done_streets.len();
let percent: f64 = if done_count > 0 || todo_count > 0 {
let float: f64 = done_count as f64 / (done_count as f64 + todo_count as f64) * 100_f64;
float
} else {
100_f64
};
// Write the bottom line to a file, so the index page show it fast.
self.set_osm_street_coverage(&format!("{percent:.2}"))?;
Ok((todo_count, done_count, percent, streets))
}