|
| 1 | +# wrap a function to reshape the input |
| 2 | + |
| 3 | +export ReshapeInput |
| 4 | + |
| 5 | +""" |
| 6 | + ReshapeInput(f, expected_shape) |
| 7 | +
|
| 8 | +Wrap a function to reshape the input. |
| 9 | +It is useful when the function `f` expects a specific shape of the input, but you want to pass it a different shape. |
| 10 | +
|
| 11 | +```julia |
| 12 | +julia> f = ReshapeInput(IndballRank(5), (10, 10)) |
| 13 | +ReshapeInput(IndBallRank{Int64}(5), (10, 10)) |
| 14 | +
|
| 15 | +julia> f(rand(100)) |
| 16 | +Inf |
| 17 | +""" |
| 18 | +struct ReshapeInput{F, S} |
| 19 | + f::F |
| 20 | + expected_shape::S |
| 21 | +end |
| 22 | + |
| 23 | +function (f::ReshapeInput)(x) |
| 24 | + # Check if the input x has the expected shape |
| 25 | + if size(x) != f.expected_shape |
| 26 | + # Reshape the input to the expected shape |
| 27 | + x = reshape(x, f.expected_shape) |
| 28 | + end |
| 29 | + return f.f(x) |
| 30 | +end |
| 31 | + |
| 32 | +function prox!(y, f::ReshapeInput, x, gamma) |
| 33 | + # Check if the input x has the expected shape |
| 34 | + if size(x) != f.expected_shape |
| 35 | + # Reshape the input to the expected shape |
| 36 | + x = reshape(x, f.expected_shape) |
| 37 | + y = reshape(y, f.expected_shape) |
| 38 | + end |
| 39 | + return prox!(y, f.f, x, gamma) |
| 40 | +end |
| 41 | + |
| 42 | +function gradient!(y, f::ReshapeInput, x) |
| 43 | + # Check if the input x has the expected shape |
| 44 | + if size(x) != f.expected_shape |
| 45 | + # Reshape the input to the expected shape |
| 46 | + x = reshape(x, f.expected_shape) |
| 47 | + y = reshape(y, f.expected_shape) |
| 48 | + end |
| 49 | + return gradient!(y, f.f, x) |
| 50 | +end |
| 51 | + |
| 52 | +function prox_naive(f::ReshapeInput, x, gamma) |
| 53 | + # Check if the input x has the expected shape |
| 54 | + if size(x) != f.expected_shape |
| 55 | + # Reshape the input to the expected shape |
| 56 | + x = reshape(x, f.expected_shape) |
| 57 | + end |
| 58 | + return prox_naive(f.f, x, gamma) |
| 59 | +end |
0 commit comments