Duplicating functions in Julia - function

I need to overwrite a function based on its previous definition, and this leads to a stackoverflow error.
I have tried with deepcopy(f), but it just returns a reference to f, so this doesn't work.
What I need to be able to do over and over is:
Old(x) = pdf(Uniform(),x)
New(x) = updating_function(Old, Y1)
Old(x) = deepcopy(New(x))
New(x) = updating_function(Old, Y2)
[...]
EDIT:
My overall goal is to have a function that takes a prior distribution and spits out a posterior with an unusual signal structure due to my application.
A simple running example of this would be
Old_pdf(x)= pdf(Uniform(),x)
Old_mean=0.5
function BU(d,low)
value, tol = quadgk(Old_pdf, Old_λ, 1)
truncated(λ)=d(λ)/value
end
Newpdf=BU(Old_pdf,Old_mean)
Old_mean, tol= quadgk(x -> Newpdf(x)*x, Old_mean, 1)
Old_pdf=BU(Old_pdf,Old_mean)
I know that this example could be addressed with functions from the Distributions package. It's not the case for my application.
I have found this question and read the documentation of the IRTools package, but I am unable to make this work. In particular when I try
Old(x) = pdf(Uniform(),x)
New(x) = updating_function(Old, Y1)
const Old_ir= IRTools.Inner.code_ir(New, Tuple{Int})
Old(x) = IRTools.func(Old_ir)
I obtain an object that doesn't behave like a function, hence generates methods error in the rest of the code. I made several attempts at this, and it is entirely possible that I am missing something trivial.

Y1 = 5.0
Y2 = 7.0
updating_function(f1,c) = x -> 2.0 * f1(x) + c
Old = x->sqrt(x)
New = updating_function(Old, Y1)
Old = New
New = updating_function(Old, Y2)

I think you just need anonymous functions:
function BU(f, λ, y)
# I guess here you would use the observations `y` in some way?
z, _ = quadgk(f, λ, 1)
return λ -> f(λ) / z
end
mean(f, λ) = quadgk(x -> f(x) * x, λ, 1)[1]
original_pdf(x) = pdf(Uniform(), x)
f = original_pdf
λ = 0.5
for y in Y
f = BU(f, λ, y)
λ = mean(f, λ)
end
Now I tried very hard, and I think I understand what you're doing, but the example you gave wasn't very clear. Consider this conceptual.
Such things make nice folds, by the way.

Related

how to create multivariate function handle in matlab in this case?

I would like to create a multivariate functional handle which the number of variables is changeable according to the input.
First, create n symbolic variables, and note that n can be changed according to your input.
n=3;
syms theta [1 n];
Now I create a function g. Via For loop, create the summation of g on all theta. As seen in the code, f is a symbolic expression.
g = #(x)(x^2);
f = 0;
for i = 1:n
f = f + g(sym(sprintfc('theta%d',i)))
end
Now I want to create a functional handle F according to f.
One potential way to do this F = #(theta1,theta2,theta3)(f). However, since n is user-specified, changeable variable, this approach is not doable.
Could someone give my hint? Many thanks!
Is this what you are looking for?
g = #(x)x.^2
fn = #(varargin) sum( cellfun(g,varargin) )
Now we have an anonymous function with a variable number of inputs. Example use below
fn(1) % = 1
fn(1,5,3) % = 35 = (1^2+5^2+3^2)
fn(1,2,3,4,5,6) % = 91 = (1^2 + 2^2 + 3^2 + 4^2 + 5^2 + 6^2)

Uppercase in name of a function in Julia

I am fairly new to Julia and got confused with the following code. After a function LucasTree is defined, it is used again as lt. Does Julia have some kind of role where I can recall a function using the uppercase abbreviation? If so, where can I find a nice reference for this feature?
function LucasTree(;γ = 2.0,
β = 0.95,
α = 0.9,
σ = 0.1,
grid_size = 100)
ϕ = LogNormal(0.0, σ)
shocks = rand(ϕ, 500)
# build a grid with mass around stationary distribution
ssd = σ / sqrt(1 - α^2)
grid_min, grid_max = exp(-4ssd), exp(4ssd)
grid = range(grid_min, grid_max, length = grid_size)
# set h(y) = β * int u'(G(y,z)) G(y,z) ϕ(dz)
h = similar(grid)
for (i, y) in enumerate(grid)
h[i] = β * mean((y^α .* shocks).^(1 - γ))
end
return (γ = γ, β = β, α = α, σ = σ, ϕ = ϕ, grid = grid, shocks = shocks, h = h)
end
function lucas_operator(lt, f)
# unpack input
#unpack grid, α, β, h = lt
z = lt.shocks
Af = LinearInterpolation(grid, f, extrapolation_bc=Line())
Tf = [ h[i] + β * mean(Af.(grid[i]^α .* z)) for i in 1:length(grid) ]
return Tf
end
No, this does not exist. It would be too nonunique to be practical, and moreover function names in Julia by convention should be entirely lowercase (structs/types can be CamelCase, but not functions, with the possible exception of constructors*).
In any case, all that is happening here in the code you have posted is that the function lucas_operator takes two arguments, lt and f, which can then be used within that lucas_operator function. These could in principle be anything, and regardless of what they are named outside the scope of the function, they will be named lt and f within the scope of the function. So for example:
function example(foo, bar)
return foo(2*bar)
end
if you then call
example(somereallylongfunctionname, somevariable)
then that will return the equivalent of
somereallylongfunctionname(2*somevariable)
or similarly
example(SomeImproperlyCapitalizedFunction, somevariable)
# equivalent to SomeImproperlyCapitalizedFunction(2*somevariable)
in either case, regardless of its name outside the scope of the example function, the first argument passed to the function will be known as foo within the function.
* Aside about constructors: that would be a function that is used to construct a custom type. This doesn't quite do that, but it does return an instance of a NamedTuple which then seems to be treated somewhat like a type/struct in the subsequent code, so perhaps it could be counted as a constructor.

Writing simple equations in Octave

Imagine I want to define a function in Octave z(var1, var2) = a(var1) + b(var1) + c(var2) + d(var2) + const. Prior to this definition, I would like to define all the neccessary functions, something like: a(var1) = var1^2 + const, b(var1) = cos(var1), c(var) = sqrt(var2 - const) etc. Later in time, I add all those functions and form the final one, z function. Afterwards, I'd like to get partial derivatives of the function z in respect to var1 and var2.
So far, my only concern is defining the functions above to work as i imagined; is it possible and how ?
You can use function handles and anonymous functions:
a = #(x) x^2 + c1;
b = #cos;
c = #(x) sqrt(x - c2);
d = #exp;
b and d are handles to existing functions. You can call them as regular functions using b(...) or d(...). a and c are anonymous functions. They provide the argument list and definition of the handle right there in the assignment, somewhat like Python's lambdas. You could do something like b = #(x) cos(x), but there is really no point since there are no additional operations necessary.
Now you can do
z = #(x, y) a(x) + b(x) + c(y) + d(y) + c3;
The alternative is to write separate m-files for each function, which I am assuming you would like to avoid.
Using the function, for example to take partial derivatives, is now fairly straightforward. Function handles are called just like any other builtin or m-file-defined function:
(z(x + delta, y) - z(x - delta, y)) / (2 * delta)
Update
Just for fun, I ran the following script (using Octave 3.4.3 on Red Hat 6.5):
octave:1> c1 = -100;
octave:2> c2 = -10;
octave:3> c3 = 42;
octave:4> a = #(x) x^2 + c1;
octave:5> b = #cos;
octave:6> c = #(x) sqrt(x - c2);
octave:7> d = #exp;
octave:8> z = #(x, y) a(x) + b(x) + c(y) + d(y) + c3;
octave:9> [X, Y] = meshgrid([-10:0.1:10], [-10:0.1:10]);
octave:10> surf(X, Y, z(X, Y));
The result is not especially interesting, but it does demonstrate the effectiveness of this technique:
Here is an IDEOne link to play with.

Defining a Differential Equation in Octave

I am attempting to use Octave to solve for a differential equation using Euler's method.
The Euler method was given to me (and is correct), which works for the given Initial Value Problem,
y*y'' + (y')^2 + 1 = 0; y(1) = 1;
That initial value problem is defined in the following Octave function:
function [YDOT] = f(t, Y)
YDOT(1) = Y(2);
YDOT(2) = -(1 + Y(2)^2)/Y(1);
The question I have is about this function definition. Why is YDOT(1) != 1? What is Y(2)?
I have not found any documentation on the definition of a function using function [YDOT] instead of simply function YDOT, and I would appreciate any clarification on what the Octave code is doing.
First things first: You have a (non linear) differential equation of order two which will require you to have two initial conditions. Thus the given information from above is not enough.
The following is defined for further explanations: A==B means A is identical to B; A=>B means B follows from A.
It seems you are mixing a few things. The guy who gave you the files rewrote the equation in the following way:
y*y'' + (y')^2 + 1 = 0; y(1) = 1; | (I) y := y1 & (II) y' := y2
(I) & (II)=>(III): y' = y2 = y1' | y2==Y(2) & y1'==YDOT(1)
Ocatve is "matrix/vector oriented" so we are writing everything in vectors or matrices. Rather writing y1=alpha and y2=beta we are writing y=[alpha; beta] where y(1)==y1=alpha and y(2)==y2=beta. You will soon realize the tremendous advantage of using especially this mathematical formalization for ALL of your problems.
(III) & f(t,Y)=>(IV): y2' == YDOT(2) = y'' = (-1 -(y')^2) / y
Now recall what is y' and y from the definitions in (I) and (II)!
y' = y2 == Y(2) & y = y1 == Y(1)
So we can rewrite equation (IV)
(IV): y2' == YDOT(2) = (-1 -(y')^2) / y == -(1 + Y(2)^2)/Y(1)
So from equation (III) and (IV) we can derive what you already know:
YDOT(1) = Y(2)
YDOT(2) = -(1 + Y(2)^2)/Y(1)
These equations are passed to the solver. Differential equations of all types are solved numerically by retrieving the "next" value in a near neighborhood to some "previously known" value. (The step size inside this neighborhood is one of the key questions when writing solvers!) So your solver uses your initial condition Y(1)==y(1)=1 to make the next step and calculate the "next" value. So right at the start YDOT(1)=Y(2)==y(2) but you didn't tell us this value! But from then on YDOT(1) is varied by the solver in dependency to the function shape to solve your problem and give you ONE unique y(t) solution.
It seems you are using Octave for the first time so let's make a last comment on function [YDOT] = f(t, Y). In general a function is defined in this way:
function[retVal1, retVal2, ...] = myArbitraryName(arg1, arg2, ...)
Where retVal is the return value or output and arg is the argument or input.

Creating a function from a 2D array in MATLAB (For use in ode45)

I am a first time MATLAB user. I have a 2d array of t vs f in MATLAB. This 2d array correponds to a function, say f(t). I am using ode45 to solve a set of differential equations and f(t) is one of the coefficients i.e. I have a set of equations of the form x'(t)=f(t)x(t) or variations thereof. How do I proceed?
I need a way to convert my array of t vs f into a function that can be used in the ode45 method. Presumably, the conversion will do some linear interpolation and give me the equation of the best fit curve.
Or if there is another approach, I'm all ears!
Thank you!
This is a simple example with passing function as a parameter to right hand side of the ODE. Create files in the same directory and run main
main.m
t = 0:0.2:10; f = sin(t);
fun = #(xc) interp1(t, f, xc);
x0=0.5
% solve diff(x, t)=sin(t)
% pass function as parameter
[tsol, xsol] = ode45(#(t, x) diff_rhs(t, x, fun),[0.0 8.0], 0.5);
% we solve equation dx/dt = sin(x), x(0)=x0
% exact solution is x(t) = - cos(t) + x(0) + 1
plot(tsol, xsol, 'x');
hold on
plot(tsol, -cos(tsol) + x0 + 1, '-');
legend('numerical', 'exact');
diff_rhs.m
function dx = diff_rhs(t, x, fun)
dx = fun(t);
end
References in the documentation: interp1 and anonymous Functions.