Basic OOP questions in Julia

Viewed 56

I'm new to OOP. I'm reading documentation on how to code multiple simulations in julia here. I have a couple questions in the first section of reading ("Building a Problem"):

  1. The document opens with an example constructor: EnsembleProblem. I think this creates an ODE simulation with different parameters for each constructor call. Is this right?

  2. The constructor contains the following lines of code: prob::DEProblem and output_func = (sol,i) -> (sol,false). How does one read this? I think: problem is some class in DEProblem with a function output_func. I'm unclear on what are on the left and right sides of the arrow though.

  3. A function is defined:

function prob_func(prob,i,repeat)
  @. prob.u0 = randn()*prob.u0
  prob
end

I think this is just changing the initial conditions -- but I'm unclear what's happening in each line of the function.

  1. It mentions that "problem types are immutable, it uses .=" -- I didn't understand this comment.
1 Answers
  1. This is a consructor for Julia data structure struct. For an example:
julia> struct MyStruct
       a::Int
       b::Int
       end

julia> function MyStruct(a)
       MyStruct(2a, 3a)
       end
MyStruct

julia> MyStruct(5)
MyStruct(10, 15)
  1. These are data type for a variable and a default value. For an example you could do:
julia> function MyStruct(a::Int=7;mult=(2,3))
       MyStruct(a*mult[1], a*mult[2])
       end
MyStruct

julia> MyStruct()
MyStruct(14, 21)

julia> MyStruct(3)
MyStruct(6, 9)

julia> MyStruct(3.4)
ERROR: InexactError: Int64(6.8)
  1. It takes a vector or array prob and mutates all elements of this array. The @. is a vectorization macro meaning "iterate over all elements". Search for "Julia dot operator" to find out more.

  2. In several programming languages for complex you can have an in inmutable reference with mutable values it points to.

julia> struct A
       x::Vector{Int}
       end

julia> a=A([1,2,3,5,6])
A([1, 2, 3, 5, 6])

julia> a.x[3:4] .= 1
2-element view(::Vector{Int64}, 3:4) with eltype Int64:
 1
 1

julia> a.x = [4,5]
ERROR: setfield!: immutable struct of type A cannot be changed
Related