Skip to content

Commit 910982d

Browse files
committed
add reshapeInput function wrapper
1 parent 8db15f0 commit 910982d

2 files changed

Lines changed: 60 additions & 0 deletions

File tree

src/ProximalOperators.jl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,7 @@ include("calculus/regularize.jl")
9292
include("calculus/separableSum.jl")
9393
include("calculus/slicedSeparableSum.jl")
9494
include("calculus/precomposedSlicedSeparableSum.jl")
95+
include("calculus/reshapeInput.jl")
9596
include("calculus/sqrDistL2.jl")
9697
include("calculus/tilt.jl")
9798
include("calculus/translate.jl")

src/calculus/reshapeInput.jl

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
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

Comments
 (0)