Quantcast
Channel: First steps - JuliaLang
Viewing all 2795 articles
Browse latest View live

Output of functions

$
0
0

@angeloaliano1 wrote:

Dear users,
I have the following function:

function Test(u,v,w)
    x = sum(v)
    y = prod(v)
    z = u .+ v 
    return (x,y,z)
end

But,if I want only the first, or only the second or only third output, how can I do it?
For example, I my mind, the command

x = Test([1,2],[2,3],[3,4])

must return only the value of x, but return

(5,6,[3,5])

Anyone could help me please?

Posts: 6

Participants: 4

Read full topic


CSV.read: why do String columns show up as PooledArrays?

$
0
0

@Sam_Johnson wrote:

I’m opening a simple .CSV file with CSV.read with no parameter modifiers. The returned DataFrame is fine and describe(df) gives me the correct element types, which are all Int64 or Strings.

When I try to onehot-encode the String attributes the function fails because the String attributes are not Strings inside the function. When I examine the attribute with typeof(df.prev_campaign_outcome) I get:

PooledArrays.PooledArray{String,UInt32,1,Array{UInt32,1}}

How has Julia made this decision? Why does describe() return the eltype as String but internally has converted the attribute to PooledArray? How can I force Julia to leave well enough alone?

Why does it seem Julia is trying too hard?

Posts: 7

Participants: 4

Read full topic

Info: registering a new package - where can i find the UUID?

$
0
0

@fipelle wrote:

Hi,

I am trying to register a (small) package I wrote for time series analysis. I am using it as a backend for more sophisticated algorithms that I plan to release on GitHub in the next couple of months.

I am in the process of creating the Project.toml file. However, I am not sure where can I find the correct UUID. Would you please explain to me where can I find it?

Thank you.

Posts: 2

Participants: 2

Read full topic

Trying to bend my mind to Julia's way

$
0
0

@LStoleriu wrote:

Hi everyone,

I’m a C&Maple physicist trying to learn the “true” Julia way of solving problems.
As a small project I’m trying to solve a nonlinear equation doing something like that:

using NLsolve

Nsteps = 101

Hk = 1.0
FieldMax = 3.0 * Hk
FieldMin = -FieldMax
H = FieldMax

theta_H = 45.0 * π / 180.0
theta_0 = 15.0 * π / 180.0

function f!(F, x)
    F[1] = Hk * cos(x[1]) * sin(x[1]) + H * sin(x[1] - theta_H)
end

function j!(J, x)
    J[1, 1] = Hk * (cos(x[1])^2 - sin(x[1])^2) + H * cos(x[1] - theta_H)
end

theta = nlsolve(f!, j!, [ 0.5 ])
println(theta.zero)
println(converged(theta))

This works great, but now I’d like to solve the same equation for Nsteps different values of H and store the results in an array called M.
I was able to do that using a C-like approach, by continuing the program like that:

M = zeros(Nsteps)
H_range = collect(range(FieldMax, length=Nsteps, stop=FieldMin))

function SWsolve(H_range, M)
    i = 0
    for H_loco in H_range
        global H = H_loco
        theta = nlsolve(f!, j!, [ 0.5 ])
        i = i+1
        M[i] = cos(theta_H - theta.zero[1])
    end
end

SWsolve(H_range, M)
hyst = plot(H_range, M)
display(hyst)

I tried a lot to simplify this using Julia-like constructions but I failed (for example, I tried to remove the for loop from the SWsolve() function while using the dot(".") operator to pass the H_range elements) but I failed.

Can you suggest a more efficient way of doing this?

Posts: 3

Participants: 3

Read full topic

Are anonymous functions efficient in allocation terms?

$
0
0

@rna1990 wrote:

Simple question:
As a little step in a function I’m working on, I need to filter a unit range, say 1:5, just by taking one of its elements away, say 2. I understand that filter() is the way to go, combined with an anonymous function this way:

@time filter(x -> x .!=2, 1:5)

I’ve tried that several times with the time macro and each time it makes 88.81 K allocations, which is simply a lot, I would say. I also tried a similar filtration not using an anonymous function:

@time filter(isodd,1:5)

Just 14 allocations! I know I just tried 2 different cases, but I’m tempted to think that anonymous functions are very inefficient? I’m working on an MCMC algorithm, so if I’m repeating this step thousands of times, it’ll take days or my laptop is just going to crash.

Any suggestions on how to make this simple filtering efficiently are highly appreciated.

Cheers.

R.

Posts: 5

Participants: 3

Read full topic

Why does in-place array assignment behave differently here?

$
0
0

@groovyda wrote:

Hi - I’m new to Julia, been playing around a bit. I’ve been struggling to understand the below. I have some code where I need to switch some values in an array. I get (surprisingly) different results if I use

w[3], w[2] = w[2], w[3]

vs. 
w_copy = copy(w)
w_copy[3], w_copy[2] = w_copy[2], w_copy[3]  # or w_copy[3], w_copy[2] = w[2], w[3]

Note this is being run in a large for loop, where w3 is being inititalised along with other similar arrays.

This seems to give the correct results:

for m1 in all_prefs, m2 in all_prefs, m3 in all_prefs, w1 in all_prefs, w2 in all_prefs, w3 in all_prefs
    w1_p1 = f([m1,m2,m3], [w1,w2,w3])[1] 
    w2_copy = copy(w2)
    w2_copy[2], w2_copy[3] = w2_copy[3], w2_copy[2]
    w1_p2 = f([m1,m2,m3], [w1,w2_copy,w3])[1] 

But the below gives different results, which doesn’t seem correct:

for m1 in all_prefs, m2 in all_prefs, m3 in all_prefs, w1 in all_prefs, w2 in all_prefs, w3 in all_prefs
    w1_p1 = f([m1,m2,m3], [w1,w2,w3])[1] 
    w2[2], w2[3] = w2[3], w2[2]
    w1_p2 = f([m1,m2,m3], [w1,w2,w3])[1] 

Why should this be? Please help

Posts: 17

Participants: 5

Read full topic

How to export Julia data to a .CSV

$
0
0

@RaquelSantos wrote:

I created an empty DataFrame and would like to export the data I got with the model solution I compiled for the DataFrame.

I am doing so, and still showing error.

df = CSV.read("//arquivo.csv")

for i ∈ 1:3
    df = JuMP.value.(N[1])
end

This is the error message that is appearing
-> Filling the remaining columns with `missing ’

Posts: 7

Participants: 3

Read full topic

Julia doesn't recognise any installed packages

$
0
0

@Calum_H wrote:

Hi all,

Quite new to Julia packages so apologies if this is obvious. I’ve been creating and using two packages which are in my dev path. This has been working for a few weeks no problem.

Today, I inserted package1 as a dependency to the project.toml of my second package (DispersionAnalysis) and it appears to have broken everything. Now when running any ‘using’ statement in a testfile.jl I get errors. This is true for my dev packages but also normal installed packages e.g. Plots, Dates, SPICE, etc.

I tried reverting the packages back to no avail. I run my testfile.jl which looks like this:

using Revise
using DispersionAnalysis
... #some code to do dispersion analysis

And the output is:

ERROR: LoadError: ArgumentError: Package Revise [295af30f-e4ad-537b-8983-00126c2a3abe] is required but does not seem to be installed:
 - Run `Pkg.instantiate()` to install all recorded dependencies.

Stacktrace:
 [1] _require(::Base.PkgId) at .\loading.jl:929
 [2] require(::Base.PkgId) at .\loading.jl:858
 [3] require(::Module, ::Symbol) at .\loading.jl:853
 [4] include_string(::Module, ::String, ::String) at .\loading.jl:1008
 [5] (::getfield(Main._vscodeserver, Symbol("##9#12")){String,Int64,Int64,String})() at c:\Users\calum\.vscode\extensions\julialang.language-julia-0.12.3\scripts\terminalserver\terminalserver.jl:153
 [6] withpath(::getfield(Main._vscodeserver, Symbol("##9#12")){String,Int64,Int64,String}, ::String) at c:\Users\calum\.vscode\extensions\julialang.language-julia-0.12.3\scripts\terminalserver\repl.jl:62
 [7] (::getfield(Main._vscodeserver, Symbol("##8#11")){String,Int64,Int64,String})() at c:\Users\calum\.vscode\extensions\julialang.language-julia-0.12.3\scripts\terminalserver\terminalserver.jl:152
 [8] hideprompt(::getfield(Main._vscodeserver, Symbol("##8#11")){String,Int64,Int64,String}) at c:\Users\calum\.vscode\extensions\julialang.language-julia-0.12.3\scripts\terminalserver\repl.jl:28
 [9] macro expansion at c:\Users\calum\.vscode\extensions\julialang.language-julia-0.12.3\scripts\terminalserver\terminalserver.jl:148 [inlined]
 [10] (::getfield(Main._vscodeserver, Symbol("##7#10")))() at .\task.jl:259
in expression starting at c:\Users\calum\Documents\Git-MissionAnalysis\mission-1\Mission01\MoonMission_auto.jl:2

I ran Instantiate on Pkg DispersionAnalysis

(DispersionAnalysis) pkg> instantiate
  Updating registry at `C:\Users\calum\.julia\registries\General`
  Updating git-repo `https://github.com/JuliaRegistries/General.git`
 Installed DelayDiffEq ─────────── v5.14.0
 Installed DifferentialEquations ─ v6.6.0
 Installed OrdinaryDiffEq ──────── v5.15.1
 Installed FFMPEG ──────────────── v0.2.2
 Installed DiffEqBase ──────────── v5.20.1
 Installed MbedTLS ─────────────── v0.7.0
 Installed SparseDiffTools ─────── v0.9.0
 Installed StochasticDiffEq ────── v6.9.1
  Building MbedTLS → `C:\Users\calum\.julia\packages\MbedTLS\a1JFn\deps\build.log`
  Building FFMPEG ─→ `C:\Users\calum\.julia\packages\FFMPEG\9JQpZ\deps\build.log`

Other useful things to know:
Julia v.1.1.
I’ve closed my julia REPL in case it was leftover from another open session,
I’ve re-built and updated all packages.
I’ve also manually checked that the desired packages are installed.

Any ideas how to solve this?

Second, as a more general question, is it ok practise to add one dev package as a dependency of another? I assumed it was fine as they are both issued uuid’s by the package manager.

Thanks!

Posts: 12

Participants: 2

Read full topic


BoundsError: attempt to access "attempt to access a data frame with 6 columns at index 14"

$
0
0

@Irene_Marchand wrote:

Hello everyone,

I am a little confused and I need your help because I am not able to understand my error.
I wrote this two functions but for both of them I have the following error: BoundsError: attempt to access “attempt to access a data frame with 6 columns at index 14”.
My dataframe is a scv file

I would be really grateful if someone could help me to understand this error and what to do about it.
Thank you!

Posts: 2

Participants: 2

Read full topic

@printf thread safety in Julia 1.3?

$
0
0

@Zhong_Pan wrote:

I heard that in Julia 1.3 I/O will be thread safe. Is it so? In a multi-threaded for loop, if I’m using @printf to write to DIFFERENT files (one file per thread id), should I still use lock/unlock to guard the file writing commands?

I’m using 1.3.0-rc4.1, and I’m doing exactly that without using a lock/unlock, which led to problems. I took great care to make sure all variables that are changed in the loop have only local scope inside the loop. But I still found out that in the files produced, some rows are missing many numbers; some rows started from the middle of the array to be printed, etc.

To complicate the problem, I cannot reproduce the issue using a simpler piece of code. I think what I’m doing is essentially the same as below (I even added sleep to make the function call during each print take longer), but the code below does not show the same issue. All rows are printed out completely and in order. Since this example code does NOT reproduce the issue, I can only ask if this is a valid use of multi-threading, or a bad practice (from the perspective of thread safety and correctness, not efficiency, as this is just an example)?

4 threads were started with Julia and all of them are used in these examples.

using Printf
using Base.Threads

function todB(x)
	sleep(0.001)
	return 10*log10(x)
end

function main()
	println("Test 1: Write to different files, with no lock")
	println("Running on $(nthreads()) threads...")
	
	for n = 1:nthreads()
		fn = "temp$n.txt"
		if isfile(fn)
			rm(fn)
		end
	end

	@threads for n = 1:10
		fp = open("temp$(threadid()).txt", "a")
		for m = 1:1000
			@printf(fp, "%.2f,", todB(m))
		end
		@printf(fp, "\n")
		close(fp)
	end

	println("All done.")
end

@time main();

Now with a lock/unlock, even when I print to the same file in multiple threads, there is no issue at all whether in the other example below or in my actual application. However, I suspect performance is degraded due to lock regardless if one or multiple files are used, since when one thread is writing a file another thread cannot write, regardless if it’s the same file or different file it wants to write to.

using Printf
using Base.Threads

function todB(x)
	sleep(0.001)
	return 10*log10(x)
end

function main()
	println("Test 2: Write to the same file, with lock")
	println("Running on $(nthreads()) threads...")
	
	fp = open("temp0.txt", "w")

	rlock = ReentrantLock()
	@threads for n = 1:10
		lock(rlock)
		for m = 1:1000
			@printf(fp, "%.2f,", todB(m))
		end
		@printf(fp, "\n")
		unlock(rlock)
	end

	close(fp)

	println("All done.")
end

@time main();

Posts: 1

Participants: 1

Read full topic

Distributions getting started example does not work

$
0
0

@ramonz wrote:

Hello

After trying the “Getting started example” in https://JuliaStats.github.io/Distributions.jl/stable/ documentation I get an error which I wasn´t expecting.


> using Random, Distributions
> Random.seed!(123) # Setting the seed
> d = Normal()

UndefVarError: Normal not defined

Stacktrace:
 [1] top-level scope at In[29]:1

This is after I have installed and updated Distributions and Random.
The version of Julia I am using is 1.1.0

Hope someone can help
Thanks

Posts: 5

Participants: 3

Read full topic

Mutating a Set during iteration

$
0
0

@Vasily_Pisarev wrote:

Is it safe to iterate over a set and mutate it in process?
Say, I have a Set{Int64} and want to replace all negative values in it by their absolute values. Is it OK to

for x in set_of_ints
    if x < 0
        pop!(set_of_ints, x)
        push!(set_of_ints, -x)
    end
end

?

Posts: 3

Participants: 2

Read full topic

Statically built .exe program using PackageCompiler.jl has dependency on project toml file?

$
0
0

@Zhong_Pan wrote:

Back in March 2019 when I was still using Julia 1.0, I built an example script into an executable binary on Windows to showcase the usage of a library I made in a standalone command line EXE. I just followed the tutorial provided with PackageCompiler.jl

The script’s name is “usage_example_5.jl”. By trial and error I found only these files are needed to run the EXE version:

  • usage_example_5.exe
  • usage_example_5.dll
  • libjulia.dll
  • libstdc++-6.dll
  • LLVM.dll

Fast forward to today, I tried running it again for no particular reason, and got this error message:

$ usage_example_5.exe
fatal: error thrown and no exception handler available.
InitError(mod=:Revise, error=Base.SystemError(prefix="opening file C:\Users\zpan\.julia\environments\v1.0\Project.toml", errnum=2, extrainfo=nothing))
rec_backtrace at /home/Administrator/buildbot/worker/package_win64/build/src\stackwalk.c:94
record_backtrace at /home/Administrator/buildbot/worker/package_win64/build/src\task.c:246
jl_throw at /home/Administrator/buildbot/worker/package_win64/build/src\task.c:577
#systemerror#39 at .\error.jl:106
systemerror at .\error.jl:106 [inlined]
#open#293 at .\iostream.jl:283
open at .\iostream.jl:275 [inlined]
#open#294 at .\iostream.jl:367
jl_invoke at /home/Administrator/buildbot/worker/package_win64/build/src\gf.c:42
open at .\iostream.jl:367 [inlined]
project_file_manifest_path at .\loading.jl:369 [inlined]
manifest_file at C:\Users\zpan\.julia\packages\Revise\yp5KG\src\pkgs.jl:259 [inlined]
manifest_file at C:\Users\zpan\.julia\packages\Revise\yp5KG\src\pkgs.jl:266 [inlined]
__init__ at C:\Users\zpan\.julia\packages\Revise\yp5KG\src\Revise.jl:856
jl_apply_generic at /home/Administrator/buildbot/worker/package_win64/build/src\gf.c:2184
jl_apply at /home/Administrator/buildbot/worker/package_win64/build/src\julia.h:1537 [inlined]
jl_module_run_initializer at /home/Administrator/buildbot/worker/package_win64/build/src\toplevel.c:90
_julia_init at /home/Administrator/buildbot/worker/package_win64/build/src/home/Administrator/buildbot/worker/package_win64/build/src\init.c:813
julia_init__threading at /home/Administrator/buildbot/worker/package_win64/build/src\task.c:302
.text at C:\test\usage_example_5.exe (unknown line)
__tmainCRTStartup at /home/abuild/rpmbuild/BUILD/mingw-w64-crt\crt\crtexe.c:339
mainCRTStartup at /home/abuild/rpmbuild/BUILD/mingw-w64-crt\crt\crtexe.c:223
BaseThreadInitThunk at C:\Windows\System32\KERNEL32.DLL (unknown line)
RtlUserThreadStart at C:\Windows\SYSTEM32\ntdll.dll (unknown line)

The reason is the EXE cannot find a Project.toml file! Since I already uninstalled Julia 1.0 and moved on to newer versions, this file has been deleted.

In near future I need to deliver .exe to colleagues that can be run without dependencies except the ones I already provide in the same ZIP file. How do I make sure this kind of toml file dependency (or any other hidden dependencies) are either satisfied or removed?

Thanks!

Posts: 2

Participants: 2

Read full topic

Array{

Define a variable that depends on a previously defined variable in JuMP

$
0
0

@Jayzyu wrote:

Hello all,

I am trying to define a variable that is dependent on a previously defined variable. A close example is as follows:

N=10
nodes = 1:N
model=Model()
@variable(model,is_not_damaged_nodes[i in nodes], Bin)
@variable(model,ω[ i in nodes[is_not_damaged_nodes.==0] ],Bin)

The error message is:

**ERROR: MethodError: no method matching iterate(::JuMP.JuMPArray{Variable,1,Tuple{UnitRange{Int64}}})**
Closest candidates are:
  iterate(::Core.SimpleVector) at essentials.jl:589
  iterate(::Core.SimpleVector, ::Any) at essentials.jl:589
  iterate(::ExponentialBackOff) at error.jl:171
  ...
Stacktrace:
 [1] copyto!(::Array{Variable,1}, ::JuMP.JuMPArray{Variable,1,Tuple{UnitRange{Int64}}}) at .\abstractarray.jl:646
 [2] _collect(::UnitRange{Int64}, ::JuMP.JuMPArray{Variable,1,Tuple{UnitRange{Int64}}}, ::Base.HasEltype, ::Base.HasLength) at .\array.jl:563
 [3] collect(::JuMP.JuMPArray{Variable,1,Tuple{UnitRange{Int64}}}) at .\array.jl:557
 [4] broadcastable(::JuMP.JuMPArray{Variable,1,Tuple{UnitRange{Int64}}}) at .\broadcast.jl:617
 [5] broadcasted(::Function, ::JuMP.JuMPArray{Variable,1,Tuple{UnitRange{Int64}}}, ::Int64) at .\broadcast.jl:1171
 [6] top-level scope at C:\Users\yuj5\.juliapro\JuliaPro_v1.0.5-1\packages\JuMP\I7whV\src\macros.jl:231

Could you give some suggestions to fix the bug? Thanks a lot!

JZ

Posts: 3

Participants: 2

Read full topic


JULIA_NUM_THREADS and physical cores

$
0
0

@Arno wrote:

In the documentation about JULIA_NUM_THREADS it states:
“If $JULIA_NUM_THREADS exceeds the number of available physical CPU cores, then the number of threads is set to the number of cores.”

What exactly is a physical core?
My PC:

Architecture:        x86_64
CPU op-mode(s):      32-bit, 64-bit
Byte Order:          Little Endian
Address sizes:       39 bits physical, 48 bits virtual
CPU(s):              8
On-line CPU(s) list: 0-7
Thread(s) per core:  2
Core(s) per socket:  4
Socket(s):           1
NUMA node(s):        1
Vendor ID:           GenuineIntel
CPU family:          6
Model:               94
Model name:          Intel(R) Core(TM) i7-6700K CPU @ 4.00GHz
Stepping:            3
CPU MHz:             800.059
CPU max MHz:         4300,0000
CPU min MHz:         800,0000
BogoMIPS:            8016.00
Virtualization:      VT-x
L1d cache:           32K
L1i cache:           32K
L2 cache:            256K
L3 cache:            8192K
NUMA node0 CPU(s):   0-7
Flags:               fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault invpcid_single pti ssbd ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm mpx rdseed adx smap clflushopt intel_pt xsaveopt xsavec xgetbv1 xsaves dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp md_clear flush_l1d

I interpret “Core per socket: 4” and “Thread(s) per core: 2” to mean that I only have 4 physical cores and 8 logical cores?
Yet by putting JULIA_NUM_THREADS=99, I get Threads.nthreads() = 8 and not 4?

Posts: 5

Participants: 5

Read full topic

Julia Packages Peacefully Coexisting in Multi-language Github Projects

$
0
0

@zot wrote:

I have a project that should include packages for several different languages (back end code), along with some common artifacts (front end things HTML, JS, and CSS).

Is there a way to handle this in Julia? Ideally I’d like a directory structure like this:

Git-repository
    |
    |-- html/ (artifacts used by packages in various languages)
    |-- julia/ (julia code in here, along with Project.toml, Manifest.toml, and Artifacts.toml)
    +-- (directories for other languages)

I don’t see way to put a git-tree reference to html/ in the current package (wherever it happens to be hosted) into Artifacts.toml . Do you have to hard-code the repository URL to do this?

It seems like this even if there was a way to refer to a git-tree in the current package, we still have to wait for PackageSpec to allow subdirectories and for Registrator.jl to handle subdirectories.

Posts: 1

Participants: 1

Read full topic

PlotlyJS/Orca not installed properly

PlotlyJS/Orca.jl not installing properly

$
0
0

@Calum_H wrote:

Hi all,

Had some bizarre issues with Julia lately so decided to start from scratch and freshly re-install Julia v1.2 and all packages. Mostly things are working again now but for some reason it seems the installation of PlotlyJS or Orca failed and I can’t figure out why.

When I select plotlyjs() back end, e.g.:

using Plots
...

plotlyjs()

I get this error:

[ Info: Recompiling stale cache file C:\Users\calum\.julia\compiled\v1.2\PlotlyJS\1r9Ld.ji for PlotlyJS [f0f68f2c-4968-5e81-91da-67840de0976a]
WARNING: using HTTP.stack in module Mux conflicts with an existing identifier.
WARNING: Method definition savehtml(IO, PlotlyBase.Plot{TT} where TT<:PlotlyBase.AbstractTrace) in module PlotlyBase at C:\Users\calum\.julia\packages\PlotlyBase\80KwD\src\output.jl:40 overwritten in module PlotlyJS at C:\Users\calum\.julia\packages\PlotlyJS\b9Efu\src\display.jl:334.
  ** incremental compilation may be fatally broken for this module **

WARNING: Method definition savehtml(PlotlyBase.Plot{TT} where TT<:PlotlyBase.AbstractTrace, AbstractString) in module PlotlyBase at C:\Users\calum\.julia\packages\PlotlyBase\80KwD\src\output.jl:52 overwritten in module PlotlyJS at C:\Users\calum\.julia\packages\PlotlyJS\b9Efu\src\display.jl:361.
  ** incremental compilation may be fatally broken for this module **

[ Info: Recompiling stale cache file C:\Users\calum\.julia\compiled\v1.2\ORCA\jvX7k.ji for ORCA [47be7bcc-f1a6-5447-8b36-7eeeff7534fd]
ERROR: LoadError: InitError: IOError: could not spawn `C:Userscalum.juliaconda3envs_ORCA_jl_orca_apporca.exe server --port=7982 --graph-only`: no such file or directory (ENOENT)
Stacktrace:
 [1] _spawn_primitive(::String, ::Cmd, ::Array{Any,1}) at .\process.jl:401
 [2] setup_stdios(::getfield(Base, Symbol("##526#527")){Cmd}, ::Array{Any,1}) at .\process.jl:414
 [3] _spawn at .\process.jl:413 [inlined]
 [4] #open#535(::Bool, ::Bool, ::typeof(open), ::Cmd, ::Base.DevNull) at .\process.jl:658
 [5] open at .\process.jl:649 [inlined] (repeats 2 times)
 [6] restart_server() at C:\Users\calum\.julia\packages\ORCA\xULYl\src\ORCA.jl:84
 [7] __init__() at C:\Users\calum\.julia\packages\ORCA\xULYl\src\ORCA.jl:94
 [8] _include_from_serialized(::String, ::Array{Any,1}) at .\loading.jl:685
 [9] _require_from_serialized(::String) at .\loading.jl:736
 [10] _require(::Base.PkgId) at .\loading.jl:1023
 [11] require(::Base.PkgId) at .\loading.jl:911
 [12] require(::Module, ::Symbol) at .\loading.jl:906
 [13] top-level scope at C:\Users\calum\.julia\packages\Plots\Iuc9S\src\backends.jl:465
during initialization of module ORCA
in expression starting at c:\Users\calum\testfile.jl:20

Really not sure how to solve this issue. Any ideas?
Thanks!

Posts: 1

Participants: 1

Read full topic

How to make this piece of code faster?

$
0
0

@ennvvy wrote:

I have a piece of code involving a large matrix. I have been trying to optimise it. I have exhausted all my options, I would like to know of suggestions that experts on this forum might have.

using Distributions
using StatsBase
using LightGraphs
using LinearAlgebra

mutable struct Par
    g::SimpleDiGraph{Int64} ;
    μ::Int64 ; 
    n::Int64 ; 
    P::Int64 ; 
    ctime::Int64 ; 
    cstub::Float64 ; 
    crate::Int64 ; 
    cvalue::Float64 ; 
    expcval::Float64 ; 
    temp::Bool ;
end

mutable struct Arr
    θ::Array{Float64,1} ;
    C::Array{Float64,1} ; 
    wts::Array{Float64,1} ; 
    upagents::Array{Int64,1} ; 
    edg::Array{Int64,1} ; 
    cedg::Array{Int64,1} ; 
    temp::Array{Float64,1} ;
end

mutable struct Mat
    θₜ::Array{Float64,2} ; 
end

function main(Cmin::Float64,Cmax::Float64,N::Int64,outdeg::Int64,Pᵣ::Float64,σ::Int64,Pᵢ::Float64)
    p = Par(SimpleDiGraph(Int64),90,5000,Int64(N/2),0,0.0,0,0.0,0.0,false) ;
    a = Arr(Float64[],Float64[],Float64[],Int64[],Int64[],Int64[],Float64[]) ;
    m = Mat(Matrix{Float64}(undef,N,p.n)) ;
    p.g = watts_strogatz(N,outdeg,Pᵣ,is_directed=true) ;
    a.θ = rand(Normal(p.μ,σ),N)*pi/180 ;
    a.C = rand(Uniform(Cmin,Cmax),N) ;
    a.wts = 1.0 .- a.C ;
    a.wts = a.wts/sum(a.wts) ;
    for t = 1:1:p.n
        m.θₜ[:,t] = a.θ ;
        a.upagents = sample([1:1:N;],Weights(a.wts),p.P,replace=false) ;
        for i ∈ a.upagents
            a.edg = inneighbors(p.g,i) ;
            a.cedg = setdiff([1:1:N;],a.edg) ;
            a.cedg = setdiff(vcat(a.edg,a.cedg[rand(length(a.cedg)).<Pᵢ]),i) ;
            a.temp = exp.(-abs.(m.θₜ[i,t] .-m.θₜ[a.cedg,t])/(1.0-a.C[i])) ;
            a.temp = vcat(a.C[i],(a.temp*(1-a.C[i]))/sum(a.temp)) ;
            a.cedg = vcat(i,a.cedg) ;
            a.θ[i] = atan(sum(a.temp.*sin.(m.θₜ[a.cedg,t])),sum(a.temp.*cos.(m.θₜ[a.cedg,t]))) ;
        end
        a.temp = round.(a.θ,digits=2) ;
        p.temp = all(y->y.==a.temp[1],a.temp) ;
        if(p.temp==true)
            p.ctime = t ;
            p.crate = 1 ;
            p.cvalue = a.θ[1] ;
            p.expcval = round(sum(a.C.*m.θₜ[:,1])/sum(a.C),digits=2) ;
            p.cstub = mean(a.C) ;
            break
        end
    end
    return p.ctime,p.crate,p.cvalue,p.expcval,p.cstub
end

For Cmin=0.5;Cmax=0.9;N=1000;outdeg=250;Pᵣ=0.0;σ=10;Pᵢ=0.5;, I get

@time main(Cmin,Cmax,N,outdeg,Pᵣ,σ,Pᵢ) 
32.085691 seconds (20.75 M allocations: 25.131 GiB, 15.87% gc time)
(316, 1, 1.5760757023650616, 1.57, 0.6931634326318095)

Posts: 6

Participants: 4

Read full topic

Viewing all 2795 articles
Browse latest View live