Great approach John! I was not aware of the linear indexing of type fields,
that opens a lot of possibilities. Thanks


On Tue, Mar 11, 2014 at 3:51 PM, John Myles White
<[email protected]>wrote:

> For now, I suspect the easiest way to do this is to switch back and forth
> between immutable types and vectors by using linear indexing in the fields
> of a type, then linear indexing within each field. Here's a specific
> example of how a generic function might work:
>
> immutable Foo
> a::Vector{Float64}
> b::Matrix{Float64}
> end
>
> f = Foo(ones(3), 2 * ones(4, 4))
> v = Array(Float64, 3 + 4 * 4)
>
> i = 0
> for fieldindex in 1:2
> field = f.(fieldindex)
> for fieldelement in field
>  i += 1
> v[i] = fieldelement
> end
> end
>
> Writing a generic function to do this isn't much more work.
>
>  -- John
>
> On Mar 10, 2014, at 12:53 PM, James Porter <[email protected]> wrote:
>
> I've struggled with this exact problem in python in the past (e.g.
> https://stackoverflow.com/questions/16182898/unpacking-parameters-for-a-simulation).
> It's exacerbated by the fact that interfaces to solvers, optimizers, etc.
> often require the parameters be passed in as a vector, so using dictionary
> won't help. Dictionary access in tight loops also has obviously bad
> performance implications. My intuition is that a macro is the way out,
> something like:
>
> @unpack params a1 a2 a3 b1 b2 C  # etc . . .
>
> as you suggest. The tricky bit is implementing it in a way that avoids
> unnecessary memory allocation. I'm not sure how good the LLVM optimization
> passes are but I suspect that doing it as you suggested previously (e.g.
> translating the above into a1 = params[1], a2 = params[2], etc.) will
> result in unnecessarily copying things onto the stack from the params array.
>
> --James
>
> On Friday, March 7, 2014 8:15:58 AM UTC-6, Yuuki Soho wrote:
>>
>> It's a bit of a stupid question, but I don't really know how to deal with
>> this efficiently.
>>
>> So, in many application I have some model with parameters, and I want to
>> the able to change the number of parameters, or they order easily.
>>
>> For passing parameters to functions I want to pack them into a vector p,
>> such that I don't have huge function definition, but inside
>>
>> the function's body I'd prefer to have all the parameters given by their
>> name, so I can use them in equations (instead of using p[1], p[2], ...).
>>
>> I can write two functions p = pack(a,b,c) and (a,b,c) = unpack(p) but
>> that's pretty restrictive because if you add or remove a parameters, I have
>> to change all
>>
>> my function calls and definition. If I add another model I also need to
>> write another pack and unpack pairs.
>>
>>
>> Is there an better approach to do this in Julia ? I was thinking maybe
>> doing a macro @unpack p that would spawn all the variables needed, but I'm
>> not
>>
>> sure that's the right way to do it.
>>
>
>

Reply via email to