Why am I getting no method matching Complex(::Sym)? - julia

I am having one function to be executed, it has been compiled but for the execution it shows me a MethodError, here is the function
For this function I'm using SymPy
function op_mat(op)
op = op.as_poly(domain="C")
op_a = op.x.gens
nab = op.length()
op_ab = ones(SymPy.Sym, nab)
coef = zeros(Complex, nab)
mat = zeros(Int64, length(op_a), nab)
for (i, (ps, c)) in enumerate(op.as_dict())
for (j, p) in enumerate(ps)
mat[j, i] = p
op_ab[i] = op_a[j]^p * op_ab[i]
end
coef[i] = c
end
return op_a, op_ab, mat, coef
end
The error message that I'm having is this one:
Complex(::T<:Number) where T<:Number at boot.jl:718
Complex(::Real) at complex.jl:16
Complex(::T<:Real, ::T<:Real) where T<:Real at complex.jl:12
...
Stacktrace:
[1] convert(::Type{Complex}, ::Sym) at ./number.jl:7
[2] setindex!(::Array{Complex,1}, ::Sym, ::Int64) at ./array.jl:766
[3] op_mat(::Sym) at ./REPL[3]:13
[4] top-level scope at REPL[7]:1

since the type of c is Sym i should have only change the type to complex coef[i]=complex(c) or coef[i]=N(c)

Related

LoadError: MethodError: "Method too new to be called from this world context." in Julia

Can someone explain in simple terms why this error occurs and how it can be avoided except not placing the code in main in a function?
Please refer to question Improving the performance of SymPy function generated from string in Julia for the function string_to_func.
Works:
using SymPy
function string_to_func(function_string)
func_lambdify = lambdify(SymPy.sympify(function_string), invoke_latest=false)
#eval func(x, y, z) = ($func_lambdify)(x, y, z)
return Nothing
end
function_string = "x + y + z"
string_to_func(function_string)
result = func(1, 2, 3)
Throws Error:
using SymPy
function string_to_func(function_string)
expr = lambdify(SymPy.sympify(function_string), invoke_latest=false)
#eval func(x, y, z) = ($expr)(x, y, z)
return Nothing
end
function main()
function_string = "x + y + z"
string_to_func(function_string)
result = func(1, 2, 3)
end
main()
Anonymized Error Message:
ERROR: LoadError: MethodError: no method matching func(::Int64, ::Int64, ::Int64)
The applicable method may be too new: running in world age 29676, while current world is 29678.
Closest candidates are:
func(::Any, ::Any, ::Any) at path_to_folder\test.jl:5 (method too new to be called from this world context.)
Stacktrace:
[1] main()
# Main path_to_folder\test.jl:12
[2] top-level scope
# path_to_folder\test.jl:15
in expression starting at path_to_folder\test.jl:15
You need to invoke func using Base.invokelatest, i.e.
function main()
function_string = "x + y + z"
string_to_func(function_string)
result = Base.invokelatest(func, 1, 2, 3)
end
See the manual for further details about world age and why invokelatest is needed here.
I should also mention GeneratedFunctions.jl that can avoid some of the overhead associated with invokelatest, although it has it is own caveats since its somewhat of a hack.

LoadError: UndefVarError: #defVar not defined

I have a piece of code about JuMP. When I run it ,it says that LoadError: UndefVarError: #defVar not defined. I have tried using global forward or backward but both fails.
See:
function T1(w_func,grid_b,β,u,z)
# objective for each grid point
for j in 1:cp.Nb
b = grid_b[j]
choice1 = Model(solver=GLPKSolverLP())
#defVar (choice1, a >= 0)
#setObjective(choice1, Max, u(a) + cp.β * (w_func.((b*(1+cp.r)+cp.w-a) .* cp.z[i])))
results1 = solve(choice1)
Tw1 = getObjectiveValue(choice1)
c_choice1 = getValue(x)
return Tw, σ
end
end
LoadError: UndefVarError: #defVar not defined
in expression starting at In[44]:37
Stacktrace:
[1] top-level scope
# :0
[2] eval
# ./boot.jl:360 [inlined]
[3] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String)
# Base ./loading.jl:1094
thanks
It seems that you're using an outdated code. Look at the fresh documentation and make sure you have installed the latest versions of libraries and Julia.
In short, #defVar and #setObjective were replaced by #variable and #objective correspondingly.
function T1(w_func,grid_b,β,u,z)
# objective for each grid point
for j in 1:cp.Nb
b = grid_b[j]
choice1 = Model(solver=GLPKSolverLP())
#variable(choice1, a >= 0)
#objective(choice1, Max, u(a) + cp.β * (w_func.((b*(1+cp.r)+cp.w-a) .* cp.z[i])))
results1 = solve(choice1)
Tw1 = getObjectiveValue(choice1)
c_choice1 = getValue(x)
return Tw, σ
end
end

Julia Flux error: MethodError: no method matching *(::Chain{Tuple{Conv{2,4,typeof(identity),Array{Float32,4},Array{Float32,1}},var"#13#15"}}, ::Int64)

using Flux
using Flux:#functor
function ConvBlock(inc,out,k,s,p,use_act)
return Chain(
Conv((k,k),inc=>out,stride = s,pad = p,bias=true),
use_act ? x -> leakyrelu.(x,0.2) : x -> x
)
end
mutable struct DenseResidualBlock
residual_beta
blocks
end
#functor DenseResidualBlock
function DenseResidualBlock(inc,c = 32,residual_beta = 0.2)
blocks = []
for i in 0:4
in_channels = inc + c*i
out_channels = i<=3 ? c : inc
use_act = i<=3 ? true : false
push!(blocks,ConvBlock(in_channels,out_channels,3,1,1,use_act))
end
return DenseResidualBlock(residual_beta,blocks)
end
function (m::DenseResidualBlock)(x)
new_inputs = x
local out,new_inputs
for block in m.blocks
out = block(new_inputs)
new_inputs = cat(new_inputs,out,dims=3)
end
return m.residual_beta * out + x
end
When I run this
drb = DenseResidualBlock(64)
I get this error
ERROR: MethodError: no method matching *(::Chain{Tuple{Conv{2,4,typeof(identity),Array{Float32,4},Array{Float32,1}},var"#13#15"}}, ::Int64)
try
function DenseResidualBlock(inc;c = 32,residual_beta = 0.2)
instead of
function DenseResidualBlock(inc,c = 32,residual_beta = 0.2)
There is an ambiguity in your code when DenseResidualBlock is called with two arguments. It could either construct the structure DenseResidualBlock directly or call DenseResidualBlock(inc,c) with residual_beta = 0.2. If you use keyword arguments for DenseResidualBlock(inc; c = 32,residual_beta = 0.2) this ambiguity is lifted.
The error message indicated that at the line in_channels = inc + c*i the parameter c is not a number as expected but a Flux.Chain which cannot be multiplied by a number.

Is it possible to convert an Array{Num,1} to Array{Float64,1} in Julia?

I have the following function that uses symbolics in Julia. Everything works fine until the moment of plotting
using Distributions
using Plots
using Symbolics
using SymbolicUtils
function BinomialMeasure(iter::Int64, p::Float64, current_level = nothing)
#variables m0 m1
if current_level == nothing
current_level = [1]
end
next_level = []
for item in current_level
append!(next_level, m0*item)
append!(next_level, m1*item)
end
If iter != 0
current_level = next_level
return BinomialMeasure(iter - 1, p , current_level)
else
return [substitute(i, Dict([m0 => p, m1 => 1 - p])) for i in next_level]
end
end
y = BinomialMeasure(10, 0.4)
x = [( i + 1 ) / length(y) for i = 1:length(y) ]
append!(x, 0)
append!(y,0)
plot(x,y)
Then it returns the following:
MethodError: no method matching AbstractFloat(::Num)
Closest candidates are:
AbstractFloat(::Real, !Matched::RoundingMode) where T<:AbstractFloat at rounding.jl:200
AbstractFloat(::T) where T<:Number at boot.jl:716
AbstractFloat(!Matched::Bool) at float.jl:258
y is an Array{Num,1} and x is an Array{Float64,1}.
I tried map(float, y), convert(float,y) and float(y), but I think it not possible to convert a type Num to a Float64 or at least I don't know how to do it.
you can access the field val without using string and parse
y_val = [i.val for i in y]
this will of course have way better performance than parsing a string

Julia - generate an array of functions programmatically

I want to generate an array of functions programmatically, with a loop so that each successive function depends on the previous.
For example in pseudo-code:
f_array = [f1, f2, f3]
with:
f1(x) = x
f2(x) = 3 * f1(x)
f3(x) = 3 * f2(x)
so that I could call:
f_array[3](x)
and get the result of f3(x)
Here is what I have tried:
# create simple function just to initialize
f(x)=x
# initialize array of functions
N = 3
f_array = fill(f, N)
# now we update each function
for i in 2:N
f_array[i] = (f(x)= 3 * f_array[i-1](x))
end
I get an error:
ERROR: MethodError: Cannot convert an object of type getfield(Main,
Symbol("#f#15")){Int64} to an object of type typeof(f)
I cannot find a solution at the moment. Any help would be appreciated.
When you use fill with f it sets expected type for the elements of f_array to f, in the code below I am switching to abstract type to make it possible to have any function in the array
# create simple function just to initialize
f(x)=x
# initialize array of functions
N = 3
f_array = Array{Function}(undef, N);
f_array[1] = f;
# now we update each function
for i in 2:N
f_array[i] = x -> 3 * f_array[i-1](x)
end
print(f_array[3](2))
which produces a value of 18
In the mean time, I also found a way using metaprogramming. I post this here as it could be useful for others:
f1(x) = x
for i in 2:N
prog = "f$i(x) = 3 * f$(i-1)(x)"
exp = Meta.parse(prog)
eval(exp)
end
f3(2)
# 18
I'd write Yegor's answer as
f_array = Function[identity]
for i in 2:3
push!(f_array, x -> 3f_array[i-1](x))
end
But more importantly, this is a well known pattern: iterated function application. And it is already implemented, not in Base, but for example in IterTools.jl, by which you should be able to write:
f_array(start, N) = collect(Iterators.take(iterated(x -> 3x, start), N))
(I didn't test this, though.)

Resources