I try to run the following code block:
using JuMP
using CPLEX
function solveRMP(cust::Int64,
routes::Array{Float64,2},
routeCost::Array{Float64,1},
m::Int64)
cust_dep = cust+2;
rmp = Model(solver = CplexSolver())
# Add decistion variables
#variable(rmp, 0<=x[1:size(routes,2)])
#
# Add objective
#objective(rmp, Min, sum(routeCost[r]*x[r] for r=1:size(routes,2)))
# #####################
# ### Constraints
#constraint(rmp, cVisitCust[i=2:cust_dep-1], sum(routes[i,r]*x[r] for r=1:size(routes,2)) == 1)
#constraint(rmp, cMaxNrRoutes, sum(x[r] for r=1:size(routes,2)) <= m )
allConstraints = vcat(cVisitCust,cMaxNrRoutes)
writeLP(rmp, "myRMP.lp", genericnames=false);
solve(rmp)
duals = zeros(1,1)
append!(duals,getdual(allConstraints))
return getvalue(x), duals
end
and I get the following error:
**LoadError: MethodError: no method matching getname(::Int64)
Closest candidates are:
getname(!Matched::Expr) at
(...) **
In the declaration of the variables x,
#variable(rmp, 0<=x[1:size(routes,2)])
the constraint needs to be on the right side of the variable name
#variable(rmp, x[1:size(routes,2)] >= 0)
Otherwise 0 is interpreted as a variable name, leading to the error.
Related
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.)
I'm attempting to code the method described here to estimate production functions of metal manufacturers. I've done this in Python and Matlab, but am trying to learn Julia.
spain_clean.csv is a dataset of log capital (lnk), log labor (lnl), log output (lnva), and log materials (lnm) that I am loading. Lagged variables are denoted with an "l" before them.
Code is at the bottom. I am getting an error:
ERROR: LoadError: MethodError: no method matching parseNLExpr_runtime(::JuMP.Model, ::JuMP.GenericQuadExpr{Float64,JuMP.Variable}, ::Array{ReverseDiffSparse.NodeData,1}, ::Int32, ::Array{Float64,1})
I think it has to do with the use of vector sums and arrays going into the non-linear objective, but I do not understand Julia enough to debug this.
using JuMP # Need to say it whenever we use JuMP
using Clp, Ipopt # Loading the GLPK module for using its solver
using CSV # csv reader
# read data
df = CSV.read("spain_clean.csv")
#MODEL CONSTRUCTION
#--------------------
acf = Model(solver=IpoptSolver())
#variable(acf, -10<= b0 <= 10) #
#variable(acf, -5 <= bk <= 5 ) #
#variable(acf, -5 <= bl <= 5 ) #
#variable(acf, -10<= g1 <= 10) #
const g = sum(df[:phihat]-b0-bk* df[:lnk]-bl* df[:lnl]-g1* (df[:lphihat]-b0-bk* df[:llnk]-bl* df[:llnl]))
const gllnk = sum((df[:phihat]-b0-bk* df[:lnk]-bl* df[:lnl]-g1* (df[:lphihat]-b0-bk* df[:llnk]-bl* df[:llnl])).*df[:llnk])
const gllnl = sum((df[:phihat]-b0-bk* df[:lnk]-bl* df[:lnl]-g1* (df[:lphihat]-b0-bk* df[:llnk]-bl* df[:llnl])).*df[:llnl])
const glphihat = sum((df[:phihat]-b0-bk* df[:lnk]-bl* df[:lnl]-g1* (df[:lphihat]-b0-bk* df[:llnk]-bl* df[:llnl])).*df[:lphihat])
#OBJECTIVE
#NLobjective(acf, Min, g* g + gllnk* gllnk + gllnl* gllnk + glphihat* glphihat)
#SOLVE IT
status = solve(acf) # solves the model
println("Objective value: ", getobjectivevalue(acf)) # getObjectiveValue(model_name) gives the optimum objective value
println("b0 = ", getvalue(b0))
println("bk = ", getvalue(bk))
println("bl = ", getvalue(bl))
println("g1 = ", getvalue(g1))
No an expert in Julia, but I think a couple of things are wrong about your code.
first, constant are not supposed to change during iteration and you are making them functions of control variables. Second, what you want to use there are nonlinear expression instead of constants. so instead of the constants what you want to write is
N = size(df, 1)
#NLexpression(acf, g, sum(df[i, :phihat]-b0-bk* df[i, :lnk]-bl* df[i, :lnl]-g1* (df[i, :lphihat]-b0-bk* df[i, :llnk]-bl* df[i, :llnl]) for i=1:N))
#NLexpression(acf, gllnk, sum((df[i,:phihat]-b0-bk* df[i,:lnk]-bl* df[i,:lnl]-g1* (df[i,:lphihat]-b0-bk* df[i,:llnk]-bl* df[i,:llnl]))*df[i,:llnk] for i=1:N))
#NLexpression(acf,gllnl,sum((df[i,:phihat]-b0-bk* df[i,:lnk]-bl* df[i,:lnl]-g1* (df[i,:lphihat]-b0-bk* df[i,:llnk]-bl* df[i,:llnl]))*df[i,:llnl] for i=1:N))
#NLexpression(acf,glphihat,sum((df[i,:phihat]-b0-bk* df[i,:lnk]-bl* df[i,:lnl]-g1* (df[i,:lphihat]-b0-bk* df[i,:llnk]-bl* df[i,:llnl]))*df[i,:lphihat] for i=1:N))
I tested this and it seems to work.
Here is my integrand()
integrand<-function(x,vecC)
{
as.numeric((2/(b-a))*vecC%*%as.matrix(cos((x-hat.a)
*(seq(0,N-1,length=N)*pi/(b-a)))))
}
it can produce the value. For example, for
a<-1
b<-10
vecC<-t(as.matrix(rnorm(80)))
hat.a<--1.2
N<-80
I get
> integrand(1.4,vecC)
[1] -0.3635195
but I met problem when I run the following code for integration
> integrate(function(x){integrand(x,vecC)},upper = 3.4,lower = 1)$value
and the error message is
Error in integrate(function(x) { :
evaluation of function gave a result of wrong length
In addition: Warning message:
In (x - hat.a) * (seq(0, N - 1, length = N) * pi/(b - a)) :
longer object length is not a multiple of shorter object length
If you read the help page for integrate you will see that the function passed to integrate should return a vector.
So the solution to your error is to use Vectorize like this
Define your function separately as
f <- function(x){integrand(x,vecC)}
Now define a vectorized version of this function like so
fv <- Vectorize(f,"x")
and then
integrate(fv,upper = 3.4,lower = 1)$value
will give you a result.
I use code like this:
p = _belineInterpolateGrid( map( p -> sin(norm(p)), grid ), grid )
f = open("/data/test.function", "w")
serialize( f, p )
close(f)
p0 = deserialize( open("/data/test.function", "r") )
where _belineInterpolateGrid is
function _belineInterpolateGrid(PP, Grid)
...
P = Array(Function, N-1, M-1);
...
poly = (x,y) -> begin
i_x, i_y = i(x, y);
return P[i_x, i_y](x, y);
end
return poly
And now, since some of v0.4, a have an error:
ERROR: MethodError: `convert` has no method matching
convert(::Type{LambdaStaticData}, ::Array{Any,1})
This may have arisen from a call to the constructor LambdaStaticData(...),
since type constructors fall back to convert methods.
Closest candidates are:
call{T}(::Type{T}, ::Any)
convert{T}(::Type{T}, ::T)
...
in deserialize at serialize.jl:435
Why It's happend? Is it bug and how to fix it?
This looks like a bug in Julia to me, and it looks like it has been fixed as of v0.4.6. Try upgrading to that version or newer and see if the problem persists.
You're returning a lambda, that's why. Can't tell if it's a bug (you can serialize a lambda but you can't deserialize it?).
You can avoid this by defining your "get interpolation at x,y" as a type:
import Base: getindex
type MyPoly
thepoly
end
function getindex(p::MyPoly, x::Int, y::Int)
p.thepoly[x+5*y]
end
function getindex(p::MyPoly, I...)
p.thepoly[I...]
end
function call(p::MyPoly, v)
#collect helps keep eltype(ans) == Int
powered_v = map( i->v^i, collect(
take(countfrom(),size(p.thepoly,1))))
powered_v.*p.thepoly
end
p=MyPoly(collect(1:10))
println(p[1])
f = open("serializedpoly", "w")
serialize( f, p)
close(f)
p0 = deserialize( open("serializedpoly", "r"))
println(p[1,1])
v=call(p, 4) #evaluate poly on 4
EDIT: added extension for call
I've got this small snippet for reducing a large system:
# set up the multipliers
g1 = (s+9)/((s)*(s+6)*(s+12)*(s+14))
g2 = ((6)*(s+9)*(s+17))/((s+12)*(s+32)*(s+68))
h1 = 13
h2 = 1/(s+7)
# reduce the system in parts
s1 = (g2)/(1 + (g2)*(h1))
s2 = (s1)*(g1)
s3 = (s2)/(1 + (s2)*(h2))
# now we have a unity feedback
g = s3
show(g)
g should be the reduced equation from doing the operations above. However, I get a bunch of errors when I run the code:
Error : object 's' not found
Error : object 's' not found
Error : object 's' not found
Error : object 'g2' not found
Error : object 's1' not found
Error : object 's2' not found
Error : object 's3' not found
Error : error in evaluating the argument 'object' in selecting a method for function 'show': Error: object 'g' not found
Am I not using equations correctly?
edit: my intentions are to have s as a free variable
In order to evaluate your first line of code, there must be an object s that is already defined.
It sounds like your goal is to create a function that outputs g from a single input s. The below code wraps your calculations in a function called make_g:
make_g <- function(s){
# set up the multipliers
g1 = (s+9)/((s)*(s+6)*(s+12)*(s+14))
g2 = ((6)*(s+9)*(s+17))/((s+12)*(s+32)*(s+68))
h1 = 13
h2 = 1/(s+7)
# reduce the system in parts
s1 = (g2)/(1 + (g2)*(h1))
s2 = (s1)*(g1)
s3 = (s2)/(1 + (s2)*(h2))
# now we have a unity feedback
g = s3
g
}
Now, you can call the functions using whatever value for s you like:
make_g(s = 1)