Skip to content

Commit 2d97b2a

Browse files
noahgiftclaude
andcommitted
fix: Replace .unwrap() with .expect() in examples and benches (Refs #41)
Replaced all .unwrap() calls with descriptive .expect() messages: - examples/*.rs: "Example data should be valid" - benches/*.rs: "Benchmark data should be valid" This satisfies GH-41 requirements and unblocks Dependabot PRs #46-50 that were failing CI due to clippy::disallowed_methods warnings. Changes: - 26 example files updated - 3 benchmark files updated - Auto-fixed format string warnings - All 742 tests still passing - Examples and benches now clippy-clean Note: Tests still use .unwrap() which is acceptable for test code. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
1 parent e3394be commit 2d97b2a

29 files changed

+386
-299
lines changed

benches/dataframe.rs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ fn bench_dataframe_to_matrix(c: &mut Criterion) {
2121
Vector::from_vec((0..n_rows).map(|i| i as f32 * 3.0).collect()),
2222
),
2323
];
24-
let df = DataFrame::new(columns).unwrap();
24+
let df = DataFrame::new(columns).expect("Benchmark data should be valid");
2525

2626
group.bench_with_input(BenchmarkId::from_parameter(n_rows), &n_rows, |b, _| {
2727
b.iter(|| black_box(&df).to_matrix());
@@ -57,10 +57,14 @@ fn bench_dataframe_select(c: &mut Criterion) {
5757
Vector::from_vec((0..n_rows).map(|i| i as f32 * 5.0).collect()),
5858
),
5959
];
60-
let df = DataFrame::new(columns).unwrap();
60+
let df = DataFrame::new(columns).expect("Benchmark data should be valid");
6161

6262
group.bench_with_input(BenchmarkId::from_parameter(n_rows), &n_rows, |b, _| {
63-
b.iter(|| black_box(&df).select(&["a", "c", "e"]).unwrap());
63+
b.iter(|| {
64+
black_box(&df)
65+
.select(&["a", "c", "e"])
66+
.expect("Benchmark data should be valid")
67+
});
6468
});
6569
}
6670

benches/kmeans.rs

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,15 +19,17 @@ fn bench_kmeans_fit(c: &mut Criterion) {
1919
}
2020
}
2121

22-
let matrix = Matrix::from_vec(n_samples, 2, data).unwrap();
22+
let matrix = Matrix::from_vec(n_samples, 2, data).expect("Benchmark data should be valid");
2323

2424
group.bench_with_input(
2525
BenchmarkId::from_parameter(n_samples),
2626
&n_samples,
2727
|b, _| {
2828
b.iter(|| {
2929
let mut kmeans = KMeans::new(2).with_random_state(42).with_max_iter(100);
30-
kmeans.fit(black_box(&matrix)).unwrap();
30+
kmeans
31+
.fit(black_box(&matrix))
32+
.expect("Benchmark data should be valid");
3133
});
3234
},
3335
);
@@ -51,9 +53,9 @@ fn bench_kmeans_predict(c: &mut Criterion) {
5153
}
5254
}
5355

54-
let matrix = Matrix::from_vec(n_samples, 2, data).unwrap();
56+
let matrix = Matrix::from_vec(n_samples, 2, data).expect("Benchmark data should be valid");
5557
let mut kmeans = KMeans::new(2).with_random_state(42);
56-
kmeans.fit(&matrix).unwrap();
58+
kmeans.fit(&matrix).expect("Benchmark data should be valid");
5759

5860
group.bench_with_input(
5961
BenchmarkId::from_parameter(n_samples),

benches/linear_regression.rs

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,15 @@ fn bench_linear_regression_fit(c: &mut Criterion) {
1111
let x_data: Vec<f32> = (0..*size).map(|i| i as f32).collect();
1212
let y_data: Vec<f32> = x_data.iter().map(|&x| 2.0 * x + 1.0).collect();
1313

14-
let x = Matrix::from_vec(*size, 1, x_data).unwrap();
14+
let x = Matrix::from_vec(*size, 1, x_data).expect("Benchmark data should be valid");
1515
let y = Vector::from_vec(y_data);
1616

1717
group.bench_with_input(BenchmarkId::from_parameter(size), size, |b, _| {
1818
b.iter(|| {
1919
let mut model = LinearRegression::new();
20-
model.fit(black_box(&x), black_box(&y)).unwrap();
20+
model
21+
.fit(black_box(&x), black_box(&y))
22+
.expect("Benchmark data should be valid");
2123
});
2224
});
2325
}
@@ -32,11 +34,11 @@ fn bench_linear_regression_predict(c: &mut Criterion) {
3234
let x_data: Vec<f32> = (0..*size).map(|i| i as f32).collect();
3335
let y_data: Vec<f32> = x_data.iter().map(|&x| 2.0 * x + 1.0).collect();
3436

35-
let x = Matrix::from_vec(*size, 1, x_data).unwrap();
37+
let x = Matrix::from_vec(*size, 1, x_data).expect("Benchmark data should be valid");
3638
let y = Vector::from_vec(y_data);
3739

3840
let mut model = LinearRegression::new();
39-
model.fit(&x, &y).unwrap();
41+
model.fit(&x, &y).expect("Benchmark data should be valid");
4042

4143
group.bench_with_input(BenchmarkId::from_parameter(size), size, |b, _| {
4244
b.iter(|| model.predict(black_box(&x)));

examples/bayesian_blocks_histogram.rs

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,12 @@ fn uniform_distribution_example() {
4646
let v = Vector::from_slice(&data);
4747
let stats = DescriptiveStats::new(&v);
4848

49-
let hist_bayesian = stats.histogram_method(BinMethod::Bayesian).unwrap();
50-
let hist_sturges = stats.histogram_method(BinMethod::Sturges).unwrap();
49+
let hist_bayesian = stats
50+
.histogram_method(BinMethod::Bayesian)
51+
.expect("Example data should be valid");
52+
let hist_sturges = stats
53+
.histogram_method(BinMethod::Sturges)
54+
.expect("Example data should be valid");
5155

5256
println!(" Data: 1, 2, 3, ..., 20 (uniform)");
5357
println!("\n Bayesian Blocks:");
@@ -77,7 +81,9 @@ fn two_clusters_example() {
7781
let v = Vector::from_slice(&data);
7882
let stats = DescriptiveStats::new(&v);
7983

80-
let hist = stats.histogram_method(BinMethod::Bayesian).unwrap();
84+
let hist = stats
85+
.histogram_method(BinMethod::Bayesian)
86+
.expect("Example data should be valid");
8187

8288
println!(" Data: Two clusters (1.0-2.0 and 9.0-10.0)");
8389
println!(" Gap: 2.0 to 9.0 (no data)");
@@ -121,7 +127,9 @@ fn multiple_density_example() {
121127
let v = Vector::from_slice(&data);
122128
let stats = DescriptiveStats::new(&v);
123129

124-
let hist = stats.histogram_method(BinMethod::Bayesian).unwrap();
130+
let hist = stats
131+
.histogram_method(BinMethod::Bayesian)
132+
.expect("Example data should be valid");
125133

126134
println!(" Data: Dense (1.0-2.0), Sparse (5, 7, 9), Dense (15.0-16.0)");
127135
println!("\n Bayesian Blocks Result:");
@@ -177,7 +185,9 @@ fn comparison_example() {
177185
println!(" {}", "-".repeat(52));
178186

179187
for (method, name) in methods {
180-
let hist = stats.histogram_method(method).unwrap();
188+
let hist = stats
189+
.histogram_method(method)
190+
.expect("Example data should be valid");
181191
let n_bins = hist.counts.len();
182192

183193
// Check if method detected the gap (should have low counts in middle bins)

examples/boston_housing.rs

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ fn main() {
2020
1600.0, 3.0, 2.0, 20.0, 3000.0, 5.0, 4.0, 1.0, 1400.0, 3.0, 1.5, 25.0,
2121
],
2222
)
23-
.unwrap();
23+
.expect("Example data should be valid");
2424

2525
// Prices (simulated based on features)
2626
let y = Vector::from_slice(&[
@@ -53,7 +53,7 @@ fn main() {
5353
let actual = y.as_slice()[i];
5454
let predicted = predictions.as_slice()[i];
5555
let error = actual - predicted;
56-
println!("{:>10.1} {:>10.1} {:>10.1}", actual, predicted, error);
56+
println!("{actual:>10.1} {predicted:>10.1} {error:>10.1}");
5757
}
5858

5959
// Calculate metrics
@@ -62,12 +62,13 @@ fn main() {
6262
let mae_val = mae(&predictions, &y);
6363

6464
println!("\nModel Performance:");
65-
println!(" R² Score: {:.4}", r2);
66-
println!(" MSE: {:.4}", mse_val);
67-
println!(" MAE: {:.4}", mae_val);
65+
println!(" R² Score: {r2:.4}");
66+
println!(" MSE: {mse_val:.4}");
67+
println!(" MAE: {mae_val:.4}");
6868

6969
// Predict on new house
70-
let new_house = Matrix::from_vec(1, 4, vec![1900.0, 4.0, 2.0, 12.0]).unwrap();
70+
let new_house =
71+
Matrix::from_vec(1, 4, vec![1900.0, 4.0, 2.0, 12.0]).expect("Example data should be valid");
7172
let predicted_price = model.predict(&new_house);
7273
println!("\nNew House Prediction:");
7374
println!(" Features: 1900 sqft, 4 bed, 2 bath, 12 years old");

examples/community_detection.rs

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
3838
for (i, community) in communities.iter().enumerate() {
3939
println!(" Community {}: {:?}", i + 1, community);
4040
}
41-
println!("Modularity: {:.3}\n", modularity);
41+
println!("Modularity: {modularity:.3}\n");
4242

4343
// Example 2: Social Network (Karate Club Style)
4444
println!("\nExample 2: Social Network Clustering");
@@ -64,7 +64,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
6464
for (i, community) in communities2.iter().enumerate() {
6565
println!(" Community {}: {:?}", i + 1, community);
6666
}
67-
println!("Modularity: {:.3}", modularity2);
67+
println!("Modularity: {modularity2:.3}");
6868
println!(
6969
"Bridge node (3) connects communities: {}",
7070
if communities2.len() >= 2 {
@@ -97,7 +97,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
9797
for (i, community) in communities3.iter().enumerate() {
9898
println!(" Community {}: {:?}", i + 1, community);
9999
}
100-
println!("Modularity: {:.3}", modularity3);
100+
println!("Modularity: {modularity3:.3}");
101101
println!("Disconnected components are correctly separated\n");
102102

103103
// Example 4: Modularity Comparison
@@ -113,15 +113,12 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
113113
let bad_mod = g3.modularity(&bad_partition);
114114

115115
println!("Good partition (by components):");
116-
println!(" {:?}", good_partition);
117-
println!(" Modularity: {:.3}", good_mod);
116+
println!(" {good_partition:?}");
117+
println!(" Modularity: {good_mod:.3}");
118118
println!("\nBad partition (all separate):");
119-
println!(" {:?}", bad_partition);
120-
println!(" Modularity: {:.3}", bad_mod);
121-
println!(
122-
"\nLouvain found modularity: {:.3} (should match good partition)",
123-
modularity3
124-
);
119+
println!(" {bad_partition:?}");
120+
println!(" Modularity: {bad_mod:.3}");
121+
println!("\nLouvain found modularity: {modularity3:.3} (should match good partition)");
125122

126123
// Example 5: Complete Graph (Single Community)
127124
println!("\n\nExample 5: Complete Graph");
@@ -137,7 +134,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
137134
communities4.len()
138135
);
139136
println!("Community: {:?}", communities4[0]);
140-
println!("Modularity: {:.3}", modularity4);
137+
println!("Modularity: {modularity4:.3}");
141138
println!("Complete graphs have Q ≈ 0 (no community structure)\n");
142139

143140
println!("=== Analysis Complete ===");

examples/cross_validation.rs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ fn train_test_split_example() {
4040
let x_data: Vec<f32> = (0..100).map(|i| i as f32).collect();
4141
let y_data: Vec<f32> = x_data.iter().map(|&x| 3.0 * x + 2.0).collect();
4242

43-
let x = Matrix::from_vec(100, 1, x_data).unwrap();
43+
let x = Matrix::from_vec(100, 1, x_data).expect("Example data should be valid");
4444
let y = Vector::from_vec(y_data);
4545

4646
// Split 80/20
@@ -66,11 +66,11 @@ fn train_test_split_example() {
6666
let train_score = model.score(&x_train, &y_train);
6767
let test_score = model.score(&x_test, &y_test);
6868

69-
println!("\n Training R²: {:.4}", train_score);
70-
println!(" Test R²: {:.4}", test_score);
69+
println!("\n Training R²: {train_score:.4}");
70+
println!(" Test R²: {test_score:.4}");
7171

7272
let generalization_gap = (train_score - test_score).abs();
73-
println!(" Generalization gap: {:.4}", generalization_gap);
73+
println!(" Generalization gap: {generalization_gap:.4}");
7474

7575
if generalization_gap < 0.05 {
7676
println!(" ✓ Model generalizes well!");
@@ -84,7 +84,7 @@ fn kfold_example() {
8484
let x_data: Vec<f32> = (0..50).map(|i| i as f32).collect();
8585
let y_data: Vec<f32> = x_data.iter().map(|&x| 2.0 * x + 1.0).collect();
8686

87-
let x = Matrix::from_vec(50, 1, x_data).unwrap();
87+
let x = Matrix::from_vec(50, 1, x_data).expect("Example data should be valid");
8888
let y = Vector::from_vec(y_data);
8989

9090
// 5-Fold cross-validation
@@ -132,16 +132,16 @@ fn kfold_example() {
132132

133133
println!("\n Cross-Validation Results:");
134134
println!(" -------------------------");
135-
println!(" Mean R²: {:.4} ± {:.4}", mean_score, std_dev);
135+
println!(" Mean R²: {mean_score:.4} ± {std_dev:.4}");
136136
println!(
137137
" Min R²: {:.4}",
138-
fold_scores.iter().cloned().fold(f32::INFINITY, f32::min)
138+
fold_scores.iter().copied().fold(f32::INFINITY, f32::min)
139139
);
140140
println!(
141141
" Max R²: {:.4}",
142142
fold_scores
143143
.iter()
144-
.cloned()
144+
.copied()
145145
.fold(f32::NEG_INFINITY, f32::max)
146146
);
147147

@@ -155,7 +155,7 @@ fn cross_validate_example() {
155155
let x_data: Vec<f32> = (0..100).map(|i| i as f32).collect();
156156
let y_data: Vec<f32> = x_data.iter().map(|&x| 4.0 * x - 3.0).collect();
157157

158-
let x = Matrix::from_vec(100, 1, x_data).unwrap();
158+
let x = Matrix::from_vec(100, 1, x_data).expect("Example data should be valid");
159159
let y = Vector::from_vec(y_data);
160160

161161
// Create model and cross-validation splitter

0 commit comments

Comments
 (0)