-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathDistribution.R
892 lines (793 loc) · 28.6 KB
/
Distribution.R
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
#' @include distr6_globals.R helpers.R
#' @title Generalised Distribution Object
#'
#' @description A generalised distribution object for defining custom probability distributions
#' as well as serving as the parent class to specific, familiar distributions.
#'
#' @name Distribution
#' @template param_decorators
#' @template method_setParameterValue
#' @template method_liesin
#' @template param_log
#' @template param_logp
#' @template param_simplify
#' @template param_data
#' @template param_lowertail
#' @template param_n
#' @template param_paramid
#' @template class_distribution
#' @template field_alias
#'
#' @return Returns R6 object of class Distribution.
#'
#' @export
Distribution <- R6Class("Distribution",
lock_objects = FALSE,
public = list(
name = character(0),
short_name = character(0),
alias = character(0),
description = NULL,
#' @description
#' Creates a new instance of this [R6][R6::R6Class] class.
#' @param name `character(1)` \cr
#' Full name of distribution.
#' @param short_name `character(1)` \cr
#' Short name of distribution for printing.
#' @param alias `character(1)` \cr
#' Alias of distribution for parsing.
#' @param type `([set6::Set])` \cr
#' Distribution type.
#' @param support `([set6::Set])` \cr
#' Distribution support.
#' @param symmetric `logical(1)` \cr
#' Symmetry type of the distribution.
#' @param pdf `function(1)` \cr
#' Probability density function of the distribution. At least one of `pdf` and
#' `cdf` must be provided.
#' @param cdf `function(1)` \cr
#' Cumulative distribution function of the distribution. At least one of `pdf` and
#' `cdf` must be provided.
#' @param quantile `function(1)` \cr
#' Quantile (inverse-cdf) function of the distribution.
#' @param rand `function(1)` \cr
#' Simulation function for drawing random samples from the distribution.
#' @param parameters `([param6::ParameterSet])` \cr
#' Parameter set for defining the parameters in the distribution, which should be set before
#' construction.
#' @param valueSupport `(character(1))` \cr
#' The support type of the distribution, one of `"discrete", "continuous", "mixture"`.
#' If `NULL`, determined automatically.
#' @param variateForm `(character(1))` \cr
#' The variate type of the distribution, one of `"univariate", "multivariate", "matrixvariate"`.
#' If `NULL`, determined automatically.
#' @param description `(character(1))` \cr
#' Optional short description of the distribution.
#' @param .suppressChecks `(logical(1))` \cr
#' Used internally.
initialize = function(name = NULL, short_name = NULL,
type, support = NULL,
symmetric = FALSE,
pdf = NULL, cdf = NULL, quantile = NULL, rand = NULL,
parameters = NULL, decorators = NULL, valueSupport = NULL,
variateForm = NULL, description = NULL,
.suppressChecks = FALSE) {
if (.suppressChecks | inherits(self, "DistributionWrapper")) {
if (!is.null(parameters)) parameters <- parameters$clone(deep = TRUE)
if (!is.null(pdf)) formals(pdf) <- c(formals(pdf), list(self = self))
if (!is.null(cdf)) formals(cdf) <- c(formals(cdf), list(self = self))
if (!is.null(quantile)) formals(quantile) <- c(formals(quantile), list(self = self))
if (!is.null(rand)) formals(rand) <- c(formals(rand), list(self = self))
} else if (getR6Class(self) == "Distribution") {
if (is.null(pdf) & is.null(cdf)) {
stop("One of pdf or cdf must be provided.")
}
#------------
# Name Checks
#------------
if (is.null(name) & is.null(short_name)) {
checkmate::assert("One of 'name' or 'short_name' must be provided.")
}
if (is.null(short_name)) short_name <- gsub(" ", "", name, fixed = T)
if (is.null(name)) name <- short_name
checkmate::assertCharacter(c(name, short_name),
.var.name = "'name' and 'short_name' must be of class 'character'."
)
checkmate::assert(length(strsplit(short_name, split = " ")[[1]]) == 1,
.var.name = "'short_name' must be one word only."
)
#------------------------
# Type and Support Checks
#------------------------
if (missing(type)) {
stop("Distribution type must be provided.")
}
if (is.null(support)) support <- type
assertSet(type)
assertSet(support)
#--------------------
# valueSupport Checks
#--------------------
if (!is.null(valueSupport)) {
valueSupport <- match.arg(valueSupport, c("continuous", "discrete", "mixture"))
} else if (support$properties$countability == "uncountable") {
valueSupport <- "continuous"
} else {
valueSupport <- "discrete"
}
#-------------------
# variateForm Checks
#-------------------
if (!is.null(variateForm)) {
variateForm <- match.arg(variateForm, c("univariate", "multivariate", "matrixvariate"))
} else if (getR6Class(type) %in% c("ProductSet", "ExponentSet")) {
variateForm <- "multivariate"
} else {
variateForm <- "univariate"
}
#-------------------
# pdf and cdf Checks
#-------------------
if (!is.null(pdf)) {
checkmate::assertSubset(names(formals(pdf)), c("x", "log"))
formals(pdf) <- c(formals(pdf), list(self = self), alist(... = )) # nolint
}
if (!is.null(cdf)) {
checkmate::assertSubset(names(formals(cdf)), c("x", "lower.tail", "log.p"))
formals(cdf) <- c(formals(cdf), list(self = self), alist(... = )) # nolint
}
#-------------------------
# quantile and rand Checks
#-------------------------
if (!is.null(quantile)) {
checkmate::assertSubset(names(formals(quantile)), c("p", "lower.tail", "log.p"))
formals(quantile) <- c(formals(quantile), list(self = self), alist(... = )) # nolint
}
if (!is.null(rand)) {
stopifnot(names(formals(rand)) == "n")
formals(rand) <- c(formals(rand), list(self = self), alist(... = )) # nolint
}
#-------------------------
# Parameter Checks
#-------------------------
if (!is.null(parameters)) {
assertParameterSet(parameters)
# parameters <- parameters$clone(deep = TRUE)$.__enclos_env__$private$.update()
}
}
if (!is.null(parameters)) {
private$.parameters <- parameters
}
if (!is.null(pdf)) {
private$.pdf <- pdf
private$.isPdf <- 1L
}
if (!is.null(cdf)) {
private$.cdf <- cdf
private$.isCdf <- 1L
}
if (!is.null(quantile)) {
private$.quantile <- quantile
private$.isQuantile <- 1L
}
if (!is.null(rand)) {
private$.rand <- rand
private$.isRand <- 1L
}
if (!is.null(name)) self$name <- name
if (!is.null(short_name)) self$short_name <- short_name
private$.properties$support <- support
private$.traits$type <- type
private$.traits$valueSupport <- valueSupport
private$.traits$variateForm <- variateForm
if (!is.null(description)) self$description <- description
symm <- ifelse(symmetric, "symmetric", "asymmetric")
private$.properties$symmetry <- symm
if (!is.null(decorators)) {
suppressMessages(decorate(self, decorators))
}
lockBinding("name", self)
lockBinding("short_name", self)
lockBinding("description", self)
lockBinding("traits", self)
lockBinding("parameters", self)
invisible(self)
},
#' @description
#' Printable string representation of the `Distribution`. Primarily used internally.
#' @param n `(integer(1))` \cr
#' Number of parameters to display when printing.
strprint = function(n = 2) {
as.character(self, 2)
},
#' @description
#' Prints the `Distribution`.
#' @param n `(integer(1))` \cr
#' Passed to `$strprint`.
#' @param ... `ANY` \cr
#' Unused. Added for consistency.
print = function(n = 2, ...) {
cat(self$strprint(n = n), "\n")
invisible(self)
},
#' @description
#' Prints a summary of the `Distribution`.
#' @param full `(logical(1))` \cr
#' If `TRUE` (default) prints a long summary of the distribution,
#' otherwise prints a shorter summary.
#' @param ... `ANY` \cr
#' Unused. Added for consistency.
summary = function(full = TRUE, ...) {
if (full) {
pars <- self$parameters()
name <- ifelse(is.null(self$description), self$name, self$description)
if (!length(pars)) {
cat(name)
} else {
cat(name, "\nParameterised with:\n\n")
print(self$parameters())
}
a_exp <- suppressMessages(try(self$mean(), silent = T))
a_var <- suppressMessages(try(self$variance(), silent = T))
a_skew <- suppressMessages(try(self$skewness(), silent = T))
a_kurt <- suppressMessages(try(self$kurtosis(), silent = T))
if (!inherits(a_exp, "try-error") | !inherits(a_var, "try-error") |
!inherits(a_skew, "try-error") | !inherits(a_kurt, "try-error")) {
cat("\n\n", "Quick Statistics", "\n", sep = "")
}
if (!inherits(a_exp, "try-error")) {
cat("\tMean:")
if (length(a_exp) > 1) {
cat("\t\t", paste0(a_exp, collapse = ", "), "\n", sep = "")
} else {
cat("\t\t", a_exp, "\n", sep = "")
}
}
if (!inherits(a_var, "try-error")) {
cat("\tVariance:")
if (length(a_var) > 1) {
cat("\t", paste0(a_var, collapse = ", "), "\n", sep = "")
} else {
cat("\t", a_var, "\n", sep = "")
}
}
if (!inherits(a_skew, "try-error")) {
cat("\tSkewness:")
# if(length(a_skew) > 1)
# cat("\t", paste0(a_skew, collapse = ", "),"\n", sep = "")
# else
cat("\t", a_skew, "\n", sep = "")
}
if (!inherits(a_kurt, "try-error")) {
cat("\tEx. Kurtosis:")
# if(length(a_kurt) > 1)
# cat("\t", paste0(a_kurt, collapse = ", "),"\n", sep = "")
# else
cat("\t", a_kurt, "\n", sep = "")
}
cat("\n")
cat("Support:", self$properties$support$strprint(),
"\tScientific Type:", self$traits$type$strprint(), "\n")
cat("\nTraits:\t\t", self$traits$valueSupport, "; ",
self$traits$variateForm, sep = "")
cat("\nProperties:\t", self$properties$symmetry, sep = "")
a_kurt <- self$properties$kurtosis
a_skew <- self$properties$skewness
if (!is.null(a_kurt)) cat(";", a_kurt)
if (!is.null(a_skew)) cat(";", a_skew)
if (length(self$decorators) != 0) {
cat("\n\n Decorated with: ", paste0(self$decorators, collapse = ", "))
}
} else {
if (length(private$.parameters) != 0) {
cat(self$strprint())
} else {
cat(self$name)
}
cat("\nScientific Type:", self$traits$type$strprint(), "\t See $traits for more")
cat("\nSupport:", self$properties$support$strprint(), "\t See $properties for more")
}
cat("\n")
invisible(self)
},
#' @description
#' Returns the full parameter details for the supplied parameter.
#' @param id Deprecated.
parameters = function(id = NULL) {
if (!is.null(id)) {
warning("'id' argument is deprecated and currently unused")
}
if (length(private$.parameters)) {
private$.parameters
}
},
#' @description
#' Returns the value of the supplied parameter.
getParameterValue = function(id, error = "warn") {
if (length(private$.parameters)) {
private$.parameters$get_values(id)
}
},
#' @description
#' Sets the value(s) of the given parameter(s).
#'
#' @examples
#' b = Binomial$new()
#' b$setParameterValue(size = 4, prob = 0.4)
#' b$setParameterValue(lst = list(size = 4, prob = 0.4))
setParameterValue = function(..., lst = list(...), error = "warn",
resolveConflicts = FALSE) {
if (resolveConflicts) {
warning("'resolveConflicts' is redundant and deprecated")
}
if (private$.parameters$length && length(lst)) {
private$.parameters$values <- unique_nlist(c(lst, private$.parameters$values))
}
invisible(self)
},
#' @description
#' For discrete distributions the probability mass function (pmf) is returned, defined as
#' \deqn{p_X(x) = P(X = x)}
#' for continuous distributions the probability density function (pdf), \eqn{f_X}, is returned
#' \deqn{f_X(x) = P(x < X \le x + dx)}
#' for some infinitesimally small \eqn{dx}.
#'
#' If available a pdf will be returned using an analytic expression. Otherwise,
#' if the distribution has not been decorated with [FunctionImputation], \code{NULL} is
#' returned.
#'
#' @param ... `(numeric())` \cr
#' Points to evaluate the function at Arguments do not need
#' to be named. The length of each argument corresponds to the number of points to evaluate,
#' the number of arguments corresponds to the number of variables in the distribution.
#' See examples.
#'
#' @examples
#' b <- Binomial$new()
#' b$pdf(1:10)
#' b$pdf(1:10, log = TRUE)
#' b$pdf(data = matrix(1:10))
#'
#' mvn <- MultivariateNormal$new()
#' mvn$pdf(1, 2)
#' mvn$pdf(1:2, 3:4)
#' mvn$pdf(data = matrix(1:4, nrow = 2), simplify = FALSE)
pdf = function(..., log = FALSE, simplify = TRUE, data = NULL) {
if (!private$.isPdf) {
return(NULL)
}
if (is.null(data)) {
if (!...length()) {
return(NULL)
} else if (!length(...elt(1))) {
return(NULL)
}
}
data <- pdq_point_assert(..., self = self, data = data)
if (!suppressWarnings(self$liesInType(as.numeric(data), all = TRUE, bound = TRUE))) {
stop(
sprintf("Not all points in %s lie in the distribution domain (%s).",
strCollapse(as.numeric(data)), self$traits$type$strprint())
)
}
if (log) {
if (private$.log) {
pdqr <- private$.pdf(data, log = log)
} else {
if ("CoreStatistics" %nin% self$decorators) {
stop("No analytical method for log available.
Use CoreStatistics decorator to numerically estimate this.")
} else {
pdqr <- log(private$.pdf(data))
}
}
} else {
pdqr <- private$.pdf(data)
}
pdqr_returner(pdqr, simplify, self$short_name)
},
#' @description
#' The (lower tail) cumulative distribution function, \eqn{F_X}, is defined as
#' \deqn{F_X(x) = P(X \le x)}
#' If \code{lower.tail} is FALSE then \eqn{1 - F_X(x)} is returned, also known as the
#' \code{\link{survival}} function.
#'
#' If available a cdf will be returned using an analytic expression. Otherwise,
#' if the distribution has not been decorated with [FunctionImputation], \code{NULL} is
#' returned.
#'
#' @param ... `(numeric())` \cr
#' Points to evaluate the function at Arguments do not need
#' to be named. The length of each argument corresponds to the number of points to evaluate,
#' the number of arguments corresponds to the number of variables in the distribution.
#' See examples.
#'
#' @examples
#' b <- Binomial$new()
#' b$cdf(1:10)
#' b$cdf(1:10, log.p = TRUE, lower.tail = FALSE)
#' b$cdf(data = matrix(1:10))
cdf = function(..., lower.tail = TRUE, log.p = FALSE, simplify = TRUE, data = NULL) {
if (!private$.isCdf) {
return(NULL)
}
if (is.null(data)) {
if (!...length()) {
return(NULL)
} else if (!length(...elt(1))) {
return(NULL)
}
}
data <- pdq_point_assert(..., self = self, data = data)
if (!suppressWarnings(self$liesInType(as.numeric(data), all = TRUE, bound = TRUE))) {
stop(
sprintf("Not all points in %s lie in the distribution domain (%s).",
strCollapse(as.numeric(data)), self$traits$type$strprint())
)
}
if (log.p | !lower.tail) {
if (private$.log) {
pdqr <- private$.cdf(data, log.p = log.p, lower.tail = lower.tail)
} else {
if ("CoreStatistics" %nin% self$decorators) {
stop("No analytical method for log.p or lower.tail available. Use CoreStatistics
decorator to numerically estimate this.")
} else {
pdqr <- private$.cdf(data)
if (!lower.tail) pdqr <- 1 - pdqr
if (log.p) pdqr <- log(pdqr)
}
}
} else {
pdqr <- private$.cdf(data)
}
pdqr_returner(pdqr, simplify, self$short_name)
},
#' @description
#' The quantile function, \eqn{q_X}, is the inverse cdf, i.e.
#' \deqn{q_X(p) = F^{-1}_X(p) = \inf\{x \in R: F_X(x) \ge p\}}{q_X(p) = F^(-1)_X(p) = inf{x \epsilon R: F_X(x) \ge p}} #nolint
#'
#' If \code{lower.tail} is FALSE then \eqn{q_X(1-p)} is returned.
#'
#' If available a quantile will be returned using an analytic expression. Otherwise,
#' if the distribution has not been decorated with [FunctionImputation], \code{NULL} is
#' returned.
#'
#' @param ... `(numeric())` \cr
#' Points to evaluate the function at Arguments do not need
#' to be named. The length of each argument corresponds to the number of points to evaluate,
#' the number of arguments corresponds to the number of variables in the distribution.
#' See examples.
#'
#' @examples
#' b <- Binomial$new()
#' b$quantile(0.42)
#' b$quantile(log(0.42), log.p = TRUE, lower.tail = TRUE)
#' b$quantile(data = matrix(c(0.1,0.2)))
quantile = function(..., lower.tail = TRUE, log.p = FALSE, simplify = TRUE, data = NULL) {
if (!private$.isQuantile) {
return(NULL)
}
if (is.null(data)) {
if (!...length()) {
return(NULL)
} else if (!length(...elt(1))) {
return(NULL)
}
}
data <- pdq_point_assert(..., self = self, data = data)
if (!log.p) {
if (!Interval$new(0, 1)$contains(as.numeric(data), all = TRUE)) {
stop(sprintf("Not all points in %s lie in [0, 1].", strCollapse(as.numeric(data))))
}
} else {
if (!Interval$new(0, 1)$contains(as.numeric(exp(data)), all = TRUE)) {
stop(sprintf("Not all points in %s lie in [0, 1].", strCollapse(as.numeric(exp(data)))))
}
}
if (log.p | !lower.tail) {
if (private$.log) {
pdqr <- private$.quantile(data, log.p = log.p, lower.tail = lower.tail)
} else {
if ("CoreStatistics" %nin% self$decorators) {
stop("No analytical method for log.p or lower.tail available. Use CoreStatistics
decorator to numerically estimate this.")
} else {
if (log.p) data <- exp(data)
if (!lower.tail) data <- 1 - data
pdqr <- private$.quantile(data)
}
}
} else {
pdqr <- private$.quantile(data)
}
pdqr_returner(pdqr, simplify, self$short_name)
},
#' @description
#' The rand function draws `n` simulations from the distribution.
#'
#' If available simulations will be returned using an analytic expression. Otherwise,
#' if the distribution has not been decorated with [FunctionImputation], \code{NULL} is
#' returned.
#'
#' @examples
#' b <- Binomial$new()
#' b$rand(10)
#'
#' mvn <- MultivariateNormal$new()
#' mvn$rand(5)
rand = function(n, simplify = TRUE) {
if (missing(n) | private$.isRand == 0L) {
return(NULL)
}
if (length(n) > 1) {
n <- length(n)
}
pdqr <- private$.rand(n)
pdqr_returner(pdqr, simplify, self$short_name)
},
#' @description
#' Returns the precision of the distribution as `1/self$variance()`.
prec = function() {
return(1 / self$variance())
},
#' @description
#' Returns the standard deviation of the distribution as `sqrt(self$variance())`.
stdev = function() {
return(sqrt(self$variance()))
},
#' @description
#' Returns the median of the distribution. If an analytical expression is available
#' returns distribution median, otherwise if symmetric returns `self$mean`, otherwise
#' returns `self$quantile(0.5)`.
#' @param na.rm `(logical(1))`\cr
#' Ignored, addded for consistency.
#' @param ... `ANY` \cr
#' Ignored, addded for consistency.
median = function(na.rm = NULL, ...) {
if (testSymmetric(self)) {
med <- try(self$mean(), silent = TRUE)
if (inherits(med, "try-error")) {
return(self$quantile(0.5))
} else if (is.null(med)) {
return(self$quantile(0.5))
} else {
return(med)
}
} else if (!testUnivariate(self)) {
return(NaN)
} else {
return(self$quantile(0.5))
}
},
#' @description
#' Inter-quartile range of the distribution. Estimated as
#' `self$quantile(0.75) - self$quantile(0.25)`.
iqr = function() {
return(self$quantile(0.75) - self$quantile(0.25))
},
#' @description
#' 1 or 2-sided confidence interval around distribution.
#' @param alpha `(numeric(1))` \cr Level of confidence, default is 95%
#' @param sides `(character(1))` \cr One of 'lower', 'upper' or 'both'
#' @param median `(logical(1))` \cr If `TRUE` also returns median
confidence = function(alpha = 0.95, sides = "both", median = FALSE) {
if (sides == "both") {
alpha <- c((1 - alpha) / 2, 1 - (1 - alpha) / 2)
} else if (sides == "lower") {
alpha <- 1 - alpha
} else if (sides != "upper") {
stop("'sides' should be one of 'lower', 'upper', or 'both'")
}
if (median) {
alpha <- unique(c(alpha, 0.5))
}
sort(self$quantile(alpha))
},
#' @description
#' If univariate returns `1`, otherwise returns the distribution correlation.
correlation = function() {
if (testUnivariate(self)) {
return(1)
} else {
return(self$variance() / (sqrt(diag(self$variance()) %*% t(diag(self$variance())))))
}
},
#' @description
#' Tests if the given values lie in the support of the distribution.
#' Uses `[set6::Set]$contains`.
liesInSupport = function(x, all = TRUE, bound = FALSE) {
return(self$properties$support$contains(x, all, bound))
},
#' @description
#' Tests if the given values lie in the type of the distribution.
#' Uses `[set6::Set]$contains`.
liesInType = function(x, all = TRUE, bound = FALSE) {
return(self$traits$type$contains(x, all, bound))
},
#' @description
#' Returns an estimate for the computational support of the distribution.
#' If an analytical cdf is available, then this is computed as the smallest interval
#' in which the cdf lower bound is `0` and the upper bound is `1`, bounds are incremented in
#' 10^i intervals. If no analytical cdf is available, then this is computed as the smallest
#' interval in which the lower and upper bounds of the pdf are `0`, this is much less precise
#' and is more prone to error. Used primarily by decorators.
workingSupport = function() {
if (testCountablyFinite(support <- private$.properties$support)) {
return(support)
}
lower <- support$lower
upper <- support$upper
if (lower == -Inf) {
if (private$.isCdf == 1L) {
for (i in -c(0, 10^(1:1000))) { # nolint
if (i >= lower & i <= upper) {
if (self$cdf(i) == 0) {
lower <- i
break() # nolint
}
}
}
} else {
for (i in -c(0, 10^(1:1000))) { # nolint
if (i >= lower & i <= upper) {
if (self$pdf(i) == 0) {
lower <- i
break() # nolint
}
}
}
}
}
if (upper == Inf) {
if (private$.isCdf == 1L) {
for (i in c(0, 10^(1:1000))) { # nolint
if (i >= lower & i <= upper) {
if (self$cdf(i) == 1) {
upper <- i
break() # nolint
}
}
}
} else {
for (i in c(0, 10^(1:1000))) { # nolint
if (i >= lower & i <= upper) {
if (self$pdf(i) == 0) {
upper <- i
break() # nolint
}
}
}
}
}
class <- if (testDiscrete(self)) "integer" else "numeric"
Interval$new(lower, upper, class = class)
}
),
active = list(
#' @field decorators
#' Returns decorators currently used to decorate the distribution.
decorators = function() {
return(private$.decorators)
},
#' @field traits
#' Returns distribution traits.
traits = function() {
return(private$.traits)
},
#' @field valueSupport
#' Deprecated, use `$traits$valueSupport`.
valueSupport = function() {
message("Deprecated. Use $traits$valueSupport instead.")
return(self$traits$valueSupport)
},
#' @field variateForm
#' Deprecated, use `$traits$variateForm`.
variateForm = function() {
message("Deprecated. Use $traits$variateForm instead.")
return(self$traits$variateForm)
},
#' @field type
#' Deprecated, use `$traits$type`.
type = function() {
message("Deprecated. Use $traits$type instead.")
return(self$traits$type)
},
#' @field properties
#' Returns distribution properties, including skewness type and symmetry.
properties = function() {
prop <- private$.properties
prop$kurtosis <- tryCatch(exkurtosisType(self$kurtosis()), error = function(e) NULL)
prop$skewness <- tryCatch(skewType(self$skewness()), error = function(e) NULL)
prop
},
#' @field support
#' Deprecated, use `$properties$type`.
support = function() {
message("Deprecated. Use $properties$support instead.")
return(self$properties$support)
},
#' @field symmetry
#' Deprecated, use `$properties$symmetry`.
symmetry = function() {
message("Deprecated. Use $properties$symmetry instead.")
return(self$properties$symmetry)
},
#' @field sup
#' Returns supremum (upper bound) of the distribution support.
sup = function() {
return(self$properties$support$upper)
},
#' @field inf
#' Returns infimum (lower bound) of the distribution support.
inf = function() {
return(self$properties$support$lower)
},
#' @field dmax
#' Returns maximum of the distribution support.
dmax = function() {
return(self$properties$support$max)
},
#' @field dmin
#' Returns minimum of the distribution support.
dmin = function() {
return(self$properties$support$min)
},
#' @field kurtosisType
#' Deprecated, use `$properties$kurtosis`.
kurtosisType = function() {
message("Deprecated. Use $properties$kurtosis instead.")
return(self$properties$kurtosis)
},
#' @field skewnessType
#' Deprecated, use `$properties$skewness`.
skewnessType = function() {
message("Deprecated. Use $properties$skewness instead.")
return(self$properties$skewness)
}
),
private = list(
.parameters = NULL,
.decorators = NULL,
.properties = list(),
.traits = NULL,
.variates = 1,
.isPdf = 0L,
.isCdf = 0L,
.isQuantile = 0L,
.isRand = 0L,
.log = FALSE,
.updateDecorators = function(decs) {
private$.decorators <- decs
}
)
)
#' @export
as.character.Distribution <- function(x, n, ...) {
if (length(x$parameters()) != 0) {
p <- sort_named_list(x$parameters()$values)
lng <- length(p)
if (lng > (2 * n)) {
string <- paste0(
x$short_name, "(",
paste(names(p)[1:n], p[1:n], sep = " = ", collapse = ", "),
",...,", paste(names(p)[(lng - n + 1):lng], p[(lng - n + 1):lng],
sep = " = ",
collapse = ", "
), ")"
)
} else {
string <- paste0(
x$short_name, "(", paste(names(p), p, sep = " = ", collapse = ", "),
")"
)
}
} else {
string <- paste0(x$short_name, "()")
}
string
}
#' @export
summary.Distribution <- function(object, ...) {
object$summary(...)
}