Skip to content

Miscellaneous

Good advice on miscellaneous topics:

Hashing

For new DataTypes, it is necessary to defined hash, ==, and isequal. hash is needed for containers such as Dicts (it is used for haskey). The way this is done can be based on AutoHashEquals.jl:

mutable struct Foo
    a::Int
    b
end
Base.hash(a::Foo, h::UInt) = hash(a.b, hash(a.a, hash(:Foo, h)))

Interpolation (1.6)

Interpolations.jl

An example from QuantEcon.

One limitation: multi-dimensional interpolation only works with unform grids. The inputs must be ranges.

The default for extrapolation is to throw an error.

Example:

xV = 1:10; yV = 5:10;
zM = xV .+ yV' .+ xV .* yV';
itp = CubicInterpolation((xV, yV), zM);
itp(1.5, 5.9)

The same (?) interpolation can be constructed the long way round:

itp2 = interpolate(zM, BSpline(Cubic(Line(OnGrid()))));
sitp = scale(itp2, xV, yV);

One difference is that bounds works on sitp but not on itp.

Latex Output (1.6)

Latexify.jl renders various expressions as Latex equations. This is useful for automatically making expressions for functional forms. Also generates Latex tables from DataFrames and Arrays.

Logging (1.6)

@debug can be used to generate self-test code that is only run while developing the code.

Example:

# test1.jl
a = 1;
b = [1,2,3];
@debug begin
   bSum = sum(b);
   """
   Debug message
   $bsum
   """
end
@debug "Debug with args:"  a, b

To run this with the @debug statements enabled, issue (in the shell):

export JULIA_DEBUG=all
julia "test1.jl"

But this generates lots of debug messages that sit in Base. To avoid this, export JULIA_DEBUG=MyPkg.

Enabling logging levels temporarily:

lg = ConsoleLogger(stderr, Logging.Debug);
with_logger(lg) do
   foo();
end

Or:

lg = ConsoleLogger(stderr, Logging.Debug);
old_logger = global_logger(lg);
foo();
global_logger(old_logger);

Random numbers (1.5)

Generating reproducible random numbers across Julia versions can be done with StableRNGs.jl. This also seems to generate the same random numbers across operating systems (in my case MacOS and Linux).

Traits

An interesting implementation is WhereTraits.jl which permits, for example, dispatch on functions that return Bool.