Julia Tips

はじめに

時々必要になるが、その時には多分忘れているであろう知識を書き残しておく。

関数の戻り値のみをパラメータ化する

# THIS FAILS.
# function myFunc{T}(a::Int, b::Int) where {T<:AbstractFloat}
#     @assert b != 0
#     a / T(b)
# end

# myFunc{Float32}(1,3)

# This is OK.
# [Creating a function with a parametric return type](https://stackoverflow.com/questions/66683629/creating-a-function-with-a-parametric-return-type)
function myFunc(::Type{T}, a::Int, b::Int) where {T<:AbstractFloat}
    @assert b != 0
    a / T(b)
end

x = myFunc(Float16,1,3)
println("x: $x")
Julia

module

IPython Notebook 中で名前空間を汚さないためによくやるやつ:

module MyModule
    foo = 16
end
module Glob
    using ..MyModule
    println(MyModule.foo)
end
Julia

local variable in list comprehension

println([(a=n*n; a+1) for n=1:3])
# [2, 5, 10]
println(a)
# UndefVarError: `a` not defined in `Main.Glob`
Julia

時間計測

time_ns 関数で現在時刻(オフセットは不定)を ns 単位で取得できる。

Plots

y 軸の描画範囲の下限または上限のいずれか一方を制限

ylims! 関数を使う。plot の戻り値から ylims の現状を入手して,下限または上限のうち必要な方だけを書き換える。

plt = plot(f->20log10(abs(H(f))), xlims=(f_min, f_max), minorgrid=true, xscale=:log10, label="|H(f)|", xlabel="f [Hz]", ylabel="gain [dB]")
ylims_0 = ylims(plt); ylims_0 = (minGain,ylims_0[2]); ylims!(plt, ylims_0)
Julia

Plots.heatmap

便利なオプション:c=:thermal, yflip=true

Polynomials.jl

変数の置き換え

p1 = Polynomial([1, 2, 3], :x)
p2 = Polynomial([1, 1], :y)
display(p1) # 1 + 2x + 3x^2
display(p2) # 1 + y
display(p1(p2)) # 6 + 8y + 3y^2
Julia

分母と分子の抽出

ドキュメントに記されていないが、 denominatornumerator 関数が使える。

Symbolics.jl

分母と分子を得る

numeratordenominator 関数で可能。ドキュメントには記載が無い。

Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

実部/虚部を取り出す

少し回りくどいが、可能。

Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

シンボリック関数から通常の関数を作る

Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

PythonCall

環境変数の設定

ガイドの Configuration に従う。自分はとくに "If you already have Conda, Mamba or MicroMamba" に当てはまったので .bashrc に次の記述を加えた。

# ----- Julia PythonCall Configuration -----
JULIA_PYTHONCALL_EXE=$(which python)
JULIA_CONDAPKG_BACKEND=System
JULIA_CONDAPKG_EXE=$(which conda)
## Future version may not need this.
PYTHON_JULIACALL_HANDLE_SIGNALS=yes
export JULIA_PYTHONCALL_EXE
export JULIA_CONDAPKG_BACKEND
export JULIA_CONDAPKG_EXE
export PYTHON_JULIACALL_HANDLE_SIGNALS
# ----------
Bash

投稿者: motchy

DSP and FPGA engineer working on measuring instrument.

コメントを残す