How to run my version of a function from a package

I have translated SAMIN (optimize) in the Optim package to another language (where it is needed) and need to add print statements to the Julia code for comparison. This is the code I wish to run:

I have placed samin.jl in my own directory (separate from the julia distribution). When I type: include(“samin.jl”) in the REPL I get:
ERROR: LoadError: UndefVarError: @with_kw not defined

Stacktrace:

[1] top-level scope

@ :0

[2] #macroexpand#66

@ ./expr.jl:122 [inlined]

[3] macroexpand

@ ./expr.jl:120 [inlined]

[4] docm(source::LineNumberNode, mod::Module, meta::Any, ex::Any, define::Bool)

@ Base.Docs ./docs/Docs.jl:555

[5] var"@doc"(::LineNumberNode, ::Module, ::String, ::Vararg{Any})

@ Core ./boot.jl:541

[6] include(fname::String)

@ Base.MainInclude ./client.jl:489

[7] top-level scope

@ REPL[1]:1

in expression starting at /Users/stimmins/julia/samin.jl:19

in expression starting at /Users/stimmins/julia/samin.jl:19

Being new I need detailed instructions please - it has something to do with defaults - but how to remedy? Thank you.

Most .jl files in packages are not supposed to be evaluated in isolation, but within another primary file. In Optim.jl/src/Optim.jl, there is a line include("multivariate/solvers/constrained/samin.jl") occurring far after a line import Parameters: @with_kw, @unpack, among other imports and includes. To make your println version work, you would need to replicate the minimum imports and includes that the original needed to work.

I don’t think it’s worth manually doing that because at worst case, you need every preceding line and you might as well fork the whole package at that point. Looking at local variables while debugging is a typical alternative, but it can be too hands-on and slow compared to a run-once-print-all approach. You could load the Optim package and @eval Optim ... modified functions right into the active Optim module, and it will work like the original in most cases. Make sure to change the function name or dispatch on a custom-typed argument so you’re not replacing the original code.

Another idea is maybe to instead of ]add Optim.jl to your environment you ]dev it instead. That creates a copy of the fully module in your .julia/dev (not quite sure about this path, haven’t double checked). There you can modify the code, i.e. add the printlns. Then you can just run a test code normally.

2 Likes