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
use crate::utils::variable_data;
use crate::utils::{tax_ranks::TaxRanks, utils, variables::Variables};
use crate::{TaxType, GOAT_URL, TAXONOMY};
use anyhow::{bail, Context, Result};
use std::fmt;
#[derive(Default, Clone, Copy)]
pub enum ReportType {
#[default]
Newick,
Histogram,
CategoricalHistogram,
Scatterplot,
}
impl fmt::Display for ReportType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ReportType::Newick => write!(f, "tree"),
_ => write!(f, "table"),
}
}
}
#[derive(Default, Debug)]
pub struct Opts {
min: Option<i32>,
max: Option<i32>,
tick_count: Option<i32>,
scale: Option<String>,
axis_title: Option<String>,
}
impl Opts {
pub const SCALE_TYPES: [&'static str; 7] = [
"linear",
"sqrt",
"log10",
"log2",
"log",
"proportion",
"ordinal",
];
pub fn try_from_string(cli_opts: &str) -> Result<Self> {
let mut tokens: Vec<Option<_>> = cli_opts
.split(',')
.map(|e| match e.trim() {
"" => None,
_ => Some(e),
})
.collect();
tokens.reverse();
let mut t: Vec<_> = tokens.iter().skip_while(|e| e.is_none()).collect();
t.reverse();
let mut opts: Opts = Default::default();
fn parse_str_to_int(el: &Option<&str>) -> Result<Option<i32>> {
let int_str = el;
let int =
match int_str {
Some(e) => Some(e.trim().parse::<i32>().context(
"Could not convert what should be an integer in the options flag.",
)?),
None => None,
};
Ok(int)
}
match t.len() {
0 => bail!("Can't split no tokens in the x or y options."),
1 => {
opts.min = parse_str_to_int(t[0])?;
}
2 => {
opts.min = parse_str_to_int(t[0])?;
opts.max = parse_str_to_int(t[1])?;
}
3 => {
opts.min = parse_str_to_int(t[0])?;
opts.max = parse_str_to_int(t[1])?;
opts.tick_count = parse_str_to_int(t[2])?;
}
4 => {
opts.min = parse_str_to_int(t[0])?;
opts.max = parse_str_to_int(t[1])?;
opts.tick_count = parse_str_to_int(t[2])?;
opts.scale = t[3].map(|e| e.to_string());
if !Self::SCALE_TYPES
.iter()
.any(|e| **e == opts.scale.clone().unwrap_or_else(|| "".into()))
{
bail!("Did not recognise scale type supplied. The options are linear, sqrt, log10, log2, log, proportion, or ordinal.")
}
}
5 => {
opts.min = parse_str_to_int(t[0])?;
opts.max = parse_str_to_int(t[1])?;
opts.tick_count = parse_str_to_int(t[2])?;
opts.scale = t[3].map(|e| e.to_string());
if !Self::SCALE_TYPES
.iter()
.any(|e| **e == opts.scale.clone().unwrap_or_else(|| "".into()))
{
bail!("Did not recognise scale type supplied. The options are linear, sqrt, log10, log2, log, proportion, or ordinal.")
}
opts.axis_title = t[4].map(|e| e.to_string());
}
_ => bail!("Too many tokens supplied to opts."),
}
Ok(opts)
}
}
impl fmt::Display for Opts {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let min = match self.min {
Some(m) => format!("{}", m),
None => "".into(),
};
let max = match self.max {
Some(m) => format!("{}", m),
None => "".into(),
};
let tick_count = match self.tick_count {
Some(m) => format!("{}", m),
None => "".into(),
};
let scale = match &self.scale {
Some(m) => m.clone(),
None => "".into(),
};
let axis_title = match &self.axis_title {
Some(m) => m.clone(),
None => "".into(),
};
write!(
f,
"{}",
[min, max, tick_count, scale, axis_title].join("%2C")
)
}
}
#[derive(Default)]
pub struct Report {
pub report_type: ReportType,
pub search: Vec<String>,
pub rank: String,
pub taxon_type: TaxType,
pub size: Option<usize>,
pub x: Option<String>,
pub y: Option<String>,
pub x_opts: Option<Opts>,
pub y_opts: Option<Opts>,
pub category: Option<String>,
}
impl Report {
pub fn new(matches: &clap::ArgMatches, report_type: ReportType) -> Result<Self> {
let mut report: Report = Report {
report_type,
..Default::default()
};
let search = matches
.get_one::<String>("taxon")
.expect("cli requires input");
report.search = utils::parse_comma_separated(search);
report.rank = matches
.get_one::<String>("rank")
.expect("cli default = species")
.to_string();
let x_variable = matches.get_one::<String>("x-variable");
if let Some(xvar) = x_variable {
let inner_x =
Variables::new(xvar).parse_one(&variable_data::GOAT_TAXON_VARIABLE_DATA)?;
report.x = Some(inner_x);
};
let size = *matches.get_one::<usize>("size").expect("cli default = 10");
report.size = Some(size);
let no_descendents = *matches
.get_one::<bool>("no-descendents")
.expect("cli default false");
if no_descendents {
report.taxon_type = TaxType::Name;
}
let y_variable = matches.get_one::<String>("y-variable");
if let Some(y_var) = y_variable {
report.y = Some(y_var.to_string());
}
let xopts = matches.get_one::<String>("x-opts");
if let Some(x_opts) = xopts {
report.x_opts = Some(Opts::try_from_string(x_opts)?);
}
let yopts = matches.get_one::<String>("y-opts");
if let Some(y_opts) = yopts {
report.y_opts = Some(Opts::try_from_string(y_opts)?);
}
let category = matches.get_one::<String>("category");
if let Some(cat) = category {
let parsed_taxon_rank = TaxRanks::parse(&TaxRanks::init(), cat, true);
let parsed_category =
Variables::new(cat).parse_one(&variable_data::GOAT_TAXON_VARIABLE_DATA);
match parsed_taxon_rank {
Ok(tr) => {
report.category = Some(tr);
return Ok(report);
}
Err(e) => {
match parsed_category {
Ok(pc) => {
report.category = Some(pc);
return Ok(report);
}
Err(e2) => {
bail!("In category: {}\n\nOr taxon rank: {}.", e2, e);
}
}
}
}
}
Ok(report)
}
pub fn make_url(&self, unique_ids: Vec<String>) -> Result<String> {
match self.report_type {
ReportType::Newick => {
let mut url = String::new();
url += &GOAT_URL;
url += "report?result=taxon";
url += &format!("&report={}", self.report_type);
let csqs = match self.search.len() {
1 => self.search[0].clone(),
_ => self.search.join("%2C"),
};
let x_value_source = format!(
"&x=tax_rank%28{}%29%20AND%20tax_tree%28{}%29",
self.rank, csqs
);
url += &x_value_source;
url += "&includeEstimates=true";
url += &format!("&taxonomy={}", &*TAXONOMY);
url += &format!("&queryId=goat_cli_{}", unique_ids[0]);
Ok(url)
}
ReportType::Histogram => {
let mut url = String::new();
url += &GOAT_URL;
url += "report?result=taxon";
url += "&includeEstimates=false";
url += &format!("&taxonomy={}", &*TAXONOMY);
url += &format!("&report={}", self.report_type);
url += &format!("&rank={}", self.rank);
let taxon_type = self.taxon_type;
let taxa = self.search.join("%2C");
let variable = self.x.clone().unwrap();
url += &format!("&x={}%28{}%29%20AND%20{}", taxon_type, taxa, variable);
if let Some(xopts) = &self.x_opts {
url += &format!("&xOpts={}", xopts);
}
Ok(url)
}
ReportType::CategoricalHistogram => {
let mut url = String::new();
url += &GOAT_URL;
url += "report?result=taxon";
url += "&includeEstimates=false";
url += &format!("&taxonomy={}", &*TAXONOMY);
url += &format!("&report={}", self.report_type);
url += &format!("&rank={}", self.rank);
let taxon_type = self.taxon_type;
let taxa = self.search.join("%2C");
let variable = self.x.clone().unwrap();
let cat = self.category.clone().unwrap();
url += &format!(
"&x={}%28{}%29%20AND%20{}&cat={}%5B{}%5D",
taxon_type,
taxa,
variable,
cat,
self.size.unwrap(),
);
if let Some(xopts) = &self.x_opts {
url += &format!("&xOpts={}", xopts);
}
Ok(url)
}
ReportType::Scatterplot => {
bail!("Scatter plots are not yet implemented; please check back in the future!")
}
}
}
}