File: methods_aaa.R

package info (click to toggle)
r-cran-marginaleffects 0.32.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 2,784 kB
  • sloc: sh: 13; makefile: 8
file content (233 lines) | stat: -rw-r--r-- 6,215 bytes parent folder | download
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
#' @include set_coef.R
#' @rdname set_coef
#' @export
set_coef.glm <- function(model, coefs, ...) {
    model[["coefficients"]] <- sub_named_vector(
        model[["coefficients"]],
        coefs
    )
    model
}


#' @rdname set_coef
#' @export
set_coef.lm <- function(model, coefs, ...) {
    model[["coefficients"]] <- sub_named_vector(
        model[["coefficients"]],
        coefs
    )
    model
}


#' @rdname get_predict
#' @export
get_predict.lm <- function(
    model,
    newdata = insight::get_data(model),
    type = "response",
    ...) {
    MM <- attr(newdata, "marginaleffects_model_matrix")
    beta <- get_coef(model)
    if (!isTRUE(checkmate::check_matrix(MM)) || ncol(MM) != length(beta)) {
        out <- get_predict.default(
            model = model,
            newdata = newdata,
            type = type,
            ...
        )
        return(out)
    }
    p <- model$rank
    p1 <- seq_len(p)
    piv <- if (p) qr(model)$pivot[p1]
    if (!all(seq_len(ncol(MM)) %in% piv)) {
        MM <- MM[, piv, drop = FALSE]
        beta <- beta[piv]
    }
    pred <- drop(MM %*% beta)

    # `pred` is a secret argument which re-uses the default get_predict to format a vector a data frame using correct `rowid`
    out <- get_predict.default(
        model = model,
        newdata = newdata,
        type = type,
        pred = pred,
        ...
    )
    return(out)
}


#' @rdname get_predict
#' @export
get_predict.glm <- function(
    model,
    newdata = insight::get_data(model),
    type = "response",
    ...) {
    out <- NULL
    MM <- attr(newdata, "marginaleffects_model_matrix")
    if (isTRUE(checkmate::check_matrix(MM))) {
        if (isTRUE(checkmate::check_choice(type, c("link")))) {
            out <- get_predict.lm(model = model, newdata = newdata, ...)
        } else if (isTRUE(checkmate::check_choice(type, "response")) || is.null(type)) {
            out <- get_predict.lm(model = model, newdata = newdata, ...)
            out$estimate <- stats::family(model)$linkinv(out$estimate)
        }
    }

    if (is.null(out)) {
        out <- get_predict.default(
            model = model,
            newdata = newdata,
            type = type,
            ...
        )
    }

    return(out)
}


#' @include set_coef.R
#' @rdname set_coef
#' @export
set_coef.nls <- function(model, coefs, ...) {
    out <- model
    out$m$setPars(coefs)
    return(out)
}


#' @include get_coef.R
#' @rdname get_coef
#' @export
get_coef.nls <- function(model, ...) {
    model$m$getPars()
}


#' @keywords internal
#' @export
get_autodiff_args.lm <- function(model, mfx) {
    # no inheritance! Important to avoid breaking other models
    if (!class(model)[1] %in% c("lm", "ivreg")) {
        return(NULL)
    }

    if (!is.null(model$offset)) {
        autodiff_warning("models with offsets")
        return(NULL)
    }

    if ("weights" %in% names(model$call)) {
        autodiff_warning("models with weights")
        return(NULL)
    }

    # Check type support
    if (!mfx@type %in% c("response", "link", "invlink(link)")) {
        autodiff_warning(sprintf("`type='%s'`", mfx@type))
        return(NULL)
    }

    # If all checks pass, return supported arguments
    out <- list(model_type = "linear")
    return(out)
}


#' @keywords internal
#' @export
get_autodiff_args.glm <- function(model, mfx) {
    # no inheritance! Important to avoid breaking other models
    if (!class(model)[1] == "glm") {
        return(NULL)
    }

    if (!is.null(model$offset)) {
        autodiff_warning("models with offsets")
        return(NULL)
    }

    if ("weights" %in% names(model$call)) {
        autodiff_warning("models with weights")
        return(NULL)
    }

    # Check type support
    if (!mfx@type %in% c("response", "link", "invlink(link)")) {
        autodiff_warning(sprintf("`type='%s'`", mfx@type))
        return(NULL)
    }

    # Check comparison type for comparisons function
    if (mfx@calling_function == "comparisons" && (!is.character(mfx@comparison) || !mfx@comparison %in% c("difference", "ratio"))) {
        comp_str <- if (is.character(mfx@comparison)) mfx@comparison else "custom function"
        autodiff_warning(sprintf("`comparison='%s'` (only 'difference' and 'ratio' supported)", comp_str))
        return(NULL)
    }

    # For GLM, check if family/link combination is supported
    family_name <- model$family$family
    link_name <- model$family$link

    # Supported family types
    supported_families <- c("gaussian", "binomial", "poisson", "Gamma")
    if (!family_name %in% supported_families) {
        autodiff_warning("unsupported GLM family/link combinations")
        return(NULL)
    }

    # Supported link types
    supported_links <- c("identity", "log", "logit", "probit", "inverse", "sqrt", "cloglog")
    if (!link_name %in% supported_links) {
        autodiff_warning("unsupported GLM family/link combinations")
        return(NULL)
    }

    # For link/invlink(link) type with GLM, use linear model approach
    model_type <- if (mfx@type %in% c("link", "invlink(link)")) "linear" else "glm"

    # Convert to Python enum values for GLM models
    family_type <- NULL
    link_type <- NULL
    if (model_type == "glm") {
        # Import Family and Link enums from Python
        mAD <- settings_get("mAD")
        Family <- mAD$glm$families$Family
        Link <- mAD$glm$families$Link

        # Family types using Python enum
        family_type <- switch(family_name,
            "gaussian" = Family$GAUSSIAN,
            "binomial" = Family$BINOMIAL,
            "poisson" = Family$POISSON,
            "Gamma" = Family$GAMMA,
            NULL
        )

        # Link types using Python enum
        link_type <- switch(link_name,
            "identity" = Link$IDENTITY,
            "log" = Link$LOG,
            "logit" = Link$LOGIT,
            "probit" = Link$PROBIT,
            "inverse" = Link$INVERSE,
            "sqrt" = Link$SQRT,
            "cloglog" = Link$CLOGLOG,
            NULL
        )
    }

    # If all checks pass, return supported arguments
    out <- list(
        model_type = model_type,
        family_type = family_type,
        link_type = link_type

    )
    return(out)
}