bambam 0.3.1

The Behavior and Advanced Mobility Big Access Model
Documentation
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
use bambam::app::oppvec::{self, oppvec_ops};
use bambam::app::overlay::{
    self, GeometryColumnType, GeometryFormat, OverlayOperation, OverlaySource,
};
use clap::{Parser, Subcommand};
#[derive(Parser)]
#[command(author, version, about, long_about = None)]
#[command(propagate_version = true)]
pub struct CliArgs {
    #[command(subcommand)]
    app: App,
}

use bambam::model::input_plugin::grid::extent_format::ExtentFormat;
use bambam::model::input_plugin::grid::grid_input_plugin;
use bambam::model::input_plugin::grid::grid_input_plugin_builder;
use bambam::model::input_plugin::grid::grid_type::GridType;
use bambam::model::input_plugin::population::population_source_config::PopulationSourceConfig;
use bambam_osm::app::wci;
use bamcensus_acs::model::AcsType;
use bamcensus_core::model::identifier::GeoidType;
use h3o::Resolution;
use serde_json::json;
use std::fs::File;
use std::io::BufWriter;
use std::io::Write;

#[derive(Subcommand)]
pub enum App {
    #[command(
        name = "walk_comfort_index",
        about = "calculate the WCI of links, set to file"
    )]
    WalkComfortIndexSet {
        /// file to write WCI values to, one per line
        #[arg(long)]
        wci_file: String,
        /// input csv file with edges OSM data
        #[arg(long)]
        edges_osm: String,
        /// input csv file with vertices OSM data
        #[arg(long)]
        vertices_osm: String,
    },
    #[command(
        name = "preprocess_grid",
        about = "processs the grid before running bambam to avoid time-out errors"
    )]
    PreProcessGrid {
        /// 1 or 5 for one- or five-year ACS (American Community Survey) population estimate
        #[arg(long)]
        acs_type: AcsType,
        /// year for estimate
        #[arg(long)]
        acs_year: u64,
        /// (Optional) GeoidType for resolution
        #[arg(long)]
        acs_resolution: Option<GeoidType>,
        /// (Optional) String for comma-separated categories
        #[arg(long)]
        acs_categories: Option<String>,
        /// (Optional) String for api token
        #[arg(long)]
        api_token: Option<String>,
        /// format of the extent in ExtentFormat, Wkt
        #[arg(long)]
        extent_format: ExtentFormat,
        /// Resolution of grid, value 0-15
        #[arg(long)]
        grid_resolution: Resolution,
        /// String of desired output file location
        #[arg(long)]
        output_file: String,
        /// String of extent to examine stored in a text file
        #[arg(long)]
        extent_file: String,
    },
    #[command(
        name = "opps-long",
        about = "vectorize an opportunity dataset CSV in long format for bambam integration"
    )]
    OpportunitiesLongFormat {
        /// a vertices-compass.csv.gz file for a RouteE Compass dataset
        vertices_compass_filename: String,
        /// a CSV file containing opportunities and geometries in long format
        opportunities_filename: String,
        /// file to write resulting opportunities dataset, designed to be a tabular
        /// opportunity input to bambam.
        output_filename: String,
        /// column name containing x coordinates. cannot be used when "geometry_column" is specified.
        #[arg(long)]
        x_column: Option<String>,
        /// column name containing y coordinates. cannot be used when "geometry_column" is specified.
        #[arg(long)]
        y_column: Option<String>,
        /// column name containing WKT geometry. cannot be used when x|y columns are specified.
        #[arg(long)]
        geometry_column: Option<String>,

        /// column name containing activity category name
        #[arg(long)]
        category_column: String,

        // /// optional column name containing activity counts. if omitted, counts each row as 1 opportunity.
        #[arg(long)]
        count_column: Option<String>,
        /// mapping from category name to activity type as comma-delimited string of "cat->acts" statements, where
        /// "cat" is the source category name, and "acts" is a hyphen-delimited non-empty list of target activity categories.
        /// wrap the entire argument in double-quotes. example: "CNS07->retail-jobs,CNS16->healthcare-jobs,CNS05->jobs"
        #[arg(long)]
        category_mapping: String,
        // // / comma-delimited list of categories to keep
        // #[arg(long)]
        // activity_categories: String,
    },
    #[command(
        name = "opps-wide",
        about = "vectorize an opportunity dataset CSV for bambam integration"
    )]
    OpportunitiesWideFormat {
        // source_format: SourceFormat,
        /// a vertices-compass.csv.gz file for a RouteE Compass dataset
        vertices_compass_filename: String,
        /// a CSV file containing opportunities and geometries in long format
        opportunities_filename: String,
        /// file to write resulting opportunities dataset, designed to be a tabular
        /// opportunity input to bambam.
        output_filename: String,
        /// column name containing x coordinates. cannot be used when "geometry_column" is specified.
        #[arg(long)]
        x_column: Option<String>,
        /// column name containing y coordinates. cannot be used when "geometry_column" is specified.
        #[arg(long)]
        y_column: Option<String>,
        /// column name containing WKT geometry. cannot be used when x|y columns are specified.
        #[arg(long)]
        geometry_column: Option<String>,
        /// mapping from column name to activity type as comma-delimited string of "col->acts" statements, where
        /// "col" is the source column name, and "acts" is a hyphen-delminited non-empty list of target activity categories.
        /// example: "CNS07->retail-jobs,CNS16->healthcare-jobs,CNS05->jobs"
        #[arg(long)]
        column_mapping: String,
        // /// comma-delimited list of categories to keep
        // #[arg(long)]
        // activity_categories: String,
    },
    #[command(
        name = "overlay-shapefile",
        about = "partition the BAMBAM output into another dataset of geospatial boundaries"
    )]
    OverlayShapefile {
        /// a CSV file containing a bambam output
        bambam_output_filepath: String,
        /// a path to the overlay boundary dataset, such as a shapefile
        overlay_filepath: String,
        /// file path to write the result dataset
        output_directory: String,
        /// used for specifying column name for the geometry x value. do not combine with
        /// geomcol argument.
        #[arg(long)]
        xcol: Option<String>,
        /// used for specifying column name for the geometry y value. do not combine with
        /// geomcol argument.
        #[arg(long)]
        ycol: Option<String>,
        /// used for specifying column name for the geometry. do not combine with xcol or
        /// ycol arguments.
        #[arg(long)]
        geomcol: Option<String>,
        /// used for specifying the geometry type of the value stored at geomcol do not combine
        /// with xcol or ycol arguments.
        #[arg(long)]
        geomfmt: Option<GeometryFormat>,
        /// overlay method to apply
        #[arg(long, default_value_t = OverlayOperation::Intersection)]
        how: OverlayOperation,
        /// name of the id field in the shapefile, used to create the output filepath
        /// for each partitioned dataset. values will be re-encoded for the filesystem,
        /// removing values such as forward slashes that could have unintended effects.
        #[arg(long, default_value_t = String::from("GEOID"))]
        id_field: String,
        /// if true, log if any rows fail to match the provided overlay dataset
        #[arg(long)]
        verbose: bool,
    },
    #[command(
        name = "gtfs-config",
        about = "modifies a BAMBAM configuration file to incorporate a directory of GTFS data assets generated by bambam-gtfs"
    )]
    GtfsConfigApp {
        /// OS directory containing processed BAMBAM-GTFS files
        #[arg(long)]
        directory: String,
        /// path to the BAMBAM configuration file to augment with this set of GTFS data
        #[arg(long)]
        base_config: String,
        /// append a relative path as a prefix for any "*input_file" entries referenced within the BAMBAM configuration file
        /// for the transit-mode. can be None if there is no relative path present.
        #[arg(long)]
        inject_filepath: Option<String>,
    },
}

impl App {
    pub fn run(&self) -> Result<(), String> {
        env_logger::init();
        match self {
            Self::WalkComfortIndexSet {
                wci_file,
                edges_osm,
                vertices_osm,
            } => {
                if let Err(error) = wci::process_wci(edges_osm, vertices_osm, wci_file) {
                    eprintln!("error! {error:?}");
                }
                Ok(())
            }
            Self::PreProcessGrid {
                acs_type,
                acs_year,
                acs_resolution,
                acs_categories,
                api_token,
                extent_format,
                grid_resolution,
                output_file,
                extent_file,
            } => {
                // build acs categories from &Option<String> to Option<Vec<String>>
                let acs_categories: Option<Vec<String>> = acs_categories
                    .as_ref()
                    .map(|str| str.split(',').map(|elem| elem.trim().to_string()).collect());

                // create popconfig
                let pop_config = PopulationSourceConfig::UsCensusAcs {
                    acs_type: *acs_type,
                    acs_year: *acs_year,
                    acs_resolution: *acs_resolution,
                    acs_categories,
                    api_token: api_token.clone(),
                };

                // Using grid_resolution, build grid_type:Gridtype
                let grid_res_add = *grid_resolution;
                let grid_type = GridType::H3 {
                    resolution: grid_res_add,
                };

                let extent = std::fs::read_to_string(extent_file)
                    .map_err(|e| format!("failed to read extent file: {e}"))?;

                // unpack the command line arguments into serde_json::Values
                let mut data: serde_json::Value = json!({
                    "extent": extent,
                    "population_source": pop_config,
                    "extent_format": extent_format,
                    "grid": grid_type,
                    "output_file": output_file
                });

                // BUILD THE PLUGIN
                let plugin = grid_input_plugin_builder::plugin_builder(&data)
                    .map_err(|e| format!("failed to read grid model arguments: {e}"))?;

                // RUN GRID BUILDING PROCESS
                grid_input_plugin::process_grid_input(
                    &mut data,
                    plugin.extent_format,
                    plugin.grid_type,
                    &plugin.population_source,
                )
                .map_err(|e| format!("failure running grid processing: {e}"))?;

                // mutable data as input to process_grid_input becomes a json array
                // these 3 lines make sure the resulting data array is json, if it is, we have an array to loop through
                let array = match data.as_array() {
                    Some(a) => a,
                    None => {
                        eprintln!(
                            "{}",
                            serde_json::to_string_pretty(&data).unwrap_or_default()
                        );
                        return Err(
                            "resulting data is not an array of JSON as expected".to_string()
                        );
                    }
                };

                // write the resulting array to the output file location as newline-delimited JSON
                let file = File::create(output_file).map_err(|e| e.to_string())?;
                let mut writeto = BufWriter::new(file);
                for value in array {
                    let json_line = serde_json::to_string(value).map_err(|e| e.to_string())?;
                    writeln!(writeto, "{json_line}").map_err(|e| e.to_string())?;
                }
                println!("Wrote newline-delimited JSON to {output_file}");
                Ok(())
            }
            Self::OpportunitiesLongFormat {
                vertices_compass_filename,
                opportunities_filename,
                output_filename,
                geometry_column,
                x_column,
                y_column,
                category_column,
                count_column,
                category_mapping,
            } => {
                let geometry_format = oppvec::GeometryFormat::new(
                    geometry_column.as_ref(),
                    x_column.as_ref(),
                    y_column.as_ref(),
                )?;
                let category_mapping = oppvec_ops::create_mapping(category_mapping)?;
                log::debug!(
                    "category mapping:\n{}",
                    serde_json::to_string_pretty(&category_mapping).unwrap_or_default()
                );
                let source_format = oppvec::SourceFormat::LongFormat {
                    geometry_format,
                    category_column: category_column.clone(),
                    count_column: count_column.clone(),
                    category_mapping,
                };
                oppvec::run(
                    vertices_compass_filename,
                    opportunities_filename,
                    output_filename,
                    &source_format,
                    // &cats,
                )
            }
            Self::OpportunitiesWideFormat {
                vertices_compass_filename,
                opportunities_filename,
                output_filename,
                geometry_column,
                x_column,
                y_column,
                column_mapping,
                // activity_categories,
            } => {
                let geometry_format = oppvec::GeometryFormat::new(
                    geometry_column.as_ref(),
                    x_column.as_ref(),
                    y_column.as_ref(),
                )?;
                if column_mapping.is_empty() {
                    return Err(String::from(
                        "cannot build wide-format source with empty column mapping",
                    ));
                }
                let column_mapping = oppvec_ops::create_mapping(column_mapping)?;
                log::debug!(
                    "column mapping:\n{}",
                    serde_json::to_string_pretty(&column_mapping).unwrap_or_default()
                );
                let source_format = oppvec::SourceFormat::WideFormat {
                    geometry_format,
                    column_mapping,
                };
                oppvec::run(
                    vertices_compass_filename,
                    opportunities_filename,
                    output_filename,
                    &source_format,
                )
            }
            Self::GtfsConfigApp {
                directory,
                base_config: base_config_filepath,
                inject_filepath: base_config_relative_path,
            } => bambam::app::gtfs_config::run(
                directory,
                base_config_filepath,
                base_config_relative_path.as_deref(),
            )
            .map_err(|e| e.to_string()),

            Self::OverlayShapefile {
                bambam_output_filepath,
                overlay_filepath,
                output_directory,
                xcol: x_column,
                ycol: y_column,
                geomcol,
                geomfmt: geomformat,
                how,
                id_field,
                verbose,
            } => {
                let col_type = GeometryColumnType::new(
                    x_column.as_ref(),
                    y_column.as_ref(),
                    geomcol.as_ref(),
                    geomformat.as_ref(),
                )?;
                let overlay_source = OverlaySource::Shapefile {
                    file: overlay_filepath.clone(),
                    id_field: id_field.clone(),
                };
                overlay::run(
                    bambam_output_filepath,
                    output_directory,
                    &overlay_source,
                    &col_type,
                    how,
                    *verbose,
                )
            }
        }
    }
}

fn main() {
    let args = CliArgs::parse();
    match args.app.run() {
        Ok(_) => log::info!("bambam_util finished."),
        Err(e) => log::error!("{e}"),
    }
}