I'm trying to write a script that draws Fourier sums of at least certain nicely behaving functions using Riemann sums. Ignoring the fact that my math might be seriously off at the moment, I can't seem to be able to print multiple PDF-files during the same script, which goes as follows:
"""
RepeatFunction(domain::Array{Real,1},fvals::Array{Complex{Real}},
repeatN::Int64,period::Float64=2*pi)
Builds a periodic function centered at origin in both directions from a set of
given function values, but more imporrtantly, also stretches out the domain to
accommodate this new extended array.
"""
function RepeatFunction(domain::Array{Float64,1},fvals::Array{Float64,1},
N::Int64,period::Float64=2*pi)
# Extending the domain
for n in 1:N/2
domain = [
linspace(domain[1]-period,domain[2],length(fvals));
domain;
linspace(domain[end],domain[end-1]+period,length(fvals))];
end
# Repeating the function
if N % 2 == 0
fvals = repeat(fvals,outer=[N+1]);
else
fvals = repeat(fvals, outer=[N]);
end
return domain, fvals
end
"""
RiemannSum(domain::Array{Float64},fvals::Array{Float64})::Float64
Calculates the discrete Riemann sum of a real valued function on a given
equipartitioned real domain.
"""
function RiemannSum(domain::Array{Complex{Real},1},fvals::Array{Complex{Real},1})
try
L = domain[end] - domain[1];
n = length(fvals);
return sum(fvals * L / n);
catch
println("You most likely attempted to divide by zero.
Check the size of your domain.")
return NaN
end
end
"""
RiemannSum(domain::StepRange{Real,Real},fvals::StepRange{Real,Real})::Float64
Calculates the discrete Riemann sum of a function on a given
equipartitioned domain.
"""
function RiemannSum(domain,fvals)
try
L = domain[end] - domain[1];
n = length(fvals);
return sum(fvals * L / n);
catch
println("You most likely attempted to divide by zero.
Check the size of your domain.")
return NaN
end
end
"""
RiemannSum(domain::StepRange{Real,Real},fvals::StepRange{Real,Real})::Float64
Calculates the discrete Riemann sum of a function on a given
equipartitioned domain.
"""
function RiemannSum(domain::StepRangeLen{Real,Base.TwicePrecision{Real},Base.TwicePrecision{Real}},
fvals::StepRangeLen{Real,Base.TwicePrecision{Real},Base.TwicePrecision{Real}})
try
L = domain[end] - domain[1];
n = length(fvals);
return sum(fvals * L / n);
catch
println("You most likely attempted to divide by zero.
Check the size of your domain.")
return NaN
end
end
"""
RiemannSum(domain::StepRange{Real,Real},fvals::StepRange{Real,Real})::Float64
Calculates the discrete Riemann sum of a function on a given
equipartitioned domain.
"""
function RiemannSum(domain,fvals)
try
L = domain[end] - domain[1];
n = length(fvals);
return sum(fvals * L / n);
catch
println("You most likely attempted to divide by zero.
Check the size of your domain.")
return NaN
end
end
"""
FourierCoefficient(domain,fvals)
Calculates an approximation to the Fourier coefficient for a function with
a period equal to the domain length.
"""
function FourierCoefficient(domain,fvals,n::Int64,T::Float64)
return 1/ T * RiemannSum(domain,fvals*exp(-1im * n * 1/T));
end
"""
FourierSum(domain.fvals)
Calculates the Fourier sum of a function on a given domain.
"""
function FourierSum(domain,fvals, N::Int64,T::Float64)
return [sum(FourierCoefficient(domain,fvals,n,T)*exp(1im * n * 1/T)) for n in -N:N];
end
using Plots;
pyplot()
n = 10;
T = 2*pi;
x = collect(linspace(-pi,pi,2n+1));
f = x.^2 + x;
funplot = plot(x,f);
#display(funfig)
savefig("./fun.pdf")
#println("Φ =",real(Φ))
x,repf = RepeatFunction(x,f,6,T)
repfunplot = plot(x,repf,reuse=false);
#display(repfunfig)
savefig("./repfun.pdf")
The trick mentioned here has no effect on the outcome, which is that only the first PDF gets printed. Any Julia gurus here that know what is causing the issue? I get no error messages whatsoever.
I ran the code on my system (Julia Version 0.6.1) without errors. Got 2 pdfs in my Folder: fun.pdf and repfun.pdf containing this:
Alright, I've figured out what the problem is or was. At least when coding in Juno/Atom, when Julia is first started it assumes that the working directory is /home/<username>, meaning if you issue a savefig()-command, the images are printed there.
If you wish the images to appear at a specific location, either give the absolute path to savefig, or put the line
cd("/path/to/desired/location")
at the beginning of your file.
How the first image somehow managed to appear in the desired folder still remains a mystery to me. I might have tried running Julia through bash, when working in said directory, but this must have been before I managed to get even the most rudimentary of figures to appear without issues.
Tried replicating your code, but the error is:
ERROR: LoadError: UndefVarError: StepRangeLen not defined
in include at boot.jl:261
in include_from_node1 at loading.jl:320
in process_options at client.jl:280
in _start at client.jl:378
while loading C:\Users\Евгений\Desktop\1.jl, in expression starting on line 433
There is not even line 433 in this code - very confused.
Related
I am working with a program which includes many function calls inside a for loop. For short, it is something like this:
function something()
....
....
timer = zeros(NSTEP);
for it = 1:NSTEP # time steps
tic = time_ns();
Threads.#threads for p in 1:2 # Star parallel of two sigma functions
Threads.lock(l);
Threads.unlock(l);
arg_in_sig[p] = func_sig[p](arg_in_sig[p]);
end
.....
.....
Threads.#threads for p in 1:2
Threads.lock(l)
Threads.unlock(l)
arg_in_vel[p] = func_vel[p](arg_in_vel[p])
end
toc=time_ns();
timer[i] = toc-tic;
end # time loop
writedlm("timer.txt",timer)
return
end
What I am trying to do, is to meassure the time that takes to perform on each loop iteration, saving the result in an output file called "timer.txt". The thing is that it doesn't work.
It saves a file with all zeros on it (except two or three values, which is more confusing).
I made a toy example like:
using DelimitedFiles;
function test()
a=zeros(1000)
for i=1:1000
tic = time_ns();
C = rand(20,20)*rand(20,20);
toc = time_ns();
a[i] = toc-tic;
end
writedlm("aaa.txt",a);
return a;
end
and these actually works (it saves fine!). Is there something to do with the fact that I am implementing Threads.#threads?. What can be happening between writedlm() and time_ns() in my program?
Any help would be much apreciated!
You are iterating over it but try to save by:
timer[i] = toc-tic;
while it should be
timer[it] = toc-tic;
Perhaps you have some i in global scope and hence the code still works.
Additionally locking the thread and immediately unlocking does not seem to make much sense. Moreover, when you iterate over p which happens to be also index of the Vector cell where you save the results there is no need to use the locking mechanism at all (unless you are calling some functions that depend on a global state).
In Julia v1.01 I would like to create a function from a string.
Background: In a numerical solver, a testcase is defined via a JSON file. It would be great if the user could specify the initial condition in string form.
This results in the following situation: Assume we have (from the JSON file)
fcn_as_string = "sin.(2*pi*x)"
Is there a way to convert this into a function fcn such that I can call
fcn(1.0) # = sin.(2*pi*1.0)
Performance is not really an issue, as the initial condition is evaluated once and then the actual computation consumes most of the time.
Can't get my code displayed correctly in a comment so here's a quick fix for crstnbr's solution
function fcnFromString(s)
f = eval(Meta.parse("x -> " * s))
return x -> Base.invokelatest(f, x)
end
function main()
s = "sin.(2*pi*x)"
f = fcnFromString(s)
f(1.)
end
julia> main()
-2.4492935982947064e-16
The functions Meta.parse and eval allow you to do this:
fcn_as_string = "sin.(2*pi*x)"
fcn = eval(Meta.parse("x -> " * fcn_as_string))
#show fcn(1.0)
This return -2.4492935982947064e-16 (due to rounding errors).
I am implementing simple modulus function on sage jupitar notebook. The function is as follows:
Mod2(v,b)=(v+b*(q-1)/2) mod q mod 2
The function is wriiten in sage as :
def modulus(v,b):
q=12289
c=[]
for i in range(len(v)):
c.append(mod(((v[i]+b[i]*(q-1)//2)%q),2))
return c
The function is executed as :
dimension = 1024 # degree of polynomials
modulus = 12289
R.<X> = PolynomialRing(GF(modulus),) Gaussian field of integers
Y.<x> = R.quotient(X^(dimension) + 1) # Cyclotomic field
pi=Y.random_element()
c=Y.random_element()
xi=Y.random_element()
sj=Y.random_element()
rj=Y.random_element()
gj=Y.random_element()
kj=((pi*c+xi)*(sj*d+rj)+(2*c*gj))
# Now, We are making another list named mon and calling the modulus function
mon=[1,2,6,5,8]
modulus(kj.list(),mon)
I get following error while executing the above code.
TypeError: 'sage.rings.integer.Integer' object is not callable
This kind of error nearly always happens when you try to do something that Sage translates as 1(3). In this case, you have redefined something!
def modulus(v,b):
versus
modulus = 12289
You can't overload things this way in Python. Sage will replace what modulus refers to by that number; your function is just gone now. So when you do
modulus(kj.list(),mon)
you are trying to call 12289 as a function.
I suggest calling your other modulus modulus1 or something like that. Do it consistently, and this problem should disappear. Good luck.
I want to add a loss function to torch that calculates the edit distance between predicted and target values.
Is there an easy way to implement this idea?
Or do I have to write my own class with backward and forward functions?
If your criterion can be represented as a composition of existing modules and criteria, it's a good idea to simply construct such composition using containers. The only problem is that standard containers are designed to work with modules only, not criteria. The difference is in :forward method signature:
module:forward(input)
criterion:forward(input, target)
Luckily, we are free to define our own container which is able work with criteria too. For example, sequential:
local GeneralizedSequential, _ = torch.class('nn.GeneralizedSequential', 'nn.Sequential')
function GeneralizedSequential:forward(input, target)
return self:updateOutput(input, target)
end
function GeneralizedSequential:updateOutput(input, target)
local currentOutput = input
for i=1,#self.modules do
currentOutput = self.modules[i]:updateOutput(currentOutput, target)
end
self.output = currentOutput
return currentOutput
end
Below is an illustration of how to implement nn.CrossEntropyCriterion having this generalized sequential container:
function MyCrossEntropyCriterion(weights)
criterion = nn.GeneralizedSequential()
criterion:add(nn.LogSoftMax())
criterion:add(nn.ClassNLLCriterion(weights))
return criterion
end
Check whether everything is correct:
output = torch.rand(3,3)
target = torch.Tensor({1, 2, 3})
mycrit = MyCrossEntropyCriterion()
-- print(mycrit)
print(mycrit:forward(output, target))
print(mycrit:backward(output, target))
crit = nn.CrossEntropyCriterion()
-- print(crit)
print(crit:forward(output, target))
print(crit:backward(output, target))
Just to add to the accepted answer, you have to be careful that the loss function you define (edit distance in your case) is differentiable with respect to the network parameters.
Below is the code for my program. I'm attempting to find the value of the integral of 1/ln(x), and then evaluate the integral from 0 to x, with this as the integrand. I'm not exactly sure what I'm doing wrong, but I am quite new to Scilab.
t = input("t");
x=10; while x<t, x=x+10,
function y=f(x), y=(1/(log (x))), endfunction
I=intg(2,x,f);
function z=g(x), z=I, endfunction
W = intg(0,x,z);
W
end
I'm not entirely sure on what you are trying to achieve, but I reformatted your code and added some suggestions to documentation.
Maybe it will help you in finding the answer.
While loop
You can convert your while loop to a for loop
Your code
x=10;
while x<t
x=x+10
//some code
end
Could be
for x=10:10:t
//some code
end
Functions
In your code, you redeclare the two functions every single iteration of the while loop. You could declare them outside the while loop and call them inside the loop.
Reformatted
t = input("Please provide t: ");
// The function of 1/ln(x)
function y=f(x), y=1/log(x), endfunction
// Every time g(x) is called the current value of I is returned
function z=g(x), z=I, endfunction
for x=10:10:t
//Find definite integral of function f from 2 to x
I = intg(2,x,f);
//Find definite integral of I from 0 to x
W = intg(0,x,g);
disp( string(W) );
end
I know the question is porbably outdated; but the topic is still active. And I was looking for a code with double integral.
Here, it looks strange to use "intg" just to calculate the area of the rectangle defined by its diagonal ((0,0), (x,I)): the result is just x*I...
May be the initial aim was to consider "I" as a function of "x" (but in this case there is a convergence problem at x=1...); so restricting the integration of "I" to something above 1 gives the following code:
x=10:10:100;W2=integrate('integrate(''1/log(x2)'',''x2'',2,x1)','x1',1.001,x);
Note the use of integration variables x1 and x2, plus the use of quotes...