How to plot a time-evolution of 3D Gaussian in Julia? - plot

I want to plot a time-evolution of 3D Gaussian with Makie.jl.
Here is a surface-version code of sin(r)/r.
So I wrote a code in reference to it.
using Makie
using FileIO
using LinearAlgebra
using AbstractPlotting
scene = Scene(backgroundcolor = :black);
f(x,y,z) = exp(-((x)^2 + (y)^2 + (z)^2))
r = LinRange(-5, 5, 50)
vol_func(t) = [Float64(f(x - cos(t),y - sin(t),z - t)) for x = r, y = r,z = r]
vol = volume!(scene,r,r,r,vol_func(20),algorithm = :mip)[end]
scene[Axis].names.textcolor = :gray
N = 20
scene
record(scene, "voloutput.mp4", range(0, stop = 5, length = N)) do t
vol[3] = vol_func(t)
end
But this code does not work.
MethodError: Cannot `convert` an object of type Array{Float64,3} to an object of type LinRange{Float64}
How should I fix the code?
P.S.
The snapshot at initial time is like this.(reference)
using Makie
using FileIO
using LinearAlgebra
using AbstractPlotting
r = LinRange(-20, 20, 500); # our value range
ρ(x, y, z) = exp(-((x-1)^2 + (y)^2 + (z)^2)) # function (charge density)
# create a Scene with the attribute `backgroundcolor = :black`,
# can be any compatible color. Useful for better contrast and not killing your eyes with a white background.
scene = Scene(backgroundcolor = :black)
volume!(
scene,
r, r, r, # coordinates to plot on
ρ, # charge density (functions as colorant)
algorithm = :mip # maximum-intensity-projection
)
scene[Axis].names.textcolor = :gray # let axis labels be seen on dark
background
save("sp.png",scene)
I want to see the yellow region moving as spiral. (2020/08/28)
I just realized not vol[3] but vol[4]. Then, it worked.
But I have a next question. (2020/08/31)
I tried to do the same thing for the matrix-form time-dependent Schrodinger equation with its initial condition being Gaussian.
using LinearAlgebra
using OrdinaryDiffEq
using DifferentialEquations
#Define the underlying equation
function time_evolution(ψdot,ψ,p,t)
ψdot.=-im.*H(Lx,Ly,Lz)*ψ
end
Lx = Ly = Lz = 10
ψ0 = [] # Initial conditions
for iz = 1:Lz
for ix = 1:Lx
for iy = 1:Ly
gauss = exp(-((ix)^2 + (iy)^2 + (iz)^2))
push!(ψ0,gauss)
end
end
end
tspan = (0.,1.0) # Simulation time span
#Pass to Solvers
prob = ODEProblem(time_evolution,ψ0,tspan)
sol = solve(prob)
Here,H(Lx,Ly,Lz) is a N×N matrix parameterized by systemsize Lx,Ly,Lz and N = Lx×Ly×Lz. The sample code of H(Lx,Ly,Lz) is here.
Then,
using Makie
using FileIO
using LinearAlgebra
using AbstractPlotting
using ColorSchemes
x = 1: Lx # our value range
y = 1: Ly
z = 1: Lz
ρ(ix,iy,iz,nt) = abs2.((sol[nt][(iz-1)*Lx*Ly + (ix-1)*Ly + (iy-1)])./norm(sol[nt][(iz-1)*Lx*Ly + (ix-1)*Ly + (iy-1)]))
ψ(nt) = Float64[ρ(ix,iy,iz,nt) for ix in x, iy in y,iz in z]
scene = Scene(backgroundcolor = :white)
c = ψ(length(sol.t))
vol = volume!(
scene,
x, y, z, # coordinates to plot on
c, # charge density (functions as colorant)
algorithm = :mip, # maximum-intensity-projection
colorrange = (0,0.01),
transparency = true,
)[end]
update_cam!(scene, Vec3f0(1,0.5,0.1), Vec3f0(0))
scene[Axis].names.textcolor = :gray # let axis labels be seen on darkbackground
record(scene, "output.mp4", range(0, stop = length(sol.t)-1, length = 1)) do nt
vol[4] = ψ(nt)
end
But this code has an error.
ArgumentError: range(0.0, stop=5.0, length=1): endpoints differ
Where is the mistake?
I found the mistake.(2020/09/02)
sol[nt]→sol(nt)
range(0, stop = length(sol.t)-1, length = 1)→range(0, stop = 1.0, length = 20)
Then, the code passed and a mp4 animation was obtained.
But the plot can't be seen in the mp4 file. Why...

Related

Why does Fractal Formula "sin(z^2)-cos(z^2)+c" work with XaoS and not UltraFractal?

While using the real-time Fractal zoomer XaoS to explore the infinite universe having user formula "sin(z^2)-cos(z^2)+c", we start out here (important for universe identification and formula matching with other zoomer software applications, libraries or frameworks.):
I found the following fractal, which I really like:
As you, perhaps, can see, I have run up against the resolution wall (floor?), which means that the deeper I zoom at that point, the more pixelated and boxy the image gets:
Here is the XaoS source code (*.xpf file contents):
;Position file automatically generated by XaoS 4.2.1
; - a realtime interactive fractal zoomer
;Use xaos -loadpos <filename> to display it
(initstate)
(defaultpalette 0)
(formula 'user)
(usrform "sin(z^2)-cos(z^2)+c")
(angle 90)
(maxiter 1000)
(view -0.241140329885861603 1.09425325699643758E-015 8.78234117374088186E-014 8.78234139599431772E-014)
And Fractal->View... yields:
So I tried to enter the formula into UltraFractal, but no matter what I try, I can't get it to work.
This works:
init:
z = #start
loop:
z = sin(z^#power) + cos(z^#power) + #pixel
This does not work:
init:
z = #start
loop:
z = sin(z^#power) - cos(z^#power) + #pixel
The only difference in the above two is the minus sign.
This does not work:
init:
z = #start
loop:
z2p = z^#power
ss = sin(z2p)
cc = cos(z2p)
z = ss - cc + #pixel
This works:
init:
z = #start
loop:
z2p = z^#power
ss = sin(z2p)
cc = cos(z2p)
z = ss + cc + #pixel
but if I add a line negating cc, it doesn't work again:
init:
z = #start
loop:
z2p = z^#power
ss = sin(z2p)
cc = cos(z2p)
cc = -cc
z = ss + cc + #pixel
Finally, one last example.
This works:
init:
z = #start
loop:
z2p = z^#power
ss = sin(z2p)
cc = cos(z2p)
z = ss + 1 - ( 1 - cc ) + #pixel
but this doesn't:
init:
z = #start
loop:
z2p = z^#power
ss = sin(z2p)
cc = cos(z2p)
z = ss + 1 - ( 1 + cc ) + #pixel
As I think I've proven, negation and subtraction seem to be working. And I keep changing only the minus sign or the subtraction to make it stop working, so I suspect that there is a bug (or an arbitrary limitation of not being able to use this particular formula? - doesn't make sense.)
In the "Fractal Mode" pane, lower right part of screen, I click the third item down, "Switch Mode", and it displays "Contains errors." This is the only helpful feedback I've been able to find.
This is a paid program, so I do not expect to be having this problem. Anyone? (secondary question - what zoomer will render this well? Thanks!)
Here is my current UltraFractal source code:
comment {
This file contains standard fractal types for Ultra Fractal. Many of the
fractal formulas here were written by other formula authors, as noted in the
comments with each formula. All formulas have been edited and simplified by
Frederik Slijkerman.
These formulas are also available as objects for the common.ulb framework in
Standard.ulb.
}
sin2_minus_cos2 {
;
; Generic Mandelbrot set.
;
init:
z = #start
z9 = 1
loop:
z2p = z^#power
ss = sin(z2p)
cc = cos(z2p)
cc = -cc
z = ss + cc + #pixel
bailout:
|z| <= #bailout
$IFDEF VER60
perturbinit:
#dz = 0
perturbloop:
if #power == (2, 0)
#dz = 2 * #z * #dz + sqr(#dz) + #dpixel
elseif #power == (3, 0)
complex z2 = sqr(#z)
complex dz2 = sqr(#dz)
#dz = 3 * z2 * #dz + 3 * #z * dz2 + #dz * dz2 + #dpixel
else ; power 4
complex z2 = sqr(#z)
complex dz2 = sqr(#dz)
complex zdz4 = 4*#z*#dz
#dz = #dpixel + zdz4*z2 + 6*z2*dz2 + zdz4*dz2 + sqr(dz2)
endif
$ENDIF
default:
title = "sin2_minus_cos2"
center = (-0.5, 0)
$IFDEF VER50
rating = recommended
$ENDIF
$IFDEF VER60
perturb = #power == (2, 0) || #power == (3, 0) || #power == (4, 0)
$ENDIF
param start
caption = "Starting point"
default = (0,0)
hint = "The starting point parameter can be used to distort the Mandelbrot \
set. Use (0, 0) for the standard Mandelbrot set."
endparam
param power
caption = "Power"
default = (2,0)
hint = "This parameter sets the exponent for the Mandelbrot formula. \
Increasing the real part to 3, 4, and so on, will add discs to \
the Mandelbrot figure. Non-integer real values and non-zero \
imaginary values will create distorted Mandelbrot sets. Use (2, 0) \
for the standard Mandelbrot set."
endparam
float param bailout
caption = "Bailout value"
default = 4.0
min = 1.0
$IFDEF VER40
exponential = true
$ENDIF
hint = "This parameter defines how soon an orbit bails out while \
iterating. Larger values give smoother outlines; values around 4 \
give more interesting shapes around the set. Values less than 4 \
will distort the fractal."
endparam
switch:
type = "Julia"
seed = #pixel
power = power
bailout = bailout
}
I just punched the formula into a zoomer on my Android, and it seems to work.
Here is that coordinate, zoomed out just a little, so that you can barely see the pixelated fractal (just another example of great beauty from this wonderful infinite universe!):
EDIT:
This formula works:
init:
z = #start
loop:
; in XaoS, user formula sin(z)^2-cos(z)^2+c
z = sin(z)^2 - cos(z)^2 + #pixel
And here's the result in UltraFractal:

Julia - MethodError: no method matching current_axis(::Nothing)

I am trying to test a linear approximation function and I am getting the error "no method matching current_axis(::Nothing)".
Here is my linear approximation function:
function linear_approx(A,b,c,p0)
p0 = [i for i in p0]
y(p) = p'*A*p .+ b'*p .+ c .-1
e = y(p0)
d = 2*A*p0 + b
(; d, e)
end
Here is the function that attempts to plot and throws an exception. I also included that value of the parameter when I tried to call it:
pts = [(1,1), (3,2), (4,4)]
function visualize_approx(pts)
# Use this function to inspect your solution, and
# ensure that the three points lie on one of
# the level-sets of your quadratic approximation.
(; A, b, c) = constant_curvature_approx(pts)
min_val = Inf
max_val = -Inf
for pt in pts
(; d, e) = linear_approx(A,b,c,pt)
P = LinRange(pt[1] - 0.2, pt[1]+0.2, 100)
Q = linear_segment(pt, d, e, P)
# the error arises here
plot!(P, Q)
plot!([pt[1]], [pt[2]])
end
delta = max_val - min_val
min_val -= 0.25*delta
max_val += 0.25*delta
X = Y = LinRange(min_val,max_val, 100)
Z = zeros(100,100)
for i = 1:100
for j = 1:100
pt = [X[i]; Y[j]]
Z[i,j] = pt'*A*pt + pt'*b + c
end
end
contour(X,Y,Z,levels=[-1,0,1,2,3])
for pt in pts
plot!([pt[1]], [pt[2]])
end
current_figure()
end
Does anyone know why this error arises?
plot! modifies a previously created plot object. It seems like you did not create a plot before calling it. This is why you get the error. Use plot when creating the plot and plot! when modifying it.

How do you find outer points in a circle from a point mathematically?

Trying to find a set of points that would allow a point to seemingly connect to a circle, like the image below however there is no overlap and it lines up with the edge of the circle. Apologies if this is hard to understand it is hard to explain.
If you want something like this:
then the python code below does this.
import numpy as np
# function that calcuates the points at which the lines are tangent to the circle
def tangent_points(Point, Circle):
Rot_90 = np.array([[0, -1],
[1, 0]])
O = Circle[0]
r = Circle[1]
unit_OP = Point - O
OP = np.sqrt( unit_OP.dot(unit_OP) )
unit_OP = unit_OP / OP
a = r**2 / OP
unit_perp = Rot_90.dot(unit_OP)
b = np.sqrt(r**2 - a**2)
return O + a*unit_OP + b*unit_perp, O + a*unit_OP - b*unit_perp
# Test example
O = np.array([0,0])
r = 2
P = np.array([7,5])
Circ = (O, r)
T1, T2 = tangent_points(P, Circ)
# plotting preparations:
# prepare circle
s = np.linspace( 0 , 2 * np.pi , 150 )
xc = O[0] + r*np.cos( s )
yc = O[1] + r*np.sin( s )
# prepare tangents
s = np.linspace( 0, 1, 150)
L1 = P[:, np.newaxis]*(1-s[np.newaxis, :]) + T1[:, np.newaxis]*s[np.newaxis, :]
L2 = P[:, np.newaxis]*(1-s[np.newaxis, :]) + T2[:, np.newaxis]*s[np.newaxis, :]
# actual plotting
# setup a figure environment
figure, axes = plt.subplots()
axes.set_aspect( 1 )
# plotting circle and center
axes.plot( xc, yc )
axes.plot(O[0], O[1], 'bo')
# plotting point ouside circle
axes.plot(P[0], P[1], 'bo')
# plotting tagnetn lines
axes.plot( L1[0], L1[1] )
axes.plot( L2[0], L2[1] )
# plotting tangent points
axes.plot(T1[0], T1[1], 'ro')
axes.plot(T2[0], T2[1], 'ro')
plt.show()

Julia dies on creation of contour plot

I want to make a contour plot of the loss space for a rather simple regression. Whenever I go to plot the space my session dies. Is there something that I'm doing wrong or do I need to trouble shoot installation? (just installed a couple days ago but haven't used Julia before)
using Plots, DataFrames, StatsPlots, Statistics, LinearAlgebra
f(t) = t.^2
c(θ₁, θ₂) = sum(f(t)-θ₁*t-θ₂*t.^2)
t = LinRange(0,1,20) |> collect
θ₁ = LinRange(-3,2,100) |> collect
θ₂ = LinRange(-1,3.5,100)|> collect
X = [t t.^2]
θ = [θ₁ θ₂]
yhats = X * transpose(θ)
ytrue = t.^2
e = yhats .- ytrue
tse = sum(e.^2, dims=1)
contour(θ[:,1],θ[:,2], tse)
It looks like you are trying to do
using Plots
f(t) = t^2
y(θ₁, θ₂, t) = θ₁ * t + θ₂ * t^2
ts = LinRange(0, 1, 20)
e(θ₁, θ₂) = sum(abs2, f(t) - y(θ₁, θ₂, t) for t in ts)
θ₁ = LinRange(-3, 2, 100)
θ₂ = LinRange(-1, 3.5, 100)
contourf(θ₁, θ₂, e)
which gives

simulate data from a linear fractional stable motion

I have to simulate some data from a Linear fractional stable motion. I have found an article where they simulate such data using Matlab. The code is from the article "Simulation methods for linear fractional stable motion and
FARIMA using the Fast Fourier Transform" by Stilian Stoev and Murad S. Taqqu. The following is the matlab code:
% Written by Stilian Stoev 05.06.2002, sstoev#math.bu.edu
%
% Usage:
% y = fftlfsn(H,alpha,m,M,C,N,n)
%
mh = 1/m;
d = H-1/alpha;
t0 = [mh:mh:1];
t1 = [1+mh:mh:M];
A = mh^(1/alpha)*[t0.^d, t1.^d-(t1-1).^d];
C = C*(sum(abs(A).^alpha)^(-1/alpha));
A = C*A;
Na = m*(M+N);
A = fft(A,Na);
y = [];
for i=1:n,
if alpha<2,
Z = rstab(alpha,0,Na)’;
elseif alpha==2,
Z = randn(1,Na);
end;
Z = fft(Z,Na);
w = real(ifft(Z.*A,Na));
y = [y; w(1:m:N*m)];
end;
Example:
The commands
H = 0.2; alpha =1.5; m = 256; M = 6000; N = 2^14 - M;
y = fftlfsn(H,alpha,m,M,1,N,1);
x = cumsum(y);
generate a simulated path y of length N of linear
fractional stable noise and a path x of LFSM.
In the following I have tried to translate it,
but I have some questions. I have commented on it in the code.
fftlfsn <- function(H,alpha,m,M,C,N,n){
mh = 1/m;
d = H-1/alpha;
t0 = seq(mh,mh, by =1);
t1 = seq(1+mh,mh, by=M);
# Is the following the right way to translate the matlab code into R?
A = mh^(1/alpha)*matrix(c(t0^d, t1^d-(t1-1)^d), ncol = length(t0), nrow = length(t1));
C = C*(sum(abs(A)^alpha)^(-1/alpha));
A = C*A;
Na = m*(M+N);
# I don't konw if it is right to use the function "fft" here.
#Does this respond directly to the function "fft" in matlab?
A = fft(A,Na);
#how can I do somthing similar in R?
#I think they create an empty matrix? Could I just write y=0?
y = [];
for (i in 1:n)
{
if(alpha<2){
# The function "rstab" generates symmetric alpha-stable variables. Is there a similar function in R, or do you know how to write one?
Z = t(rstab(alpha,0,Na))
}
else if(alpha==2){
Z = matrix (rnorm(Na, mean = 0, sd = 1), nrow = 1, ncol = Na)
}
# Again, can I just use the R-function "fft" directly?
Z = fft(Z,Na);
w = Re(fft(Z*A,Na, inverse= TRUE));
#I have trouble understanding the following and therefore I can't translate it.
y = [y; w(1:m:N*m)];
}
}
Any help appreciated!

Resources