-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.rs
1365 lines (1219 loc) · 42.3 KB
/
main.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
#![feature(impl_trait_in_bindings)]
#[macro_use]
extern crate serde_derive;
use std::{
io::{stdin, BufReader, Read},
// path::Path,
prelude::*,
task,
};
use std::cmp::Ordering;
use std::collections::{BTreeMap, HashSet};
use std::env;
use std::error::Error;
use std::ffi::OsString;
use std::fs::{read_dir, File};
use std::hash::{Hash, Hasher};
use std::io::{self, BufRead};
use std::iter::FromIterator;
use std::str;
use std::sync::{Arc, RwLock};
use std::thread;
use actix_web::{http, web, App, HttpRequest, HttpResponse, HttpServer};
use flate2::read::GzDecoder;
use rayon::prelude::*;
use regex::Regex;
use time::SteadyTime;
use avro_rs::Reader;
// for write test
use avro_rs::types::{Record, Value};
use avro_rs::Schema;
use avro_rs::Writer;
use rand::prelude::*;
const BQ_DATA_PATH: &str = "./bq_data";
const BQ_FILE_REGEX: &str = "jaccard_similarity_ipv4";
const BQ_REGEX: &str = "_2019-12-16_";
// const BQ_DATE_REGEX: &str = r"_^\d{4}-\d{2}-\d{2}_";
fn load_avro_from_stdin() -> Result<BTreeMap<u32, Vec<(u32, f32)>>, Box<dyn Error>> {
let start_time = SteadyTime::now();
let mut similarity_map: BTreeMap<u32, Vec<(u32, f32)>> = BTreeMap::new();
let mut tot_rec_num: usize = 0;
let schema = r#"{
"type": "record",
"name": "test",
"fields": [
{"name": "prbId1", "type": "long"},
{"name": "prbId2", "type": "long"},
{"name": "median25", "type": "double"},
{"name": "median5", "type": "double"},
{"name": "median75", "type": "double"}
]
}"#;
let reader_schema = Schema::parse_str(schema).unwrap();
let stdin = std::io::stdin();
let stdin = stdin.lock();
// let ss = BufReader::new(stdin);
let source = Reader::with_schema(&reader_schema, stdin).unwrap();
source.for_each(|chunk: Result<Value, _>| match chunk.unwrap() {
Value::Record(n) => {
let mut nn = n.into_iter();
let prb_id1 =
avro_rs::from_value::<u32>(&nn.find(|kv| kv.0 == "prbId1").unwrap().1).unwrap();
let prb_id2 =
avro_rs::from_value::<u32>(&nn.find(|kv| kv.0 == "prbId2").unwrap().1).unwrap();
let pct50_similarity =
avro_rs::from_value::<f32>(&nn.find(|kv| kv.0 == "median5").unwrap().1).unwrap();
let prb_entry1 = similarity_map.entry(prb_id1).or_insert(vec![]);
prb_entry1.push((prb_id2, pct50_similarity));
let prb_entry2 = similarity_map.entry(prb_id2).or_insert(vec![]);
prb_entry2.push((prb_id1, pct50_similarity));
if tot_rec_num % 1_000_000 == 0 || tot_rec_num < 1 {
println!(
"{:?}mil records loaded in {:?}s...",
tot_rec_num / 1_000_000,
(SteadyTime::now() - start_time).num_seconds(),
);
};
tot_rec_num += 1;
}
err => {
println!("some err");
println!("{:?}", err);
}
});
println!("total records processed: {}", tot_rec_num);
println!("total records in map: {}", &similarity_map.len());
Ok(similarity_map)
}
fn load_avro_from_file() -> Result<BTreeMap<u32, Vec<(u32, f32)>>, Box<dyn Error>> {
let start_time = SteadyTime::now();
let mut similarity_map: BTreeMap<u32, Vec<(u32, f32)>> = BTreeMap::new();
let mut tot_rec_num: usize = 0;
let schema = r#"{
"type": "record",
"name": "test",
"fields": [
{"name": "prbId1", "type": "long"},
{"name": "prbId2", "type": "long"},
{"name": "median25", "type": "double"},
{"name": "median5", "type": "double"},
{"name": "median75", "type": "double"}
]
}"#;
let reader_schema = Schema::parse_str(schema).unwrap();
let data_dir = read_dir(BQ_DATA_PATH)?;
data_dir.into_iter().for_each(|file| {
let file_path = file.unwrap().path();
if &file_path.to_str().unwrap()[..BQ_FILE_REGEX.len()] != BQ_FILE_REGEX {
()
}
let file = File::open(&file_path).unwrap();
let source = Reader::with_schema(&reader_schema, file).unwrap();
source.for_each(|chunk: Result<Value, _>| match chunk.unwrap() {
Value::Record(n) => {
let mut nn = n.into_iter();
let prb_id1 =
avro_rs::from_value::<u32>(&nn.find(|kv| kv.0 == "prbId1").unwrap().1).unwrap();
let prb_id2 =
avro_rs::from_value::<u32>(&nn.find(|kv| kv.0 == "prbId2").unwrap().1).unwrap();
let pct50_similarity =
avro_rs::from_value::<f32>(&nn.find(|kv| kv.0 == "median5").unwrap().1)
.unwrap();
let prb_entry1 = similarity_map.entry(prb_id1).or_insert(vec![]);
prb_entry1.push((prb_id2, pct50_similarity));
let prb_entry2 = similarity_map.entry(prb_id2).or_insert(vec![]);
prb_entry2.push((prb_id1, pct50_similarity));
if tot_rec_num % 1_000_000 == 0 || tot_rec_num < 1 {
println!(
"{:?}mil records loaded in {:?}s from file {:?}..",
tot_rec_num / 1_000_000,
(SteadyTime::now() - start_time).num_seconds(),
&file_path
);
};
tot_rec_num += 1;
}
err => {
println!("some err");
println!("{:?}", err);
}
});
println!("file: {:?}", file_path);
println!("total records processed: {}", tot_rec_num);
println!("total records in map: {}", &similarity_map.len());
});
Ok(similarity_map)
}
fn load_avro_from_file_multithreaded(
src_files: Vec<std::path::PathBuf>,
) -> Result<(BTreeMap<u32, Vec<(u32, f32)>>, String), Box<dyn Error>> {
let start_time = SteadyTime::now();
let schema = r#"{
"type": "record",
"name": "test",
"fields": [
{"name": "prbId1", "type": "long"},
{"name": "prbId2", "type": "long"},
{"name": "median25", "type": "double"},
{"name": "median5", "type": "double"},
{"name": "median75", "type": "double"}
]
}"#;
let reader_schema = Schema::parse_str(schema).unwrap();
// extract the base name from the files vector,
// will be returned from this function so that
// it can be used to compare to another run of select_files
// to see if new files are available.
let base_name: String;
match src_files.get(0) {
Some(b_n) => {
base_name = b_n.file_name().unwrap().to_str().unwrap()
[..(BQ_FILE_REGEX.len() + BQ_REGEX.len())]
.to_string();
}
None => {
return Err(From::from(format!(
"No suitable files found in {}.",
BQ_DATA_PATH
)));
}
};
let similarity_map = src_files
.par_iter()
.fold(
|| (0, BTreeMap::new()),
|mut part_map: (usize, BTreeMap<u32, Vec<(u32, f32)>>), file_path| {
let f = File::open(file_path).unwrap();
let source = Reader::with_schema(&reader_schema, f).unwrap();
source.for_each(|chunk: Result<Value, _>| match chunk.unwrap() {
Value::Record(n) => {
let mut nn = n.into_iter();
let prb_id1 =
avro_rs::from_value::<u32>(&nn.find(|kv| kv.0 == "prbId1").unwrap().1)
.unwrap();
let prb_id2 =
avro_rs::from_value::<u32>(&nn.find(|kv| kv.0 == "prbId2").unwrap().1)
.unwrap();
let pct50_similarity =
avro_rs::from_value::<f32>(&nn.find(|kv| kv.0 == "median5").unwrap().1)
.unwrap();
let prb_entry1 = part_map.1.entry(prb_id1).or_insert(vec![]);
prb_entry1.push((prb_id2, pct50_similarity));
let prb_entry2 = part_map.1.entry(prb_id2).or_insert(vec![]);
prb_entry2.push((prb_id1, pct50_similarity));
let dur = SteadyTime::now() - start_time;
if part_map.0 % 1_000_000 == 0 || part_map.0 < 1 {
println!(
"{:?}mil records loaded in {}s from file {:?}...",
part_map.0 / 1_000_000,
dur.num_milliseconds() as f32 / 1000.0 as f32,
file_path
);
};
part_map.0 += 1;
}
err => {
println!("some err");
println!("{:?}", err);
}
});
println!(
"total records processed in file {:?}: {}",
&file_path, &part_map.0
);
println!(
"total probe records in map in file {:?}: {}",
&*file_path,
&part_map.1.len()
);
part_map
},
)
.reduce(
|| (0, BTreeMap::new()),
|mut total_map, next_chunk_map| {
next_chunk_map.1.into_iter().for_each(|mut kv| {
let existing_entry = total_map.1.entry(kv.0).or_insert(vec![]);
existing_entry.append(&mut kv.1);
});
total_map.0 += next_chunk_map.0;
total_map
},
);
let dur = SteadyTime::now() - start_time;
println!(
"grand total of {} records loaded in {}s",
similarity_map.0,
dur.num_milliseconds() as f32 / 1000.0
);
println!("grand total of {} probes in map", similarity_map.1.len());
Ok((similarity_map.1, base_name))
}
fn check_updated_files(
base_name: &String,
) -> Result<Option<(Vec<std::path::PathBuf>, String)>, Box<dyn Error>> {
let updated_files: Option<(Vec<std::path::PathBuf>, String)>;
let new_base_name: Option<String> = None;
match select_latest_files(BQ_DATA_PATH) {
Ok(files) => {
if files.get(0).is_some()
&& &files[0].file_name().unwrap().to_string_lossy().to_string()
[..(BQ_FILE_REGEX.len() + BQ_REGEX.len())]
!= base_name
{
println!("new files found...");
println!("current base name: {}", base_name);
let new_base_name = files[0].file_name().unwrap().to_string_lossy()
[..(BQ_FILE_REGEX.len() + BQ_REGEX.len())]
.to_string();
println!("new base name: {}", new_base_name);
updated_files = Some((files, new_base_name));
} else {
updated_files = None;
};
}
Err(e) => {
return Err(From::from(
"Error occurred while checking for updated files...",
))
}
};
Ok(updated_files)
}
fn load_with_bufreader_multithreaded() -> Result<BTreeMap<u32, Vec<(u32, f32)>>, Box<dyn Error>> {
let file_path = get_first_arg()?;
let file = File::open(file_path)?;
let data = GzDecoder::new(file);
let buffer = io::BufReader::new(data);
let start_time = SteadyTime::now();
let bufbuf: Vec<String> = buffer.lines().skip(1).map(|l| l.unwrap()).collect();
println!("file in memory, now processing in parallel");
let similarity_map = bufbuf
.par_iter()
.enumerate()
.fold(
|| BTreeMap::new(),
|mut part_map, (line_num, line)| -> BTreeMap<u32, Vec<(u32, f32)>> {
let b: Vec<String> = line.split_whitespace().map(|s| s.to_string()).collect();
let prb_id1 = b[0].parse::<u32>().unwrap();
let prb_id2 = b[1].parse::<u32>().unwrap();
let pct50_similarity = b[7].parse::<f32>().unwrap();
let prb_entry_1 = part_map.entry(prb_id1).or_insert(vec![]);
prb_entry_1.push((prb_id2, pct50_similarity));
let prb_entry_2 = part_map.entry(prb_id2).or_insert(vec![]);
prb_entry_2.push((prb_id1, pct50_similarity));
if line_num % 1_000_000 == 0 || line_num == 1 {
println!("{:?}", b);
println!("{:?}mil", line_num / 1_000_000);
println!("{:?}", SteadyTime::now() - start_time);
};
part_map
},
)
.reduce(
|| BTreeMap::new(),
|mut total_map, next_chunk_map| {
next_chunk_map.into_iter().for_each(|kv| {
let mut kkv = kv.1.clone();
let existing_entry = total_map.entry(kv.0).or_insert(vec![]);
existing_entry.append(&mut kkv);
});
total_map
},
);
println!("completed BTreeMap");
println!("{:?}", SteadyTime::now() - start_time);
Ok(similarity_map)
}
fn load_with_cursor_single_thread() -> Result<BTreeMap<u32, Vec<(u32, f32)>>, Box<dyn Error>> {
let file_path = get_first_arg()?;
let file = File::open(file_path)?;
let unzipdata = GzDecoder::new(file);
let mut data = io::BufReader::new(unzipdata);
let mut line = vec![];
let start_time = SteadyTime::now();
let mut similarity_map: BTreeMap<u32, Vec<(u32, f32)>> = BTreeMap::new();
let mut line_num: u64 = 0;
println!("Start processing in one thread");
'line: loop {
let num_bytes = data.read_until(b'\n', &mut line).unwrap();
if num_bytes == 0 {
break;
}
// let b: Vec<String> = line.split_whitespace().map(|s| s.to_string()).collect();
let b: Vec<String> = line
.split(|c| c == &b' ')
.map(|s| str::from_utf8(s).unwrap().to_string())
.collect();
let prb_id1;
match b[0].parse::<u32>() {
Ok(prb_id) => {
prb_id1 = prb_id;
}
Err(_) => {
println!("header");
line.clear();
continue 'line;
}
};
let prb_id2 = b[1].parse::<u32>()?;
let pct50_similarity = b[7].parse::<f32>()?;
let prb_entry_1 = similarity_map.entry(prb_id1).or_insert(vec![]);
prb_entry_1.push((prb_id2, pct50_similarity));
let prb_entry_2 = similarity_map.entry(prb_id2).or_insert(vec![]);
prb_entry_2.push((prb_id1, pct50_similarity));
if line_num % 1_000_000 == 0 || line_num == 1 {
println!("{:?}", SteadyTime::now() - start_time);
println!("{:?}", b);
println!("{:?}mil", line_num / 1_000_000);
};
line_num += 1;
line.clear();
}
println!("completed BTreeMap");
println!("{:?}", SteadyTime::now() - start_time);
Ok(similarity_map)
}
fn get_first_arg() -> Result<OsString, Box<dyn Error>> {
match env::args_os().nth(1) {
None => Err(From::from(
"Expected at least 1 argument with the gzipped csv file, but got none",
)),
Some(file_path) => Ok(file_path),
}
}
fn get_second_arg() -> Result<OsString, Box<dyn Error>> {
match env::args_os().nth(2) {
None => Err(From::from("skipping second argument")),
Some(bind_string) => Ok(bind_string),
}
}
struct AppState {
similarity_map: Arc<RwLock<BTreeMap<u32, Vec<(u32, f32)>>>>,
}
#[derive(Deserialize)]
struct Info {
prb_id: String,
}
#[derive(Deserialize)]
struct DualProbesInfo {
prb_id1: u32,
prb_id2: u32,
}
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "lowercase")]
enum Mode {
Similar,
Dissimilar,
}
#[derive(Deserialize)]
struct QueryInfo {
cutoff: Option<f32>,
limit: Option<u32>,
mode: Option<String>,
band: Option<String>,
}
#[derive(Serialize, Clone)]
struct SimilarProbe {
prb_id: u32,
similarity: f32,
}
#[derive(Serialize)]
struct JsonResult {
id: u32,
count: usize,
result: Vec<SimilarProbe>,
}
#[derive(Clone)]
struct SimProbVec(Vec<(u32, f32)>);
// struct PrbSimPair(u32, f32);
impl SimilarProbe {
fn new_vec_of(similar_probes: Vec<(u32, f32)>) -> Vec<SimilarProbe> {
similar_probes
.iter()
.map(|v| SimilarProbe {
prb_id: v.0,
similarity: v.1,
})
.collect()
}
}
impl std::fmt::Debug for SimilarProbe {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "prb_id: {}, s: {}", self.prb_id, self.similarity)
}
}
impl PartialEq for SimilarProbe {
// use only the prb_id in this tuple
// for matching them as the same element
fn eq(&self, other: &SimilarProbe) -> bool {
self.prb_id == other.prb_id
}
}
impl Eq for SimilarProbe {}
impl Hash for SimilarProbe {
fn hash<H: Hasher>(&self, state: &mut H) {
self.prb_id.hash(state);
}
}
async fn similarities_for_prb_id(
data: (web::Data<AppState>, web::Path<Info>, web::Query<QueryInfo>),
) -> std::io::Result<web::Json<JsonResult>> {
let (state, path, query) = data;
let similarity_map = state.similarity_map.read().unwrap();
println!("{:?}", path.prb_id);
println!("{:?}", query.cutoff);
println!("{:?}", query.mode);
let mut cutoff: f32 = 0.0;
let mut limit: usize = 0;
let mut query_err: Vec<&str> = vec![];
if let Some(co) = query.cutoff {
cutoff = co;
} else {
match query.limit {
Some(l) => {
limit = l as usize;
}
None => {
query_err.push("cutoff");
query_err.push("limit");
}
}
};
let mode = if let Some(mode) = &query.mode {
mode
} else {
"similar"
};
if query_err.len() > 0 {
return Err(std::io::Error::new(
std::io::ErrorKind::Other,
format!(
"queryparameter{}: `{}` required",
if query_err.len() == 1 { "" } else { "s" },
query_err.join("`,`")
),
));
};
let prb_id = &path.prb_id.parse::<u32>().unwrap();
let mut v: Vec<SimilarProbe> = similarity_map
.get(prb_id)
.unwrap()
.iter()
.filter(|ps| {
if mode == "dissimilar" {
ps.1 <= cutoff
} else {
ps.1 >= cutoff
}
})
.map(|v| SimilarProbe {
prb_id: v.0,
similarity: v.1,
})
.collect::<Vec<_>>();
v.sort_by(|a, b| {
b.similarity
.partial_cmp(&a.similarity)
.unwrap_or(Ordering::Equal)
});
Ok(web::Json(JsonResult {
id: *prb_id,
count: v.len(),
result: if limit == 0 { v } else { v[..limit].to_vec() },
}))
}
async fn nadir(
data: (web::Data<AppState>, web::Query<QueryInfo>),
) -> std::io::Result<web::Json<JsonResult>> {
let (state, query) = data;
let similarity_map = state.similarity_map.read().unwrap();
println!("{:?} nadir", query.mode);
let mut mode: Mode = Mode::Similar;
let mut query_err: Vec<&str> = vec![];
if let Some(m) = &query.mode {
match m.as_str() {
"similar" => {
mode = Mode::Similar;
}
"dissimilar" => {
mode = Mode::Dissimilar;
}
_ => {
query_err.push("mode");
}
}
};
let cutoff = if let Some(co) = query.cutoff {
co
} else {
match mode {
// kick out low similarities
Mode::Similar => 0.3,
// kick out probes that are basically the same out (by default)
Mode::Dissimilar => 0.99,
}
};
if query_err.len() > 0 {
return Err(std::io::Error::new(
std::io::ErrorKind::Other,
format!(
"queryparameter{}: `{}` invalid",
if query_err.len() == 1 { "" } else { "s" },
query_err.join("`,`")
),
));
};
// let sim_iter = state.similarity_map.iter();
let mut sim_sums: Vec<(u32, f32)> = Vec::from_iter(similarity_map.iter().map(|kv| {
(
*kv.0,
kv.1.iter()
.map(|v| v.1)
.filter(|v| match mode {
Mode::Similar => v > &cutoff,
Mode::Dissimilar => v < &cutoff,
})
.sum(),
)
}));
match mode {
Mode::Similar => {
sim_sums.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
}
Mode::Dissimilar => {
sim_sums.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap());
}
}
let nadir_probes = sim_sums[..25].to_vec();
Ok(web::Json(JsonResult {
id: 0,
count: nadir_probes.len(),
result: SimilarProbe::new_vec_of(nadir_probes),
}))
}
fn _get_recursive_dissim_probes<'a>(
sim_map: &BTreeMap<u32, Vec<(u32, f32)>>,
// prb_id: u32,
acc_prbs_vec: &'a mut Vec<SimilarProbe>,
max_count: usize,
band: &(f32, f32),
) {
let prb_id = acc_prbs_vec.last().unwrap().prb_id;
let dissim_prb_vec: &Vec<(u32, f32)> = sim_map.get(&prb_id).unwrap();
dissim_prb_vec
.to_owned()
.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap());
let filtered_iter = dissim_prb_vec
.into_iter()
.filter(|p| acc_prbs_vec.into_iter().all(|ps| ps.prb_id != p.0))
.filter(|ps| ps.1 >= band.0 && ps.1 <= band.1)
.collect::<Vec<_>>();
let len = filtered_iter.len();
if len == 0 {
//retreat and rerun!
let p = acc_prbs_vec.pop();
println!(
"retreat {}, count {}",
p.unwrap().prb_id,
acc_prbs_vec.len()
);
return _get_recursive_dissim_probes(sim_map, acc_prbs_vec, max_count, band);
}
let mut rng = thread_rng();
let i = if len > 1 {
rng.sample(rand::distributions::Uniform::new_inclusive(0, len - 1))
} else {
0
};
println!(
"size {}, selected i {}, count {}",
len,
i,
acc_prbs_vec.len()
);
match filtered_iter.into_iter().nth(i) {
Some(prb) => {
println!("{:?}", prb);
acc_prbs_vec.push(SimilarProbe {
prb_id: prb.0,
similarity: prb.1,
});
}
None => {
println!("size {}, none selected, count {}", len, acc_prbs_vec.len());
()
}
};
// if len == 1 {
// return ();
// }
// .sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap());
// let dissim_prb = dissim_prb_vec.last().unwrap();
if max_count >= acc_prbs_vec.len() {
return _get_recursive_dissim_probes(sim_map, acc_prbs_vec, max_count, band);
}
}
async fn recursive_dissimilarities_for_prb_id(
data: (web::Data<AppState>, web::Path<Info>, web::Query<QueryInfo>),
) -> std::io::Result<web::Json<JsonResult>> {
let (state, path, query) = data;
let similarity_map = state.similarity_map.read().unwrap();
let mut query_err: Vec<&str> = vec![];
let limit: usize;
let mut band: (f32, f32) = (0.0, 1.0);
let prb_id = &(path.prb_id.parse::<u32>().unwrap());
match query.limit {
Some(l) => {
limit = l as usize;
}
None => {
limit = 10;
}
};
match &query.band {
Some(b) => {
let v: Vec<f32> = b
.split(",")
.map(|s: &str| s.parse::<f32>().unwrap())
.collect::<Vec<_>>();
band.0 = *v.first().unwrap();
band.1 = *v.last().unwrap();
}
None => band = (0.3, 0.5),
}
let mode = if let Some(m) = &query.mode {
match m.as_str() {
"similar" => Mode::Similar,
"dissimilar" => Mode::Dissimilar,
_ => {
query_err.push("mode");
// This last line just to satisfy the type
// it isn't actually used, because we're going to throw.
Mode::Dissimilar
}
}
} else {
Mode::Dissimilar
};
let results = &mut Vec::<SimilarProbe>::new();
results.push(SimilarProbe {
prb_id: *prb_id,
similarity: 1.0,
});
_get_recursive_dissim_probes(&similarity_map, results, limit, &band);
println!("--- end of query ---");
Ok(web::Json(JsonResult {
id: *prb_id,
count: results.len(),
result: results.to_owned(),
}))
}
fn _get_aggregated_recursive_dissim_probes<'a>(
sim_map: &BTreeMap<u32, Vec<(u32, f32)>>,
mode: Mode,
acc_prbs_sum_vecs: &'a mut Vec<(u32, f32)>,
max_count: usize,
mut recurse_count: usize,
band: &(f32, f32),
) {
let last_acc_prbs_vec: &(u32, f32) = acc_prbs_sum_vecs.last().unwrap();
let last_prb_id = last_acc_prbs_vec.0;
let vv = acc_prbs_sum_vecs.to_owned();
let vv1 = acc_prbs_sum_vecs.to_owned();
let mut sums_for_prb_id: Vec<(u32, f32)> = sim_map
// get all similarities for the last probe in the vector holding all the sums,
// that were passed in to this function.
.get(&last_prb_id)
.unwrap()
.iter()
// add all the sums that are already in the vec of probes and sums,
// or fill in the blanks.
.map(move |(prb_id, sum)| {
let exist_sum = vv1.iter().find(|p| &p.0 == prb_id);
match exist_sum {
Some(s) => {
println!(
"adding for prb_id {}: {} + {} = {}",
prb_id,
sum,
s.1,
sum + s.1
);
(*prb_id, sum + s.1)
}
None => (*prb_id, *sum),
}
})
.collect::<Vec<_>>();
match mode {
// sort by the lowest sum if dissimilar was chosen by the user (the default also)
Mode::Dissimilar => {
sums_for_prb_id.sort_by(|a: &(u32, f32), b: &(u32, f32)| a.1.partial_cmp(&b.1).unwrap())
}
// sort by the highest sum if similar was chosen by the user.
Mode::Similar => {
sums_for_prb_id.sort_by(|a: &(u32, f32), b: &(u32, f32)| b.1.partial_cmp(&a.1).unwrap())
}
};
let sums_for_prb_id_clone = sums_for_prb_id.clone();
let f_sums = sums_for_prb_id
.into_iter()
.filter(|(prb_id, ps)| {
ps >= &band.0 && ps <= &band.1 && vv.iter().find(|p| &p.0 == prb_id).is_none()
})
.collect::<Vec<_>>();
// select a random probe from the set that is consists of the
// first 10 probes of the probes with (summes) similarities within the band.
let len = if f_sums.len() < 10 { f_sums.len() } else { 10 };
println!("length of filtered sums set: {:?}", len);
let mut rng = thread_rng();
let i = if len > 1 {
rng.sample(rand::distributions::Uniform::new_inclusive(0, len - 1))
} else {
0
};
match f_sums.get(i) {
Some(prb) => {
assert_eq!(
true,
acc_prbs_sum_vecs
.iter()
.all(|(prb_id, _)| { prb_id != &prb.0 })
);
acc_prbs_sum_vecs.push(*prb);
println!(
"Added prb {:?} to the selection set with a value of {} in round {}.",
prb.0, prb.1, recurse_count
);
}
None => {
recurse_count += 1;
println!("Empty new probe set in round {}", recurse_count);
}
};
// change all the occurences to hold the (updated) intermediary sum
acc_prbs_sum_vecs.clone().iter().for_each(|(prb_id, _)| {
match sums_for_prb_id_clone.iter().find(|p| &p.0 == prb_id) {
Some(p) => {
acc_prbs_sum_vecs.retain(|p| &p.0 != prb_id);
// only restore the probe if the ps value is within the set band,
// otherwise update the recursion_count to make sure we do not
// keep on doing this forever.
// Note that this way we may return less than the number of probes set
// by the `limit` query pararmeter.
if p.1 <= band.1 && p.1 >= band.0 {
acc_prbs_sum_vecs.push(*p);
} else {
recurse_count += 1;
println!(
"No new {:?} probe within the band found for probe {} in round {}",
mode, prb_id, recurse_count
);
}
}
None => {
println!(
"No {:?} probe found for probe {} in round {}",
mode, prb_id, recurse_count
);
}
};
});
if &max_count >= &acc_prbs_sum_vecs.len() && recurse_count <= max_count * 2 {
return _get_aggregated_recursive_dissim_probes(
sim_map,
mode,
acc_prbs_sum_vecs,
max_count,
recurse_count,
band,
);
}
}
async fn aggregated_recursive_dissimilarities_for_prb_id(
data: (web::Data<AppState>, web::Path<Info>, web::Query<QueryInfo>),
) -> std::io::Result<web::Json<JsonResult>> {
let (state, path, query) = data;
let similarity_map = state.similarity_map.read().unwrap();
let mut query_err: Vec<&str> = vec![];
// let mut limit: usize = 10;
// let mut band: (f32, f32) = (0.0, 1.0);
let prb_id = &(path.prb_id.parse::<u32>().unwrap());
let mode = if let Some(m) = &query.mode {
match m.as_str() {
"similar" => Mode::Similar,
"dissimilar" => Mode::Dissimilar,
_ => {
query_err.push("mode");
Mode::Dissimilar
}
}
} else {
Mode::Dissimilar
};
let band = if let Some(b) = &query.band {
let v: Vec<f32> = b
.split(",")
.map(|s: &str| s.parse::<f32>().unwrap())
.collect::<Vec<_>>();
(*v.first().unwrap(), *v.last().unwrap())
} else {
(0.0, 1.0)
};
let limit: usize = if let Some(l) = query.limit {
l as usize
} else {
10
};
if query_err.len() > 0 {
return Err(std::io::Error::new(
std::io::ErrorKind::Other,
format!(
"queryparameter{}: `{}` invalid",
if query_err.len() == 1 { "" } else { "s" },
query_err.join("`,`")
),
));
};
let probe_vecs = &mut vec![(prb_id.to_owned(), 1.0)];
_get_aggregated_recursive_dissim_probes(&similarity_map, mode, probe_vecs, limit, 0, &band);
println!("result: {:?}", probe_vecs);
println!("--- end of query ---");
Ok(web::Json(JsonResult {
id: *prb_id,
count: probe_vecs.len(),
result: SimilarProbe::new_vec_of(probe_vecs.to_owned()),
}))