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
pub mod load;
pub mod store;

#[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct ProposalId(pub i32);

#[derive(Debug)]
pub struct AlignmentReviews(pub Vec<Review>);
pub struct AlignmentScore(f64);
#[derive(Debug)]
pub struct FeasibilityReviews(pub Vec<Review>);
pub struct FeasibilityScore(f64);
#[derive(Debug)]
pub struct AuditabilityReviews(pub Vec<Review>);
pub struct AuditabilityScore(f64);

pub fn calc_score(
    allocated_weight: f64,
    not_allocated_weight: f64,
    alignment_reviews: &AlignmentReviews,
    feasibility_reviews: &FeasibilityReviews,
    auditability_review: &AuditabilityReviews,
) -> Result<(AlignmentScore, FeasibilityScore, AuditabilityScore), Error> {
    let alignment_score = AlignmentScore(weighted_avarage_score(
        allocated_weight,
        not_allocated_weight,
        &alignment_reviews.0,
    )?);
    let feasibility_score = FeasibilityScore(weighted_avarage_score(
        allocated_weight,
        not_allocated_weight,
        &feasibility_reviews.0,
    )?);
    let auditability_score = AuditabilityScore(weighted_avarage_score(
        allocated_weight,
        not_allocated_weight,
        &auditability_review.0,
    )?);

    Ok((alignment_score, feasibility_score, auditability_score))
}

#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[error("Invalid allocated or not allocated weights, the sum of them should be less than 1.0. Got {0} and {1}")]
    InvalidWeights(f64, f64),
}

#[derive(Debug)]
pub struct Review {
    rating: u32,
    allocated: bool,
}

fn review_weight(weight: f64, reviews_amount: usize) -> f64 {
    if reviews_amount != 0 {
        weight / reviews_amount as f64
    } else {
        0.0
    }
}

/// weighted average score calculation
fn weighted_avarage_score(
    allocated_weight: f64,
    not_allocated_weight: f64,
    reviews: &[Review],
) -> Result<f64, Error> {
    if allocated_weight + not_allocated_weight > 1.0 {
        return Err(Error::InvalidWeights(
            allocated_weight,
            not_allocated_weight,
        ));
    }

    let mut allocated_count = 0;
    let mut not_allocated_count = 0;

    let mut total_allocated_rating = 0;
    let mut total_not_allocated_rating = 0;
    for review in reviews {
        if review.allocated {
            allocated_count += 1;

            total_allocated_rating += review.rating;
        } else {
            not_allocated_count += 1;

            total_not_allocated_rating += review.rating;
        }
    }

    let allocated_weight = review_weight(allocated_weight, allocated_count);
    let not_allocated_weight = review_weight(not_allocated_weight, not_allocated_count);

    let mut res = (total_allocated_rating as f64 * allocated_weight
        + total_not_allocated_rating as f64 * not_allocated_weight)
        / (allocated_weight * allocated_count as f64
            + not_allocated_weight * not_allocated_count as f64);

    // round to 1 decimal place
    res = (10.0 * res).round() / 10.0;
    Ok(res)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn review_weight_test() {
        let total_weight = 0.2;
        let reviews_amount = 5;
        let result = review_weight(total_weight, reviews_amount);
        assert_eq!(result, 0.04);

        let total_weight = 0.8;
        let reviews_amount = 2;
        let result = review_weight(total_weight, reviews_amount);
        assert_eq!(result, 0.4);
    }

    #[test]
    fn weighted_score_test_1() {
        let allocated_weight = 0.8;
        let not_allocated_weight = 0.2;

        let reviews = vec![
            Review {
                rating: 5,
                allocated: false,
            },
            Review {
                rating: 5,
                allocated: false,
            },
            Review {
                rating: 5,
                allocated: false,
            },
            Review {
                rating: 5,
                allocated: false,
            },
            Review {
                rating: 5,
                allocated: false,
            },
            Review {
                rating: 2,
                allocated: true,
            },
            Review {
                rating: 2,
                allocated: true,
            },
        ];

        let result =
            weighted_avarage_score(allocated_weight, not_allocated_weight, &reviews).unwrap();
        assert_eq!(result, 2.6);

        assert!(weighted_avarage_score(0.5, 0.6, &[]).is_err());
    }

    #[test]
    fn weighted_score_test_2() {
        let allocated_weight = 0.7;
        let not_allocated_weight = 0.3;

        let reviews = vec![
            Review {
                rating: 1,
                allocated: false,
            },
            Review {
                rating: 2,
                allocated: false,
            },
            Review {
                rating: 3,
                allocated: false,
            },
            Review {
                rating: 4,
                allocated: false,
            },
            Review {
                rating: 5,
                allocated: false,
            },
            Review {
                rating: 6,
                allocated: true,
            },
            Review {
                rating: 8,
                allocated: true,
            },
        ];

        let result =
            weighted_avarage_score(allocated_weight, not_allocated_weight, &reviews).unwrap();
        // To be precise the result should be `5.799999999999999`, but we are rounding to 1 decimal place
        assert_eq!(result, 5.8);
    }

    #[test]
    fn weighted_score_test_3() {
        let allocated_weight = 0.7;
        let not_allocated_weight = 0.3;

        let reviews = vec![
            Review {
                rating: 1,
                allocated: false,
            },
            Review {
                rating: 2,
                allocated: false,
            },
            Review {
                rating: 3,
                allocated: false,
            },
            Review {
                rating: 4,
                allocated: false,
            },
            Review {
                rating: 5,
                allocated: false,
            },
            Review {
                rating: 6,
                allocated: true,
            },
            Review {
                rating: 7,
                allocated: true,
            },
        ];

        let result =
            weighted_avarage_score(allocated_weight, not_allocated_weight, &reviews).unwrap();
        // To be precise the result should be `5.449999999999999`, but we are rounding to 1 decimal place
        assert_eq!(result, 5.4);
    }

    #[test]
    fn full_test() {
        let allocated_weight = 0.8;
        let not_allocated_weight = 0.2;

        let proposals_file =
            std::path::PathBuf::from("src/proposal_score/test_data/proposals.json");
        let reviews_file =
            std::path::PathBuf::from("src/proposal_score/test_data/reviews-example.csv");

        let reviews = load::load_reviews_from_csv(&reviews_file).unwrap();
        let mut proposals = load::load_proposals_from_json(&proposals_file).unwrap();

        for (proposal_id, (alignment_reviews, feasibility_reviews, auditability_reviews)) in reviews
        {
            let (alignment_score, feasibility_score, auditability_score) = calc_score(
                allocated_weight,
                not_allocated_weight,
                &alignment_reviews,
                &feasibility_reviews,
                &auditability_reviews,
            )
            .unwrap();

            if let Some(proposal) = proposals.get_mut(&proposal_id) {
                store::store_score_into_proposal(
                    proposal,
                    alignment_score,
                    feasibility_score,
                    auditability_score,
                )
                .unwrap();
            }
        }

        store::store_proposals_into_file(&proposals_file, proposals.into_values().collect())
            .unwrap();
    }
}