forked from WinVector/RcppDynProg
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolve_for_partition.R
More file actions
295 lines (289 loc) · 9.5 KB
/
Copy pathsolve_for_partition.R
File metadata and controls
295 lines (289 loc) · 9.5 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
#' @importFrom stats approx lm predict
NULL
#' Solve for a piecewise linear partiton.
#'
#' Solve for a good set of right-exclusive x-cuts such that the
#' overall graph of y~x is well-approximated by a piecewise linear
#' function.
#'
#' @param x numeric, input variable (no NAs).
#' @param y numeric, result variable (no NAs, same length as x).
#' @param ... not used, force later arguments by name.
#' @param w numeric, weights (no NAs, positive, same length as x).
#' @param penalty per-segment cost penalty.
#' @param min_n_to_chunk minimum n to subdivied problem.
#' @param min_seg positive integer, minimum segment size.
#' @param max_k maximum segments to divide into.
#' @param costs_fn function to produce cost matrix.
#' @param cost_f function to score intervals
#' @return a data frame appropriate for stats::approx().
#'
#' @noRd
#'
solve_for_partition_xs <- function(x, y,
...,
w = NULL,
penalty = 0.0,
min_n_to_chunk = 1000,
min_seg = 1,
max_k = length(x),
cost_fn = lin_costs, cost_f = lin_cost) {
wrapr::stop_if_dot_args(substitute(list(...)), "RcppDynProg::solve_for_partition_xs")
n <- length(x)
if(n<1) {
return(NULL)
}
if(length(unique(x))<=1) {
return(c(1, n+1))
}
if(length(w)<=0) {
w = 1 + numeric(n)
}
chunk_size <- max(1, round(sqrt(n)))
if(n<min_n_to_chunk) {
chunk_size <- 1
}
d <- data.frame(x = x, y = y)
d$orig_index <- seq_len(n)
d <- d[order(d$x), , drop = FALSE]
# build a smaller problem
indices = sort(unique(c(1, seq(1, n, by = chunk_size), n)))
# can only start indices where x differs
is_dup <- c(FALSE, x[indices[-1]]==x[indices[-length(indices)]])
indices <- indices[!is_dup]
indices = sort(unique(c(1, indices, n)))
# solve dynamic program
xmat <- cost_fn(x, y, w, min_seg, indices)
xmat <- xmat + penalty
soln1 <- solve_interval_partition(xmat, max_k)
if(length(soln1)<=2) {
return(c(1, n+1))
}
# translate back to original indices
soln1 <- c(indices[soln1[-length(soln1)]], n+1)
# now polish interior boundaries
# only run once under assumption dynprog has isolated
# most long-range effects
soln2 <- soln1
R_INDEX_SHIFT = -1
for(trial in seqi(1,5)) {
old_soln = soln2
for(ii in seqi(2, length(soln2)-1)) {
low <- max(soln2[ii-1]+(1+min_seg), soln2[ii]-chunk_size)
high <- min(soln2[ii+1]-(1+min_seg), soln2[ii]+chunk_size)
if((low<high)&&(low<=soln2[ii])&&(high>=soln2[ii])) {
best_can <- -1
best_cost <- 0
for(candidate in seqi(low, high)) {
costi <- cost_f(x, y, w, min_seg, R_INDEX_SHIFT + soln2[ii-1], R_INDEX_SHIFT + candidate-1) +
cost_f(x, y, w, min_seg, R_INDEX_SHIFT + candidate, R_INDEX_SHIFT + soln2[ii+1]-1)
if((best_can<0)||(costi<best_cost)) {
best_can <- candidate
best_cost <- costi
}
}
if(best_can>0) {
soln2[ii] <- best_can
}
}
}
if(isTRUE(all.equal(old_soln, soln2))) {
break
}
}
soln2
}
#' Solve for a piecewise linear partiton.
#'
#' Solve for a good set of right-exclusive x-cuts such that the
#' overall graph of y~x is well-approximated by a piecewise linear
#' function. Solution is a ready for use with
#' with \code{base::findInterval()} and \code{stats::approx()}
#' (demonstrated in the examples).
#'
#' @param x numeric, input variable (no NAs).
#' @param y numeric, result variable (no NAs, same length as x).
#' @param ... not used, force later arguments by name.
#' @param w numeric, weights (no NAs, positive, same length as x).
#' @param penalty per-segment cost penalty.
#' @param min_n_to_chunk minimum n to subdivied problem.
#' @param min_seg positive integer, minimum segment size.
#' @param max_k maximum segments to divide into.
#' @return a data frame appropriate for stats::approx().
#'
#' @examples
#'
#' # example data
#' d <- data.frame(
#' x = 1:8,
#' y = c(1, 2, 3, 4, 4, 3, 2, 1))
#'
#' # solve for break points
#' soln <- solve_for_partition(d$x, d$y)
#' # show solution
#' print(soln)
#'
#' # label each point
#' d$group <- base::findInterval(
#' d$x,
#' soln$x[soln$what=='left'])
#' # apply piecewise approximation
#' d$estimate <- stats::approx(
#' soln$x,
#' soln$pred,
#' xout = d$x,
#' method = 'linear',
#' rule = 2)$y
#' # show result
#' print(d)
#'
#' @export
#'
solve_for_partition <- function(x, y,
...,
w = NULL,
penalty = 0.0,
min_n_to_chunk = 1000,
min_seg = 1,
max_k = length(x)) {
wrapr::stop_if_dot_args(substitute(list(...)), "RcppDynProg::solve_for_partition")
n <- length(x)
if(n<1) {
return(NULL)
}
if(length(unique(x))<=1) {
return(data.frame(x = mean(x), y = mean(y)))
}
if(length(w)<=0) {
w = 1 + numeric(n)
}
soln2 <- solve_for_partition_xs(x, y,
w = w,
penalty = penalty,
min_n_to_chunk = min_n_to_chunk,
min_seg = min_seg,
max_k = max_k,
cost_fn = lin_costs, cost_f = lin_cost)
d <- data.frame(x = x, y = y, w = w)
d$orig_index <- seq_len(n)
d <- d[order(d$x), , drop = FALSE]
# solve for linear funciton in each region to get endpoint values
d$group <- as.character(findInterval(d$x, d$x[soln2[-length(soln2)]]))
dlist <- base::split(d, d$group)
points <- lapply(
dlist,
function(di) {
mi <- lm(y~x, data=di, weights = di$w)
di$pred <- predict(mi, newdata = di)
dmin <- di[which(di$x<=min(di$x))[[1]], c("x", "pred", "group"), drop = FALSE]
dmin$what <- "left"
dmax <- di[which(di$x>=max(di$x))[[1]], c("x", "pred", "group"), drop = FALSE]
dmax$what <- "right"
ri <- rbind(dmin, dmax)
rownames(ri) <- NULL
ri
}
)
points <- do.call(rbind, points)
rownames(points) <- NULL
points <- points[order(points$x), , drop = FALSE]
points
}
#' Solve for a piecewise constant partiton.
#'
#' Solve for a good set of right-exclusive x-cuts such that the
#' overall graph of y~x is well-approximated by a piecewise linear
#' function. Solution is a ready for use with
#' with \code{base::findInterval()} and \code{stats::approx()}
#' (demonstrated in the examples).
#'
#' @param x numeric, input variable (no NAs).
#' @param y numeric, result variable (no NAs, same length as x).
#' @param ... not used, force later arguments by name.
#' @param w numeric, weights (no NAs, positive, same length as x).
#' @param penalty per-segment cost penalty.
#' @param min_n_to_chunk minimum n to subdivied problem.
#' @param min_seg positive integer, minimum segment size.
#' @param max_k maximum segments to divide into.
#' @return a data frame appropriate for stats::approx().
#'
#' @examples
#'
#' # example data
#' d <- data.frame(
#' x = 1:8,
#' y = c(-1, -1, -1, -1, 1, 1, 1, 1))
#'
#' # solve for break points
#' soln <- solve_for_partitionc(d$x, d$y)
#' # show solution
#' print(soln)
#'
#' # label each point
#' d$group <- base::findInterval(
#' d$x,
#' soln$x[soln$what=='left'])
#' # apply piecewise approximation
#' d$estimate <- stats::approx(
#' soln$x,
#' soln$pred,
#' xout = d$x,
#' method = 'constant',
#' rule = 2)$y
#' # show result
#' print(d)
#'
#' @export
#'
solve_for_partitionc <- function(x, y,
...,
w = NULL,
penalty = 0.0,
min_n_to_chunk = 1000,
min_seg = 1,
max_k = length(x)) {
wrapr::stop_if_dot_args(substitute(list(...)), "RcppDynProg::solve_for_partitionc")
n <- length(x)
if(n<1) {
return(NULL)
}
if(length(unique(x))<=1) {
return(data.frame(x = mean(x), y = mean(y)))
}
if(length(w)<=0) {
w = 1 + numeric(n)
}
ord <- order(x)
fn <- function(x, y, w, min_seg, indices) { const_costs(y, w, min_seg, indices) }
f <- function(x, y, w, min_seg, i, j) { const_cost(y, w, min_seg, i, j) }
soln2 <- solve_for_partition_xs(x[ord], y[ord],
w = w[ord],
penalty = penalty,
min_n_to_chunk = min_n_to_chunk,
min_seg = min_seg,
max_k = max_k,
cost_fn = fn, cost_f = f)
# solve for constant funciton in each region to get endpoint values
d <- data.frame(x = x, y = y, w = w)
d$orig_index <- seq_len(n)
d <- d[order(d$x), , drop = FALSE]
d$group <- as.character(findInterval(d$x, d$x[soln2[-length(soln2)]]))
dlist <- base::split(d, d$group)
points <- lapply(
dlist,
function(di) {
di$pred <- sum(di$y*di$w)/sum(di$w)
dmin <- di[which(di$x<=min(di$x))[[1]], c("x", "pred", "group"), drop = FALSE]
dmin$what <- "left"
dmax <- di[which(di$x>=max(di$x))[[1]], c("x", "pred", "group"), drop = FALSE]
dmax$what <- "right"
ri <- rbind(dmin, dmax)
rownames(ri) <- NULL
ri
}
)
points <- do.call(rbind, points)
rownames(points) <- NULL
points <- points[order(points$x), , drop = FALSE]
points
}