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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
use json::{JsonValue, object};
use crate::stats::{stdev, stdevp, variance, variancep};

pub struct Spc {
    /// 数据
    pub data: Vec<f64>,
    /// 数据长度
    pub data_len: usize,
    /// 样本分组数量
    pub group_len: usize,
    /// 规格上限
    pub upper: f64,
    /// 规格下限
    pub lower: f64,
    /// 标准值
    pub value: f64,

    /// 最大值
    pub max: f64,
    /// 最小值
    pub min: f64,
    /// 平均值
    pub avg: f64,
    /// 总值
    pub total: f64,
    /// 组均值
    pub group_avg: Vec<f64>,
    /// 组极差
    pub group_range: Vec<f64>,
    /// 组极差-最大
    pub group_range_max: f64,
    /// 组极差-最小
    pub group_range_min: f64,

    /// 组极差-r-均值集合
    pub group_r_avgs: Vec<f64>,
    /// 组极差-x-均值集合
    pub group_x_avgs: Vec<f64>,
    /// 组极差-r-均值
    pub group_r_avg: f64,
    /// 组极差-x-均值
    pub group_x_avg: f64,

    pub group_r_avg_sum: f64,
    pub group_x_avg_sum: f64,

    /// 组极差-合计-集合
    pub group_sums: Vec<f64>,

    /// 组数据
    pub group_data: Vec<Vec<f64>>,
    /// 小数位
    pub decimal: usize,
    /// 能力指数上限(CPU)
    pub cpu: f64,
    /// 能力指数下限(CPL)
    pub cpl: f64,
    /// 控制 A2 系数
    pub a2: f64,
    /// 控制 d2 系数
    pub d2: f64,
    /// 控制 D3 系数
    pub d3: f64,
    /// 控制 D4 系数
    pub d4: f64,

    /// 能力指数 (Cp)
    pub cp: f64,
    /// 过程能力指数 (Cpk)
    pub cpk: f64,
    /// 过程能力比值 (CR)
    pub cr: f64,
    /// 标准差 (n-1)
    pub stdev: f64,
    /// 标准差 (n)
    pub stdevp: f64,
    /// 变差 (n-1)
    pub var: f64,
    /// 变差 (n)
    pub varp: f64,
    /// 性能指数 (PP)
    pub pp: f64,
    /// 性能比率 (PR)
    pub pr: f64,
    /// 性能指数 (PPK)
    pub ppk: f64,

    /// 西格玛
    pub sigma: f64,
    /// 西格玛数组
    pub sigma_list: Vec<f64>,

    /// R 图 UCLr指标
    pub uclr: f64,
    /// R 图 极差值均值
    pub clr: f64,
    /// R 图 LCLr指标
    pub lclr: f64,

    /// X 图 UCLx 指标
    pub uclx: f64,
    /// X 图 CLx 均值指标
    pub clx: f64,
    /// X 图 UCLx 指标
    pub lclx: f64,
}

impl Spc {
    /// 初始化
    ///
    /// * usl 上限值
    /// * lsl 下限值
    /// * value 标准值
    /// * array 测量数据
    /// * group_len 样本组数量
    /// * decimal 小数位
    pub fn new(upper: f64, lower: f64, value: f64, array: Vec<f64>, group_len: usize, decimal: usize) -> Self {
        Self {
            data: array.clone(),
            data_len: array.len(),
            total: 0.0,
            upper,
            value,
            lower,
            // stddev,
            max: 0.0,
            min: 0.0,
            avg: 0.0,
            // cpk,
            // ca: ca * 100.0,
            // cp,
            group_len: group_len.clone(),
            group_avg: vec![],
            group_range: vec![],
            group_range_max: 0.0,
            group_range_min: 0.0,
            group_r_avgs: vec![],
            group_data: vec![],
            decimal,
            cpu: 0.0,
            cpl: 0.0,
            a2: a2(group_len),
            d2: d2(group_len),
            d3: d3(group_len),
            d4: d4(group_len),
            cp: 0.0,
            cpk: 0.0,
            cr: 0.0,
            stdev: 0.0,
            stdevp: 0.0,
            var: 0.0,
            varp: 0.0,
            pp: 0.0,
            pr: 0.0,
            ppk: 0.0,
            sigma: 0.0,
            sigma_list: vec![],
            group_x_avgs: vec![],
            group_r_avg: 0.0,
            group_x_avg: 0.0,
            group_r_avg_sum: 0.0,
            group_x_avg_sum: 0.0,
            group_sums: vec![],
            uclr: 0.0,
            clr: 0.0,
            lclr: 0.0,
            uclx: 0.0,
            clx: 0.0,
            lclx: 0.0,
        }
    }
    pub fn compute(&mut self) -> &mut Self {
        self.max = 0.0;
        self.min = self.data[0].to_string().parse::<f64>().unwrap();
        let mut group_list = vec![];

        for x in self.data.clone() {
            self.total += x.clone();
            if x > self.max.clone() {
                self.max = x.clone();
            }
            if x < self.min.clone() {
                self.min = x.clone();
            }
            group_list.push(x.clone());
            if group_list.len() == self.group_len {
                self.get_group_list_info(group_list.clone());
                self.group_data.push(group_list.clone());
                group_list = vec![];
            }
        }
        // 补数组不够的
        if !group_list.is_empty() {
            self.get_group_list_info(group_list.clone());
            self.group_data.push(group_list.clone());
        }

        self.uclr = self.d4 * self.group_r_avg;
        self.uclr = format!("{0:.1$}", self.uclr, self.decimal).parse::<f64>().unwrap();

        self.clr = self.group_r_avg;
        self.clr = format!("{0:.1$}", self.clr, self.decimal).parse::<f64>().unwrap();

        self.lclr = self.d3 * self.group_r_avg;
        self.lclr = format!("{0:.1$}", self.lclr, self.decimal).parse::<f64>().unwrap();


        self.uclx = self.group_x_avg + self.a2 * self.group_r_avg;
        self.uclx = format!("{0:.1$}", self.uclx, self.decimal).parse::<f64>().unwrap();

        self.clx = self.group_x_avg;
        self.clx = format!("{0:.1$}", self.clx, self.decimal).parse::<f64>().unwrap();

        self.lclx = self.group_x_avg - self.a2 * self.group_r_avg;
        self.lclx = format!("{0:.1$}", self.lclx, self.decimal).parse::<f64>().unwrap();

        self.cp = (self.upper - self.lower) / (6.0 * (self.group_r_avg / self.d2));

        let k = (self.value - self.group_x_avg).abs() / ((self.upper - self.lower) / 2.0);
        self.cpk = (1.0 - k) * self.cp;

        self.cp = format!("{0:.1$}", self.cp, self.decimal).parse::<f64>().unwrap();
        self.cpk = format!("{0:.1$}", self.cpk, self.decimal).parse::<f64>().unwrap();


        return self;
        let mut sigma_t = 0.0;
        for sigma in self.sigma_list.clone() {
            sigma_t += sigma;
        }
        self.sigma = sigma_t / self.sigma_list.len() as f64;

        // self.group_range_max = self.avg_r * 2.282;
        // self.group_range_min = 0.0;
        // self.group_range_max = format!("{0:.1$}", self.group_range_max, self.decimal).parse::<f64>().unwrap();

        // 平均值
        self.avg = format!("{0:.1$}", self.total / self.data_len as f64, self.decimal).parse::<f64>().unwrap();
        self.total = format!("{0:.1$}", self.total, self.decimal).parse::<f64>().unwrap();


        self.cpu = (self.upper - self.avg) / (3.0 * self.sigma);
        self.cpu = format!("{0:.1$}", self.cpu, self.decimal).parse::<f64>().unwrap();

        self.cpl = (self.avg - self.lower) / (3.0 * self.sigma);
        self.cpl = format!("{0:.1$}", self.cpl, self.decimal).parse::<f64>().unwrap();

        self.cpk = self.cpl.min(self.cpu);

        self.cp = (self.upper - self.lower) / (6.0 * self.sigma);
        self.cp = format!("{0:.1$}", self.cp, self.decimal).parse::<f64>().unwrap();

        self.cr = 6.0 * self.sigma / (self.upper - self.lower);
        self.cr = format!("{0:.1$}", self.cr, self.decimal).parse::<f64>().unwrap();

        self.stdev = stdev(self.data.clone());
        self.stdev = format!("{0:.1$}", self.stdev, self.decimal).parse::<f64>().unwrap();

        self.stdevp = stdevp(self.data.clone());
        self.stdevp = format!("{0:.1$}", self.stdevp, self.decimal).parse::<f64>().unwrap();


        self.pp = (self.upper - self.lower) / (6.0 * self.sigma);
        self.pp = format!("{0:.1$}", self.pp, self.decimal).parse::<f64>().unwrap();

        self.pr = (6.0 * self.sigma) / (self.upper - self.lower);
        self.pr = format!("{0:.1$}", self.pr, self.decimal).parse::<f64>().unwrap();

        let ppu = (self.upper - self.avg) / (3.0 * self.sigma);
        let ppl = (self.avg - self.lower) / (3.0 * self.sigma);

        self.ppk = ppu.min(ppl);
        self.ppk = format!("{0:.1$}", self.ppk, self.decimal).parse::<f64>().unwrap();

        self.var = variance(self.data.clone());
        self.var = format!("{0:.1$}", self.var, self.decimal).parse::<f64>().unwrap();

        self.varp = variancep(self.data.clone());
        self.varp = format!("{0:.1$}", self.varp, self.decimal).parse::<f64>().unwrap();

        self.sigma = format!("{0:.1$}", self.sigma, self.decimal).parse::<f64>().unwrap();

        self
    }
    fn get_group_list_info(&mut self, mut group_list: Vec<f64>) {
        group_list.sort_by(|a, b| a.partial_cmp(b).unwrap());

        let max = group_list.last().unwrap();
        let min = group_list.first().unwrap();
        self.group_r_avgs.push(max - min);
        self.group_r_avg_sum = self.group_r_avgs.iter().sum();
        self.group_r_avg = self.group_r_avg_sum / self.group_r_avgs.len() as f64;

        let mut total = 0.0;
        for group in group_list.clone() {
            total += group;
        }
        self.group_sums.push(total);

        // self.sigma_list.push(total / group_list.len() as f64 / d2(group_list.len()));

        self.group_x_avgs.push(total / group_list.len() as f64);
        self.group_x_avg_sum = self.group_x_avgs.iter().sum();
        self.group_x_avg = self.group_x_avg_sum / self.group_x_avgs.len() as f64;

        // let binding = format!("{0:.1$}", max, self.decimal.clone()).parse::<f64>().unwrap();
        // max = &binding;
        // let binding = format!("{0:.1$}", min, self.decimal.clone()).parse::<f64>().unwrap();
        // min = &*&binding;

        // let binding = format!("{0:.1$}", max, self.decimal.clone()).parse::<f64>().unwrap();
        // self.group_range_max = binding;
        // let binding = format!("{0:.1$}", min, self.decimal.clone()).parse::<f64>().unwrap();
        // self.group_range_min = *&binding;


        // let binding = format!("{0:.1$}", range, self.decimal.clone()).parse::<f64>().unwrap();
        // range = *&binding;
        // let mut avg = total / group_list.len() as f64;
        // let binding = format!("{0:.1$}", avg, self.decimal.clone()).parse::<f64>().unwrap();
        // avg = binding;

        // let mut group_range_avg_total = 0.0;
        // for item in self.group_range.iter() {
        //     group_range_avg_total += item;
        // }
        // self.group_range_avg = group_range_avg_total / self.group_range.len() as f64;
        // self.group_avg.push(self.group_range_avg);
    }

    pub fn xbar_r(&self) -> JsonValue {
        object! {
            data:self.group_r_avgs.clone(),
            UCLR:self.uclr,
            CLR:self.clr,
            LCLR:self.lclr
        }
    }
    pub fn xbar_x(&self) -> JsonValue {
        object! {
            data:self.group_x_avgs.clone(),
            UCLX:self.uclx,
            CLX:self.clx,
            LCLX:self.lclx
        }
    }
    pub fn cpk_rating_criteria(&self) -> (&'static str, &'static str) {
        if self.cpk >= 2.0 {
            return ("A++", "特优,可考虑降低成本。");
        } else if 1.67 <= self.cpk && self.cpk < 2.0 {
            return ("A+", "优,应当保持之。");
        } else if 1.33 <= self.cpk && self.cpk < 1.67 {
            ("A", "良,能力好,状态稳定,但应尽力提升到A+级。")
        } else if 1.00 <= self.cpk && self.cpk < 1.33 {
            ("B", "一般,制程因素稍有变异即有生产不良的危险,应利用各种资源及方法将其提升为A级。")
        } else if 0.67 <= self.cpk && self.cpk < 1.00 {
            ("C", "差,制程不良较多。须提升其能力。")
        } else {
            ("D", "不可接受,其能力太差,应考虑重新整改设计制程。")
        }
    }
    pub fn cp_rating_criteria(&self) -> (&'static str, &'static str) {
        if self.cp >= 1.67 {
            ("A+", "无缺点,可考虑降低成本。")
        } else if 1.33 <= self.cp && self.cp <= 1.67 {
            ("A", "状态良好维持现状。")
        } else if 1.00 <= self.cp && self.cp <= 1.33 {
            ("B", "可以改进为A级。")
        } else if 0.67 <= self.cp && self.cp <= 1.00 {
            ("C", "制程不良较多。须提升能力。")
        } else {
            ("D", "制程能力好差,应考虑重新整改设计制程。")
        }
    }
}

/// 计量型 X-R图 A2
fn a2(len: usize) -> f64 {
    match len {
        2 => 1.880,
        3 => 1.023,
        4 => 0.729,
        5 => 0.577,
        6 => 0.483,
        7 => 0.149,
        8 => 0.373,
        9 => 0.337,
        10 => 0.308,
        11 => 0.285,
        12 => 0.266,
        13 => 0.249,
        14 => 0.235,
        15 => 0.223,
        16 => 0.212,
        17 => 0.203,
        18 => 0.194,
        19 => 0.187,
        20 => 0.180,
        21 => 0.173,
        22 => 0.167,
        23 => 0.162,
        24 => 0.157,
        25 => 0.153,
        _ => 0.0
    }
}

/// 计量型 X-R图 d2
fn d2(len: usize) -> f64 {
    match len {
        2 => 1.128,
        3 => 1.693,
        4 => 2.059,
        5 => 2.326,
        6 => 2.534,
        7 => 2.704,
        8 => 2.847,
        9 => 2.970,
        10 => 3.078,
        11 => 3.173,
        12 => 3.258,
        13 => 3.336,
        14 => 3.407,
        15 => 3.472,
        16 => 3.532,
        17 => 3.588,
        18 => 3.640,
        19 => 3.689,
        20 => 3.735,
        21 => 3.778,
        22 => 3.819,
        23 => 3.858,
        24 => 3.895,
        25 => 3.931,
        _ => 0.0
    }
}

/// 计量型 X-R图 D3 计算控制限用的系数 LCLr
fn d3(len: usize) -> f64 {
    match len {
        7 => 0.076,
        8 => 0.136,
        9 => 0.184,
        10 => 0.223,
        11 => 0.256,
        12 => 0.283,
        13 => 0.307,
        14 => 0.328,
        15 => 0.347,
        16 => 0.363,
        17 => 0.738,
        18 => 0.391,
        19 => 0.403,
        20 => 0.415,
        21 => 0.425,
        22 => 0.434,
        23 => 0.443,
        24 => 0.451,
        25 => 0.459,
        _ => 0.0
    }
}

/// 计量型 X-R图 D4 计算控制限用的系数 UCLr
fn d4(len: usize) -> f64 {
    match len {
        2 => 3.267,
        3 => 2.574,
        4 => 2.282,
        5 => 2.114,
        6 => 2.004,
        7 => 1.924,
        8 => 1.864,
        9 => 1.816,
        10 => 1.777,
        11 => 1.744,
        12 => 1.717,
        13 => 1.693,
        14 => 1.672,
        15 => 1.653,
        16 => 1.637,
        17 => 1.622,
        18 => 1.608,
        19 => 1.597,
        20 => 1.585,
        21 => 1.575,
        22 => 1.566,
        23 => 1.557,
        24 => 1.548,
        25 => 1.541,
        _ => 0.0
    }
}