Repository navigation
Expand file tree
/
Copy pathPointProcessModel.cs
More file actions
3004 lines (2660 loc) · 128 KB
/
Copy pathPointProcessModel.cs
File metadata and controls
3004 lines (2660 loc) · 128 KB
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
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using Numerics;
using Numerics.Data;
using Numerics.Data.Statistics;
using Numerics.Distributions;
using Numerics.Mathematics.Integration;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Xml.Linq;
namespace RMC.BestFit.Models
{
/// <summary>
/// Point-process model for peaks-over-threshold (POT) data using competing GEV distributions.
/// </summary>
/// <remarks>
/// <para>
/// Authors:
/// Haden Smith, USACE Risk Management Center, cole.h.smith@usace.army.mil
/// </para>
/// <para>
/// The <see cref="PointProcessModel"/> represents POT data with an
/// underlying Poisson process for exceedance times and GEV (or seasonal
/// GEV) models for magnitudes. It supports:
/// </para>
/// <list type="bullet">
/// <item><description>
/// Non-seasonal point process (single GEV).
/// </description></item>
/// <item><description>
/// Seasonal point process (two GEVs with block-day based seasons).
/// </description></item>
/// <item><description>
/// Parameter priors and optional quantile priors in a Bayesian framework.
/// </description></item>
/// </list>
/// </remarks>
public class PointProcessModel : UnivariateDistributionModelBase, ISimulatable<double[]>, IUnivariateModel
{
#region Construction
/// <summary>
/// Constructs an empty point-process model with a default
/// (non-seasonal) competing risks distribution.
/// </summary>
public PointProcessModel()
{
SetDistribution();
}
/// <summary>
/// Constructs a point-process model using the specified data frame
/// and competing risks distribution.
/// </summary>
/// <param name="dataFrame">The data frame to fit to.</param>
/// <param name="distribution">The competing risks distribution.</param>
public PointProcessModel(DataFrame dataFrame, CompetingRisks distribution)
{
Distribution = (CompetingRisks)distribution.Clone();
DataFrame = dataFrame;
}
/// <summary>
/// Constructs a point-process model from an XML element and associated
/// data frame.
/// </summary>
/// <param name="dataFrame">The data frame to fit to.</param>
/// <param name="xElement">The XML element to deserialize.</param>
/// <remarks>
/// Saved distribution parameters and model parameters are restored independently; seasonal
/// files may contain annualized distribution values alongside unadjusted seasonal model
/// values. Default-generation setters are reserved for subsequent user edits.
/// </remarks>
public PointProcessModel(DataFrame dataFrame, XElement xElement)
{
// Hydrate serialized state through backing fields before rebuilding derived data.
// Public setters intentionally generate defaults for user edits and must not run here.
_dataFrame = dataFrame;
// Inputs
var thresholdAttr = xElement.Attribute(nameof(Threshold));
if (thresholdAttr != null) double.TryParse(thresholdAttr.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out _threshold);
var totalYearsAttr = xElement.Attribute(nameof(TotalYears));
if (totalYearsAttr != null) double.TryParse(totalYearsAttr.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out _totalYears);
var useDefaultsAttr = xElement.Attribute(nameof(UseDefaults));
if (useDefaultsAttr != null) bool.TryParse(useDefaultsAttr.Value, out _useDefaults);
var totalYearsInferredAttr = xElement.Attribute(nameof(IsTotalYearsInferred));
if (totalYearsInferredAttr != null)
{
bool.TryParse(totalYearsInferredAttr.Value, out _isTotalYearsInferred);
}
else
{
_isTotalYearsInferred = _useDefaults && !HasStoredSourceExposure();
}
_totalYearsExplicit = !_useDefaults;
var isSeasonalAttr = xElement.Attribute(nameof(IsSeasonal));
if (isSeasonalAttr != null) bool.TryParse(isSeasonalAttr.Value, out _isSeasonal);
var timeBlockAttr = xElement.Attribute(nameof(TimeBlock));
if (timeBlockAttr != null) Enum.TryParse(timeBlockAttr.Value, out _timeBlock);
var startMonthAttr = xElement.Attribute(nameof(StartMonth));
if (startMonthAttr != null) int.TryParse(startMonthAttr.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out _startMonth);
// Distribution
var distElement = xElement.Element("Distribution");
if (distElement != null)
_distribution = CompetingRisks.FromXElement(distElement);
// Parameters
var flatPriorsAttr = xElement.Attribute(nameof(UseDefaultFlatPriors));
if (flatPriorsAttr != null) bool.TryParse(flatPriorsAttr.Value, out _useDefaultFlatPriors);
var jeffreysAttr = xElement.Attribute(nameof(UseJeffreysRuleForScale));
if (jeffreysAttr != null) bool.TryParse(jeffreysAttr.Value, out _useJeffreysRuleForScale);
var parms = new List<ModelParameter>();
foreach (XElement p in xElement.Elements(nameof(Parameters)).Elements(nameof(ModelParameter)))
parms.Add(new ModelParameter(p));
Parameters = parms;
// Quantiles
var enableQuantilesAttr = xElement.Attribute(nameof(EnableQuantilePriors));
if (enableQuantilesAttr != null) bool.TryParse(enableQuantilesAttr.Value, out _enableQuantilePriors);
var singleQuantileAttr = xElement.Attribute(nameof(UseSingleQuantile));
if (singleQuantileAttr != null) bool.TryParse(singleQuantileAttr.Value, out _useSingleQuantile);
var quants = new List<QuantilePrior>();
foreach (XElement q in xElement.Elements(nameof(QuantilePriors)).Elements(nameof(QuantilePrior)))
quants.Add(new QuantilePrior(q));
QuantilePriors = quants;
// Rebuild derived state only after every persisted field has been restored, then
// subscribe for the normal edit-time default refresh behavior.
_dataFrame.ProcessThresholdSeries();
_dataFrame.CreateFullTimeSeries();
SetAMSData();
CalculateLambda();
_dataFrame.PropertyChanged += DataFrame_PropertyChanged;
}
#endregion
#region Members
/// <summary>
/// The set of univariate distribution types supported by the point process model.
/// The point process likelihood requires Generalized Extreme Value (GEV) distributions.
/// </summary>
private static readonly HashSet<UnivariateDistributionType> _supportedDistributionTypes = new()
{
UnivariateDistributionType.GeneralizedExtremeValue,
};
/// <summary>
/// Determines whether the specified distribution type is supported by the point process model.
/// </summary>
/// <param name="distributionType">The distribution type to check.</param>
/// <returns><c>true</c> if the distribution type is supported; otherwise, <c>false</c>.</returns>
/// <remarks>
/// The point process model requires all component distributions to be Generalized Extreme Value (GEV).
/// </remarks>
public static bool IsSupportedDistributionType(UnivariateDistributionType distributionType)
{
return _supportedDistributionTypes.Contains(distributionType);
}
private CompetingRisks? _distribution = null;
private DataFrame _amsDataFrame = new DataFrame();
private List<int> _potDays = new List<int>();
private bool _isSeasonal = false;
private TimeBlockWindow _timeBlock = TimeBlockWindow.WaterYear;
private int _startMonth = 10;
private double _threshold = double.NaN;
private double _totalYears = double.NaN;
private bool _useDefaults = true;
private double _lambda = double.NaN;
private bool _isTotalYearsInferred = true;
/// <summary>The latest automatic-initialization sample error, reported through model validation.</summary>
private string? _defaultParameterInitializationError;
/// <summary>
/// Tracks whether automatic exposure updates may replace <see cref="TotalYears"/>.
/// Explicit values remain protected while defaults are disabled; enabling defaults
/// restores source-exposure or event-span inference.
/// </summary>
private bool _totalYearsExplicit = false;
/// <inheritdoc/>
public override DataFrame DataFrame
{
get { return _dataFrame; }
set
{
if (_dataFrame != null)
_dataFrame.PropertyChanged -= DataFrame_PropertyChanged;
_dataFrame = value;
if (_dataFrame != null)
{
_dataFrame.PropertyChanged += DataFrame_PropertyChanged;
_dataFrame.ProcessThresholdSeries();
}
SetAMSData();
if (UseDefaults && _dataFrame != null)
SetDefaultThresholdAndTotalYears(forceTotalYears: true);
else
CalculateLambda();
if (UseDefaultFlatPriors && _dataFrame != null)
SetDefaultParameters();
RaisePropertyChange(nameof(DataFrame));
}
}
/// <summary>
/// Gets or sets the competing risks distribution representing the
/// parent population of exceedances.
/// </summary>
[Category("Inputs")]
[DisplayName("Competing Risks Distribution")]
[Description("The competing risks distribution representing the parent population.")]
[Browsable(true)]
public CompetingRisks? Distribution
{
get { return _distribution; }
set
{
_distribution = value;
RaisePropertyChange(nameof(Distribution));
SetDefaultParameters();
SetDefaultQuantilePriors();
}
}
/// <inheritdoc/>
UnivariateDistributionBase? IUnivariateModel.Distribution => _distribution;
/// <inheritdoc/>
/// <remarks>
/// Peaks-over-threshold models in RMC-BestFit are currently stationary;
/// exceedance intensity and mark distribution parameters are constant.
/// Always returns <c>false</c>.
/// </remarks>
public bool IsNonstationary => false;
/// <summary>
/// Gets the pre-processed annual maximum (or block) data frame derived from the input POT data.
/// </summary>
public DataFrame AMSDataFrame => _amsDataFrame;
/// <summary>
/// Gets the one-based block day for each peaks-over-threshold event.
/// </summary>
public List<int> POTDays => _potDays;
/// <summary>
/// Gets the empirical number of exact POT events per year.
/// </summary>
/// <remarks>
/// This compatibility alias is identical to <see cref="EmpiricalEventRate"/>.
/// It is not the fitted threshold intensity used by the point-process likelihood.
/// </remarks>
public double Lambda => _lambda;
/// <summary>
/// Gets the number of exact observations treated as Poisson POT events.
/// </summary>
/// <remarks>
/// Uncertain, interval, and threshold-count records contribute to the hybrid magnitude
/// likelihood but are not silently converted into occurrence-process events.
/// </remarks>
public int EmpiricalEventCount => DataFrame?.ExactSeries.Count ?? 0;
/// <summary>
/// Gets the empirical exact-event rate, equal to <see cref="EmpiricalEventCount"/> divided
/// by <see cref="TotalYears"/>.
/// </summary>
public double EmpiricalEventRate => _lambda;
/// <summary>
/// Gets the fitted total threshold intensity per year at <see cref="Threshold"/>.
/// </summary>
/// <remarks>
/// In seasonal mode this is the exposure-weighted sum of the two fitted seasonal
/// intensities, which is also the annual rate of the seasonal simulators. Nonseasonal
/// simulation uses the separately documented empirical <see cref="Lambda"/>.
/// </remarks>
public double FittedThresholdIntensity
{
get
{
return TryGetFittedIntensities(out double total, out _, out _, out _, out _)
? total
: double.NaN;
}
}
/// <summary>
/// Gets the fitted, unweighted threshold intensity for seasonal component one.
/// </summary>
public double FittedSeasonOneThresholdIntensity
{
get
{
return IsSeasonal && TryGetFittedIntensities(out _, out double first, out _, out _, out _)
? first
: double.NaN;
}
}
/// <summary>
/// Gets the fitted, unweighted threshold intensity for seasonal component two.
/// </summary>
public double FittedSeasonTwoThresholdIntensity
{
get
{
return IsSeasonal && TryGetFittedIntensities(out _, out _, out double second, out _, out _)
? second
: double.NaN;
}
}
/// <summary>
/// Gets the exposure weight for wrapped seasonal component one.
/// </summary>
public double SeasonOneExposureWeight
{
get
{
return IsSeasonal && TryGetFittedIntensities(out _, out _, out _, out double firstWeight, out _)
? firstWeight
: double.NaN;
}
}
/// <summary>
/// Gets the exposure weight for interior seasonal component two.
/// </summary>
public double SeasonTwoExposureWeight
{
get
{
return IsSeasonal && TryGetFittedIntensities(out _, out _, out _, out _, out double secondWeight)
? secondWeight
: double.NaN;
}
}
/// <summary>
/// Gets a value indicating whether <see cref="TotalYears"/> was inferred from the span of
/// retained exact events rather than supplied explicitly or preserved from source exposure.
/// </summary>
public bool IsTotalYearsInferred => _isTotalYearsInferred;
/// <summary>
/// Gets or sets the threshold above which events are modeled by the point process.
/// </summary>
[Category("Inputs")]
[DisplayName("Threshold")]
[Description("Defines the threshold above which events are modeled in the point process.")]
[Browsable(true)]
public double Threshold
{
get { return _threshold; }
set
{
if (!_threshold.AlmostEquals(value))
{
_threshold = value;
RaisePropertyChange(nameof(Threshold));
}
}
}
/// <summary>
/// Gets or sets the total number of years over which POT events were observed.
/// </summary>
[Category("Inputs")]
[DisplayName("Total Years")]
[Description("Sets the total number of years over which peaks-over-threshold events were recorded.")]
[Browsable(true)]
public double TotalYears
{
get { return _totalYears; }
set
{
bool valueChanged = !_totalYears.AlmostEquals(value);
bool inferenceChanged = _isTotalYearsInferred;
_totalYears = value;
_totalYearsExplicit = true;
_isTotalYearsInferred = false;
CalculateLambda();
if (inferenceChanged)
RaisePropertyChange(nameof(IsTotalYearsInferred));
if (valueChanged)
RaisePropertyChange(nameof(TotalYears));
}
}
/// <summary>
/// Gets or sets a value indicating whether the default threshold
/// and total years should be inferred from the data.
/// </summary>
[Category("Inputs")]
[DisplayName("Use Defaults")]
[Description("Use the default threshold and total observed years inferred from the data.")]
[Browsable(true)]
public bool UseDefaults
{
get { return _useDefaults; }
set
{
if (_useDefaults != value)
{
_useDefaults = value;
if (_useDefaults)
SetDefaultThresholdAndTotalYears(forceTotalYears: true);
else
_totalYearsExplicit = Tools.IsFinite(_totalYears) && _totalYears > 0.0;
RaisePropertyChange(nameof(UseDefaults));
}
}
}
/// <summary>
/// Gets or sets a value indicating whether the model should be
/// treated as seasonal (two GEVs) or non-seasonal (single GEV).
/// </summary>
[Category("Model Options")]
[DisplayName("Is Seasonal")]
[Description("Specifies whether the point process model includes seasonal effects.")]
[Browsable(true)]
public bool IsSeasonal
{
get { return _isSeasonal; }
set
{
if (_isSeasonal != value)
{
_isSeasonal = value;
RaisePropertyChange(nameof(IsSeasonal));
SetDistribution();
SetAMSData();
SetDefaultParameters();
}
}
}
/// <summary>
/// Gets or sets the time block window used to build the block series (default is water year).
/// </summary>
[Category("Time Series Options")]
[DisplayName("Time Block Window")]
[Description("Defines the time block window for creating the block series (default is water year).")]
[Browsable(true)]
public TimeBlockWindow TimeBlock
{
get { return _timeBlock; }
set
{
if (_timeBlock != value)
{
_timeBlock = value;
RaisePropertyChange(nameof(TimeBlock));
SetAMSData();
if (UseDefaultFlatPriors)
SetDefaultParameters();
}
}
}
/// <summary>
/// Gets or sets the starting month for the water year (default is October).
/// </summary>
[Category("Time Series Options")]
[DisplayName("Start Month")]
[Description("Specifies the starting month for the water year (default is October).")]
[Browsable(true)]
public int StartMonth
{
get { return _startMonth; }
set
{
if (_startMonth != value)
{
_startMonth = value;
RaisePropertyChange(nameof(StartMonth));
SetAMSData();
if (UseDefaultFlatPriors)
SetDefaultParameters();
}
}
}
#endregion
#region Methods
/// <inheritdoc/>
protected override void DataFrame_PropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(DataFrame.PlottingParameter) ||
e.PropertyName == "PlottingPosition")
{
return;
}
if (DataFrame == null)
return;
DataFrame.ProcessThresholdSeries();
RaisePropertyChange(nameof(DataFrame));
SetAMSData();
if (UseDefaults)
SetDefaultThresholdAndTotalYears(forceTotalYears: true);
else
CalculateLambda();
if (UseDefaultFlatPriors)
SetDefaultParameters();
}
/// <summary>
/// Sets the default threshold and total number of years based on the data.
/// </summary>
/// <param name="peaksOverThreshold">Optional threshold used to create a peaks-over-threshold input series.</param>
/// <param name="forceTotalYears">If true, overwrites a previously explicit <see cref="TotalYears"/> value.</param>
/// <remarks>
/// <para>
/// Point-process exposure is the time span over which exact POT events could have occurred.
/// Threshold, uncertain, and interval data contribute to the censored magnitude likelihood,
/// but they do not extend the Poisson exposure duration.
/// </para>
/// </remarks>
public void SetDefaultThresholdAndTotalYears(double? peaksOverThreshold = null, bool forceTotalYears = false)
{
if (DataFrame == null)
return;
if (DataFrame.ExactSeries.Count > 0)
{
double exactMinimum = DataFrame.ExactSeries.MinimumValue();
if (peaksOverThreshold.HasValue &&
Tools.IsFinite(peaksOverThreshold.Value) &&
peaksOverThreshold.Value < exactMinimum)
{
Threshold = peaksOverThreshold.Value;
}
else
{
Threshold = Math.BitDecrement(exactMinimum);
}
}
else
{
// Robust min across non-empty non-exact series; ignore series with no data.
var minima = new List<double>();
if (DataFrame.UncertainSeries.Count > 0)
minima.Add(DataFrame.UncertainSeries.MinimumValue());
if (DataFrame.IntervalSeries.Count > 0)
minima.Add(DataFrame.IntervalSeries.MinimumValue());
if (minima.Count > 0)
Threshold = Math.BitDecrement(minima.Min());
}
bool totalYearsChanged = false;
bool inferenceChanged = false;
if (forceTotalYears || !_totalYearsExplicit)
{
bool hasSourceExposure = HasStoredSourceExposure();
double inferred = hasSourceExposure
? DataFrame.PointProcessObservationYears
: DataFrame.ExactSeries.Count > 0
? DataFrame.ExactSeries.IndexSpan()
: 1.0;
if (!_totalYears.AlmostEquals(inferred))
{
_totalYears = inferred;
totalYearsChanged = true;
}
_totalYearsExplicit = false;
bool isInferred = !hasSourceExposure;
inferenceChanged = _isTotalYearsInferred != isInferred;
_isTotalYearsInferred = isInferred;
}
CalculateLambda();
if (inferenceChanged)
RaisePropertyChange(nameof(IsTotalYearsInferred));
if (totalYearsChanged)
RaisePropertyChange(nameof(TotalYears));
}
/// <summary>
/// Calculates λ, the average number of POT events per year.
/// </summary>
public void CalculateLambda()
{
_lambda = DataFrame == null || !Tools.IsFinite(_totalYears) || _totalYears <= 0.0
? double.NaN
: EmpiricalEventCount / _totalYears;
RaisePropertyChange(nameof(EmpiricalEventCount));
RaisePropertyChange(nameof(EmpiricalEventRate));
RaisePropertyChange(nameof(Lambda));
}
/// <summary>
/// Preprocesses the annual maximum (or block) data and, for seasonal
/// models, computes the configured calendar- or water-year block day for each POT event.
/// </summary>
/// <remarks>
/// Seasonal processing requires a valid date on every exact observation. Missing dates
/// or dated block-processing failures leave the derived collections empty, and
/// <see cref="Validate()"/> reports that the seasonal model cannot be estimated.
/// </remarks>
public void SetAMSData()
{
_amsDataFrame = new DataFrame();
_potDays = new List<int>();
if (DataFrame == null || DataFrame.ExactSeries == null || DataFrame.ExactSeries.Count == 0)
{
return;
}
if (IsSeasonal && DataFrame.ExactSeries.Cast<ExactData>().Any(data => data.DateTime == default))
return;
try
{
if (!IsSeasonal)
{
// Get block-maximum values over each unique index.
var maxByIndex = DataFrame.ExactSeries.GroupBy(item => item.Index).ToDictionary(group => group.Key, group => group.Max(item => item.Value));
foreach (var item in maxByIndex)
{
_amsDataFrame.ExactSeries.Add(new ExactData(item.Key, item.Value));
}
}
else
{
// Build irregular time series from exact data.
var ts = new TimeSeries(TimeInterval.Irregular);
for (int i = 0; i < DataFrame.ExactSeries.Count; i++)
{
var exact = (ExactData)DataFrame.ExactSeries[i];
ts.Add(new SeriesOrdinate<DateTime, double>(exact.DateTime, exact.Value));
}
// Compute block maxima.
_amsDataFrame.CreateBlockSeries(ts, TimeBlock, BlockFunctionType.Maximum, SmoothingFunctionType.None, StartMonth);
for (int i = 0; i < ts.Count; i++)
{
_potDays.Add(GetBlockDay(ts[i].Index));
}
}
}
catch (Exception ex)
{
Debug.WriteLine($"PointProcessModel.SetAMSData: time-series processing skipped: {ex.Message}");
}
}
/// <summary>
/// Initializes the underlying competing risks distribution with one
/// (non-seasonal) or two (seasonal) GEV components.
/// </summary>
public void SetDistribution()
{
if (!IsSeasonal)
{
_distribution = new CompetingRisks(new IUnivariateDistribution[] { new GeneralizedExtremeValue() })
{
MinimumOfRandomVariables = false,
Dependency = Probability.DependencyType.Independent
};
}
else
{
_distribution = new CompetingRisks(new IUnivariateDistribution[] { new GeneralizedExtremeValue(), new GeneralizedExtremeValue() })
{
MinimumOfRandomVariables = false,
Dependency = Probability.DependencyType.Independent
};
}
}
/// <inheritdoc/>
/// <remarks>Expected block-sample validation failures retain editable parameters and are reported
/// by Validate while automatic priors are enabled. A new model exposes editable component parameters using
/// existing component values and ModelParameter defaults, plus seasonal changepoint defaults where applicable.
/// The initialization error prevents these placeholders from being treated as automatic GEV priors.</remarks>
public override void SetDefaultParameters()
{
_defaultParameterInitializationError = null;
var initializationConstraints = new List<Tuple<double[], double[], double[]>>();
if (Distribution is not null && DataFrame is not null && DataFrame.Validate().IsValid &&
Distribution.Distributions is not null && Distribution.Distributions.Count > 0)
{
List<double> initializationSample = AMSDataFrame.ExactSeries.Select(x => x.Value).ToList();
foreach (UnivariateDistributionBase component in Distribution.Distributions)
{
if (!UnivariateDistribution.TryGetDefaultParameterConstraints(
component, initializationSample, out var constraints, out _defaultParameterInitializationError))
{
if (Parameters.Count == 0)
{
if (Distribution.Distributions.Count > 1)
AddDefaultChangePointParameters();
for (int i = 0; i < Distribution.Distributions.Count; i++)
{
var distribution = Distribution.Distributions[i];
var names = distribution.ParametersToString;
var values = distribution.GetParameters;
for (int j = 0; j < distribution.NumberOfParameters; j++)
{
Parameters.Add(new ModelParameter
{
OwnerName = IsSeasonal ? "D" + (i + 1).ToString(CultureInfo.InvariantCulture) : string.Empty,
Name = names[j, 0],
Value = values[j]
});
}
}
foreach (ModelParameter parameter in Parameters)
parameter.PropertyChanged += Parameter_PropertyChanged;
}
RaisePropertyChange(nameof(SetDefaultParameters));
return;
}
initializationConstraints.Add(constraints!);
}
}
// Remove old handlers
if (Parameters.Count > 0)
{
for (int i = 0; i < NumberOfParameters; i++)
Parameters[i].PropertyChanged -= Parameter_PropertyChanged;
}
_parameters = new List<ModelParameter>();
if (Distribution is null ||
DataFrame == null ||
!DataFrame.Validate().IsValid ||
Distribution.Distributions == null ||
!Distribution.Distributions.Any())
{
RaisePropertyChange(nameof(SetDefaultParameters));
return;
}
if (Distribution.Distributions.Count() > 1)
AddDefaultChangePointParameters();
// Priors for GEV distribution parameters.
for (int i = 0; i < Distribution.Distributions.Count(); i++)
{
var gev = Distribution.Distributions[i];
var tuple = initializationConstraints[i];
var initials = tuple.Item1;
var lowers = tuple.Item2;
var uppers = tuple.Item3;
var parametersToString = gev.ParametersToString;
for (int j = 0; j < gev.NumberOfParameters; j++)
{
Parameters.Add(new ModelParameter
{
OwnerName = IsSeasonal ? "D" + (i + 1).ToString(CultureInfo.InvariantCulture) : string.Empty,
Name = parametersToString[j, 0],
Value = initials[j],
LowerBound = lowers[j],
UpperBound = uppers[j],
IsPositive = lowers[j] == Tools.DoubleMachineEpsilon,
PriorDistribution = new Uniform(lowers[j], uppers[j])
});
}
}
// Add handlers
for (int i = 0; i < NumberOfParameters; i++)
Parameters[i].PropertyChanged += Parameter_PropertyChanged;
RaisePropertyChange(nameof(SetDefaultParameters));
}
/// <summary>Adds the existing seasonal changepoint defaults independently of GEV magnitude initialization.</summary>
private void AddDefaultChangePointParameters()
{
var changePointDefaults = GetDefaultChangePointParameters();
Parameters.Add(new ModelParameter
{
Name = "Change Point K₁",
Value = changePointDefaults[0].Value,
LowerBound = changePointDefaults[0].Lower,
UpperBound = changePointDefaults[0].Upper,
PriorDistribution = new Uniform(changePointDefaults[0].Lower, changePointDefaults[0].Upper)
});
Parameters.Add(new ModelParameter
{
Name = "Change Point K₂",
Value = changePointDefaults[1].Value,
LowerBound = changePointDefaults[1].Lower,
UpperBound = changePointDefaults[1].Upper,
PriorDistribution = new Uniform(changePointDefaults[1].Lower, changePointDefaults[1].Upper)
});
}
/// <summary>
/// Gets broad or histogram-informed default parameters for the two seasonal changepoints.
/// </summary>
/// <returns>
/// Two tuples containing the latent value and inclusive floating-point bounds for
/// <c>K₁</c> and <c>K₂</c>, respectively.
/// </returns>
/// <remarks>
/// The histogram rule is an empirical initialization aid, not an estimator. It counts
/// exact dated POT events by month, rotates the bins to the configured block-year start,
/// and locates broad valleys between two separated seasonal peaks. Ambiguous histograms
/// retain the broad default supports <c>K₁ ∈ [1,251)</c> and
/// <c>K₂ ∈ [200,367)</c>.
/// </remarks>
private (double Value, double Lower, double Upper)[] GetDefaultChangePointParameters()
{
var broadDefaults = new[]
{
(Value: 90.0, Lower: 1.0, Upper: Math.BitDecrement(251.0)),
(Value: 250.0, Lower: 200.0, Upper: Math.BitDecrement(367.0))
};
if (DataFrame == null)
return broadDefaults;
int firstMonth = TimeBlock == TimeBlockWindow.CalendarYear ? 1 : StartMonth;
if (firstMonth < 1 || firstMonth > 12)
return broadDefaults;
var monthlyCounts = new double[12];
int datedCount = 0;
foreach (ExactData observation in DataFrame.ExactSeries)
{
if (observation.DateTime == default)
continue;
int blockMonth = (observation.DateTime.Month - firstMonth + 12) % 12;
monthlyCounts[blockMonth] += 1.0;
datedCount++;
}
if (datedCount < 10)
return broadDefaults;
int[] monthStarts = GetBlockMonthStarts(firstMonth);
if (IsEffectivelyFlat(monthlyCounts, monthStarts) ||
!TryFindSeasonalValleys(monthlyCounts, out int firstValley, out int secondValley))
{
return broadDefaults;
}
if (!TryCreateChangePointDefault(firstValley, monthStarts, 1.0, 251.0, out var firstDefault) ||
!TryCreateChangePointDefault(secondValley, monthStarts, 200.0, 367.0, out var secondDefault))
{
return broadDefaults;
}
return new[] { firstDefault, secondDefault };
}
/// <summary>
/// Determines whether monthly counts are consistent with uniform daily occurrence exposure.
/// </summary>
/// <param name="monthlyCounts">Monthly counts ordered from the configured block-year start.</param>
/// <param name="monthStarts">Canonical one-based block-month boundaries.</param>
/// <returns><c>true</c> when broad random variation should not be interpreted as two seasons.</returns>
/// <remarks>
/// Expected counts are proportional to the number of modeled days in each month. The
/// fixed cutoff 19.675 is the 95th percentile of a chi-square distribution with 11
/// degrees of freedom. This guard only selects the broad prior fallback; it is not a
/// point-process parameter estimate or a likelihood calculation.
/// </remarks>
private static bool IsEffectivelyFlat(double[] monthlyCounts, int[] monthStarts)
{
double total = monthlyCounts.Sum();
if (total <= 0.0)
return true;
double statistic = 0.0;
for (int i = 0; i < monthlyCounts.Length; i++)
{
double expected = total * (monthStarts[i + 1] - monthStarts[i]) / 366.0;
double difference = monthlyCounts[i] - expected;
statistic += difference * difference / expected;
}
return statistic <= 19.675;
}
/// <summary>
/// Locates the two seasonal valleys in a twelve-bin monthly occurrence histogram.
/// </summary>
/// <param name="monthlyCounts">Monthly counts ordered from the configured block-year start.</param>
/// <param name="firstValley">The earlier valley-month index in block-year order.</param>
/// <param name="secondValley">The later valley-month index in block-year order.</param>
/// <returns><c>true</c> when two separated peaks and their intervening valleys are identifiable.</returns>
/// <remarks>
/// Detection uses one circular <c>[1,2,1]/4</c> smoothing pass. The smoothing affects
/// only the default-prior neighborhood; it does not alter observations or likelihoods.
/// </remarks>
private static bool TryFindSeasonalValleys(double[] monthlyCounts, out int firstValley, out int secondValley)
{
firstValley = -1;
secondValley = -1;
double minimum = monthlyCounts.Min();
double maximum = monthlyCounts.Max();
if (maximum <= minimum)
return false;
var smoothed = new double[12];
for (int i = 0; i < smoothed.Length; i++)
{
int previous = (i + 11) % 12;
int next = (i + 1) % 12;
smoothed[i] = (monthlyCounts[previous] + 2.0 * monthlyCounts[i] + monthlyCounts[next]) / 4.0;
}
var peaks = new List<int>();
for (int i = 0; i < smoothed.Length; i++)
{
double previous = smoothed[(i + 11) % 12];
double next = smoothed[(i + 1) % 12];
if (smoothed[i] >= previous && smoothed[i] >= next &&
(smoothed[i] > previous || smoothed[i] > next))
{
peaks.Add(i);
}
}
double mean = smoothed.Average();
int bestFirstPeak = -1;
int bestSecondPeak = -1;
double bestScore = double.NegativeInfinity;
int bestPairCount = 0;
for (int i = 0; i < peaks.Count; i++)
{
for (int j = i + 1; j < peaks.Count; j++)
{
int separation = (peaks[j] - peaks[i] + 12) % 12;
if (separation < 3 || separation > 9 ||
smoothed[peaks[i]] <= mean || smoothed[peaks[j]] <= mean)
{
continue;
}
double score = smoothed[peaks[i]] + smoothed[peaks[j]];
if (score > bestScore)
{
bestScore = score;
bestFirstPeak = peaks[i];
bestSecondPeak = peaks[j];
bestPairCount = 1;
}
else if (score == bestScore)
{
bestPairCount++;
}
}
}
if (bestPairCount != 1)
return false;
int valleyA = FindCircularValley(smoothed, bestFirstPeak, bestSecondPeak);
int valleyB = FindCircularValley(smoothed, bestSecondPeak, bestFirstPeak);
if (valleyA < 0 || valleyB < 0 ||
smoothed[valleyA] >= Math.Min(smoothed[bestFirstPeak], smoothed[bestSecondPeak]) ||
smoothed[valleyB] >= Math.Min(smoothed[bestFirstPeak], smoothed[bestSecondPeak]))
{
return false;
}
firstValley = Math.Min(valleyA, valleyB);
secondValley = Math.Max(valleyA, valleyB);
return true;
}
/// <summary>
/// Finds the lowest monthly bin on the forward circular arc between two peak bins.