Julia plotting in 3D: How to draw a line between coordinates? - julia

I am working on a program that a friend wrote in Julia. We have to do some work for university, especially for a course called "dynamic modelling".
The thing is to reproduce some great work of Kashtan and Alon; maybe you know their publication about biological networks and genetic algorithms. Now my friend asked me to find out, whether we can plot something in 3D and I don't know how to do that. He gave me some part of our program (see code below) and wrote me to find out, whether we can draw a line from one coordinate (x,y,z) to another coordinate (x,y,z). Do you know how to do that in Julia?
module ShowGateNet
export
showGate,
setGattaStruct;
using Plots;
using BPIPopulation;
abstract GrafGate
type GGate <: GrafGate
in1::Array{Integer};
in2::Array{Integer};
out::Array{Integer};
end;
#---------------------------------------------------------------
# creates a 2D-matrix for almost a circle:
# mx:: x-coordinate of the center circle
# my:: y-coordinate of the center circle
# r:: radius of the circle
#---------------------------------------------------------------
function circNumba(rx=2::Integer,cx=0::Integer,cy=0::Integer, cz=0)
k=0:360;
c=zeros(length(k),4);
c[:,1] = k;
c[:,2] = round(cos(radian(k))*rx+cx,3);
c[:,3] = cy;
c[:,4] = round(sin(radian(k))*rx+cz,3);
return c;
end;
function radian(grad)
return round(2*pi*grad/360,3);
end
function showGate(cx,cy,cz,numba)
r = 2;
centr = [cx;cy;cz];
# A = [centr[1]-1;centr[2];centr[3]];
# B = [centr[1];centr[2]+1;centr[3]];
C = [centr[1];centr[2]-1;centr[3]];
in2 = [centr[1]-3;centr[2]+1;centr[3]-1];
in1 = [centr[1]+3;centr[2]-1;centr[3]-1];
K = [centr[1];centr[2];centr[3]-1];
O = [centr[1];centr[2];centr[3]-3];
kCirc = circNumba(r,K[1],K[2],K[3]);
#display(plot!(kCirc[:,2],kCirc[:,3],kCirc[:,4],title="test-circ",line=3,color="red",zlabel="Z",xlabel="X",ylabel="Y"));
#display(plot!([centr[1],centr[1],centr[1]],[centr[2],centr[2],centr[2]],[centr[3]-1-r,centr[3]-1-r,centr[3]-3-r],w=3,color="blue"));
#display(plot!([centr[1]-3,centr[1]-3,centr[1]-2],[centr[2],centr[2],centr[2]],[centr[3],centr[3],centr[3]]-1,w=3,color="green")); #A nach K
#display(plot!([centr[1]+2,centr[1]+2,centr[1]+3],[centr[2],centr[2],centr[2]],[centr[3],centr[3],centr[3]]-1,w=3,color="green")); #A nach K
display(plot(kCirc[:,2],kCirc[:,3],kCirc[:,4],title="test-circ",line=3,color="red",zlabel="Z",xlabel="X",ylabel="Y"));
plot!([centr[1],centr[1],centr[1]],[centr[2],centr[2],centr[2]],[centr[3]-1-r,centr[3]-1-r,centr[3]-3-r],w=3,color="blue");#senkrechte
plot!([centr[1]-3,centr[1]-3,centr[1]-2],[centr[2],centr[2],centr[2]],[centr[3],centr[3],centr[3]]-1,w=3,color="green"); #A nach K
plot!([centr[1]+2,centr[1]+2,centr[1]+3],[centr[2],centr[2],centr[2]],[centr[3],centr[3],centr[3]]-1,w=3,color="green"); #A nach K
plotNumba(K,numba);
end;
function showGate2(cx,cy,cz,numba)
r = 2;
centr = [cx;cy;cz];
# A = [centr[1]-1;centr[2];centr[3]];
# B = [centr[1];centr[2]+1;centr[3]];
C = [centr[1];centr[2]-1;centr[3]];
in2 = [centr[1]+1;centr[2]+1;centr[3]];
in1 = [centr[1]+1;centr[2]-1;centr[3]];
K = [centr[1];centr[2]-r*2;centr[3]-1];
O = [centr[1];centr[2];centr[3]-1];
kCirc = circNumba(r,K[1],K[2],K[3]);
display(plot(kCirc[:,2],kCirc[:,3],kCirc[:,4],title="test-circ",line=3,color="red",zlabel="Z",xlabel="X",ylabel="Y"));
plot!([centr[1],centr[1],centr[1]],[centr[2],centr[2],centr[2]],[centr[3]-1-r,centr[3]-1-r,centr[3]-3-r],w=3,color="blue");
plotNumba(K,numba);
end;
function showGate2!(cx,cy,cz,numba)
r = 2;
centr = [cx;cy;cz];
# A = [centr[1]-1;centr[2];centr[3]];
# B = [centr[1];centr[2]+1;centr[3]];
C = [centr[1];centr[2]-1;centr[3]];
in2 = [centr[1]+1;centr[2]+1;centr[3]];
in1 = [centr[1]+1;centr[2]-1;centr[3]];
K = [centr[1];centr[2];centr[3]-1];
O = [centr[1];centr[2];centr[3]-1];
kCirc = circNumba(r,K[1],K[2],K[3]);
plot!(kCirc[:,2],kCirc[:,3],kCirc[:,4],title="test-circ",line=3,color="red",zlabel="Z",xlabel="X",ylabel="Y");
plot!([centr[1],centr[1],centr[1]],[centr[2],centr[2],centr[2]],[centr[3]-1-r,centr[3]-1-r,centr[3]-3-r],w=3,color="blue");
plot!([centr[1]-3,centr[1]-3,centr[1]-2],[centr[2],centr[2],centr[2]],[centr[3],centr[3],centr[3]]-1,w=3,color="green"); #A nach K
plot!([centr[1]+2,centr[1]+2,centr[1]+3],[centr[2],centr[2],centr[2]],[centr[3],centr[3],centr[3]]-1,w=3,color="green"); #A nach K
plotNumba(K,numba);
end;
function showGateIn!(cx,cy,cz,numba)
r = 2;
centr = [cx;cy;cz];
# A = [centr[1]-1;centr[2];centr[3]];
# B = [centr[1];centr[2]+1;centr[3]];
C = [centr[1];centr[2]-1;centr[3]];
in2 = [centr[1]+1;centr[2]+1;centr[3]];
in1 = [centr[1]+1;centr[2]-1;centr[3]];
K = [centr[1];centr[2];centr[3]-1];
O = [centr[1];centr[2];centr[3]-1];
kCirc = circNumba(r,K[1],K[2],K[3]);
plot!(kCirc[:,2],kCirc[:,3],kCirc[:,4],title="test-circ",line=3,color="red",zlabel="Z",xlabel="X",ylabel="Y");
if numba == 1
display(plot!([centr[1],centr[1],centr[1]],[centr[2],centr[2],centr[2]],[centr[3]-1-r,centr[3]-1-r,centr[3]-3-r],w=3,color="blue"));
else
plot!([centr[1],centr[1],centr[1]],[centr[2],centr[2],centr[2]],[centr[3]-1-r,centr[3]-1-r,centr[3]-3-r],w=3,color="blue");
end;
plotNumba(K,numba);
end;
function showGateL!(cx,cy,cz,numba)
r = 2;
centr = [cx;cy;cz];
# A = [centr[1]-1;centr[2];centr[3]];
# B = [centr[1];centr[2]+1;centr[3]];
C = [centr[1];centr[2]-1;centr[3]];
in2 = [centr[1]+1;centr[2]+1;centr[3]];
in1 = [centr[1]+1;centr[2]-1;centr[3]];
K = [centr[1]-1-r;centr[2];centr[3]-1];
O = [centr[1];centr[2];centr[3]-1];
kCirc = circNumba(r,K[1],K[2],K[3]);
plot!(kCirc[:,2],kCirc[:,3],kCirc[:,4],title="test-circ",line=3,color="red");
plot!([centr[1]-1,centr[1]-1,centr[1]],[centr[2],centr[2],centr[2]],[centr[3],centr[3],centr[3]]-1,w=3,color="green"); #A nach K
plot!([centr[1],centr[1],centr[1]+1],[centr[2],centr[2],centr[2]]+0.5,[centr[3]-1,centr[3]-1,centr[3]-1],w=3,color="green");# B nach D
plot!([centr[1],centr[1],centr[1]+1],[centr[2],centr[2],centr[2]]-0.5,[centr[3],centr[3],centr[3]]-1,w=3,color="green");# C nach E
plot!([centr[1],centr[1],centr[1]],[centr[2]-0.5,centr[2]-0.5,centr[2]+0.5],[centr[3],centr[3],centr[3]]-1,w=3,color="green"); # C nach B (waagerechte
plot!([centr[1],centr[1],centr[1]],[centr[2],centr[2],centr[2]],[centr[3]-1,centr[3]-1,centr[3]-3],w=3,color="blue");
plotNumba(K,numba);
end;
function showGateR!(cx,cy,cz,numba)
r = 2;
centr = [cx;cy;cz];
# A = [centr[1]-1;centr[2];centr[3]];
# B = [centr[1];centr[2]+1;centr[3]];
C = [centr[1];centr[2]-1;centr[3]];
in2 = [centr[1]+1;centr[2]+1;centr[3]];
in1 = [centr[1]+1;centr[2]-1;centr[3]];
K = [centr[1]+1+r;centr[2];centr[3]-1];
O = [centr[1];centr[2];centr[3]-1];
kCirc = circNumba(r,K[1],K[2],K[3]);
plot!(kCirc[:,2],kCirc[:,3],kCirc[:,4],title="test-circ",line=3,color="red");
plot!([centr[1]+1,centr[1]+1,centr[1]],[centr[2],centr[2],centr[2]],[centr[3],centr[3],centr[3]]-1,w=3,color="green"); #A nach K
plot!([centr[1],centr[1],centr[1]-1],[centr[2],centr[2],centr[2]]+0.5,[centr[3]-1,centr[3]-1,centr[3]-1],w=3,color="green");# B nach D
plot!([centr[1],centr[1],centr[1]-1],[centr[2],centr[2],centr[2]]-0.5,[centr[3],centr[3],centr[3]]-1,w=3,color="green");# C nach E
plot!([centr[1],centr[1],centr[1]],[centr[2]-0.5,centr[2]-0.5,centr[2]+0.5],[centr[3],centr[3],centr[3]]-1,w=3,color="green"); # C nach B (waagerechte
plot!([centr[1],centr[1],centr[1]],[centr[2],centr[2],centr[2]],[centr[3]-1,centr[3]-1,centr[3]-3],w=3,color="blue");
plotNumba(K,numba);
end;
#function setGattaStruct(pEle::BPIPopulation.popElement)
function setGattaStruct()
showGate(0,0,-4,15); # 15
showGate2!(-4,0,8,14); #14
showGate2!(4,0,8,13); #13
showGateL!(-8,4,16,12); #12
showGateL!(-8,-4,16,11); #11
showGateR!(8,4,16,10); #10
showGateR!(8,-4,16,9); #9
showGateL!(-8,4, 32,8); #8
showGateL!(-8,-4, 32,7); #7
showGateR!(8,4, 32,6); #6
showGateR!(8,-4, 32,5); #5
showGateIn!(0,6, 40,4); #4
showGateIn!(0,2, 40,3); #3
showGateIn!(0,-2, 40,2); #2
showGateIn!(0,-6, 40,1); #1
# hier dann evtl "PLOTTEN "der verbindungen
end;
function plotNumba(K,numba)
if numba>=10
plot!([K[1],K[1],K[1]]-0.25,[K[2],K[2],K[2]],
[K[3]-1,K[3]-1,K[3]-3]+2,w=3,color="blue");
end;
if numba%10 == 0
plot!([K[1],K[1],K[1]]+1.25,[K[2],K[2],K[2]],
[K[3]-1,K[3]-1,K[3]-3]+2,w=3,color="blue");
plot!([K[1],K[1],K[1]]+0.25,[K[2],K[2],K[2]],
[K[3]-1,K[3]-1,K[3]-3]+2,w=3,color="blue");
plot!([K[1]+1,K[1]+1,K[1]]+0.25,[K[2],K[2],K[2]],
[K[3],K[3],K[3]]-1,w=3,color="blue");
plot!([K[1]+1,K[1]+1,K[1]]+0.25,[K[2],K[2],K[2]],
[K[3],K[3],K[3]]+1,w=3,color="blue");
end;
if numba%10 == 1
plot!([K[1],K[1],K[1]]+1.25,[K[2],K[2],K[2]],
[K[3]-1,K[3]-1,K[3]-3]+2,w=3,color="blue");
end;
if numba%10 == 2
plot!([K[1],K[1],K[1]]+0.25,[K[2],K[2],K[2]],
[K[3]-2,K[3]-2,K[3]-3]+2,w=3,color="blue");
plot!([K[1],K[1],K[1]]+1.25,[K[2],K[2],K[2]],
[K[3]-1,K[3]-1,K[3]-2]+2,w=3,color="blue");
plot!([K[1]+1,K[1]+1,K[1]]+0.25,[K[2],K[2],K[2]],
[K[3],K[3],K[3]]-1,w=3,color="blue");
plot!([K[1]+1,K[1]+1,K[1]]+0.25,[K[2],K[2],K[2]],
[K[3],K[3],K[3]],w=3,color="blue");
plot!([K[1]+1,K[1]+1,K[1]]+0.25,[K[2],K[2],K[2]],
[K[3],K[3],K[3]]+1,w=3,color="blue");
end;
if numba%10 == 3
plot!([K[1],K[1],K[1]]+1.25,[K[2],K[2],K[2]],
[K[3]-1,K[3]-1,K[3]-3]+2,w=3,color="blue");
plot!([K[1]+1,K[1]+1,K[1]]+0.25,[K[2],K[2],K[2]],
[K[3],K[3],K[3]]-1,w=3,color="blue");
plot!([K[1]+1,K[1]+1,K[1]]+0.25,[K[2],K[2],K[2]],
[K[3],K[3],K[3]],w=3,color="blue");
plot!([K[1]+1,K[1]+1,K[1]]+0.25,[K[2],K[2],K[2]],
[K[3],K[3],K[3]]+1,w=3,color="blue");
end;
if numba%10 == 4
plot!([K[1],K[1],K[1]]+1.25,[K[2],K[2],K[2]],[K[3]-1,K[3]-1,K[3]-3]+2,w=3,color="blue");
plot!([K[1]+1,K[1]+1,K[1]]+0.25,[K[2],K[2],K[2]],[K[3],K[3],K[3]],w=3,color="blue");
plot!([K[1],K[1],K[1]]+0.25,[K[2],K[2],K[2]],[K[3]-1,K[3]-1,K[3]-2]+2,w=3,color="blue");
end;
if numba%10 == 5
plot!([K[1],K[1],K[1]]+1.25,[K[2],K[2],K[2]],[K[3]-2,K[3]-2,K[3]-3]+2,w=3,color="blue");
plot!([K[1],K[1],K[1]]+0.25,[K[2],K[2],K[2]],[K[3]-1,K[3]-1,K[3]-2]+2,w=3,color="blue");
plot!([K[1]+1,K[1]+1,K[1]]+0.25,[K[2],K[2],K[2]],[K[3],K[3],K[3]]-1,w=3,color="blue");
plot!([K[1]+1,K[1]+1,K[1]]+0.25,[K[2],K[2],K[2]],[K[3],K[3],K[3]],w=3,color="blue");
plot!([K[1]+1,K[1]+1,K[1]]+0.25,[K[2],K[2],K[2]],[K[3],K[3],K[3]]+1,w=3,color="blue");
end;
if numba%10 == 6
plot!([K[1],K[1],K[1]]+1.25,[K[2],K[2],K[2]],[K[3]-2,K[3]-2,K[3]-3]+2,w=3,color="blue");
plot!([K[1],K[1],K[1]]+0.25,[K[2],K[2],K[2]],[K[3]-1,K[3]-1,K[3]-3]+2,w=3,color="blue");
plot!([K[1]+1,K[1]+1,K[1]]+0.25,[K[2],K[2],K[2]],[K[3],K[3],K[3]]-1,w=3,color="blue");
plot!([K[1]+1,K[1]+1,K[1]]+0.25,[K[2],K[2],K[2]],[K[3],K[3],K[3]],w=3,color="blue");
plot!([K[1]+1,K[1]+1,K[1]]+0.25,[K[2],K[2],K[2]],[K[3],K[3],K[3]]+1,w=3,color="blue");
end;
if numba%10 == 7
plot!([K[1],K[1],K[1]]+1.25,[K[2],K[2],K[2]],[K[3]-1,K[3]-1,K[3]-3]+2,w=3,color="blue");
plot!([K[1]+1,K[1]+1,K[1]]+0.25,[K[2],K[2],K[2]],[K[3],K[3],K[3]]+1,w=3,color="blue");
end;
if numba%10 == 8
plot!([K[1],K[1],K[1]]+1.25,[K[2],K[2],K[2]],[K[3]-1,K[3]-1,K[3]-3]+2,w=3,color="blue");
plot!([K[1],K[1],K[1]]+0.25,[K[2],K[2],K[2]],[K[3]-1,K[3]-1,K[3]-3]+2,w=3,color="blue");
plot!([K[1]+1,K[1]+1,K[1]]+0.25,[K[2],K[2],K[2]],[K[3],K[3],K[3]]-1,w=3,color="blue");
plot!([K[1]+1,K[1]+1,K[1]]+0.25,[K[2],K[2],K[2]],[K[3],K[3],K[3]],w=3,color="blue");
plot!([K[1]+1,K[1]+1,K[1]]+0.25,[K[2],K[2],K[2]],[K[3],K[3],K[3]]+1,w=3,color="blue");
end;
if numba%10 == 9
plot!([K[1],K[1],K[1]]+0.25,[K[2],K[2],K[2]],[K[3]-1,K[3]-1,K[3]-2]+2,w=3,color="blue");
plot!([K[1],K[1],K[1]]+1.25,[K[2],K[2],K[2]],[K[3]-1,K[3]-1,K[3]-3]+2,w=3,color="blue");
plot!([K[1]+1,K[1]+1,K[1]]+0.25,[K[2],K[2],K[2]],[K[3],K[3],K[3]]-1,w=3,color="blue");
plot!([K[1]+1,K[1]+1,K[1]]+0.25,[K[2],K[2],K[2]],[K[3],K[3],K[3]],w=3,color="blue");
plot!([K[1]+1,K[1]+1,K[1]]+0.25,[K[2],K[2],K[2]],[K[3],K[3],K[3]]+1,w=3,color="blue");
end;
end;
end; # END MODULE

Related

How to pass multiple dimension arrays into a function in Julia?

I am still learning the language Julia, however, i am writing a population model that describes the dynamics of 100 mosquito subpopulations. I have many different functions but i think the error lays in the passing to my main function.
xf = XLSX.readxlsx("C:/Scriptie_mosquitoes/knmi_csv.xlsx")
sh = xf["knmi_csv"]
temperature = sh["B3:B368"]
precip = sh["F3:F368"]
subpopulation_amount = 100
imat_list = zeros(subpopulation_amount,length(temperature))
adul_list = zeros(subpopulation_amount,length(temperature))
egg_list = zeros(subpopulation_amount,length(temperature))
diaegg_list = zeros(subpopulation_amount,length(temperature))
imat_list[1] = 100.0
adul_list[1] = 1000.0
egg_list[1] = 100.0
diaegg_list[1] = 100.0
for counter = 1:subpopulation_amount
u = Normal()
temp_change = rand(u)
tempa = temperature .+ temp_change
e = Normal()
precip_change = rand(e)
main(counter,tempa,precip,precip_change,imat_list[:],adul_list[:],egg_list[:],diaegg_list[:])
end
This is the error shown
julia> for counter = 1:subpopulation_amount
u = Normal()
temp_change = rand(u)
tempa = temperature .+ temp_change
e = Normal()
precip_change = rand(e)
main(counter,tempa,precip,precip_change,imat_list,adul_list,egg_list,diaegg_list)
end
ERROR: UndefVarError: Point2f0 not defined
Stacktrace:
[1] newImmaturetoAdult(::Float64) at .\REPL[1137]:9
[2] main(::Int64, ::Array{Float64,2}, ::Array{Any,2}, ::Float64, ::Array{Float64,2}, ::Array{Float64,2}, ::Array{Float64,2}, ::Array{Float64,2}) at .\REPL[1158]:10
[3] top-level scope at .\REPL[1187]:7
I would very much appreciate it if you guys would like to help me. Anything can help.
Thanks!
I will add the whole code below as well.
using Statistics
using Plots
using JuliaDB
using XLSX
using Distributions
using Random
# Possible struct for climaticfactors per day
struct Climaticfactors
temperature
precipiation
evaporation
photoperiod
end
# First function written, describes the development rate of larvae to adults. on Temperature
# function developRate(temp)
# # function
# develop = (-1/225)*(temp-25)^2+1
# # Check if development is not negative
# if develop < 0
# develop = 0
# return develop
# else
# return develop
# end
# end
# Linear segments between the data points. The function finds the percentage of larvae growing up on temperature
function newImmaturetoAdult(temp)
# Data point from literature
x = [5.0, 10.0, 15.0, 20.0, 25.0, 30.0, 35.0, 40.0]
y = [0.0, 0.0, 50.0, 77.5, 76.3, 67.5, 2.5, 0.0]
# Loop that goes through all possible temperatures
for i in 1:length(x)-1
# If in the temperature falls between a segment find that point
if temp >= x[i] && temp <= x[i+1]
a = LineSegment(Point2f0(x[i], y[i]), Point2f0(x[i+1], y[i+1]))
b = LineSegment(Point2f0(temp,0.0),Point2f0(temp,100.0))
j = intersects(a,b)
c = j[2]
# Returning the percentage
return c[2]
# Temperatures do nothing
elseif temp>40.0 || temp<5.0
return 0.0
end
end
end
# Same technique as before but with egg to larvae on temperature
function eggtolarvea(temp)
# Data from literature
x = [5.0, 10.0, 15.0, 20.0, 25.0, 30.0, 35.0, 40.0]
y = [4.4, 4.0, 8.2, 66.9, 49.2, 51.4, 10, 0.0]
for i in 1:(length(x)-1)
if temp >= x[i] && temp <= x[i+1]
a = LineSegment(Point2f0(x[i], y[i]), Point2f0(x[i+1], y[i+1]))
b = LineSegment(Point2f0(temp,0.0),Point2f0(temp,100.0))
j = intersects(a,b)
c = j[2]
return c[2]
elseif temp>40.0 || temp<5.0
return 0.0
end
end
end
# function humidityindex(temp, precip...)
# moist_effect = 0
# temp_effect = 0
# for i in 1:size(precip)
# moist_effect += ((precip[i]/100) * (1-(i/10)))
# temp_effect -= ((temp[i]/25) * (1-(i/10)))
# end
# effect = temp_effect + moist_effect
# return effect
# end
function diapauserate(day)
y = 0.045*day - 10.75
end
# Egg_population dynamics
function eggpop(hatch,effect,diarate,egg_pop, adult_pop)
# if eggs don't hatch do nothing
if hatch == 0
egg_pop *= 0.8
end
if effect > 0
tot = adult_pop * 10
dia_pop = tot * diarate
egg_pop = tot - dia_pop
else
tot = adult_pop * 4
dia_pop = tot * diarate
egg_pop = tot - dia_pop
end
return dia_pop, egg_pop
end
# Larvae population dynamics
function immaturepop(develop_rate, hatch, immature_pop, egg_pop)
# Hatch encreases larvae population
if hatch == 0
change = immature_pop * develop_rate
immature_pop -= change
else
change = immature_pop * develop_rate
immature_pop -= change
immature_pop += egg_pop * hatch
end
return immature_pop
end
# Adult population dynamics
function adultpop(develop_rate,immature_pop,adult_pop)
# New adults
change = immature_pop * develop_rate
adult_pop = adult_pop + change
# Survival of 80%
adult_pop *= 0.95
return adult_pop
end
# Main
function main(counter,temperature,precip, precip_change,imat_list,adul_list,egg_list,diaegg_list)
# Iterating through temperature data (year)
for i in 2:1:length(temperature);
# Only from 10 march to 30 september mosquito season, otherwise diapause
if i >= 69 && i <= 273;
# temperatures in 1 degrees celcius
temp = temperature[i] / 10;
# Development and hatch values in 0.02 values
develop = newImmaturetoAdult(temp) / 100;
# println(develop)
hatch = eggtolarvea(temp) / 100;
# println(hatch)
# Moist_index
evap = collect(1:1:7);
precipi = collect(1:1:7);
for j in 1:7
t = temperature[-j+i];
evap[j]= t;
p = precip[-j+i];
precipi[j] = p;
end
moist_effect = 0;
temp_effect = 0;
for h in 1:length(precipi)
moist_effect += ((precipi[h]/100.0) * (1.0-(h/10.0)));
temp_effect -= ((evap[h]/200.0) * (1.0-(h/10.0)));
end
effect = temp_effect + moist_effect + precip_change;
if diapauserate(i) <= 0
diarate = 0 ;
elseif diapauserate(i) >= 1
diarate = 1;
else
diarate = diapauserate(i);
end
egg = eggpop(hatch,effect,diarate, egg_list[counter,i-1],adul_list[counter,i-1]);
egg_list[counter, i] = egg[2]
diaegg_list[counter, i] = egg[1]
# Changing and adding eggpop
# Changing and adding immature pop
ima = immaturepop(develop, hatch, imat_list[counter,i], egg_list[counter,i-1]);
imat_list[counter,i] = ima
# Changing and adding adult pop
adu = adultpop(develop, imat_list[counter,i-1], adul_list[counter,i]);
adul_list[counter,i] = adu
# from 30 september keep egg_level the same but larvae and adult decreasing
elseif i > 273 && i < 365
egg_list[counter,i] = egg_list[counter,i-1]/1.1
diaegg_list[counter,i] = diaegg_list[counter,i-1]
imat_list[counter,i] = imat_list[counter,i-1]/1.1
adul_list[counter,i] = adul_list[counter,i-1]/1.1
else i > 0 && i < 69
egg_list[counter,i] = egg_list[counter,i-1]
diaegg_list[counter,i] = diaegg_list[counter,i-1]
imat_list[counter,i] = imat_list[counter,i-1]
adul_list[counter,i] = adul_list[counter,i-1]
end
end
end
# using Distributions, Random
# Random.seed!(123)
# td = Truncated(Normal(0, 0.05),-5,5)
# x = rand(td, 10000000)'
# using Distributions
# using Random
# Random.seed!(123)
# d = Normal()
# x = rand(d, 100)
# Importing KNMI data
xf = XLSX.readxlsx("C:/Scriptie_mosquitoes/knmi_csv.xlsx")
sh = xf["knmi_csv"]
temperature = sh["B3:B368"]
precip = sh["F3:F368"]
# Starting values
# imat_list = collect(1.0:1:length(temperature));
# adul_list = collect(1.0:1:length(temperature));
# egg_list = collect(1.0:1:length(temperature));
# diaegg_list = collect(1.0:1:length(temperature));
subpopulation_amount = 100
imat_list = zeros(subpopulation_amount,length(temperature))
adul_list = zeros(subpopulation_amount,length(temperature))
egg_list = zeros(subpopulation_amount,length(temperature))
diaegg_list = zeros(subpopulation_amount,length(temperature))
imat_list[1] = 100.0
adul_list[1] = 1000.0
egg_list[1] = 100.0
diaegg_list[1] = 100.0
for counter = 1:subpopulation_amount
u = Normal()
temp_change = rand(u)
tempa = temperature .+ temp_change
e = Normal()
precip_change = rand(e)
main(counter,tempa,precip,precip_change,imat_list,adul_list,egg_list,diaegg_list)
end
# # Visualizing
# populaties = [imat_list, adul_list]
# x = 1:1:length(temperature)
# p1 = plot(x,populaties, title= "Populatie niveaus", label = ["ImmaturePopulatie" "AdultPopulatie"], lw = 3)
# plot(p1)
# # plot(x,egg_list, title="Egg population")
# egg_popu = [egg_list, diaegg_list]
# p2 = plot(x,egg_popu, title="Egg populations", label=["Eggpop" "DiaeggPop"])
# plot(p1,p2, layout=(2,1), legend=true)
You forgot to import the package that defines Point2f0:
using GeometryTypes
BTW your structs should have types for fields - never used untyped structs because of performance.
Moreover to generate normally distributed numbers use randn().
It is also worth noting that when defining a distribution parameters such as Normal() it is enough to do it once and than reuse the object.

I have written a path tracer using julia programming language but i think it is slow

I have changed my post and posted the whole of my code! Could someone tell me how can I optimize it?
import Base: *, +, -, /, ^
using Images
const Π = convert(Float64, π)
#define vector
mutable struct Vec3
x::Float64
y::Float64
z::Float64
end
function +(u::Vec3, v::Vec3)
Vec3(u.x+v.x, u.y+v.y, u.z+v.z)
end
function -(u::Vec3, v::Vec3)
Vec3(u.x-v.x, u.y-v.y, u.z-v.z)
end
function /(u::Vec3, v::Float64)
Vec3(u.x/v, u.y/v, u.z/v)
end
function *(u, v::Vec3)
if typeof(u) == Float64
Vec3(u*v.x, u*v.y, u*v.z)
elseif typeof(u) == Vec3
Vec3(u.x*v.x, u.y*v.y, u.z*v.z)
end
end
function ^(u::Vec3, v::Float64)
Vec3(u.x^v, u.y^v, u.z^v)
end
function dot(u::Vec3, v::Vec3)
u.x*v.x + u.y*v.y + u.z*v.z
end
function normalize(u::Vec3)
u/sqrt(dot(u,u))
end
function cross(u::Vec3, v::Vec3)
Vec3(u.y*v.z - v.y*u.z, u.z*v.x - v.z*u.x, u.x*v.y - v.x*u.y)
end
function gamma(u::Vec3)
Vec3(u.x^(1/2.2), u.y^(1/2.2), u.z^(1/2.2))
end
function clamp(u::Vec3)
u.x = u.x <= 1 ? u.x : 1
u.y = u.y <= 1 ? u.y : 1
u.z = u.z <= 1 ? u.z : 1
u
end
#define ray
struct Ray
s::Vec3
d::Vec3
end
#define planes
struct xyRect
z; x1; x2; y1; y2::Float64
normal; emittance; reflectance::Vec3
isLight::Bool
end
struct xzRect
y; x1; x2; z1; z2::Float64
normal; emittance; reflectance::Vec3
isLight::Bool
end
struct yzRect
x; y1; y2; z1; z2::Float64
normal; emittance; reflectance::Vec3
isLight::Bool
end
#define sphere
mutable struct Sphere
radius::Float64
center; normal; emittance; reflectance::Vec3
isLight::Bool
end
#define empty object
struct Empty
normal; emittance; reflectance::Vec3
end
#define surfaces
Surfaces = Union{xyRect, xzRect, yzRect, Sphere}
#define intersection function
function intersect(surface::Surfaces, ray::Ray)
if typeof(surface) == xyRect
t = (surface.z - ray.s.z)/ray.d.z
if surface.x1 < ray.s.x + t*ray.d.x < surface.x2 && surface.y1 < ray.s.y + t*ray.d.y < surface.y2 && t > 0
t
else
Inf
end
elseif typeof(surface) == xzRect
t = (surface.y - ray.s.y)/ray.d.y
if surface.x1 < ray.s.x + t*ray.d.x < surface.x2 && surface.z1 < ray.s.z + t*ray.d.z < surface.z2 && t > 0
t
else
Inf
end
elseif typeof(surface) == yzRect
t = (surface.x - ray.s.x)/ray.d.x
if surface.y1 < ray.s.y + t*ray.d.y < surface.y2 && surface.z1 < ray.s.z + t*ray.d.z < surface.z2 && t > 0
t
else
Inf
end
elseif typeof(surface) == Sphere
a = dot(ray.d, ray.d)
b = 2dot(ray.d, ray.s - surface.center)
c = dot(ray.s - surface.center, ray.s - surface.center) - surface.radius*surface.radius
Δ = b*b - 4*a*c
if Δ > 0
Δ = sqrt(Δ)
t1 = 0.5(-b-Δ)/a
t2 = 0.5(-b+Δ)/a
if t1 > 0
surface.normal = normalize(ray.s + t1*ray.d - surface.center)
t1
elseif t2 > 0
surface.normal = normalize(ray.s + t2*ray.d - surface.center)
t2
else
Inf
end
else
Inf
end
end
end
#define nearest function
function nearest(surfaces::Array{Surfaces, 1}, ray::Ray, tMin::Float64)
hitSurface = Empty(Vec3(0,0,0), Vec3(0,0,0), Vec3(0,0,0))
for surface in surfaces
t = intersect(surface, ray)
if t < tMin
tMin = t
hitSurface = surface
end
end
tMin, hitSurface
end
#cosine weighted sampling of hemisphere
function hemiRand(n::Vec3)
ξ1 = rand()
ξ2 = rand()
x = cos(2π*ξ2)*sqrt(ξ1)
y = sin(2π*ξ2)*sqrt(ξ1)
z = sqrt(1-ξ1)
r = normalize(Vec3(2rand()-1, 2rand()-1, 2rand()-1))
b = cross(n,r)
t = cross(n,b)
Vec3(x*t.x + y*b.x + z*n.x, x*t.y + y*b.y + z*n.y, x*t.z + y*b.z + z*n.z)
end
#trace the path
function trace(surfaces::Array{Surfaces, 1}, ray::Ray, depth::Int64, maxDepth::Int64)
if depth >= maxDepth
return Vec3(0,0,0)
end
t, material = nearest(surfaces, ray, Inf)
if typeof(material) == Empty
return Vec3(0,0,0)
end
if material.isLight == true
return material.emittance
end
ρ = material.reflectance
BRDF = ρ/Π
n = material.normal
R = hemiRand(n)
In = trace(surfaces, Ray(ray.s + t*ray.d, R), depth+1, maxDepth)
return Π*BRDF*In
end
#define camera
struct Camera
eye; v_up; N::Vec3
fov; aspect; distance::Float64
end
#render function
function render(surfaces::Array{Surfaces,1},camera::Camera,xRes::Int64,yRes::Int64,numSamples::Int64,maxDepth::Int64)
n = normalize(camera.N)
e = camera.eye
c = e - camera.distance*n
θ = camera.fov*(π/180)
H = 2*camera.distance*tan(θ/2)
W = H*camera.aspect
u = normalize(cross(camera.v_up,n))
v = cross(n,u)
img = zeros(3, xRes, yRes)
pixHeight = H/yRes
pixWidth = W/xRes
L = c - 0.5*W*u - 0.5*H*v
for i=1:xRes
for j=1:yRes
cl = Vec3(0,0,0)
for s=1:numSamples
pt = L + (i-rand())*pixWidth*u + (yRes-j+rand())*pixHeight*v
cl = cl + trace(surfaces, Ray(e, pt-e), 0, maxDepth)
end
cl = gamma(clamp(cl/convert(Float64, numSamples)))
img[:,j,i] = [cl.x, cl.y, cl.z]
end
end
img
end
#the scene
p1 = xzRect(1.,0.,1.,-1.,0.,Vec3(0,-1,0),Vec3(0,0,0),Vec3(0.75,0.75,0.75),false)
p2 = xzRect(0.,0.,1.,-1.,0.,Vec3(0,1,0),Vec3(0,0,0),Vec3(0.75,0.75,0.75),false)
p3 = xyRect(-1.,0.,1.,0.,1.,Vec3(0,0,1),Vec3(0,0,0),Vec3(0.75,0.75,0.75),false)
p4 = yzRect(0.,0.,1.,-1.,0.,Vec3(1,0,0),Vec3(0,0,0),Vec3(0.75,0.25,0.25),false)
p5 = yzRect(1.,0.,1.,-1.,0.,Vec3(-1,0,0),Vec3(0,0,0),Vec3(0.25,0.25,0.75),false)
p6 = xzRect(0.999,0.35,0.65,-0.65,-0.35,Vec3(0,-1,0),Vec3(18,18,18),Vec3(0,0,0),true)
s1 = Sphere(0.15,Vec3(0.3,0.15,-0.6),Vec3(0,0,0),Vec3(0,0,0),Vec3(0.75,0.75,0.75),false)
surfs = Surfaces[p1,p2,p3,p4,p5,p6,s1]
cam = Camera(Vec3(0.5,0.5,2),Vec3(0,1,0),Vec3(0,0,1),28.07,1,2)
#time image = render(surfs, cam, 400, 400, 1, 4);
colorview(RGB, image)
I need to know why my code is bad and slow. I am a beginner programmer and I don't have enough experience. My path tracer scene contains 7 objects, its maximum depth is 4, and it takes more than 2 seconds to generate an image of size 400*400. I think It shouldn't be that slow because my cpu is core i7 4770.
Sorry for changing my post.
To start with,
struct yzRect
x; y1; y2; z1; z2::Float64
normal; emittance; reflectance::Vec3
isLight::Bool
end
ends up only applying the type to the last variable for each line:
julia> fieldtypes(yzRect)
(Any, Any, Any, Any, Float64, Any, Any, Vec3, Bool)
so Julia will basically not know about any types in your structs which slows things down.
Also, your Vec3 should really be immutable and you then just create new instances of it when you want to "modify" the Vector.
There might be many more issues but those are two standing out.
Reading through https://docs.julialang.org/en/v1/manual/performance-tips/index.html and applying the guidelines in there is strongly recommended when analyzing performance.

Modular inverses and unsigned integers

Modular inverses can be computed as follows (from Rosetta Code):
#include <stdio.h>
int mul_inv(int a, int b)
{
int b0 = b, t, q;
int x0 = 0, x1 = 1;
if (b == 1) return 1;
while (a > 1) {
q = a / b;
t = b, b = a % b, a = t;
t = x0, x0 = x1 - q * x0, x1 = t;
}
if (x1 < 0) x1 += b0;
return x1;
}
However, the inputs are ints, as you can see. Would the above code work for unsigned integers (e.g. uint64_t) as well? I mean, would it be ok to replaced all int with uint64_t? I could try for few inputs but it is not feasible to try for all 64-bits combinations.
I'm specifically interested in two aspects:
for values [0, 264) of both a and b, would all calculation not overflow/underflow (or overflow with no harm)?
how would (x1 < 0) look like in unsigned case?
First of all how this algorithm works? It is based on the Extended Euclidean algorithm for computation of the GCD. In short the idea is following: if we can find some integer coefficients m and n such that
a*m + b*n = 1
then m will be the answer for the modular inverse problem. It is easy to see because
a*m + b*n = a*m (mod b)
Luckily the Extended Euclidean algorithm does exactly that: if a and b are co-prime, it finds such m and n. It works in the following way: for each iteration track two triplets (ai, xai, yai) and (bi, xbi, ybi) such that at every step
ai = a0*xai + b0*yai
bi = a0*xbi + b0*ybi
so when finally the algorithm stops at the state of ai = 0 and bi = GCD(a0,b0), then
1 = GCD(a0,b0) = a0*xbi + b0*ybi
It is done using more explicit way to calculate modulo: if
q = a / b
r = a % b
then
r = a - q * b
Another important thing is that it can be proven that for positive a and b at every step |xai|,|xbi| <= b and |yai|,|ybi| <= a. This means there can be no overflow during calculation of those coefficients. Unfortunately negative values are possible, moreover, on every step after the first one in each equation one is positive and the other is negative.
What the code in your question does is a reduced version of the same algorithm: since all we are interested in is the x[a/b] coefficients, it tracks only them and ignores the y[a/b] ones. The simplest way to make that code work for uint64_t is to track the sign explicitly in a separate field like this:
typedef struct tag_uint64AndSign {
uint64_t value;
bool isNegative;
} uint64AndSign;
uint64_t mul_inv(uint64_t a, uint64_t b)
{
if (b <= 1)
return 0;
uint64_t b0 = b;
uint64AndSign x0 = { 0, false }; // b = 1*b + 0*a
uint64AndSign x1 = { 1, false }; // a = 0*b + 1*a
while (a > 1)
{
if (b == 0) // means original A and B were not co-prime so there is no answer
return 0;
uint64_t q = a / b;
// (b, a) := (a % b, b)
// which is the same as
// (b, a) := (a - q * b, b)
uint64_t t = b; b = a % b; a = t;
// (x0, x1) := (x1 - q * x0, x0)
uint64AndSign t2 = x0;
uint64_t qx0 = q * x0.value;
if (x0.isNegative != x1.isNegative)
{
x0.value = x1.value + qx0;
x0.isNegative = x1.isNegative;
}
else
{
x0.value = (x1.value > qx0) ? x1.value - qx0 : qx0 - x1.value;
x0.isNegative = (x1.value > qx0) ? x1.isNegative : !x0.isNegative;
}
x1 = t2;
}
return x1.isNegative ? (b0 - x1.value) : x1.value;
}
Note that if a and b are not co-prime or when b is 0 or 1, this problem has no solution. In all those cases my code returns 0 which is an impossible value for any real solution.
Note also that although the calculated value is really the modular inverse, simple multiplication will not always produce 1 because of the overflow at multiplication over uint64_t. For example for a = 688231346938900684 and b = 2499104367272547425 the result is inv = 1080632715106266389
a * inv = 688231346938900684 * 1080632715106266389 =
= 743725309063827045302080239318310076 =
= 2499104367272547425 * 297596738576991899 + 1 =
= b * 297596738576991899 + 1
But if you do a naive multiplication of those a and inv of type uint64_t, you'll get 4042520075082636476 so (a*inv)%b will be 1543415707810089051 rather than expected 1.
The mod_inv C function :
return a modular multiplicative inverse of n with respect to the modulus
return 0 if the linear congruence has no solutions
unsigned mod_inv(unsigned n, const unsigned mod) {
unsigned a = mod, b = a, c = 0, d = 0, e = 1, f, g;
for (n *= a > 1; n > 1 && (n *= a > 0); e = g, c = (c & 3) | (c & 1) << 2) {
g = d, d *= n / (f = a);
a = n % a, n = f;
c = (c & 6) | (c & 2) >> 1;
f = c > 1 && c < 6;
c = (c & 5) | (f || e > d ? (c & 4) >> 1 : ~c & 2);
d = f ? d + e : e > d ? e - d : d - e;
}
return n ? c & 4 ? b - e : e : 0;
}
Examples
n = 7 and mod = 45 then res = 13 so 1 == ( 13 * 7 ) % 45
n = 52 and mod = 107 then res = 35 so 1 == ( 35 * 52 ) % 107
n = 213 and mod = 155 then res = 147 so 1 == ( 147 * 213 ) % 155
n = 392 and mod = 45 then res = 38 so 1 == ( 38 * 392 ) % 45
n = 3708141711 and mod = 4280761040 it still works...

error bernstein vandermonde julia.

the following error occurs. I tried to change the n .... but not working
"LoadError: BoundsError: attempt to access 9-element Array{Float64,1}:"
function bernstein_vandermonde( n )
if n == 1
v = ones(1, 1);
return v
end
v = zeros( n, n );
x = linspace( 0, 1, n );
for i = 1:n
println("entra no loop")
v[i,1:n] = bernstein_poly_01(n - 1, x[i])
end
return v
end
function bernstein_poly_01( n, x )
bern = ones(n)
if n == 0
bern[1] = 1
elseif 0 < n
bern[1] = 1 -x
bern[2] = x
for i = 2:n
bern[i+1] = x*bern[i];
for j = i-1:-1: 1
bern[j+1] = x*bern[j] + (1 - x)*bern[j+1]
end
bern[1] = (1 - x)*bern[1]
end
end
return bern
end
I can not solve :(

Invalid index error in a for loop

I've been working in this code for a while, it's pretty simple, just recursive calculation. At the while loop, in the first line I got an index error. Funny thing is before I start using the if statement in loop my index was fine and I could compile it. My believe my problem is the lack of familiarity with the scilab way of programming.
///CONSTANTES////
roh_H20 = 1030.00 // [kg/m^3] Água Salgada
roh_ar = 1.22 // [kg/m^3]
g = 9.81 // [m/s^2]
V_elo = 0.00041 // [m^3]
V_boia = 0.00811 // [m^3]
V_lastro = 0.00811 // [m^3]
D_corda = 0.030 // [m]
A_corda = 1/4*%pi*D_corda**2
L_corda = 30 // [m]
roh_corda = 905 // [kg/m^3] poliester
V_corda = A_corda*L_corda // [m^3]
roh_elo = 952 // [kg/m^3] PE Alta Densidade
m_elo = 0.38817 // [kg]
m_boia = 1.5654 // [Kg]
m_lastro = 2.5 // [kg] CHUTE
m_corda = roh_corda*V_corda; // [kg]
Cd = 1.3 // coeficiente de arrasto placa plana FOX pg 396
N_elo = 7*24 // conjuntos a cada 1 metro
N_corda = 4 // A definir
N_boia = 7 // 2 primeiros conjuntos
N_lastro = 7 // 2 últimos conjuntos
/// PROBLEMA ESTATICO ////
M = N_elo*m_elo + N_boia*(m_boia + m_lastro) // FALTA CORDA
P = M*g
Emp = g*(N_boia*V_boia + N_elo*V_elo + N_lastro*V_lastro)*roh_H20;
printf("\n*****PROBLEMA ESTATICO*****\n")
printf("\nO Peso do conjunto eh: %f N\n", P)
printf("\nO Empuxo eh: %f N\n", Emp)
/// PROBLEMA DINÂMICO ///
A_vela = 0.03230 // [m^2] dado pelo SolidWorks
N_vela = 7
printf("\n*****PROBLEMA DINAMICO*****\n")
a = zeros(0,1e3)
a(1)= (Emp-P)/ M
printf("\na_0 = %f [m/s^2]\n", a(1))
t=0
v= zeros(0,1e3)
dy = zeros(0,1e3)
Fd = zeros(0,1e3)
for i=1:50
// if i == 1 then
// a(i)= (Emp-P)/ M
// else
// 1+1
// end
v(i+1) = v(i) + a(i)*t
dy(i+1) = dy(i)+v(i+1)*t+ a(i)*t*t/2.0
Fd(i+1) = 0.5*roh_H20*Cd*N_vela*A_vela*v(i+1)**2
if v(i+1) > 0 then
a(i+1) = (Emp - P - Fd(i+1))/ M;
elseif v(i+1) <= 0 then
a(i+1) = (Emp - P + Fd(i+1))/ M;
end,
t=t+0.05
end
x = linspace(0,t,int(i))
// Grafico velocidade/aceleração
clf(0)
scf(0)
subplot(2,1,1)
plot(x,a,'ro-')
xlabel("Tempo [s]")
ylabel("Acelaração [m/s^2]")
legend("aceleração")
subplot(2,1,2)
plot(x,v,'bs:')
xlabel("Tempo [s]")
ylabel("velocidade [m/s]")
legend("velocidade")
// Grafico forca/deslocamento
clf(1)
scf(1)
subplot(2,1,1)
plot(x,Fd,'r--d')
xlabel("Tempo [s]")
ylabel("Força [N]")
legend("Força Arrasto")
subplot(2,1,2)
plot(x,dy,'m--^')
xlabel("Tempo [s]")
ylabel("Descolcamento [m]")
legend("deslocamento")
Whenever you have index error, there are two things to do in the console:
Check the value of the index variable (just by entering its name)
Check the size(s) of any arrays involved (using the command size)
In this case, checking the size of a would show it's not what you expected it to be. Why? Because of this:
a = zeros(0,1e3)
v= zeros(0,1e3)
dy = zeros(0,1e3)
Fd = zeros(0,1e3)
The arguments of zeros are the height and width of a matrix. You are asking for height 0... this means empty matrix, since it has no rows. What you want is a row vector, which is a matrix with one row.
After fixing this you'll run into a problem with
x = linspace(0,t,int(i))
plot(x,a,'ro-')
because x and a are not of the same size.
To keep sizes consistent, you could do something like this:
imax = 50;
a = zeros(1,imax)
v= zeros(1,imax)
dy = zeros(1,imax)
Fd = zeros(1,imax)
and later for i=1:imax and x = linspace(0,t,imax).
This way you are not creating oversized arrays, but only arrays of the size you want, which can be adjusted by changing the value of imax.

Resources