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

Current State of Live Plots in Atom/Juno?

$
0
0

@ckneale wrote:

What is the current status of live plotting/updating plots in Juno/Atom?

My ultimate hope is to have low latency 3-D scatter plots. So far I’ve tried every example I can involving tricks with GR, using gui(), etc. Then I tried Makie(can’t install correctly on my laptop due to HW so I’m stuck using CairoMakie backend). No luck, everything generates a new plot, or doesn’t display at all. The new plot for each animation step tanks my RAM insanely fast.

Would it be over-kill to send the data over ZMQ to a JAVA/JS plotting application or something? Is there something really easy I’m missing out on? I can offer a minimum working example, but honestly its just the following pseudo code:

a = scatter( data )
for i in 1:500
    update data
    update display
end 

Posts: 7

Participants: 3

Read full topic


Correct way of passing paths in the REPL for a project containing sub folders

$
0
0

@aortizb wrote:

Hi all, I’ve been using Atom for a while and now I am trying to run my codes directly from the REPL without using Atom, that is, I write the *.jl files using an external text editor and then invoke julia.exe to run the code. My project contains sub folders where *.jl files reside. When I run this code from the REPL I get some errors because (I think) Julia can’t find the sub folders in the julia path. I’ve prepared a small sample project to show the problem I am facing. I describe it next.

There is a folder named “julia_test” in the root directory (C:) that contains sub folders and files:
folders

The *jl files are the following:

main.jl

include("../setpaths.jl")
setpaths()

using VectorOperations: dotproduct

v1 = [1.0,2.0,3.0]
v2 = [2.0,2.0,2.0]

p = dotproduct(v1,v2)

println("v1 * v2 = $p")

setpaths.jl

function setpaths()
  rootdir = pwd()
  testdir = joinpath(rootdir,"test")
  sourcedir = joinpath(rootdir,"src")
  sourcedir1 = joinpath(rootdir,"src/VectorOperations")
  push!(LOAD_PATH, rootdir, testdir, sourcedir, sourcedir1)
end

VectorOperations.jl

module VectorOperations

using LinearAlgebra: dot

# VectorOperations functions
include("VectorOperationsFunctions.jl")
export dotproduct

end

VectorOperationsFunctions.jl

function dotproduct(v1,v2)
  return dot(v1,v2)
end

The file I run is “main.jl”. To this end, I make sure julia.exe is started inside folder “test”:

Then, in the REPL I execute the following:

include("main.jl")

However, I get the following error:

julia> include("main.jl")
ERROR: LoadError: ArgumentError: Package VectorOperations not found in current path:
- Run `import Pkg; Pkg.add("VectorOperations")` to install the VectorOperations package.

Stacktrace:
 [1] require(::Module, ::Symbol) at .\loading.jl:823
 [2] include at .\boot.jl:326 [inlined]
 [3] include_relative(::Module, ::String) at .\loading.jl:1038
 [4] include(::Module, ::String) at .\sysimg.jl:29
 [5] include(::String) at .\client.jl:403
 [6] top-level scope at none:0
in expression starting at C:\julia_test\test\main.jl:4

This means that Julia can’t find the definition of VectorOperations module that I defined. The folder where this module resides is “source/VectorOperations” and is specified inside function “setpaths”. I suppose Julia can’t find this sub folder. By the way, this code runs without any problems in Atom. Am I missing something?

Posts: 1

Participants: 1

Read full topic

VSCode can't find pkgs

$
0
0

@fracasss wrote:

When I typed the code below in VSCode on MacOS10.14.5, it seems that VSCode can’t find the standard library of Julia. But I can use the pkgs in the REPL, and I can also run the file successfully.

How can I fix this problem? I have already set the Executable Path in VSCode to be “/Applications/Julia-1.2.app/Contents/Resources/julia/bin/Julia”.
Thanks for your help.

Posts: 2

Participants: 2

Read full topic

The Atom in juliapro is crashed while opening package manager

Scheduler Function in Agents.jl

$
0
0

@ennvvy wrote:

I am trying to use the package Agents.jl for modelling. I see that there are three scheduler functions to activate agents at each step. However, I would like to pick agents according to their weights, i.e.,if I could select activation_prob number of agents with higher weights. How can I do this?

Posts: 1

Participants: 1

Read full topic

Get task id of `@asyncmap`

$
0
0

@innerlee wrote:

How to get the task id in a asyncmap, similar to myid() in pmap?

Something like

asyncmap(_->myasyncid(), 1:10)

I want to use the id to balance workload on GPUs.

Posts: 3

Participants: 2

Read full topic

How to create a text report saved using Julia Language statistics

$
0
0

@gedmundos wrote:

I created a procedure using gsadf test in Julia Language. The final procedure generates two graphs and a mini-report. My difficulty has been how to generate a text report saved in the final of procedure.
Sincerely yours, Geraldo

Posts: 3

Participants: 3

Read full topic

How to delete zeros from matrix?


Initializing struct members after struct has been constructed

$
0
0

@Jonas_Hjulstad wrote:

I’m trying to add members to my struct, but get:
BoundsError: attempt to access 0-element Array{Node,1} at index [1]

mutable struct Node
    i::Int
    j::Int
    floor::Bool
    neighbors::Array{Node}
    color::Union{String,Nothing}
    distance::Union{Int,Nothing}
    predecessor::Union{Node,Nothing}
end
Node(i, j, floor=true) = Node(i, j, floor, [], nothing, nothing, nothing)

A matrix called nodearray is full of initialized nodes, which currently has member neighbors initialized to ‘nothing’

nodearray[i,j].neighbors[n] = Node(i-1,j)

I am not able to add nodes as neighbors. Why?

Posts: 4

Participants: 2

Read full topic

Optimal way of checking neighboring elements in matrix

$
0
0

@Jonas_Hjulstad wrote:

With any two-dimensional matrix, is there an optimal way of checking wether a neighboring element exists (and if it can be accessed)?

Example:

mat = [1 0 0 0 1
            0 1 1 1 0
            0 1 0 0 0
            0 1 0 0 0
            1 0 0 0 0]

for all mat[i,j] I want to check elements to the right/left/top/bottom, but only if that index exists. Is there a more efficient way than using if-statements for start/end columns and rows?

Posts: 4

Participants: 3

Read full topic

Juno - information of current working module

$
0
0

@PaulJaval wrote:

Hi everyone,
I’m working with Juno 0.3.0, and my question is on knowing which module we are currently working in.

Starting up the REPL in Juno sets me in the “Main” module, and my current version of Julia (1.2)

Now when I generate a new package called Example, here is what happens:

  1. before activating the Example environment, I am still in the Main one, which is as expected.

  1. after activating the Example environment

In all of these screenshots, my cursor was at the end of line 3 of example.jl
This has some importance as when I set my cursor in the REPL, Juno says I am always working the Main module, independently of the activated environment:

What I was expecting after activating the Example environment: see “Example” written at the bottom right corner of Juno, and not Main/Example. About Juno always showing that we are in the Main environment when my cursor in the REPL, I am also unsure about why this is the case.

This might have to do with the following question: can we leave the “Main” module?

Also, I might use “environment” and “module” words inappropriately!

Thanks for any help!

Posts: 3

Participants: 2

Read full topic

Methods seem to match but don't

$
0
0

@alacritas wrote:

I’m trying to call a function I’ve defined with only on method but will not call although I’m pretty sure all of my types are matching up

a=[1,2,3]
b=[3,2,1]
function foo(a::Array{Float64,1}, b::Array{Float64,1}, c)
   #definition
end
foo(a,b,0.1)

The first two arguments match but not the last one.

Posts: 3

Participants: 3

Read full topic

Attempting to make my module code Threadsafe

$
0
0

@StevenSiew wrote:

I wrote my module PDFPs.jl to implement Precision Decimal Floating Point object. I was very very careful to make my code purely functional with pure functions. So I thought that my code is thread safe by default.

But alas, i reaised that it depends heavily on one “Global Variable” called DEFAULT_PRECISION

module PDFPs

    # Use the Ref hack to speed up DEFAULT_PRECISION
    # to get the value use DEFAULT_PRECISION[]
    # to set the value use DEFAULT_PRECISION[] = newvalue
    const DEFAULT_PRECISION = Ref(16)

    @inline function PDFP_getDefaultPrecision()
        DEFAULT_PRECISION[]
    end

    @inline function PDFP_setDefaultPrecision(prec::Int)
        global DEFAULT_PRECISION[] = prec < 0 ? 0 : prec
    end

end

It took me a while to realised that this is totally unsafe as when I have multiple threads running, each thread could be changing the DEFAULT_PRECISION and interferring with each other. What I need is a local copy of DEFAULT_PRECISION for each thread. So I came up with this.

module PDFPs

const DEFAULT_PRECISION = Ref(16)

# Thread id for the main thread is always 1, so put in the local copy
LocalCopy_DefaultPrecision = Dict{Int64,Int64}(1=>DEFAULT_PRECISION[])
Mutex_LocalCopy_DefaultPrecision = Base.Threads.SpinLock()

function PDFP_getDefaultPrecision()
    thread_id = Base.Threads.threadid()
    Base.Threads.lock(Mutex_LocalCopy_DefaultPrecision)
    if ! haskey(LocalCopy_DefaultPrecision,thread_id)
        LocalCopy_DefaultPrecision[thread_id] = DEFAULT_PRECISION[]
    end
    result = LocalCopy_DefaultPrecision[thread_id]
    Base.Threads.unlock(Mutex_LocalCopy_DefaultPrecision)
    return result
end

function PDFP_setDefaultPrecision(prec::Int)
    thread_id = Base.Threads.threadid()
    Base.Threads.lock(Mutex_LocalCopy_DefaultPrecision)
    LocalCopy_DefaultPrecision[thread_id] = prec < 0 ? 0 : prec
    Base.Threads.unlock(Mutex_LocalCopy_DefaultPrecision)
end

# Next we need to replace all DefaultPrecision[] with
# PDFP_getDefaultPrecision()
#
# And replace all DefaultPrecision[]=<number> with
# PDFP_setDefaultPrecision(<number>)

end

Would my new code make my module Thread safe for Julia 1.2 and 1.3?

Do you think it is possible to have a magical MACRO called @localtoeachthread so that I can simple do this instead?

module PDFPs

    # Use the Ref hack to speed up DEFAULT_PRECISION
    # to get the value use DEFAULT_PRECISION[]
    # to set the value use DEFAULT_PRECISION[] = newvalue
    @localtoeachthread  const DEFAULT_PRECISION = Ref(16)

    @inline function PDFP_getDefaultPrecision()
        DEFAULT_PRECISION[]
    end

    @inline function PDFP_setDefaultPrecision(prec::Int)
        global DEFAULT_PRECISION[] = prec < 0 ? 0 : prec
    end

end

Posts: 10

Participants: 4

Read full topic

Numerical Jacobian

Packages on JupyterNotebook Supercloud

$
0
0

@yejinyou wrote:

Hi.

I have some troubles installing packages on Jupyter Notebook supercloud.

Packages like Flux, Plots work with :

import Pkg; Pkg.add("Flux")

However, packages from git clones fail to clone.

Examples are DiffEqFlux, OrdinaryDiffEq, DifferentialEquations.

Sample output error is as follows


Resolving package versions...
   Cloning [0c46a032-eb83-5123-abaf-570d42b7fbaa] DifferentialEquations from https://github.com/JuliaDiffEq/DifferentialEquations.jl.git
failed to clone from https://github.com/JuliaDiffEq/DifferentialEquations.jl.git, error: GitError(Code:ERROR, Class:Net, curl error: 
)

Stacktrace:
 [1] pkgerror(::String) at /buildworker/worker/package_linux64/build/usr/share/julia/stdlib/v1.1/Pkg/src/Types.jl:120
 [2] #clone#3(::String, ::Base.Iterators.Pairs{Symbol,Any,Tuple{Symbol,Symbol},NamedTuple{(:isbare, :credentials),Tuple{Bool,LibGit2.CachedCredentials}}}, ::Function, ::String, ::String) at /buildworker/worker/package_linux64/build/usr/share/julia/stdlib/v1.1/Pkg/src/GitTools.jl:111
 [3] (::getfield(Pkg.Operations, Symbol("##18#20")){Base.UUID,String,Base.SHA1,Array{String,1}})(::LibGit2.CachedCredentials) at ./none:0
 [4] shred!(::getfield(Pkg.Operations, Symbol("##18#20")){Base.UUID,String,Base.SHA1,Array{String,1}}, ::LibGit2.CachedCredentials) at ./secretbuffer.jl:184

I tried Pkg.update() but it doesn’t seem to fix the problem as it gives me the following error.

 Cloning git-repo `https://github.com/Accla/D4M.jl`
failed to clone from https://github.com/Accla/D4M.jl, error: GitError(Code:ERROR, Class:Net, curl error: 
)

Stacktrace:
 [1] pkgerror(::String) at /buildworker/worker/package_linux64/build/usr/share/julia/stdlib/v1.1/Pkg/src/Types.jl:120

Any help will be greatly appreciated! Thanks.

Posts: 1

Participants: 1

Read full topic


@nbinclude in the REPL

$
0
0

@PhilipDLoewen wrote:

Maybe this is a bug report. Please advise.

I have a small notebook that runs perfectly when I open it in Jupyter, but not at the REPL.

Working at a freshly-started Julia 1.2.0 REPL, when I say

using NBInclude
@nbinclude("CALO-MWE.ipynb")

I expect the minimalist workbook attached here to run successfully and print the computed result, but instead I get the error message below:

ERROR: LoadError: UndefVarError: slacksum not defined
Stacktrace:
 [1] top-level scope at /home/loew/loewCloud/CALO/2019-10/CALO-MWE.ipynb:In[2]:4
 [2] include_string(::Module, ::String, ::String) at ./loading.jl:1064
 [3] my_include_string(::Module, ::String, ::String, ::Nothing, ::Bool) at /home/loew/.julia/packages/NBInclude/m4rfj/src/NBInclude.jl:29
 [4] #nbinclude#1(::Bool, ::UnitRange{Int64}, ::Regex, ::typeof(identity), ::Bool, ::typeof(nbinclude), ::Module, ::String) at /home/loew/.julia/packages/NBInclude/m4rfj/src/NBInclude.jl:82
 [5] nbinclude(::Module, ::String) at /home/loew/.julia/packages/NBInclude/m4rfj/src/NBInclude.jl:53
 [6] top-level scope at REPL[14]:1
in expression starting at /home/loew/loewCloud/CALO/2019-10/CALO-MWE.ipynb:In[2]:3 

I have Julia 1.2.0, with IJulia v1.20.0 and NBInclude v2.1.0.

What do you suggest?

Sorry, new here, don’t know how to attach the file named CALO-MWE.ipynb, so I’ll just paste it here:

{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "slacks = [1,2];"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Total slack: 3.\n"
     ]
    }
   ],
   "source": [
    "slacksum = 0;\n",
    "\n",
    "for sl in slacks\n",
    "        slacksum += sl\n",
    "end\n",
    "println(\"\\nTotal slack: $(slacksum).\")"
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Julia 1.2.0",
   "language": "julia",
   "name": "julia-1.2"
  },
  "language_info": {
   "file_extension": ".jl",
   "mimetype": "application/julia",
   "name": "julia",
   "version": "1.2.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}

Posts: 1

Participants: 1

Read full topic

What's a good way to get some value (doesn't matter what the value is) of a type `T` `where T`

$
0
0

@xiaodai wrote:

I am writing some program that requires a value from a type T but it doesn’t matter what this type is.

Is there a generic way to get some value of type T for whatever T? Happy to accept T for isbits.

Posts: 12

Participants: 7

Read full topic

Best way to dispatch on whether a value is `isbits`?

$
0
0

@xiaodai wrote:

There are infinitely many types for which isbits is true. But I want to make my function dispatch on whether the eltype is isbits. What’s the best way to do that?

I think of 4 approaches to do that

1.Use if

Don’t use dispatch at all; just use if-statements
Easy to understand but doesn’t use “dispatch”

2. Use Val{true|false}

fn(v) = fn(Val(isbits(eltype(v)), v) 
fn(Val{True}, v) = # do something
fn(Val{False}, v) = # do something else

3. Make a new type IsBitsType

with two subtypes which are IsBitsTrueType and IsBitsFalseType and make a series of function like in 2. to dispatch

4. Make a new type IsBitsType2 with 2 values

The two possible values are isbitstrue and isbitsfalse and the type is defined like so

struct IsBitsType2
  val::Bool

and dispatch using similar mechanism as in 2.

It feels like 2 is what I would do, but keen to hear opinions on this. It sounds like 3 is very Julia specific way but I always get confused, e.g when I use the Algorithm type when sorting, so I think I should avoid creating sub-types just for dispatch.

Posts: 2

Participants: 2

Read full topic

Best way to write nested try/catch blocks

$
0
0

@xiaodai wrote:

I have a piece of code that tries a few things in a nested try/catch block which can look ugly. Is there a better way to write this? Using Macros perhaps? I can imagine wrting a macro with this syntax instead

`@nested_trycatch zero(T) T(0) rand(T) Vector{T}(undef, 1)[1] throw(“the type $T is not supported”)

some_elm(::Type{T}) where T = begin
    try
        return zero(T)
    catch
        try
            return T(0)
        catch
            try
                rand(T)
            catch
                try
                    Vector{T}(undef, 1)[1]
                catch
                    throw("the type $T is not supported")
                end
            end
        end
    end
end

Posts: 2

Participants: 2

Read full topic

Agents Based Modeling (using Agents.jl)

$
0
0

@ennvvy wrote:

I am trying to use Agents.jl package to model my system. I use the following code

using Agents
using LightGraphs
using Distributions

mutable struct MyAgent{T<:Integer,Y<:AbstractFloat} <: AbstractAgent
    id::T ;
    pos::Y ; 
    W::Y ; 
end

mutable struct MyNet{T<:Integer,Y<:AbstractArray} <: AbstractSpace
    dimensions::T ; 
    space::SimpleDiGraph{Int64} ; 
    agent_positions::Y ;
end

mutable struct MyModel{T<:AbstractArray,Y<:AbstractFloat,Z<:AbstractSpace} <: AbstractModel
    space::Z ; 
    agents::T ;
    scheduler::Function ; 
    activation_prob::Y ; 
    interaction_prob::Y ; 
end
function instantiate_model(;num_agents,mean,sd,out_deg,prob_rew,prob_up,prob_int)
    agents = [MyAgent(i,rand(Normal(mean,sd))*pi/180,rand(Uniform(0.5,0.9))) for i in 1:num_agents] ;
    ntwk = MyNet(num_agents,watts_strogatz(num_agents,out_deg,prob_rew,is_directed=true),collect(1:num_agents)) ;
    model = MyModel(ntwk,agents,partial_activation,prob_up,prob_int) ;
    return model
end

function agent_step!(agent::AbstractAgent,model::AbstractModel)
agent.pos = agent.pos + agent[rand].pos ;
end

I want to make sure that the quantities used on the RHS agent[rand].pos are all from [t-1] time step. On using the step!(agent_step!,model) function, this is not possible as everything inside agent_step! gets executed, updated and no exceptions can be made. How can I have a copy of values of agent.pos from [t-1] ?

Posts: 1

Participants: 1

Read full topic

Viewing all 2795 articles
Browse latest View live