ferrisup 0.2.5

A versatile Rust project bootstrapping tool - start anywhere, scale anywhere
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
423
424
425
426
427
428
429
use anyhow::Result;
use clap::{Arg, Command, Parser};
use ndarray::{Array1, Array2, Ix1};
use std::env;
use std::fs::{self, File};
use std::path::Path;
use linfa::prelude::*;
use rand::Rng;
use rand_xoshiro::Xoshiro256Plus;
use rand::SeedableRng;
use csv;
use serde_json;

mod clustering;
mod regression;
mod classification;
mod decision_tree;
mod data_utils;

fn print_usage() {
    println!("Linfa 0.7.1 Examples");
    println!("Usage: cargo run -- [example]");
    println!("Available examples:");
    println!("  classification - Run classification example with LogisticRegression");
    println!("  clustering     - Run clustering example");
    println!("  regression     - Run regression example with LinearRegression");
    println!("  decision_tree  - Run classification example with Decision Tree");
    println!("  all            - Run all examples sequentially");
    println!("  generate       - Generate sample data files in CSV and JSON formats");
    println!("  help           - Show this help message");
}

fn main() -> Result<()> {
    let args: Vec<String> = env::args().collect();
    
    if args.len() < 2 {
        print_usage();
        return Ok(());
    }
    
    match args[1].as_str() {
        "classification" => classification::run_logistic_regression_example()?,
        "clustering" => clustering::run_clustering_example()?,
        "regression" => regression::run_regression_example()?,
        "decision_tree" => decision_tree::run_decision_tree_example()?,
        "help" => print_usage(),
        "generate" => {
            if args.len() < 3 {
                println!("Please specify what kind of data to generate: classification, regression, clustering");
                return Ok(());
            }
            
            let data_type = args[2].as_str();
            let format = if args.len() >= 4 { args[3].as_str() } else { "all" };
            
            match data_type {
                "classification" => generate_classification_data(format)?,
                "regression" => generate_regression_data(format)?,
                "clustering" => generate_clustering_data(format)?,
                _ => {
                    println!("Unknown data type: {}", data_type);
                    println!("Available data types: classification, regression, clustering");
                }
            }
        },
        "all" => {
            println!("\n=== Running LogisticRegression Classification Example ===\n");
            classification::run_logistic_regression_example()?;
            
            println!("\n=== Running Decision Tree Classification Example ===\n");
            decision_tree::run_decision_tree_example()?;
            
            println!("\n=== Running Linear Regression Example ===\n");
            regression::run_regression_example()?;
            
            println!("\n=== Running Clustering Example ===\n");
            clustering::run_clustering_example()?;
            
            println!("\n=== All examples completed successfully ===\n");
        },
        _ => {
            println!("Unknown example: {}", args[1]);
            print_usage();
        }
    }
    
    Ok(())
}

// Function to generate classification data in different formats
fn generate_classification_data(format: &str) -> Result<()> {
    println!("Generating classification data...");
    
    // Create synthetic dataset
    let dataset = create_synthetic_classification_dataset()?;
    
    // Create data directory if it doesn't exist
    fs::create_dir_all("data")?;
    
    // Save in requested format(s)
    match format {
        "csv" => {
            save_classification_csv(&dataset, "data/sample_classification.csv")?;
            println!("Generated CSV data: data/sample_classification.csv");
        },
        "json" => {
            save_classification_json(&dataset, "data/sample_classification.json")?;
            println!("Generated JSON data: data/sample_classification.json");
        },
        "all" => {
            save_classification_csv(&dataset, "data/sample_classification.csv")?;
            save_classification_json(&dataset, "data/sample_classification.json")?;
            println!("Generated data in all formats:");
            println!("  CSV: data/sample_classification.csv");
            println!("  JSON: data/sample_classification.json");
        },
        _ => {
            println!("Unknown format: {}", format);
            println!("Available formats: csv, json, all");
        }
    }
    
    Ok(())
}

// Function to generate regression data in different formats
fn generate_regression_data(format: &str) -> Result<()> {
    println!("Generating regression data...");
    
    // Create synthetic dataset
    let dataset = create_synthetic_regression_dataset()?;
    
    // Create data directory if it doesn't exist
    fs::create_dir_all("data")?;
    
    // Save in requested format(s)
    match format {
        "csv" => {
            save_regression_csv(&dataset, "data/sample_regression.csv")?;
            println!("Generated CSV data: data/sample_regression.csv");
        },
        "json" => {
            save_regression_json(&dataset, "data/sample_regression.json")?;
            println!("Generated JSON data: data/sample_regression.json");
        },
        "all" => {
            save_regression_csv(&dataset, "data/sample_regression.csv")?;
            save_regression_json(&dataset, "data/sample_regression.json")?;
            println!("Generated data in all formats:");
            println!("  CSV: data/sample_regression.csv");
            println!("  JSON: data/sample_regression.json");
        },
        _ => {
            println!("Unknown format: {}", format);
            println!("Available formats: csv, json, all");
        }
    }
    
    Ok(())
}

// Function to generate clustering data in different formats
fn generate_clustering_data(format: &str) -> Result<()> {
    println!("Generating clustering data...");
    
    // Create synthetic dataset
    let dataset = create_synthetic_clustering_dataset()?;
    
    // Create data directory if it doesn't exist
    fs::create_dir_all("data")?;
    
    // Save in requested format(s)
    match format {
        "csv" => {
            save_clustering_csv(&dataset, "data/sample_clustering.csv")?;
            println!("Generated CSV data: data/sample_clustering.csv");
        },
        "json" => {
            save_clustering_json(&dataset, "data/sample_clustering.json")?;
            println!("Generated JSON data: data/sample_clustering.json");
        },
        "all" => {
            save_clustering_csv(&dataset, "data/sample_clustering.csv")?;
            save_clustering_json(&dataset, "data/sample_clustering.json")?;
            println!("Generated data in all formats:");
            println!("  CSV: data/sample_clustering.csv");
            println!("  JSON: data/sample_clustering.json");
        },
        _ => {
            println!("Unknown format: {}", format);
            println!("Available formats: csv, json, all");
        }
    }
    
    Ok(())
}

// Function to create a synthetic classification dataset
fn create_synthetic_classification_dataset() -> Result<Dataset<f64, usize, Ix1>> {
    let mut rng = Xoshiro256Plus::seed_from_u64(42);
    let num_samples = 100;
    
    let mut features_data = Vec::with_capacity(num_samples);
    let mut targets_data = Vec::with_capacity(num_samples);
    
    // Create two clusters of points
    for i in 0..num_samples {
        let cluster = i % 2; // Alternating between cluster 0 and 1
        
        let (center_x, center_y) = if cluster == 0 {
            (0.0, 0.0) // Cluster 0 centered at origin
        } else {
            (3.0, 3.0) // Cluster 1 centered at (3,3)
        };
        
        // Add some noise
        let x = center_x + rng.gen_range(-0.5..0.5);
        let _y = center_y + rng.gen_range(-0.5..0.5);
        
        features_data.push(x);
        targets_data.push(cluster);
    }
    
    // Create feature array (each sample has 1 feature)
    let features = Array2::from_shape_vec((num_samples, 1), features_data)?;
    let targets = Array1::from_vec(targets_data);
    
    Ok(Dataset::new(features, targets))
}

// Function to create a synthetic regression dataset
fn create_synthetic_regression_dataset() -> Result<Dataset<f64, f64, Ix1>> {
    let mut rng = Xoshiro256Plus::seed_from_u64(42);
    let num_samples = 100;
    
    let mut features_data = Vec::with_capacity(num_samples);
    let mut targets_data = Vec::with_capacity(num_samples);
    
    // Create a simple linear relationship: y = 2x + 1 + noise
    for _ in 0..num_samples {
        let x = rng.gen_range(0.0..10.0);
        let noise = rng.gen_range(-1.0..1.0);
        let y = 2.0 * x + 1.0 + noise;
        
        features_data.push(x);
        targets_data.push(y);
    }
    
    // Create feature array (each sample has 1 feature)
    let features = Array2::from_shape_vec((num_samples, 1), features_data)?;
    let targets = Array1::from_vec(targets_data);
    
    Ok(Dataset::new(features, targets))
}

// Function to create a synthetic clustering dataset
fn create_synthetic_clustering_dataset() -> Result<Dataset<f64, f64, Ix1>> {
    let mut rng = Xoshiro256Plus::seed_from_u64(42);
    let num_samples = 100;
    
    let mut features_data = Vec::with_capacity(num_samples * 2);
    let mut targets_data = Vec::with_capacity(num_samples);
    
    // Create three clusters
    let centers = [(0.0, 0.0), (5.0, 5.0), (0.0, 5.0)];
    
    for i in 0..num_samples {
        let cluster_idx = i % 3;
        let (center_x, center_y) = centers[cluster_idx];
        
        // Add noise to create a cluster
        let x = center_x + rng.gen_range(-0.5..0.5);
        let y = center_y + rng.gen_range(-0.5..0.5);
        
        features_data.push(x);
        features_data.push(y);
        targets_data.push(0.0); // Dummy target (not used for clustering)
    }
    
    // Create feature array (each sample has 2 features)
    let features = Array2::from_shape_vec((num_samples, 2), features_data)?;
    let targets = Array1::from_vec(targets_data);
    
    Ok(Dataset::new(features, targets))
}

// Functions to save classification data in different formats
fn save_classification_csv(dataset: &Dataset<f64, usize, Ix1>, path: &str) -> Result<()> {
    let file = File::create(path)?;
    let mut writer = csv::Writer::from_writer(file);
    
    // Write header
    writer.write_record(&["x", "y", "class"])?;
    
    // Write data
    for i in 0..dataset.nsamples() {
        let x = dataset.records().row(i)[0];
        let y = 0.0; // Add a dummy y value for compatibility with the classification example
        let class = dataset.targets()[i];
        writer.write_record(&[x.to_string(), y.to_string(), class.to_string()])?;
    }
    
    writer.flush()?;
    Ok(())
}

fn save_classification_json(dataset: &Dataset<f64, usize, Ix1>, path: &str) -> Result<()> {
    #[derive(serde::Serialize)]
    struct DataPoint {
        x: f64,
        y: f64,
        target: usize,
    }
    
    #[derive(serde::Serialize)]
    struct DataSet {
        data: Vec<DataPoint>,
    }
    
    let mut data_points = Vec::new();
    
    for i in 0..dataset.nsamples() {
        let x = dataset.records().row(i)[0];
        let y = 0.0; // Add a dummy y value for compatibility with the classification example
        let target = dataset.targets()[i];
        
        data_points.push(DataPoint { x, y, target });
    }
    
    let dataset = DataSet { data: data_points };
    let file = File::create(path)?;
    serde_json::to_writer_pretty(file, &dataset)?;
    
    Ok(())
}

// Functions to save regression data in different formats
fn save_regression_csv(dataset: &Dataset<f64, f64, Ix1>, path: &str) -> Result<()> {
    let file = File::create(path)?;
    let mut writer = csv::Writer::from_writer(file);
    
    // Write header
    writer.write_record(&["x", "y"])?;
    
    // Write data
    for i in 0..dataset.nsamples() {
        let x = dataset.records().row(i)[0];
        let y = dataset.targets()[i];
        writer.write_record(&[x.to_string(), y.to_string()])?;
    }
    
    writer.flush()?;
    Ok(())
}

fn save_regression_json(dataset: &Dataset<f64, f64, Ix1>, path: &str) -> Result<()> {
    #[derive(serde::Serialize)]
    struct DataPoint {
        x: f64,
        y: f64,
    }
    
    #[derive(serde::Serialize)]
    struct DataSet {
        data: Vec<DataPoint>,
    }
    
    let mut data_points = Vec::new();
    
    for i in 0..dataset.nsamples() {
        let x = dataset.records().row(i)[0];
        let y = dataset.targets()[i];
        
        data_points.push(DataPoint { x, y });
    }
    
    let dataset_json = DataSet { data: data_points };
    let file = File::create(path)?;
    serde_json::to_writer_pretty(file, &dataset_json)?;
    
    Ok(())
}

// Functions to save clustering data in different formats
fn save_clustering_csv(dataset: &Dataset<f64, f64, Ix1>, path: &str) -> Result<()> {
    let file = File::create(path)?;
    let mut writer = csv::Writer::from_writer(file);
    
    // Write header
    writer.write_record(&["x", "y"])?;
    
    // Write data
    for i in 0..dataset.nsamples() {
        let x = dataset.records().row(i)[0];
        let y = dataset.records().row(i)[1];
        writer.write_record(&[x.to_string(), y.to_string()])?;
    }
    
    writer.flush()?;
    Ok(())
}

fn save_clustering_json(dataset: &Dataset<f64, f64, Ix1>, path: &str) -> Result<()> {
    #[derive(serde::Serialize)]
    struct DataPoint {
        x: f64,
        y: f64,
    }
    
    #[derive(serde::Serialize)]
    struct DataSet {
        data: Vec<DataPoint>,
    }
    
    let mut data_points = Vec::new();
    
    for i in 0..dataset.nsamples() {
        let x = dataset.records().row(i)[0];
        let y = dataset.records().row(i)[1];
        
        data_points.push(DataPoint { x, y });
    }
    
    let dataset_json = DataSet { data: data_points };
    let file = File::create(path)?;
    serde_json::to_writer_pretty(file, &dataset_json)?;
    
    Ok(())
}