utilityFunctions.R 19.2 KB
Newer Older
1
2
3
4
#' @include mortalityTable.R
NULL


5
fitExtrapolationLaw = function(data, ages, data.ages = ages, Dx = NULL, Ex = NULL, qx = NULL, method = "LF2", law = "HP", fit = 75:99, extrapolate = 80:120, fadeIn = 80:90, fadeOut = NULL, verbose = FALSE) {
6
7
8
9
10
11
12
13
14
15
16
    # Add the extrapolate ages to the needed ages
    neededAges = union(ages, extrapolate)
    # constrain the fit and fade-in range to given ages
    fit = intersect(ages, fit)
    if (!is.null(fadeIn))
        fadeIn = intersect(ages, fadeIn)
    if (!is.null(fadeOut))
        fadeOut = intersect(ages, fadeOut)

    # Hohe Alter: Fitte Heligman-Pollard im Bereich 75-99
    fitLaw = MortalityLaw(
17
        x = data.ages, Dx = Dx, Ex = Ex, qx = qx,
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
        law = law, opt.method = method,
        fit.this.x = fit)
    # summary(fitAP.m.75.99)
    # plot(fitAP.m.75.99)
    qPredict = predict(fitLaw, extrapolate)

    weights = rep(0, length(neededAges))
    names(weights) = neededAges
    if (!is.null(fadeIn)) {
        weights[neededAges < min(fadeIn)] = 0
        fadeInLen = length(fadeIn);
        weights[match(fadeIn, neededAges)] = (0:(fadeInLen - 1)) / (fadeInLen - 1)
        weights[neededAges > max(fadeIn)] = 1
    } else if (!is.null(fadeOut)) {
        weights[neededAges < min(fadeOut)] = 1
        fadeOutLen = length(fadeOut);
        weights[match(fadeOut, neededAges)] = ((fadeOutLen - 1):0) / (fadeOutLen - 1)
        weights[neededAges > max(fadeOut)] = 0
    }

    probs = fillAges(qPredict, givenAges = extrapolate, neededAges = neededAges, fill = 0) * weights +
        fillAges(data, givenAges = ages, neededAges = neededAges, fill = 0) * (1 - weights)

    if (verbose) {
        list(probs = probs, law = fitLaw, weights = weights)
    } else {
        probs
    }
}




# Fit an exponential function exp(-A*(x-x0)) to the last value (f(100) and f'(100) need to coincide):
fitExpExtrapolation = function(data, idx, up = TRUE, verbose = FALSE) {
    # browser()
    # Anchor point of the extrapolation
    f0 = data[[idx]]
    if (up) {
        A = -(data[[idx]] - data[[idx - 1]]) / f0
    } else {
        A = -(data[[idx + 1]] - data[[idx]]) / f0
    }
    x0 = idx + (log(f0) / A)
    fun.extra = function(x) exp(-A*(x - x0))
    if (up) {
        newdata = c(data[1:idx], sapply((idx + 1):length(data), fun.extra))
    } else {
        newdata = c(sapply(1:(idx - 1), fun.extra), data[idx:length(data)])
    }
    if (verbose) {
        list(data = newdata, A = A, x0 = x0, idx = idx)
    } else {
        newdata
    }
}


#' @export
77
mT.setName = function(table, name) {
78
79
80
81
82
    if (is.array(table)) {
        return(array(
            lapply(table, mT.setName, name = name),
            dim = dim(table), dimnames = dimnames(table))
        )
83
84
    } else if (is.list(table)) {
        return(lapply(table, mT.setName, name = name))
85
    }
86
    if (!is(table, "mortalityTable"))
87
        stop("First argument must be a mortalityTable or a list of mortalityTable objects.")
88
89
90
91
92
93
94
95
96

    table@name = name
    table
}



#' @export
mT.fillAges = function(table, neededAges, fill = 0) {
97
98
99
100
101
    if (is.array(table)) {
        return(array(
            lapply(table, mT.fillAges, neededAges = neededAges, fill = fill),
            dim = dim(table), dimnames = dimnames(table))
        )
102
103
    } else if (is.list(table)) {
        return(lapply(table, mT.fillAges, neededAges = neededAges, fill = fill))
104
    }
105
    if (!is(table, "mortalityTable"))
106
        stop("First argument must be a mortalityTable or a list of mortalityTable objects.")
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122

    existingAges = ages(table)
    if (.hasSlot(table, "ages"))
        table@ages = neededAges
    if (.hasSlot(table, "deathProbs"))
        table@deathProbs = fillAges(table@deathProbs, givenAges = existingAges, neededAges = neededAges, fill = fill)
    if (.hasSlot(table, "exposures") && !is.null(table@exposures) && length(table@exposures) > 1)
        table@exposures = fillAges(table@exposures, givenAges = existingAges, neededAges = neededAges, fill = 0)
    if (.hasSlot(table, "trend") && !is.null(table@trend) && length(table@trend) > 1)
        table@trend = fillAges(table@trend, givenAges = existingAges, neededAges = neededAges, fill = 0)
    if (.hasSlot(table, "trend2") && !is.null(table@trend2) && length(table@trend2) > 1)
        table@trend2 = fillAges(table@trend2, givenAges = existingAges, neededAges = neededAges, fill = 0)
    if (.hasSlot(table, "loading") && !is.null(table@loading) && length(table@loading) > 1)
        table@loading = fillAges(table@loading, givenAges = existingAges, neededAges = neededAges, fill = 0)
    if (!is.null(table@data$deaths))
        table@data$deaths = fillAges(table@data$deaths, givenAges = existingAges, neededAges = neededAges, fill = 0)
123
124
    if (!is.null(table@data$rawProbs))
        table@data$rawProbs = fillAges(table@data$rawProbs, givenAges = existingAges, neededAges = neededAges, fill = 0)
125
126
127
128
    table
}

#' @export
129
mT.scaleProbs = function(table, factor = 1.0, name.postfix = "scaled", name = NULL) {
130
131
132
133
134
    if (is.array(table)) {
        return(array(
            lapply(table, mT.scaleProbs, factor = factor, name.postfix = name.postfix, name = name),
            dim = dim(table), dimnames = dimnames(table))
        )
135
136
    } else if (is.list(table)) {
        return(lapply(table, mT.scaleProbs, factor = factor, name.postfix = name.postfix, name = name))
137
138
139
140
    }
    if (!is(table, "mortalityTable"))
        stop("First argument must be a mortalityTable or a list of mortalityTable objects.")

141
    table@deathProbs = factor * table@deathProbs
142
143
144
145
146
    if (is.null(name)) {
        if (!is.null(name.postfix)) {
            name = paste(table@name, name.postfix)
        }
    }
147
148
149
150
151
152
153
154
    if (!is.null(name)) {
        table@name = name
    }
    table
}


#' @export
155
mT.setTrend = function(table, trend, trendages = NULL, baseYear = NULL, dampingFunction = identity) {
156
157
158
159
160
    if (is.array(table)) {
        return(array(
            lapply(table, mT.setTrend, trend = trend, trendages = trendages, baseYear = baseYear, dampingFunction = dampingFunction),
            dim = dim(table), dimnames = dimnames(table))
        )
161
162
    } else if (is.list(table)) {
        return(lapply(table, mT.setTrend, trend = trend, trendages = trendages, baseYear = baseYear, dampingFunction = dampingFunction))
163
    }
164
    if (!is(table, "mortalityTable"))
165
        stop("First argument must be a mortalityTable or a list of mortalityTable objects.")
166
167
168

    t = mortalityTable.trendProjection(
        table,
169
170
        baseYear = if (is.null(baseYear)) table@baseYear else baseYear,
        trend = trend[match(table@ages, if (is.null(trendages)) ages(table) else trendages)],
171
        dampingFunction = dampingFunction
172
173
174
175
176
177
178
179
180
181
182
    )
    t
}
#' @describeIn mT.setTrend Add a trend to the mortality table (returns a mortalityTable.trendProjection obect)
#' @export
mT.addTrend = mT.setTrend



#' @export
mT.extrapolateTrendExp = function(table, idx, up = TRUE) {
183
184
185
186
187
    if (is.array(table)) {
        return(array(
            lapply(table, mT.extrapolateTrendExp, idx = idx, up = up),
            dim = dim(table), dimnames = dimnames(table))
        )
188
189
    } else if (is.list(table)) {
        return(lapply(table, mT.extrapolateTrendExp, idx = idx, up = up))
190
    }
191
    if (!is(table, "mortalityTable"))
192
        stop("First argument must be a mortalityTable or a list of mortalityTable objects.")
193

194
    if (.hasSlot(table, "trend") && !is.null(table@trend) && length(table@trend) > 1)
195
        table@trend = fitExpExtrapolation(table@trend, idx = idx,up = up)
196
    if (.hasSlot(table, "trend2") && !is.null(table@trend2) && length(table@trend2) > 1)
197
198
199
200
201
202
        table@trend2 = fitExpExtrapolation(table@trend2, idx = idx,up = up)
    table
}


#' @export
203
mT.translate = function(table, baseYear, name = NULL) {
204
205
206
207
208
    if (is.array(table)) {
        return(array(
            lapply(table, mT.translate, baseYear = baseYear, name = name),
            dim = dim(table), dimnames = dimnames(table))
        )
209
210
    } else if (is.list(table)) {
        return(lapply(table, mT.translate, baseYear = baseYear, name = name))
211
    }
212
    if (!is(table, "mortalityTable"))
213
        stop("First argument must be a mortalityTable or a list of mortalityTable objects.")
214
215
216

    table@deathProbs = periodDeathProbabilities(table, Period = baseYear)
    table@baseYear = baseYear
217
218
219
    if (!is.null(name)) {
        table@name = name
    }
220
221
222
223
224
225
    table
}


#' @export
mT.extrapolateProbsExp = function(table, age, up = TRUE) {
226
227
228
229
230
    if (is.array(table)) {
        return(array(
            lapply(table, mT.extrapolateProbsExp, age = age, up = up),
            dim = dim(table), dimnames = dimnames(table))
        )
231
232
    } else if (is.list(table)) {
        return(lapply(table, mT.extrapolateProbsExp, age = age, up = up))
233
    }
234
    if (!is(table, "mortalityTable"))
235
        stop("First argument must be a mortalityTable or a list of mortalityTable objects.")
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251

    if (.hasSlot(table, "deathProbs")) {
        idx = match(age, ages(table))
        fit = fitExpExtrapolation(table@deathProbs, idx = idx, up = up, verbose = TRUE)
        table@deathProbs = fit$data
        table@data$extrapolationData = c(
            table@data$extrapolationData,
            list(list(law = "Exp", idx = idx, up = up, fit = fit)))
    }
    table
}


#' @export
mT.fitExtrapolationLaw = function(table, method = "LF2", law = "HP",
                                  fit = 75:99, extrapolate = 80:120,
252
                                  fadeIn = 80:90, fadeOut = NULL, raw = NULL) {
253
254
    if (!is(table, "mortalityTable"))
        stop("First argument must be a mortalityTable.")
255
    ages = ages(table)
256
257
258
    # if (!is.null(table@exposures) && !is.na(table@exposures)) {
        # Ex = table@exposures
        # qx = table@deathProbs
259
260
261
262
263
        # if (!is.null(table@data$deaths)) {
        #     Dx = table@data$deaths
        # } else {
        #     Dx = table@deathProbs * Ex
        # }
264
265
    # } else {
        # Ex = rep(1, length(ages))
266
        # Dx = table@deathProbs
267
268
        # qx = table@deathProbs
    # }
269
270
271
272
273
274
275
    if (!is.null(raw)) {
        rawData = raw
    } else if (!is.null(table@data$rawProbs)) {
        rawData = table@data$rawProbs
    } else {
        rawData = table@deathProbs
    }
276
277
278
    table  = mT.fillAges(table, neededAges = union(ages, extrapolate), fill = 0)
    fitted = fitExtrapolationLaw(
        data = table@deathProbs, ages = ages(table),
279
        qx = rawData, data.ages = ages,
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
        method = method, law = law,
        fit = fit, extrapolate = extrapolate,
        fadeIn = fadeIn, fadeOut = fadeOut,
        verbose = TRUE
    )
    # Store all fit parameters in the data slot of the mortality table
    table@data$extrapolationData = c(
        table@data$extrapolationData,
        list(list(law = law, method = method, fit = fit,
                  extrapolate = extrapolate, fadeIn = fadeIn, fadeOut = fadeOut,
                  fit = fitted)))
    table@deathProbs = fitted$probs

    table
}

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
#' @export
pT.setDimInfo = function(table, ..., append = TRUE) {
    if (is.array(table)) {
        return(array(
            lapply(table, pT.setDimInfo, ..., append = append),
            dim = dim(table), dimnames = dimnames(table))
        )
    } else if (is.list(table)) {
        return(lapply(table, pT.setDimInfo, ..., append = append))
    }
    if (!is(table, "pensionTable"))
        stop("First argument must be a pensionTable or a list of pensionTable objects.")

    if (append) {
        table@data[names(list(...))] = list(...)
    } else {
        table@data = list(...)
    }

    table@qx = mT.setDimInfo(table@qx, ..., append = append)
    table@ix = mT.setDimInfo(table@ix, ..., append = append)
    table@qix = mT.setDimInfo(table@qix, ..., append = append)
    table@rx = mT.setDimInfo(table@rx, ..., append = append)
    table@apx = mT.setDimInfo(table@apx, ..., append = append)
    table@qpx = mT.setDimInfo(table@qpx, ..., append = append)
    table@hx = mT.setDimInfo(table@hx, ..., append = append)
    table@qwy = mT.setDimInfo(table@qwy, ..., append = append)
    table@qgx = mT.setDimInfo(table@qgx, ..., append = append)
    table
}


328
329
#' @export
mT.setDimInfo = function(table, ..., append = TRUE) {
330
331
332
333
334
    if (is.array(table)) {
        return(array(
            lapply(table, mT.setDimInfo, ..., append = append),
            dim = dim(table), dimnames = dimnames(table))
        )
335
336
    } else if (is.list(table)) {
        return(lapply(table, mT.setDimInfo, ..., append = append))
337
338
    } else if (is(table, "pensionTable")) {
        return(pT.setDimInfo(table, ..., append = append))
339
    }
340

341
    if (!is(table, "mortalityTable"))
342
        stop("First argument must be a mortalityTable or a list of mortalityTable objects.")
343
344
345
346
347
348
349
350
351

    if (append) {
        table@data$dim[names(list(...))] = list(...)
    } else {
        table@data$dim = list(...)
    }
    table
}

352
353
354
355
356
357
358
359
360
361
362
363
364
365

#' @export
pT.getSubTable = function(table, subtable = "qx") {
    if (is.array(table)) {
        return(array(
            lapply(table, pT.getSubTable, subtable = subtable),
            dim = dim(table), dimnames = dimnames(table))
        )
    } else if (is.list(table)) {
        return(lapply(table, pT.getSubTable, subtable = subtable))
    }
    if (!is(table, "pensionTable"))
        stop("First argument must be a pensionTable or a list of pensionTable objects.")

366
367
368
369
370
371
372
373
    if (length(subtable) > 1) {
        return(lapply(subtable, function(st) pT.getSubTable(table, subtable = st)))
    } else {
        if (.hasSlot(table, subtable))
            slot(table, subtable)
        else
            NULL
    }
374
}
375

376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
#' @export
mT.switchover = function(table, to, at, weights = NULL) {
    if (is.array(table)) {
        return(array(
            lapply(table, mT.switchover, to = to, at = at, weights = weights),
            dim = dim(table), dimnames = dimnames(table))
        )
    } else if (is.list(table)) {
        return(lapply(table, mT.switchover, to = to, at = at, weights = weights))
    }
    if (!is(table, "mortalityTable"))
        stop("First argument must be a mortalityTable or a list of mortalityTable objects.")

    if (is.null(weights)) {
        ags.table = ages(table)
        ags.to = ages(to)
        weights = 1 * (ags.to >= at)
    }
    table@deathProbs = table@deathProbs * (1 - weights) + to@deathProbs * weights
    table
}

398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421


#' @exportMethod mT.round
setGeneric("mT.round", function(object, digits = 8) standardGeneric("mT.round"));

#' @describeIn setModification Return the life table with the given modification set
setMethod("mT.round", "mortalityTable",
          function(object, digits = 8) {
              object
          })
setMethod("mT.round", "mortalityTable.period",
          function(object, digits = 8) {
              o = callNextMethod()
              o@deathProbs = round(o@deathProbs, digits = digits)
              o@loading    = round(o@loading, digits = digits)
              o
          })
setMethod("mT.round", "mortalityTable.trendProjection",
          function(object, digits = 8) {
              o = callNextMethod()
              if (!is.null(o@trend) && !is.na(o@trend)) {
                  o@trend  = round(o@trend, digits = digits)
              }
              if (!is.null(o@trend2) && !is.na(o@trend2)) {
422
                  o@trend2 = round(o@trend2, digits = digits)
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
              }
              o
          })
setMethod("mT.round", "mortalityTable.improvementFactors",
          function(object, digits = 8) {
              o = callNextMethod()
              o@improvement = round(o@improvement, digits = digits)
              if (!is.null(o@loading) && !is.na(o@loading)) {
                  o@loading    = round(o@loading, digits = digits)
              }
              o
          })
setMethod("mT.round", "array",
          function(object, digits = 8) {
              array(
                  lapply(object, mT.round, digits = digits),
                  dim = dim(object), dimnames = dimnames(object))
          })
setMethod("mT.round", "list",
          function(object, digits = 8) {
              lapply(object, mT.round, digits = digits)
          })

setMethod("mT.round", "pensionTable",
          function(object, digits = 8) {
              object@qx = mT.round(object@qx, digits = digits)
              object@ix = mT.round(object@ix, digits = digits)
              object@qix = mT.round(object@qix, digits = digits)
              object@rx = mT.round(object@rx, digits = digits)
              object@apx = mT.round(object@apx, digits = digits)
              object@qpx = mT.round(object@qpx, digits = digits)
              object@hx = mT.round(object@hx, digits = digits)
              object@qwy = mT.round(object@qwy, digits = digits)
              object@qgx = mT.round(object@qgx, digits = digits)
              object
          })


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

#' @exportMethod mT.cleanup
setGeneric("mT.cleanup", function(object) standardGeneric("mT.cleanup"));

setMethod("mT.cleanup", "mortalityTable",
          function(object) {
              object@data = list(dim = object@data$dim)
              object
          })
setMethod("mT.cleanup", "mortalityTable.period",
          function(object) {
              o = callNextMethod()
              o@ages = unname(o@ages)
              o@deathProbs = unname(o@deathProbs)
              o@exposures = NULL
              o
          })
setMethod("mT.cleanup", "mortalityTable.trendProjection",
          function(object) {
              o = callNextMethod()
              o@trend = unname(o@trend)
              o@trend2 = unname(o@trend2)
              o
          })
setMethod("mT.cleanup", "array",
          function(object) {
              array(
                  lapply(object, mT.cleanup),
                  dim = dim(object), dimnames = dimnames(object))
          })
setMethod("mT.cleanup", "list",
          function(object) {
              lapply(object, mT.cleanup)
          })

setMethod("mT.cleanup", "pensionTable",
          function(object) {
              object = callNextMethod()
              object@qx = mT.cleanup(object@qx)
              object@ix = mT.cleanup(object@ix)
              object@qix = mT.cleanup(object@qix)
              object@rx = mT.cleanup(object@rx)
              object@apx = mT.cleanup(object@apx)
              object@qpx = mT.cleanup(object@qpx)
              object@hx = mT.cleanup(object@hx)
              object@qwy = mT.cleanup(object@qwy)
              object@qgx = mT.cleanup(object@qgx)
              object
          })


#' @export
pT.calculateTotalMortality = function(object, ...) {
    probs = transitionProbabilities(object, Period = object@baseYear, as.data.frame = TRUE)
    probs$qgALT = probs$qg

    la = head(Reduce('*', (1 - probs$q - probs$i), init = 100000, accumulate = TRUE), -1)
    lg = la
    for (idx in seq_along(lg)) {
        probs$qg[idx] = probs$qi[idx] - la[idx]/lg[idx] * (probs$qi[idx] - probs$q[idx] - probs$i[idx] * 1/2 * probs$qi[idx] / (1 - 1/2*probs$qi[idx]))
        lg[idx + 1] = lg[idx] * (1 - probs$qg[idx])
    }
    lg = head(lg, -1)

    probs$qg
}


#' @export
pT.recalculateTotalMortality = function(object, ...) {
    if (is.array(table)) {
        return(array(
            lapply(table, pT.recalculateTotalMortality, ...),
            dim = dim(table), dimnames = dimnames(table))
        )
    } else if (is.list(table)) {
        return(lapply(table, pT.recalculateTotalMortality, ...))
    }
    if (!is(table, "pensionTable"))
        stop("First argument must be a pensionTable or a list of pensionTable objects.")

    qg = pT.calculateTotalMortality(object)
    object@qgx@deathProbs = qg
    object
}

547
548
549
550
# pensionTables.list()
# pensionTables.load("*")
# library(tidyverse)
# AVOe2008P.male %>% mT.round(digits = 2)