Repository navigation
Expand file tree
/
Copy pathMixtureModel.cs
More file actions
2022 lines (1823 loc) · 94.1 KB
/
Copy pathMixtureModel.cs
File metadata and controls
2022 lines (1823 loc) · 94.1 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 System.ComponentModel;
using System.Globalization;
using System.Xml.Linq;
using Numerics;
using Numerics.Distributions;
using Numerics.Mathematics;
using Numerics.Mathematics.Integration;
using Numerics.Mathematics.LinearAlgebra;
using Numerics.Mathematics.Optimization;
using RMC.BestFit.Estimation;
namespace RMC.BestFit.Models
{
/// <summary>
/// Mixture model for univariate distributions, with optional zero inflation.
/// </summary>
/// <remarks>
/// <para>
/// Authors:
/// Haden Smith, USACE Risk Management Center, cole.h.smith@usace.army.mil
/// </para>
/// <para>
/// The <see cref="MixtureModel"/> represents a finite mixture of
/// univariate distributions, optionally with a zero-inflated mass at
/// zero. It supports:
/// </para>
/// <list type="bullet">
/// <item><description>Mixtures of one to three component distributions.</description></item>
/// <item><description>Bayesian priors on parameters and quantiles.</description></item>
/// <item><description>A fixed atom at zero with continuous components conditioned on positive values.</description></item>
/// <item><description>Expectation–Maximization (EM) for approximate MLE.</description></item>
/// </list>
/// </remarks>
public class MixtureModel : UnivariateDistributionModelBase, ISimulatable<double[]>, IUnivariateModel
{
#region Construction
/// <summary>
/// Constructs an empty mixture distribution model with a default
/// Normal–Normal mixture and a single quantile prior.
/// </summary>
public MixtureModel()
{
_useSingleQuantile = true;
SetDefaultMixture(new[] { UnivariateDistributionType.Normal, UnivariateDistributionType.Normal });
}
/// <summary>
/// Constructs a mixture distribution model.
/// </summary>
/// <param name="dataFrame">The data frame to fit to.</param>
/// <param name="distribution">The mixture distribution.</param>
public MixtureModel(DataFrame dataFrame, Mixture distribution)
{
_useSingleQuantile = true;
Mixture = (Mixture)distribution.Clone();
DataFrame = dataFrame;
}
/// <summary>
/// Constructs a mixture distribution model from a list of existing
/// component distributions.
/// </summary>
/// <param name="dataFrame">The data frame to fit to.</param>
/// <param name="distributions">The list of component distributions.</param>
/// <param name="isZeroInflated">
/// If true, derives a fixed atom from exact observations equal to zero.
/// </param>
public MixtureModel(DataFrame dataFrame, List<UnivariateDistributionBase> distributions, bool isZeroInflated = false)
{
_useSingleQuantile = true;
DataFrame = dataFrame;
IsZeroInflated = isZeroInflated;
if (distributions == null || distributions.Count == 0)
throw new ArgumentException("At least one component distribution is required.", nameof(distributions));
int k = distributions.Count;
var weights = Enumerable.Repeat(1.0 / k, k).ToArray();
// Use the user-provided distributions directly.
Mixture = new Mixture(weights, distributions.ToArray());
}
/// <summary>
/// Constructs a mixture distribution model from a list of component
/// distribution types with equal initial weights.
/// </summary>
/// <param name="dataFrame">The data frame to fit to.</param>
/// <param name="distributionTypes">The list of univariate distribution types.</param>
/// <param name="isZeroInflated">
/// If true, derives a fixed atom from exact observations equal to zero.
/// </param>
public MixtureModel(DataFrame dataFrame, List<UnivariateDistributionType> distributionTypes, bool isZeroInflated = false)
{
_useSingleQuantile = true;
DataFrame = dataFrame;
IsZeroInflated = isZeroInflated;
SetDefaultMixture(distributionTypes);
}
/// <summary>
/// Constructs a mixture distribution model from an XML element and
/// an associated data frame.
/// </summary>
/// <param name="dataFrame">The data frame to fit to.</param>
/// <param name="xElement">The XML element to deserialize.</param>
public MixtureModel(DataFrame dataFrame, XElement xElement)
{
// Set data frame
if (_dataFrame != null)
_dataFrame.PropertyChanged -= DataFrame_PropertyChanged;
_dataFrame = dataFrame;
// Configuration undo is also available before an input data set is selected.
if (_dataFrame != null)
{
_dataFrame.PropertyChanged += DataFrame_PropertyChanged;
_dataFrame.ProcessThresholdSeries();
_dataFrame.CreateFullTimeSeries();
}
var distributionElement = xElement.Element("Distribution");
if (distributionElement != null)
Mixture = Mixture.FromXElement(distributionElement);
var isZeroInflatedAttr = xElement.Attribute(nameof(IsZeroInflated));
if (isZeroInflatedAttr != null)
{
bool.TryParse(isZeroInflatedAttr.Value, out var isZeroInflated);
IsZeroInflated = isZeroInflated;
}
// Parameters
var useDefaultFlatPriorsAttr = xElement.Attribute(nameof(UseDefaultFlatPriors));
if (useDefaultFlatPriorsAttr != null)
bool.TryParse(useDefaultFlatPriorsAttr.Value, out _useDefaultFlatPriors);
var useJeffreysRuleForScaleAttr = xElement.Attribute(nameof(UseJeffreysRuleForScale));
if (useJeffreysRuleForScaleAttr != null)
bool.TryParse(useJeffreysRuleForScaleAttr.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 (mixture model uses a single quantile prior)
var enableQuantilePriorsAttr = xElement.Attribute(nameof(EnableQuantilePriors));
if (enableQuantilePriorsAttr != null)
bool.TryParse(enableQuantilePriorsAttr.Value, out _enableQuantilePriors);
_useSingleQuantile = true;
var quants = new List<QuantilePrior>();
foreach (XElement q in xElement.Elements(nameof(QuantilePriors)).Elements(nameof(QuantilePrior)))
quants.Add(new QuantilePrior(q));
QuantilePriors = quants;
}
#endregion
#region Members
/// <summary>
/// The set of univariate distribution types supported by the mixture model.
/// </summary>
private static readonly HashSet<UnivariateDistributionType> _supportedDistributionTypes = new()
{
UnivariateDistributionType.Exponential,
UnivariateDistributionType.GammaDistribution,
UnivariateDistributionType.GeneralizedExtremeValue,
UnivariateDistributionType.GeneralizedLogistic,
UnivariateDistributionType.GeneralizedNormal,
UnivariateDistributionType.GeneralizedPareto,
UnivariateDistributionType.Gumbel,
UnivariateDistributionType.KappaFour,
UnivariateDistributionType.LnNormal,
UnivariateDistributionType.Logistic,
UnivariateDistributionType.LogNormal,
UnivariateDistributionType.LogPearsonTypeIII,
UnivariateDistributionType.Normal,
UnivariateDistributionType.PearsonTypeIII,
UnivariateDistributionType.Weibull,
};
/// <summary>
/// Determines whether the specified distribution type is supported by the mixture 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>
public static bool IsSupportedDistributionType(UnivariateDistributionType distributionType)
{
return _supportedDistributionTypes.Contains(distributionType);
}
private Mixture? _mixture = null;
/// <summary>The latest automatic-initialization sample error, reported through model validation.</summary>
private string? _defaultParameterInitializationError;
private bool _isZeroInflated = 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();
if (Mixture is not null)
{
if (IsZeroInflated)
{
Mixture.ZeroWeight = GetExactZeroWeight();
}
else
{
Mixture.ZeroWeight = 0.0;
}
}
if (UseDefaultFlatPriors)
SetDefaultParameters();
}
RaisePropertyChange(nameof(DataFrame));
}
}
/// <summary>
/// Gets or sets the mixture distribution representing the parent population.
/// </summary>
[Category("Inputs")]
[DisplayName("Mixture Distribution")]
[Description("The mixture distribution representing the parent population.")]
[Browsable(true)]
public Mixture? Mixture
{
get { return _mixture; }
set
{
_mixture = value;
RaisePropertyChange(nameof(Mixture));
if (_mixture is not null)
{
_mixture.IsZeroInflated = IsZeroInflated;
if (IsZeroInflated)
{
_mixture.ZeroWeight = DataFrame is not null ? GetExactZeroWeight() : 0.0;
}
else
{
_mixture.ZeroWeight = 0.0;
}
}
SetDefaultParameters();
SetDefaultQuantilePriors();
}
}
/// <inheritdoc/>
UnivariateDistributionBase? IUnivariateModel.Distribution => _mixture;
/// <inheritdoc/>
/// <remarks>
/// Mixture component distributions are treated as stationary within this model.
/// Always returns <c>false</c>.
/// </remarks>
public bool IsNonstationary => false;
/// <summary>
/// Determines whether a fixed atom is assigned to exact observations equal to zero.
/// </summary>
[Category("Inputs")]
[DisplayName("Is Zero-Inflated")]
[Description("If true, a weight derived from the input data is assigned to all data points ≤ 0.")]
[Browsable(true)]
public bool IsZeroInflated
{
get { return _isZeroInflated; }
set
{
if (_isZeroInflated != value)
{
_isZeroInflated = value;
RaisePropertyChange(nameof(IsZeroInflated));
if (Mixture is not null)
{
Mixture.IsZeroInflated = _isZeroInflated;
if (_isZeroInflated)
{
Mixture.ZeroWeight = DataFrame != null ? GetExactZeroWeight() : 0.0;
}
else
{
Mixture.ZeroWeight = 0.0;
}
}
if (_useDefaultFlatPriors)
SetDefaultParameters();
}
}
}
/// <summary>
/// Mixture model currently supports only a single quantile prior.
/// Attempts to disable this are ignored.
/// </summary>
[Category("Inputs")]
[DisplayName("Use Single Quantile")]
[Description("Mixture model currently supports only a single quantile prior.")]
[Browsable(true)]
public override bool UseSingleQuantile
{
get { return true; }
set
{
// Mixture model is restricted to a single quantile prior.
if (!value)
return;
if (!_useSingleQuantile)
{
_useSingleQuantile = true;
RaisePropertyChange(nameof(UseSingleQuantile));
SetDefaultQuantilePriors();
}
}
}
#endregion
#region Methods
/// <summary>
/// Computes the fixed zero atom from exact annual records only.
/// </summary>
/// <returns>The number of exact values equal to zero divided by the number of exact records.</returns>
private double GetExactZeroWeight()
{
if (DataFrame?.ExactSeries is null || DataFrame.ExactSeries.Count == 0) return 0.0;
int zeroCount = DataFrame.ExactSeries.Count(data => data.Value == 0.0);
return zeroCount / (double)DataFrame.ExactSeries.Count;
}
/// <summary>
/// Gets the exact sample used to initialize continuous component parameters.
/// </summary>
/// <returns>All exact values for an ordinary mixture, or strictly positive exact values for a hurdle mixture.</returns>
private List<double> GetComponentInitializationSample()
{
return DataFrame.ExactSeries
.Where(data => !IsZeroInflated || data.Value > 0.0)
.Select(data => data.Value)
.ToList();
}
/// <summary>
/// Gets the number of free physical mixture weights.
/// </summary>
/// <param name="mixture">The Numerics mixture.</param>
/// <returns>Zero for one component; otherwise, one less than the component count.</returns>
private static int GetFreeWeightCount(Mixture mixture)
{
return Math.Max(0, mixture.Distributions.Length - 1);
}
/// <summary>
/// Gets the number of weight coordinates in the public BestFit parameter vector.
/// </summary>
/// <param name="mixture">The Numerics mixture.</param>
/// <returns>All component weights when there are multiple components; otherwise, zero.</returns>
/// <remarks>
/// The zero-weight single-component convention and the full K-weight multi-component
/// convention are retained for public API and project-file compatibility.
/// </remarks>
private static int GetPublicWeightCount(Mixture mixture)
{
return mixture.Distributions.Length > 1 ? mixture.Distributions.Length : 0;
}
/// <summary>
/// Gets the probability mass assigned to the continuous mixture components.
/// </summary>
/// <returns>One for an ordinary mixture or one minus the fixed zero weight.</returns>
private double GetComponentMass()
{
return IsZeroInflated ? 1.0 - Mixture!.ZeroWeight : 1.0;
}
/// <summary>
/// Expands the independent EM weight vector to Numerics' full physical-weight vector.
/// </summary>
/// <param name="parameters">The independent EM parameter vector.</param>
/// <param name="physicalParameters">The full Numerics parameter vector when feasible.</param>
/// <returns><see langword="true"/> when the proposal has the expected size and lies on the configured simplex.</returns>
private bool TryExpandIndependentParameters(IList<double> parameters, out double[] physicalParameters)
{
physicalParameters = Array.Empty<double>();
if (Mixture is null || parameters is null) return false;
int componentCount = Mixture.Distributions.Length;
int freeWeightCount = GetFreeWeightCount(Mixture);
int distributionParameterCount = Mixture.Distributions!.Sum(distribution => distribution.NumberOfParameters);
if (parameters.Count != freeWeightCount + distributionParameterCount) return false;
double componentMass = GetComponentMass();
if (!Tools.IsFinite(componentMass) || componentMass <= 0.0) return false;
physicalParameters = new double[componentCount + distributionParameterCount];
double trackedWeightSum = 0.0;
for (int i = 0; i < freeWeightCount; i++)
{
double weight = parameters[i];
if (!Tools.IsFinite(weight) || weight < 0.0) return false;
physicalParameters[i] = weight;
trackedWeightSum += weight;
}
double finalWeight = componentMass - trackedWeightSum;
if (!Tools.IsFinite(finalWeight)) return false;
if (finalWeight < 0.0)
{
// A posterior summary of the free weights can land a few ULP above the component
// mass from floating-point accumulation (a posterior mean concentrated at the
// simplex boundary, for example), making the residual weight a vanishingly small
// negative. That is the boundary of the simplex, not an infeasible point, so clamp
// it to zero within a tight tolerance; a rejection here used to make the
// point-estimator reprocess throw and silently freeze the GUI on stale results. A
// genuinely negative residual is still rejected.
if (finalWeight < -1E-12 * Math.Max(1.0, componentMass)) return false;
finalWeight = 0.0;
}
physicalParameters[componentCount - 1] = finalWeight;
for (int i = 0; i < distributionParameterCount; i++)
{
physicalParameters[componentCount + i] = parameters[freeWeightCount + i];
}
return true;
}
/// <summary>
/// Determines whether a stored parameter-vector length is the reduced K-1 sampled weight
/// shape, rather than the full-K public shape, for this mixture.
/// </summary>
/// <param name="length">The stored vector length to test.</param>
/// <returns>
/// <see langword="true"/> when the mixture has more than one component and
/// <paramref name="length"/> equals the free-weight count plus the total component
/// parameter count (one fewer than the full-K public length); otherwise
/// <see langword="false"/>.
/// </returns>
/// <remarks>
/// The length formula (free-weight count plus total component parameter count) is the
/// same arithmetic <see cref="TryExpandIndependentParameters"/> uses to accept or reject a
/// proposal, so it reads the mixture's structure (<see cref="Mixture"/>) directly rather
/// than <see cref="ModelBase.NumberOfParameters"/>: the latter is <c>Parameters.Count</c>,
/// which requires a validated <see cref="DataFrame"/> to be populated by
/// <see cref="SetDefaultParameters"/> and is not a precondition of the low-level expansion.
/// This does <i>not</i> mirror <see cref="TryExpandIndependentParameters"/> exactly at
/// K = 1: that method has no component-count guard, so it accepts a length-D proposal for
/// a single-component mixture (its own free-weight count is zero, so the formula reduces
/// to the distribution parameter count, coinciding with the full-K length). This method
/// adds the <c>Distributions.Length > 1</c> guard on top of the formula, because for a
/// single-component mixture that length is always the full-K shape and never a distinct
/// K-1 shape — so this always returns <see langword="false"/> for it. The API's results
/// mapper calls this directly to decide which name to omit, without expanding anything; it
/// does not need to re-derive the arithmetic. <see cref="TryGetPhysicalParameters"/> uses
/// it only to choose the public output shape after expansion succeeds, not to gate whether
/// expansion is attempted (see that method's remarks for why).
/// </remarks>
public bool IsSampledWeightVectorLength(int length)
{
if (Mixture is null || Mixture.Distributions.Length <= 1) return false;
int freeWeightCount = GetFreeWeightCount(Mixture);
int distributionParameterCount = Mixture.Distributions.Sum(distribution => distribution.NumberOfParameters);
return length == freeWeightCount + distributionParameterCount;
}
/// <summary>
/// Expands a stored mixture result to the full public parameter vector.
/// </summary>
/// <param name="parameters">A K-1 sampled vector or a legacy full-K vector.</param>
/// <param name="physicalParameters">The full public parameter vector when the stored shape is recognized and feasible.</param>
/// <returns><see langword="true"/> when the vector is either a valid K-1 sampled shape or the established full-K shape.</returns>
/// <remarks>
/// This is the single K-1/full-K expansion rule for result consumers outside this
/// assembly. The App's parameter-sets table uses it directly to expand a stored draw; the
/// API's results mapper only needs the shape decision
/// (<see cref="IsSampledWeightVectorLength"/>) to choose which name to omit and never
/// expands anything itself. A full-K vector (length
/// <see cref="ModelBase.NumberOfParameters"/>) is returned unchanged. Otherwise the vector
/// is expanded as the independent EM/sampling coordinates it was always accepted as (this
/// control flow, including the full-K check preceding an unconditional expansion attempt,
/// is unchanged from before this method was made public): its derived final weight is
/// computed as the remaining component mass minus the tracked free weights and clamped to
/// zero when that residual lies within <c>1E-12 * Math.Max(1.0, componentMass)</c> of zero
/// — the boundary of the physical simplex from floating-point accumulation, not an
/// infeasible point — while a genuinely negative residual beyond that tolerance is still
/// rejected. For a single-component mixture this expansion path is reached only when
/// <see cref="ModelBase.NumberOfParameters"/> itself is stale or unpopulated (for example,
/// no <see cref="DataFrame"/>): there is no distinct K-1 shape to gate on, so
/// <see cref="IsSampledWeightVectorLength"/> is consulted only to choose the output shape
/// (full Numerics vector versus the weight-free public convention), never to decide
/// whether to attempt the expansion at all — gating entry on it would silently reject
/// every single-component proposal instead of reproducing the established behavior.
/// Public model methods (<see cref="LogLikelihood"/> and siblings) continue to require the
/// established full-K vector; this method is restricted to BestFit result consumption. The
/// caller-owned array is never mutated, and no result migration or rewritten serialization
/// occurs.
/// </remarks>
public bool TryGetPhysicalParameters(IList<double> parameters, out double[] physicalParameters)
{
physicalParameters = Array.Empty<double>();
if (Mixture is null || parameters is null) return false;
if (parameters.Count == NumberOfParameters)
{
physicalParameters = parameters.ToArray();
return true;
}
if (!TryExpandIndependentParameters(parameters, out double[] numericsParameters))
return false;
physicalParameters = IsSampledWeightVectorLength(parameters.Count)
? numericsParameters
: numericsParameters.Skip(1).ToArray();
return true;
}
/// <summary>
/// Expands a stored mixture result to the full public parameter vector.
/// </summary>
/// <param name="parameters">A K-1 sampled vector or a legacy full-K vector.</param>
/// <returns>The full public parameter vector.</returns>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="parameters"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException">Thrown when the vector shape is unrecognized or its derived weight is infeasible.</exception>
internal double[] GetPhysicalParameters(IList<double> parameters)
{
ArgumentNullException.ThrowIfNull(parameters);
if (!TryGetPhysicalParameters(parameters, out double[] physicalParameters))
{
throw new ArgumentOutOfRangeException(
nameof(parameters),
"The stored mixture parameters do not match the K-1 sampled or full-K public parameterization.");
}
return physicalParameters;
}
/// <summary>
/// Evaluates the full mixture posterior from the identified K-1 sampling coordinates.
/// </summary>
/// <param name="parameters">The K-1 sampled weights followed by component parameters.</param>
/// <returns>The full posterior log likelihood, or negative infinity for an infeasible residual weight.</returns>
/// <remarks>
/// The derived final weight is inserted before the public full-K likelihood is called, so
/// every configured weight prior, including the prior on the derived weight, remains active.
/// </remarks>
internal double SamplingLogLikelihood(double[] parameters)
{
if (parameters is null || !TryExpandIndependentParameters(parameters, out double[] numericsParameters))
return double.NegativeInfinity;
double[] publicParameters = Mixture!.Distributions.Length > 1
? numericsParameters
: numericsParameters.Skip(1).ToArray();
return LogLikelihood(publicParameters);
}
/// <summary>
/// Converts independent EM coordinates to the original full-K parameter vector.
/// </summary>
/// <param name="parameters">The independent EM parameter vector.</param>
/// <returns>The full-K public vector for a multi-component mixture.</returns>
/// <exception cref="ArgumentOutOfRangeException">Thrown when the estimation vector is infeasible.</exception>
private double[] ToFullParameterVector(IList<double> parameters)
{
if (!TryExpandIndependentParameters(parameters, out double[] physicalParameters))
{
throw new ArgumentOutOfRangeException(
nameof(parameters),
"The mixture estimation parameters are outside the feasible physical simplex.");
}
if (Mixture!.Distributions.Length > 1)
return physicalParameters;
return physicalParameters.Skip(1).ToArray();
}
/// <summary>
/// Attempts to reconstruct a Numerics mixture from the public BestFit parameter vector.
/// </summary>
/// <param name="parameters">The BestFit parameter vector.</param>
/// <param name="distribution">The reconstructed distribution when the proposal is valid.</param>
/// <returns><see langword="true"/> when reconstruction succeeds and all Numerics parameters are valid.</returns>
private bool TryCreateDistribution(IList<double> parameters, out Mixture? distribution)
{
distribution = null;
if (Mixture is null || parameters is null) return false;
int expectedParameterCount = GetPublicWeightCount(Mixture) +
Mixture.Distributions.Sum(component => component.NumberOfParameters);
if (parameters.Count != expectedParameterCount) return false;
try
{
var candidate = (Mixture)Mixture.Clone();
double[] parameterCopy = parameters.ToArray();
candidate.SetParameters(ref parameterCopy);
if (!candidate.ParametersValid) return false;
distribution = candidate;
return true;
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// Reconstructs a Numerics mixture from a stored or public BestFit parameter vector without mutating the caller.
/// </summary>
/// <param name="parameters">A K-1 stored result vector or full-K public vector.</param>
/// <returns>A reconstructed Numerics mixture with all physical component weights.</returns>
/// <exception cref="ArgumentOutOfRangeException">Thrown when the proposal is outside the feasible simplex or contains invalid component parameters.</exception>
internal Mixture CreateDistribution(IList<double> parameters)
{
if (!TryGetPhysicalParameters(parameters, out double[] physicalParameters) ||
!TryCreateDistribution(physicalParameters, out Mixture? distribution))
{
throw new ArgumentOutOfRangeException(
nameof(parameters),
"The mixture proposal is outside the feasible physical simplex or contains invalid component parameters.");
}
return distribution!;
}
/// <summary>
/// Evaluates an uncertain observation, including the fixed atom and continuous contribution.
/// </summary>
/// <param name="model">The configured Numerics mixture.</param>
/// <param name="measurementDistribution">The observation's measurement-error distribution.</param>
/// <returns>The retained-window observation probability, or zero when the window is invalid.</returns>
private static double UncertainObservationProbability(
Mixture model,
UnivariateDistributionBase measurementDistribution)
{
const double lowerProbability = 1E-8;
const double upperProbability = 1.0 - 1E-8;
double lower = measurementDistribution.InverseCDF(lowerProbability);
double upper = measurementDistribution.InverseCDF(upperProbability);
double retainedMass = upperProbability - lowerProbability;
if (!Tools.IsFinite(lower) || !Tools.IsFinite(upper) || !Tools.IsFinite(retainedMass) ||
retainedMass <= 0.0 || lower >= upper)
{
return 0.0;
}
double probability = 0.0;
if (model.IsZeroInflated && lower <= 0.0 && upper >= 0.0)
{
probability += model.ZeroWeight * measurementDistribution.PDF(0.0);
}
double integrationLower = model.IsZeroInflated ? Math.Max(0.0, lower) : lower;
if (integrationLower < upper)
{
probability += Integration.GaussLegendre20(
value => measurementDistribution.PDF(value) * model.PDF(value),
integrationLower,
upper);
}
probability /= retainedMass;
return Tools.IsFinite(probability) && probability > 0.0 ? probability : 0.0;
}
/// <summary>
/// Evaluates the complete BestFit data likelihood for a configured Numerics mixture.
/// </summary>
/// <param name="model">The configured Numerics mixture.</param>
/// <returns>The data log likelihood, or negative infinity for an impossible observation.</returns>
private double EvaluateDataLogLikelihood(Mixture model)
{
double logLikelihood = 0.0;
foreach (ExactData data in DataFrame.ExactSeries)
{
if (model.IsZeroInflated && data.Value < 0.0) return double.NegativeInfinity;
logLikelihood += !data.IsLowOutlier
? model.LogLikelihood(data.Value)
: model.LogLikelihood_LeftCensored(DataFrame.LowOutlierThreshold, 1);
}
foreach (UncertainData data in DataFrame.UncertainSeries!)
{
double probability = UncertainObservationProbability(model, data.Distribution);
if (probability <= 0.0) return double.NegativeInfinity;
logLikelihood += Math.Log(probability);
}
foreach (IntervalData data in DataFrame.IntervalSeries)
{
logLikelihood += model.LogLikelihood_Intervals(data.LowerValue, data.UpperValue);
}
foreach (ThresholdData data in DataFrame.ThresholdSeries)
{
if (data.NumberBelow > 0)
logLikelihood += model.LogLikelihood_LeftCensored(data.Value, data.NumberBelow);
if (data.NumberAbove > 0)
logLikelihood += model.LogLikelihood_RightCensored(data.Value, data.NumberAbove);
}
return Tools.IsFinite(logLikelihood) ? logLikelihood : double.NegativeInfinity;
}
/// <inheritdoc/>
protected override void DataFrame_PropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(DataFrame.PlottingParameter) ||
e.PropertyName == "PlottingPosition")
{
return;
}
if (DataFrame is null)
return;
DataFrame.ProcessThresholdSeries();
RaisePropertyChange(nameof(DataFrame));
if (Mixture is not null)
{
if (IsZeroInflated)
{
Mixture.ZeroWeight = GetExactZeroWeight();
}
else
{
Mixture.ZeroWeight = 0.0;
}
}
if (UseDefaultFlatPriors)
SetDefaultParameters();
}
/// <summary>
/// Sets the default mixture distribution with equal weights
/// for the given distribution types.
/// </summary>
/// <param name="distributionTypes">The list of component distribution types.</param>
public void SetDefaultMixture(IList<UnivariateDistributionType> distributionTypes)
{
if (distributionTypes == null || distributionTypes.Count == 0)
throw new ArgumentException("At least one distribution type is required.", nameof(distributionTypes));
var weights = new List<double>();
var distributions = new List<UnivariateDistributionBase>();
double w = 1d / distributionTypes.Count;
double sum = 0d;
for (int i = 0; i < distributionTypes.Count; i++)
{
if (i != distributionTypes.Count - 1)
{
sum += w;
weights.Add(w);
}
else
{
// Ensure exact sum of weights is one.
weights.Add(1d - sum);
}
distributions.Add(UnivariateDistributionFactory.CreateDistribution(distributionTypes[i]));
}
Mixture = new Mixture(weights.ToArray(), distributions.ToArray());
}
/// <inheritdoc/>
public override void SetDefaultParameters()
{
_defaultParameterInitializationError = null;
var initializationConstraints = new List<Tuple<double[], double[], double[]>>();
if (Mixture is not null && DataFrame is not null && DataFrame.Validate().IsValid &&
Mixture.Distributions is not null && Mixture.Distributions.Length > 0)
{
List<double> initializationSample = GetComponentInitializationSample();
foreach (UnivariateDistributionBase component in Mixture.Distributions)
{
if (!UnivariateDistribution.TryGetDefaultParameterConstraints(
component, initializationSample, out var constraints, out _defaultParameterInitializationError))
{
// Keep the current editable parameters; Validate reports why automatic defaults are unavailable.
RaisePropertyChange(nameof(SetDefaultParameters));
return;
}
initializationConstraints.Add(constraints!);
}
}
foreach (ModelParameter parameter in Parameters)
{
parameter.PropertyChanged -= Parameter_PropertyChanged;
}
_parameters = new List<ModelParameter>();
if (Mixture is null ||
DataFrame == null ||
!DataFrame.Validate().IsValid ||
Mixture.Distributions == null ||
Mixture.Distributions.Length == 0)
{
RaisePropertyChange(nameof(SetDefaultParameters));
return;
}
int componentCount = Mixture.Distributions.Length;
int publicWeightCount = GetPublicWeightCount(Mixture);
double componentMass = GetComponentMass();
double initialWeight = componentMass / componentCount;
for (int i = 0; i < publicWeightCount; i++)
{
Parameters.Add(new ModelParameter
{
Name = "Weight (w" + SubscriptFormatter.ToSubscript(i + 1) + ")",
Value = initialWeight,
LowerBound = 0.0,
UpperBound = componentMass,
PriorDistribution = new Uniform(0.0, componentMass)
});
}
for (int i = 0; i < componentCount; i++)
{
UnivariateDistributionBase component = Mixture.Distributions[i];
Tuple<double[], double[], double[]> constraints = initializationConstraints[i];
double[] initials = constraints.Item1;
double[] lowers = constraints.Item2;
double[] uppers = constraints.Item3;
string[,] parametersToString = component.ParametersToString;
for (int j = 0; j < component.NumberOfParameters; j++)
{
Parameters.Add(new ModelParameter
{
OwnerName = "D" + (i + 1).ToString(CultureInfo.InvariantCulture),
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])
});
}
}
foreach (ModelParameter parameter in Parameters)
{
parameter.PropertyChanged += Parameter_PropertyChanged;
}
RaisePropertyChange(nameof(SetDefaultParameters));
}
/// <inheritdoc/>
public override void SetDefaultQuantilePriors()
{
if (Mixture is null)
return;
// Remove old handlers
if (_quantilePriors != null)
{
for (int i = 0; i < _quantilePriors.Count; i++)
_quantilePriors[i].PropertyChanged -= QuantilePrior_PropertyChanged;
}
// If quantile priors are not enabled, clear the list and return
if (EnableQuantilePriors == false)
{
_quantilePriors = new List<QuantilePrior>();
_quantilePriorsTrue = new List<QuantilePrior>();
RaisePropertyChange(nameof(SetDefaultQuantilePriors));
return;
}
var priors = new List<QuantilePrior>();
int qCount = 1; // mixture model uses single quantile prior
if (QuantilePriors.Count >= 1)
{
priors = QuantilePriors.ToList();
while (priors.Count > qCount)
priors.Remove(priors.Last());
while (priors.Count < qCount)
{
priors.Add(new QuantilePrior(priors.Last().Alpha / 10.0, new LnNormal()));
double mu = Math.Round(Mixture.InverseCDF(1 - priors.Last().Alpha), 2);
double sigma = Math.Round(mu * 0.15, 2);
priors.Last().Distribution.SetParameters(new[] { mu, sigma });
}
}
else
{
for (int i = 1; i <= qCount; i++)
{
priors.Add(new QuantilePrior(Math.Pow(10, -i), new LnNormal()));
double mu = Math.Round(Mixture.InverseCDF(1 - priors[i - 1].Alpha), 2);
double sigma = Math.Round(mu * 0.15, 2);
priors[i - 1].Distribution.SetParameters(new[] { mu, sigma });
}
}
// Reset the quantile priors with the new list and add handlers
_quantilePriors = priors;
for (int i = 0; i < _quantilePriors.Count; i++)
_quantilePriors[i].PropertyChanged += QuantilePrior_PropertyChanged;
ProcessQuantilePriors();
RaisePropertyChange(nameof(SetDefaultQuantilePriors));
}
/// <inheritdoc/>
public override void ProcessQuantilePriors()
{
_quantilePriorsTrue.Clear();
if (QuantilePriors.Count == 1)
{
_quantilePriorsTrue.Add(QuantilePriors[0].Clone());
return;
}
// Currently mixture uses only a single quantile prior; multi-quantile
// branch is left here for possible future extension but not used.
if (!UseSingleQuantile &&
Mixture is not null &&
QuantilePriors.Count == Mixture.NumberOfParameters)
{
_quantilePriorsTrue.Add(QuantilePriors[0].Clone());
for (int i = 1; i < QuantilePriors.Count; i++)
{
double muDiff = QuantilePriors[i].Distribution.Mean - QuantilePriors[i - 1].Distribution.Mean;
double sigmaDiff = Math.Sqrt(QuantilePriors[i].Distribution.Variance + QuantilePriors[i - 1].Distribution.Variance);
var gamma = new GammaDistribution();
gamma.SetParameters(gamma.ParametersFromMoments(new[] { muDiff, sigmaDiff }));
_quantilePriorsTrue.Add(new QuantilePrior(QuantilePriors[i].Alpha, gamma));
}
}
}
/// <summary>
/// Returns the logarithmic density of one continuous EM component, with positive conditioning when configured.
/// </summary>
/// <param name="model">The current physical mixture.</param>
/// <param name="componentIndex">The continuous component index.</param>
/// <param name="value">The evaluation value.</param>
/// <returns>The log density, or negative infinity outside the positive conditional support.</returns>
private static double ComponentLogDensity(Mixture model, int componentIndex, double value)
{
var component = model.Distributions[componentIndex];
if (!model.IsZeroInflated) return component.LogPDF(value);
return value > 0.0
? component.LogPDF(value) - component.LogCCDF(0.0)
: double.NegativeInfinity;
}
/// <summary>
/// Returns a continuous component's log CDF under the configured positive conditioning.
/// </summary>
/// <param name="model">The current physical mixture.</param>
/// <param name="componentIndex">The continuous component index.</param>
/// <param name="value">The censoring threshold.</param>
/// <returns>The log CDF, bounded above by zero for a conditional probability.</returns>
private static double ComponentLogCdf(Mixture model, int componentIndex, double value)
{
var component = model.Distributions[componentIndex];