ningshuxia
2025-04-16 ed113213fc94c3d9886ea08dfddd09d08d9ba7d5
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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
using MathNet.Numerics.Distributions;
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Double;
 
namespace IStation.Test
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var bll = new BLL.StationSignalRecordPacket();
            var projectId = 661070185922629;
            IStation.SettingsD.Project.ID = projectId;
            var monitorDataSourcesId = 606203941007429;
            var dateStart = new DateTime(2024, 1, 1);
            var dateEnd = new DateTime(2025, 1, 1);
            var stationDict = new Dictionary<int, long>();
            stationDict.Add(1, 462958406303813);
            stationDict.Add(2, 462958422204485);
             
 
            var ptFilterList = new List<PointViewModel>();
            foreach (var station in stationDict)
            {
                var stationIndex = station.Key;
                var stationId = station.Value;
                var packets = bll.Get(monitorDataSourcesId, stationId);
                var ptList = new List<PointViewModel>();
 
                var records = packets.SelectMany(x => x.StationSignalRecords).ToList();
                foreach (var x in records)
                {
                    if (x.TotalPressure > 0 && x.TotalFlow > 0)
                    {
                        if (stationIndex==2&& Math.Abs(x.DiffFlow) > 5000)
                        {
                            continue;
                        }
                        ptList.Add(new PointViewModel(x.Time, x.TotalFlow, x.TotalPressure, x.DiffFlow, stationIndex));
                    }
                }
           
 
                var newPtList = DynamicThresholdProcessor.Filter(ptList);
                ptFilterList.AddRange(newPtList);
            }
 
 
            var recordList = new List<RecordViewModel>();
            var timeGroup = ptFilterList.GroupBy(x => x.Time);
            foreach (var group in timeGroup)
            {
                if (group.Count() < 2)
                    continue;
                var record = new RecordViewModel
                {
                    Time = group.Key
                };
                foreach (var item in group)
                {
                    if (item.Index == 1)
                    {
                        record.Flow1 = item.X;
                        record.Pressure1 = item.Y;
                    }
                    else
                    {
                        record.Flow2 = item.X;
                        record.Pressure2 = item.Y;
                        record.FlowDiff2 = item.Diff;
                    }
                }
 
                recordList.Add(record);
            }
 
            var fullPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "csv");
            if (!Directory.Exists(fullPath))
            {
                Directory.CreateDirectory(fullPath);
            }
 
 
            {
 
                string filePath = Path.Combine(fullPath, "all.csv");
                using StreamWriter writer = new StreamWriter(filePath, false, System.Text.Encoding.UTF8);
 
                writer.WriteLine($"Time,Flow1,Pressure1,Flow2,Pressure2,FlowDiff2");
 
                foreach (var record in recordList)
                {
                    writer.WriteLine($"{record.Time},{record.Flow1},{record.Pressure1},{record.Flow2},{record.Pressure2},{record.FlowDiff2}");
                }
 
            }
 
 
 
            var dataCellList = new List<DataCell>() {
                new() { Name = "Flow1", ValueList = recordList.Select(x => x.Flow1).ToArray() },
                new() { Name = "Pressure1", ValueList = recordList.Select(x => x.Pressure1).ToArray() },
                new() { Name = "Flow2", ValueList = recordList.Select(x => x.Flow2).ToArray() },
                new() { Name = "Pressure2", ValueList = recordList.Select(x => x.Pressure2).ToArray() },
                new() { Name = "FlowDiff2", ValueList = recordList.Select(x => x.FlowDiff2).ToArray() } };
 
 
            var combineList = IStation.Curve.PermutationAndCombination<DataCell>.GetCombination(dataCellList.ToArray(), 2);
            Console.WriteLine("输出文件");
            foreach (var combine in combineList)
            {
                var x = combine[0];
                var y = combine[1];
 
                string filePath = Path.Combine(fullPath, $"{x.Name}-{y.Name}.csv");
                using StreamWriter writer = new StreamWriter(filePath, false, System.Text.Encoding.UTF8);
                var count = x.ValueList.Length;
                writer.WriteLine($"{x.Name},{y.Name}");
                for (int i = 0; i < count; i++)
                {
                    var xv = x.ValueList[i];
                    var yv = y.ValueList[i];
                    writer.WriteLine($"{xv},{yv}");
                } 
            }
 
 
            Console.WriteLine("计算皮尔逊积差相关系数");
            foreach (var combine in combineList)
            {
                var x = combine[0];
                var y = combine[1];
                var (r, pValue) = PearsonTest(x.ValueList, y.ValueList);
                Console.WriteLine($"{x.Name}-{y.Name}: r = {r:F3}");
 
            }
 
            Console.WriteLine("计算斯皮尔曼等级相关系数");
            foreach (var combine in combineList)
            {
                var x = combine[0];
                var y = combine[1];
 
                var (rho, pValue) = SpearmanTest(x.ValueList, y.ValueList);
                Console.WriteLine($"{x.Name}-{y.Name}: ρ = {rho:F3}");
            }
 
            foreach (var combine in combineList)
            {
                var x = combine[0];
                var y = combine[1];
 
                string filePath = Path.Combine(fullPath, $"{x.Name}-{y.Name}.csv");
                using StreamWriter writer = new StreamWriter(filePath, false, System.Text.Encoding.UTF8);
                var count = x.ValueList.Length;
                writer.WriteLine($"{x.Name},{y.Name}");
                for (int i = 0; i < count; i++)
                {
                    var xv = x.ValueList[i];
                    var yv = y.ValueList[i];
                    writer.WriteLine($"{xv},{yv}");
                }
            }
 
            //foreach (var combine in combineList)
            //{
            //    var x = combine[0];
            //    var y = combine[1];
            //    var name = $"{x.Name}-{y.Name}";
            //    if (name.Equals("Flow2-Pressure2") || name.Equals("Pressure1-Pressure2") || name.Equals("Flow1-Pressure2"))
            //    {
            //        NonlinearRegressionExample2.Test(x, y);
            //    }
            //}
 
 
            Console.WriteLine("ok");
            Console.ReadKey();
        }
 
 
 
        /// <summary>
        /// 计算皮尔逊相关系数及显著性p值
        /// </summary>
        public static (double r, double pValue) PearsonTest(double[] x, double[] y)
        {
            // 计算皮尔逊相关系数
            double r = Correlation.Pearson(x, y);
 
            // 计算显著性p值(双尾t检验)
            int n = x.Length;
            double t = r * Math.Sqrt((n - 2) / (1 - r * r));
            var tDist = new StudentT(location: 0, scale: 1, freedom: n - 2);
            double pValue = 2 * (1 - tDist.CumulativeDistribution(Math.Abs(t)));
 
            return (r, pValue);
        }
 
        /// <summary>
        /// 计算斯皮尔曼等级相关系数及显著性p值
        /// </summary>
        public static (double rho, double pValue) SpearmanTest(double[] x, double[] y)
        {
            // 计算斯皮尔曼相关系数
            double rho = Correlation.Spearman(x, y);
 
            // 大样本正态近似法计算p值
            int n = x.Length;
            double z = rho * Math.Sqrt(n - 1);
            var normalDist = new Normal();
            double pValue = 2 * (1 - normalDist.CumulativeDistribution(Math.Abs(z)));
 
            return (rho, pValue);
        }
 
    }
 
 
 
    public class DataCell
    {
        public string Name { get; set; }
        public double[] ValueList { get; set; }
 
    }
 
    public class PointViewModel
    {
        public PointViewModel() { }
        public PointViewModel(DateTime dt, double x, double y, double diff, int index)
        {
            this.Time = dt;
            this.X = x;
            this.Y = y;
            this.Diff = diff;
            this.Index = index;
        }
 
        public PointViewModel(PointViewModel rhs)
        {
            this.Time = rhs.Time;
            this.X = rhs.X;
            this.Y = rhs.Y;
            this.Index = rhs.Index;
            this.Diff = rhs.Diff;
        }
 
        public DateTime Time { get; set; }
        public int Index { get; set; }
        public double X { get; set; }
        public double Y { get; set; }
        public double Diff { get; set; }
 
    }
 
    public class RecordViewModel
    {
        public RecordViewModel() { }
 
        public DateTime Time { get; set; }
 
        public double Flow1 { get; set; }
        public double Pressure1 { get; set; }
 
        public double Flow2 { get; set; }
        public double Pressure2 { get; set; }
 
        public double FlowDiff2 { get; set; }
    }
 
    public static class Correlation
    {
        /// <summary>
        /// 计算皮尔逊积差相关系数
        /// </summary>
        /// <param name="dataA">数据样本A</param>
        /// <param name="dataB">数据样本B</param>
        /// <returns>皮尔逊积差相关系数</returns>
        public static double Pearson(IEnumerable<double> dataA, IEnumerable<double> dataB)
        {
            int n = 0;
            double r = 0.0;
            double meanA = 0;
            double meanB = 0;
            double varA = 0;
            double varB = 0;
 
            using (var ieA = dataA.GetEnumerator())
            using (var ieB = dataB.GetEnumerator())
            {
                while (ieA.MoveNext())
                {
                    if (!ieB.MoveNext())
                    {
                        throw new ArgumentOutOfRangeException("dataB", "数据长度不一致");
                    }
 
                    double currentA = ieA.Current;
                    double currentB = ieB.Current;
 
                    double deltaA = currentA - meanA;
                    double scaleDeltaA = deltaA / ++n;
 
                    double deltaB = currentB - meanB;
                    double scaleDeltaB = deltaB / n;
 
                    meanA += scaleDeltaA;
                    meanB += scaleDeltaB;
 
                    varA += scaleDeltaA * deltaA * (n - 1);
                    varB += scaleDeltaB * deltaB * (n - 1);
                    r += (deltaA * deltaB * (n - 1)) / n;
                }
 
                if (ieB.MoveNext())
                {
                    throw new ArgumentOutOfRangeException("dataA", "数据长度不一致");
                }
            }
 
            return r / Math.Sqrt(varA * varB);
        }
 
        /// <summary>
        /// 计算斯皮尔曼等级相关系数
        /// </summary>
        public static double Spearman(IEnumerable<double> dataA, IEnumerable<double> dataB)
        {
            return Pearson(Rank(dataA), Rank(dataB));
        }
 
        private static IEnumerable<double> Rank(IEnumerable<double> sequence)
        {
            var sorted = new List<double>(sequence);
            sorted.Sort();
 
            return (IEnumerable<double>)sequence.Select(x => (double)sorted.IndexOf(x) + 1);
        }
    }
 
 
 
    public class DynamicThresholdProcessor
    {
 
        public static List<PointViewModel> Filter(List<PointViewModel> ptList)
        {
            var pressures = ptList.Select(p => p.Y).ToList();
 
            // 计算统计量
            var (mean, stdDev) = CalculateStats(pressures);
            double skewness = CalculateSkewness(pressures);
            // 动态调整σ倍数
            double sigmaMultiplier = CalculateSigmaMultiplier(skewness);
            sigmaMultiplier = 3;
 
 
            // 计算边界
            double lower = mean - sigmaMultiplier * stdDev;
            double upper = mean + sigmaMultiplier * stdDev;
 
            return ptList.Where(p => p.Y >= lower && p.Y <= upper).ToList();
        }
 
 
        // 核心统计计算
        private static (double mean, double stdDev) CalculateStats(List<double> values)
        {
            double mean = values.Average();
            double stdDev = Math.Sqrt(values.Sum(v => Math.Pow(v - mean, 2)) / (values.Count - 1));
            return (mean, stdDev);
        }
 
        // 偏度计算(Pearson's moment coefficient)
        private static double CalculateSkewness(List<double> values)
        {
            double mean = values.Average();
            double std = CalculateStats(values).stdDev;
            double sum = values.Sum(v => Math.Pow((v - mean) / std, 3));
            return (sum * values.Count) / ((values.Count - 1) * (values.Count - 2));
        }
 
        // 动态σ倍数计算规则
        private static double CalculateSigmaMultiplier(double skewness)
        {
 
            return skewness switch
            {
                > 1.0 => 2.0,    // 强正偏态
                > 0.5 => 2.5,
                > -0.5 => 3.0,   // 近似正态
                > -1.0 => 3.5,
                _ => 4.0    // 强负偏态
            };
        }
 
    }
 
 
 
    public class NonlinearRegressionExample
    {
        //static void Main(string[] args)
        //{
        //    // 示例数据:Flow1 和 Pressure1
        //    double[] flow1 = { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0 };
        //    double[] pressure1 = { 2.1, 4.5, 6.8, 9.2, 11.5, 13.8, 16.1, 18.4, 20.7, 23.0 };
 
        //    // 多项式回归的阶数(例如,二次多项式)
        //    int degree = 2;
 
        //    // 拟合多项式回归模型
        //    double[] coefficients = FitPolynomial(flow1, pressure1, degree);
 
        //    // 输出回归系数
        //    Console.WriteLine("多项式回归系数:");
        //    for (int i = 0; i <= degree; i++)
        //    {
        //        Console.WriteLine($"系数 {i}: {coefficients[i]}");
        //    }
 
        //    // 使用模型进行预测
        //    double xNew = 11.0;
        //    double yPredicted = PredictPolynomial(xNew, coefficients);
        //    Console.WriteLine($"\n当 Flow1 = {xNew} 时,预测的 Pressure1 = {yPredicted}");
 
        //    // 计算 R² 和 MSE
        //    double rSquared = CalculateRSquared(flow1, pressure1, coefficients);
        //    double mse = CalculateMSE(flow1, pressure1, coefficients);
        //    Console.WriteLine($"\nR² = {rSquared}");
        //    Console.WriteLine($"MSE = {mse}");
        //}
 
        public static void Test(DataCell xCell, DataCell yCell)
        {
            var x = xCell.ValueList.ToArray();
            var y = yCell.ValueList.ToArray();
 
            // 多项式回归的阶数(例如,二次多项式)
            int degree = 4;
 
            // 拟合多项式回归模型
            double[] coefficients = FitPolynomial(x, y, degree);
 
            // 输出回归系数
            Console.WriteLine("多项式回归系数:");
            for (int i = 0; i <= degree; i++)
            {
                Console.WriteLine($"系数 {i}: {coefficients[i]}");
            }
 
            // 使用模型进行预测
            double xNew = x.Average();
            double yPredicted = PredictPolynomial(xNew, coefficients);
            Console.WriteLine($"\n当 {xCell.Name} = {xNew} 时,预测的 {yCell.Name} = {yPredicted}");
 
            // 计算 R² 和 MSE
            double rSquared = CalculateRSquared(x, y, coefficients);
            double mse = CalculateMSE(x, y, coefficients);
            Console.WriteLine($"\nR² = {rSquared}");
            Console.WriteLine($"MSE = {mse}");
 
            Console.WriteLine();
            Console.WriteLine();
 
        }
 
        // 多项式回归拟合
        public static double[] FitPolynomial(double[] x, double[] y, int degree)
        {
            // 构建设计矩阵
            Matrix<double> X = DenseMatrix.OfArray(new double[x.Length, degree + 1]);
            for (int i = 0; i < x.Length; i++)
            {
                for (int j = 0; j <= degree; j++)
                {
                    X[i, j] = Math.Pow(x[i], j);
                }
            }
 
            // 构建目标向量
            Vector<double> Y = DenseVector.OfArray(y);
 
            // 使用最小二乘法求解
            var qr = X.QR();
            Vector<double> coefficients = qr.Solve(Y);
 
            return coefficients.ToArray();
        }
 
        // 使用多项式模型进行预测
        public static double PredictPolynomial(double x, double[] coefficients)
        {
            double prediction = 0.0;
            for (int i = 0; i < coefficients.Length; i++)
            {
                prediction += coefficients[i] * Math.Pow(x, i);
            }
            return prediction;
        }
 
        // 计算 R²(决定系数)
        public static double CalculateRSquared(double[] x, double[] y, double[] coefficients)
        {
            double yMean = 0.0;
            double ssTotal = 0.0;
            double ssResidual = 0.0;
 
            for (int i = 0; i < y.Length; i++)
            {
                yMean += y[i];
            }
            yMean /= y.Length;
 
            for (int i = 0; i < y.Length; i++)
            {
                double yPredicted = PredictPolynomial(x[i], coefficients);
                ssTotal += Math.Pow(y[i] - yMean, 2);
                ssResidual += Math.Pow(y[i] - yPredicted, 2);
            }
 
            return 1.0 - (ssResidual / ssTotal);
        }
 
        // 计算 MSE(均方误差)
        public static double CalculateMSE(double[] x, double[] y, double[] coefficients)
        {
            double mse = 0.0;
            for (int i = 0; i < y.Length; i++)
            {
                double yPredicted = PredictPolynomial(x[i], coefficients);
                mse += Math.Pow(y[i] - yPredicted, 2);
            }
            return mse / y.Length;
        }
    }
 
 
 
    class NonlinearRegressionExample2
    {
        //static void Main(string[] args)
        //{
        //    // 示例数据:Flow 和 Pressure
        //    double[] flow = { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0 };
        //    double[] pressure = { 2.1, 4.5, 6.8, 9.2, 11.5, 13.8, 16.1, 18.4, 20.7, 23.0 };
 
        //    // 指数回归
        //    double[] exponentialCoefficients = FitExponentialRegression(flow, pressure);
        //    Console.WriteLine("指数回归系数:");
        //    Console.WriteLine($"a = {Math.Exp(exponentialCoefficients[0])}");
        //    Console.WriteLine($"b = {exponentialCoefficients[1]}");
 
        //    double flowNew = 11.0;
        //    double pressurePredictedExponential = PredictExponential(flowNew, exponentialCoefficients);
        //    Console.WriteLine($"\n当 Flow = {flowNew} 时,指数回归预测的 Pressure = {pressurePredictedExponential}");
 
        //    // 对数回归
        //    double[] logarithmicCoefficients = FitLogarithmicRegression(flow, pressure);
        //    Console.WriteLine("\n对数回归系数:");
        //    Console.WriteLine($"a = {logarithmicCoefficients[0]}");
        //    Console.WriteLine($"b = {logarithmicCoefficients[1]}");
 
        //    double pressurePredictedLogarithmic = PredictLogarithmic(flowNew, logarithmicCoefficients);
        //    Console.WriteLine($"\n当 Flow = {flowNew} 时,对数回归预测的 Pressure = {pressurePredictedLogarithmic}");
 
        //    // 模型评估
        //    double rSquaredExponential = CalculateRSquaredExponential(flow, pressure, exponentialCoefficients);
        //    double mseExponential = CalculateMSEExponential(flow, pressure, exponentialCoefficients);
        //    Console.WriteLine($"\n指数回归模型评估:");
        //    Console.WriteLine($"R² = {rSquaredExponential}");
        //    Console.WriteLine($"MSE = {mseExponential}");
 
        //    double rSquaredLogarithmic = CalculateRSquaredLogarithmic(flow, pressure, logarithmicCoefficients);
        //    double mseLogarithmic = CalculateMSELogarithmic(flow, pressure, logarithmicCoefficients);
        //    Console.WriteLine($"\n对数回归模型评估:");
        //    Console.WriteLine($"R² = {rSquaredLogarithmic}");
        //    Console.WriteLine($"MSE = {mseLogarithmic}");
        //}
 
        public static void Test(DataCell xCell, DataCell yCell)
        {
            // 示例数据:Flow 和 Pressure
            double[] x = xCell.ValueList.ToArray();
            double[] y = yCell.ValueList.ToArray();
 
            // 指数回归
            double[] exponentialCoefficients = FitExponentialRegression(x, y);
            Console.WriteLine("指数回归系数:");
            Console.WriteLine($"a = {Math.Exp(exponentialCoefficients[0])}");
            Console.WriteLine($"b = {exponentialCoefficients[1]}");
 
            double flowNew = x.Average();
            double pressurePredictedExponential = PredictExponential(flowNew, exponentialCoefficients);
            Console.WriteLine($"\n当 {xCell.Name} = {flowNew} 时,指数回归预测的 {yCell.Name} = {pressurePredictedExponential}");
 
            // 对数回归
            double[] logarithmicCoefficients = FitLogarithmicRegression(x, y);
            Console.WriteLine("\n对数回归系数:");
            Console.WriteLine($"a = {logarithmicCoefficients[0]}");
            Console.WriteLine($"b = {logarithmicCoefficients[1]}");
 
            double pressurePredictedLogarithmic = PredictLogarithmic(flowNew, logarithmicCoefficients);
            Console.WriteLine($"\n当 {xCell.Name} = {flowNew} 时,对数回归预测的 {yCell.Name} = {pressurePredictedLogarithmic}");
 
            // 模型评估
            double rSquaredExponential = CalculateRSquaredExponential(x, y, exponentialCoefficients);
            double mseExponential = CalculateMSEExponential(x, y, exponentialCoefficients);
            Console.WriteLine($"\n指数回归模型评估:");
            Console.WriteLine($"R² = {rSquaredExponential}");
            Console.WriteLine($"MSE = {mseExponential}");
 
            double rSquaredLogarithmic = CalculateRSquaredLogarithmic(x, y, logarithmicCoefficients);
            double mseLogarithmic = CalculateMSELogarithmic(x, y, logarithmicCoefficients);
            Console.WriteLine($"\n对数回归模型评估:");
            Console.WriteLine($"R² = {rSquaredLogarithmic}");
            Console.WriteLine($"MSE = {mseLogarithmic}");
        }
 
 
 
        // 指数回归拟合
        static double[] FitExponentialRegression(double[] x, double[] y)
        {
            // 将 y 转换为自然对数
            double[] logY = new double[y.Length];
            for (int i = 0; i < y.Length; i++)
            {
                logY[i] = Math.Log(y[i]);
            }
 
            // 构建设计矩阵
            Matrix<double> X = DenseMatrix.OfArray(new double[x.Length, 2]);
            for (int i = 0; i < x.Length; i++)
            {
                X[i, 0] = 1.0;  // 常数项
                X[i, 1] = x[i];
            }
 
            // 构建目标向量
            Vector<double> Y = DenseVector.OfArray(logY);
 
            // 使用最小二乘法求解
            var qr = X.QR();
            Vector<double> coefficients = qr.Solve(Y);
 
            return coefficients.ToArray();
        }
 
        // 指数回归预测
        static double PredictExponential(double x, double[] coefficients)
        {
            double a = Math.Exp(coefficients[0]);
            double b = coefficients[1];
            return a * Math.Exp(b * x);
        }
 
        // 对数回归拟合
        static double[] FitLogarithmicRegression(double[] x, double[] y)
        {
            // 将 x 转换为自然对数
            double[] logX = new double[x.Length];
            for (int i = 0; i < x.Length; i++)
            {
                logX[i] = Math.Log(x[i]);
            }
 
            // 构建设计矩阵
            Matrix<double> X = DenseMatrix.OfArray(new double[x.Length, 2]);
            for (int i = 0; i < x.Length; i++)
            {
                X[i, 0] = 1.0;  // 常数项
                X[i, 1] = logX[i];
            }
 
            // 构建目标向量
            Vector<double> Y = DenseVector.OfArray(y);
 
            // 使用最小二乘法求解
            var qr = X.QR();
            Vector<double> coefficients = qr.Solve(Y);
 
            return coefficients.ToArray();
        }
 
        // 对数回归预测
        static double PredictLogarithmic(double x, double[] coefficients)
        {
            double a = coefficients[0];
            double b = coefficients[1];
            return a + b * Math.Log(x);
        }
 
        // 计算指数回归的 R²
        static double CalculateRSquaredExponential(double[] x, double[] y, double[] coefficients)
        {
            double yMean = 0.0;
            double ssTotal = 0.0;
            double ssResidual = 0.0;
 
            for (int i = 0; i < y.Length; i++)
            {
                yMean += y[i];
            }
            yMean /= y.Length;
 
            for (int i = 0; i < y.Length; i++)
            {
                double yPredicted = PredictExponential(x[i], coefficients);
                ssTotal += Math.Pow(y[i] - yMean, 2);
                ssResidual += Math.Pow(y[i] - yPredicted, 2);
            }
 
            return 1.0 - (ssResidual / ssTotal);
        }
 
        // 计算指数回归的 MSE
        static double CalculateMSEExponential(double[] x, double[] y, double[] coefficients)
        {
            double mse = 0.0;
            for (int i = 0; i < y.Length; i++)
            {
                double yPredicted = PredictExponential(x[i], coefficients);
                mse += Math.Pow(y[i] - yPredicted, 2);
            }
            return mse / y.Length;
        }
 
        // 计算对数回归的 R²
        static double CalculateRSquaredLogarithmic(double[] x, double[] y, double[] coefficients)
        {
            double yMean = 0.0;
            double ssTotal = 0.0;
            double ssResidual = 0.0;
 
            for (int i = 0; i < y.Length; i++)
            {
                yMean += y[i];
            }
            yMean /= y.Length;
 
            for (int i = 0; i < y.Length; i++)
            {
                double yPredicted = PredictLogarithmic(x[i], coefficients);
                ssTotal += Math.Pow(y[i] - yMean, 2);
                ssResidual += Math.Pow(y[i] - yPredicted, 2);
            }
 
            return 1.0 - (ssResidual / ssTotal);
        }
 
        // 计算对数回归的 MSE
        static double CalculateMSELogarithmic(double[] x, double[] y, double[] coefficients)
        {
            double mse = 0.0;
            for (int i = 0; i < y.Length; i++)
            {
                double yPredicted = PredictLogarithmic(x[i], coefficients);
                mse += Math.Pow(y[i] - yPredicted, 2);
            }
            return mse / y.Length;
        }
    }
 
 
 
}