I'm attempting to add in a constraint to a JuMP 0.2.0 (Gurobi as a solver) model that reads in the original paper (pg 12) as follows:
c_t = argmax(N_kt) for k in 1...K
This constraint is designed to read through a matrix column by column, locate the index of the cell with the greatest value in that column, and assign that index to a cell c_t.
While Julia has an argmax function in the Base package, this function does not work in JuMP. Attempting to execute
for t in 1:T
#constraint(model, c_t == argmax(N_Kt[:,t])
end
throws an error of DenseAxisArray does not support this operation. Changing N_Kt to a non-dense JuMP array gets rid of that error, but instead throws an error of MethodError: no method matching isless(::VariableRef, ::VariableRef).
Is there an equivalent function for argmax within JuMP that I've managed to miss, or alternately, is there a clever way to reformulate this constraint? I've toyed with list comprehensions, i.e.
for t in t_l
for i in 1:num_features
#constraint(model, [i for k in 1:6 if N_kt[i,t] >= N_kt[k,t]] == c_t[t])
end
end
but Julia throws various errors when attempting this kind of formulation. This final approach of "set c_t equal to the index whose corresponding value is greater than or equal to all other values in this range" seems promising, but again, even the snippet above generates an error. Is there a better way to add in a conditional statement to a constraint declaration that I'm missing?
Thanks for any help you can offer here!
Related
Suppose I want to write a dynamic function that gets an object subtype of AbstractMatrix and shuffles the values along a specified dimension. Surely there can be various approaches and ways to do this, but suppose the following way:
import Random.shuffle
function shuffle(data::AbstractMatrix; dims=1)
n = size(data, dims)
shuffled_idx = shuffle(1:n)
data[shuffled_idx, :] #This line is wrong. It's not dynamic
A wrong way is to use several (actually indefinite) if-else statements like if dims==1 do... if dims==2 do. But it isn't the way to do these kinds of things. I could write data::AbstractArray then the input could have various dimensions. So this came to my mind that this can be possible if I can do something like getindex(data, [idxs]; dims). But I checked for the dims keyword argument (or even positional one) in the dispatches of getindex, but there isn't such a definition. So how can I get values by specified indexes and along a dim?
You are looking for selectdim:
help?> selectdim
search: selectdim
selectdim(A, d::Integer, i)
Return a view of all the data of A where the index for dimension d equals i.
Equivalent to view(A,:,:,...,i,:,:,...) where i is in position d.
Here's a code example:
function myshuffle(data::AbstractMatrix; dim=1)
inds = shuffle(axes(data, dim))
return selectdim(data, dim, inds)
end
Make sure not to use 1:n as indices for AbstractArrays, as they may have non-standard indices. Use axes instead.
BTW, selectdim apparently returns a view, so you may or may not need to use collect on it.
I wish to find an optimisation tool in R that lets me determine the value of an input parameter (say, a specific value between 0.001 and 0.1) that results in my function producing a desired output value.
My function takes an input parameter and computes a value. I want this output value to exactly match a predetermined number, so the function outputs the absolute of the difference between these two values; when they are identical, the output of the function is zero.
I've tried optimize(), but it seems to be set up to minimise the input parameter, not the output value. I also tried uniroot(), but it produces the error f() values at end points not of opposite sign, suggesting that it doesn't like the fact that increasing/decreasing the input parameter reduces the output value up to a point, but going beyond that point then increases it again.
Apologies if I'm missing something obvious here—I'm completely new to optimising functions.
Indeed you are missing something obvious:-) It's very obvious how you should/could formulate your problem.
Assuming the function that must equal a desired output value is f.
Define a function g satisfying
g <- function(x) f(x) - output_value
Now you can use uniroot to find a zero of g. But you must provide endpoints that satisfy the requirements of uniroot. I.e. the value of g for one endpoint must be positive and the value of g for the other endpoint must be negative (or the other way around).
Example:
f <- function(x) x - 10
g <- function(x) f(x) - 8
then
uniroot(g,c(0,20))
will do what you want but
uniroot(g,c(0,2))
will issue the error message values at end points not of opposite sign.
You could also use an optimization function but then you want to minimize the function g. To set you straight: optimize does not minimize the input paramater. Read the help thoroughly.
I'm trying to create a predicate in prolog which will hold true if it reaches the lowest numerical value out of a set of values.
For example:
I have something like this at the moment
Base Step
lowest(Object, Value) :- \+ lessThan(Object, Value, NewValue).
Recursive Step
lowest(Object, Value) :- lessThan(Object, Value, NewValue), lowest(Object, NewValue).
Where Object is some abstract object which can have multiple numerical values attached to it.
lessThan returns Values (NewValue) for the Object which are less than the input Value.
And since NewValue will be lower than the input of Value I can assume that with each recursive step Value will be decreasing.
I have abstracted this problem from another which I am trying to solve, but basically what is happening is that I expect only 2 outputs from the whole recursive function, but instead I am getting as many outputs as lessThan(Object, Initial, X) + 2.
I'm not sure if this question is clear, please let me know so I can clarify.
I believe that my base step is correct, since I am making the assumption that if Value is the lowest coupled with Object, then there are no other values less than Value.
I am unsure where to terminate the recursion also, which is adding to my confusion. My guess is that it will terminate once it reaches a state where there are no lower Values for Object.
This sample should work, renaming value/2 as appropriate for your domain.
value(a, 10).
value(a, 3).
value(a, 100).
lowest(Object, L) :-
value(Object, First), !, lowest(Object, First, L).
lowest(Object, LowestSoFar, Lowest) :-
value(Object, Try), Try < LowestSoFar, !,
lowest(Object, Try, Lowest).
lowest(_, Lowest, Lowest).
it yields
?- lowest(a,X).
X = 3.
Note that it repeats the value 'peek' each time, then is not efficient.
A possible alternative is storing the lower value and run a failure driven loop.
Otherwise, SWI-Prolog (and YAP) has library(aggregate):
?- aggregate(min(V), value(a,V), M).
M = 3.
This is related to my previous question. if I don't have the insert, it goes into a recursive loop as expected. But if I do have the insert the program ends. What am I missing here?
rule "Recurse"
when
f : Fibonacci(value == 0)
not Fibonacci(sequence == 0)
then
System.out.println(f.sequence + "/" + f.value);
insert(new Fibonacci(f.sequence - 1));
f.value = 0;
update(f);
end
For the purpose of explaining this example, lets assume:
there is only one rule in the system
that the initial fact set provided to the rule engine meets the criteria of the when in that rule
that sequence is a positive integer value
Firstly, we consider the case where the insert is commented out:
We know that the Working Memory contains at least one object that has value == 0 and there are no objects that have sequence == 0. (I find the more verbose form of not slightly more legible, you can replace not Fibonacci (...) with not ( exists Fibonacci(...))). Note that the rule is valid if there is a single object that meets both criteria.
The consequence sets the object's value to zero and notifies the engine that this object has changed. An infinite loop is then encountered as there is no object in the system with sequence == 0 and we've set the value to be such that this object will trigger the rule to fire.
Now, lets consider the case where the insert is uncommented:
We already know that the initial fact set fires the rule at least once. The consequence is that now an object is placed in working memory which has a decremented sequence and the object referenced by f has its value set to zero (it isn't changed from zero) and updated. There is a mechanism in place by which the end conditions are met, since now, at some point there will be an object inserted that has a zero sequence. That meets the end condition.
In short: the engine will exit when there is a Fibonacci object with sequence zero in it.
I, err.., think that this system might need a little bit of changing before it will output the Fibonacci sequence. You need a way to reference the previous two Fibonacci numbers to evaluate the one being set, the recursive method is much more elegent ;)
Cyclomatic complexity measures how many possible branches can be taken through a function. Is there an existing function/tool to calculate it for R functions? If not, suggestions are appreciated for the best way to write one.
A cheap start towards this would be to count up all the occurences of if, ifelse or switch within your function. To get a real answer though, you need to understand when branches start and end, which is much harder. Maybe some R parsing tools would get us started?
You can use codetools::walkCode to walk the code tree. Unfortunately codetools' documentation is pretty sparse. Here's an explanation and sample to get you started.
walkCode takes an expression and a code walker. A code walker is a list that you create, that must contain three callback functions: handler, call, and leaf. (You can use the helper function makeCodeWalker to provide sensible default implementations of each.) walkCode walks over the code tree and makes calls into the code walker as it goes.
call(e, w) is called when a compound expression is encountered. e is the expression and w is the code walker itself. The default implementation simply recurses into the expression's child nodes (for (ee in as.list(e)) if (!missing(ee)) walkCode(ee, w)).
leaf(e, w) is called when a leaf node in the tree is encountered. Again, e is the leaf node expression and w is the code walker. The default implementation is simply print(e).
handler(v, w) is called for each compound expression and can be used to easily provide an alternative behavior to call for certain types of expressions. v is the character string representation of the parent of the compound expression (a little hard to explain--but basically <- if it's an assignment expression, { if it's the start of a block, if if it's an if-statement, etc.). If the handler returns NULL then call is invoked as usual; if you return a function instead, that's what's called instead of the function.
Here's an extremely simplistic example that counts occurrences of if and ifelse of a function. Hopefully this can at least get you started!
library(codetools)
countBranches <- function(func) {
count <- 0
walkCode(body(func),
makeCodeWalker(
handler=function(v, w) {
if (v == 'if' || v == 'ifelse')
count <<- count + 1
NULL # allow normal recursion
},
leaf=function(e, w) NULL))
count
}
Also, I just found a new package called cyclocomp (released 2016). Check it out!