check if an element exist in nested tuple with Clingo and appending an element to tuple with python API - answer-set-programming

I am new to Clingo. so, I am trying to find out how it works. I have two questions regarding Clingo and its python API.
first, I have nested tuple such as tuple((1,(2,(3,(4,5))))). the length of the nested tuple may vary and the sequence is random. I want to check if a number for example n exists in the tuple if not do something. I am trying to check it with python API something like the code below obviously my code does not work.
#script (python)
import clingo
def is_in_tuple(x,n):
if n in x.arguments:
return True
else:
return False
#end.
tuple((1,(2,(3,(4,5))))).
h(X) :- tuple(X), #is_in_tuple(X,2).
#show h/1.
my other question is about appending to a simple tuple in python API for example we have tuple((1,2,3,4)) in Clingo and I want to append 0 to its beginning so the answer must look like ((0,1,2,3,4)). I want to use something like the code below. but the code will return the first element and 0. is it even possible to change the tuple like this?
#script (python)
import clingo
def append(x,n):
return [n, *x.arguments]
#end.
tuple(c(1,2,3,4,5)).
h(#append(X,0)) :- tuple(X).
#show h/1.

Related

numba error with tuple sorting containing numpy arrays

I have a (working) function that uses the heapq module to build a priority queue of tuples and I would like to compile it with numba, however I get a very long and unclear error. It seems to boil down to a problem with tuple order comparison needed for the queue. The tuples have a fixed format, where the first item is a a floating point number (whose order I care about) and then a numpy array, which I need for computation but never get compared when running normally. This is intended because comparison on numpy arrays yields an array which cannot be used in conditionals and raises an exception. However, I guess numba needs a scalar yielding comparison to be at least defined for all items in the tuple, and hence the numba error.
I have a very minimal example:
#numba.njit
def f():
return 1 if (1, numpy.arange(3)) < (2, numpy.arange(3)) else 2
f()
where the numba compilation fails (without numba it works since it never needs to actually compare the arrays, as in the original code).
Here is a slightly less minimal but maybe clearer example, which shows what I am actually doing:
from heapq import heappush
import numpy
import numba
#numba.njit
def f(n):
heap = [(1, 0, numpy.random.rand(2, 3))]
for unique_id in range(n):
order = numpy.random.rand()
data = numpy.random.rand(2, 3)
heappush(heap, (order, unique_id, data))
return heap[0]
f(100)
Here order is the variable whose order I care about in the queue, unique_id is a trick to avoid that when order is the same the comparison goes on to data and throws an exception.
I tried to bypass the problem converting the numpy array to a list when in the tuple and back to array for computation, but while this compiles, the numba version is slower than the interpreted one, even thought the array is quite small (usually 2x3). Without converting I would need to rewrite the code as loops which I would prefer to avoid (but is doable).
Is there a better alternative to get this working with numba, hopefully running faster than the python interpreter?
I'll try to respond based on the minimal example you provided.
I think that the problem here is not related to the ability of numba to perform comparison between all the elements of the tuple, but rather on where to store the result of such a comparison. This is stated in the error log returned when trying to execute your example:
cannot store {i8*, i8*, i64, i64, i8*, [1 x i64], [1 x i64]} to i1*: mismatching types
Basically, you are trying to store the result of a comparison between a pair of floats and a pair of arrays into a single boolean, and numba doesn't know how to do that.
If you are only interested in comparing the first elements of the tuples, the quickest workaround I can think of is forcing the comparison to happen only on the first elements, e.g.
#numba.njit
def f():
return 1 if (1, numpy.arange(3))[0] < (2, numpy.arange(3))[0] else 2
f()
If this is not applicable to your use case, please provide more details about it.
EDIT
According to the further information you provided, I think the best way to solve this is avoiding pushing the numpy arrays to the heap. Since you're only interested in the ordering properties of the heap, you can just push the keys to the heap and store the corresponding numpy arrays in a separate dictionary, using as keys the same values you push in the heap.
As a sidenote, when you use standard library functions in nopython-jitted functions, you are resorting on specific numba's re-implementation of those functions rather then the "original" python's ones. A comprehensive list of the available python's features in numba can be found here.
Ok, I found a solution to the problem: since storing the array in the heap tuple is the cause of the numba error, it is enough to store it in a separate dictionary with an unique key and store only the key in the heap tuple. For instance, using an integer as the key:
from heapq import heappush
import numpy
import numba
#numba.njit
def f(n):
key = 0
array_storage = {key: numpy.random.rand(2, 3)}
heap = [(1.0, key)]
for _ in range(n):
order = numpy.random.rand()
data = numpy.random.rand(2, 3)
key += 1
heappush(heap, (order, key))
array_storage[key] = data
return heap[0]
f(100)
Now the tuples in the heap can be compared yielding a boolean value and I still get to associate the data with its tuple. I am not completely satisfied since it seems a workaround, but it works pretty well and it is not overly complicated. If anyone has a better one please let me know!

scala seq.combinations returns out of order results

scala docs say that combinations method should do the following
Iterates over combinations. A _combination_ of length n is a subsequence of the original sequence, with the elements taken in order.
https://www.scala-lang.org/api/2.13.3/scala/collection/immutable/List.html
but running
"aba".combinations(3).toList // return List("aab")
this is obviously out of order, it is expected to return List("aba"). As a side note, this is how it works in other languages, like python itertools.combinations, where we get List("aba") as expected. Am I misunderstanding how this should work, or is it a bug?
https://scastie.scala-lang.org/TdluwxaiQ6CGkckU4Uk3AA

Head of empty list in Scala

I've made this recursive metod in Scala that returns a list made of all distinct elements of another list.
object es20 extends App{
def filledList:List[Int]=List()
#scala.annotation.tailrec
def distinct(l:List[Int]):List[Int] ={
if (l.isEmpty) filledList
if (filledList.forall(_!=l.head)) l.head::filledList
distinct(l.tail)
}
println(distinct(List(1,1,5,6,6,3,8,3))) //Should print List(1,5,6,3,8)
}
However, when I compile the code and then I run it, there's this exception:
java.util.NoSuchElementException: head of empty list
I thought that this exception was handle by the condition if (l.isEmpty).
How can I fix the code?
In Scala method returns last expression of the block. In your case you have three expressions: two if-expressions which result in unit and call to distinct, so checks will be executed every time you call distinct, no matter if the list is empty or not.
To fix it you can use if / else construct, or pattern match on input list, or make operation on headOption.
Anyway I doubt if this code correct: you trying to check something on 'filledList' which is always empty
You can fix this particular error by inserting else before the second if. However, as mentioned in the other answer, your code isn't correct, and won't work anyway, you need to rewrite it.
Also, I understand, that you are just trying to write this function as an exercise (if not, just do list.distinct), but I submit, that implementing quadratic solutions to trivially linear problems is never a good exercise to begin with.

How can I make the value of an expression equal to a second return value of another expression

Is there an idiomatic way in Matlab to bind the value of an expression to the nth return value of another expression?
For example, say I want an array of indices corresponding to the maximum value of a number of vectors stored in a cell array. I can do that by
function I = max_index(varargin)
[~,I]=max(varargin{:});
cellfun(#max_index, my_data);
But this requires one to define a function (max_index) specific for each case one wants to select a particular return value in an expression. I can of course define a generic function that does what I want:
function y = nth_return(n,fun,varargin)
[vals{1:n}] = fun(varargin{:});
y = vals{n};
And call it like:
cellfun(#(x) nth_return(2,#max,x), my_data)
Adding such functions, however, makes code snippets less portable and harder to understand. Is there an idiomatic to achieve the same result without having to rely on the custom nth_return function?
This is as far as I know not possible in another way as with the solutions you mention. So just use the syntax:
[~,I]=max(var);
Or indeed create an extra function. But I would also suggest against this. Just write the extra line of code, in case you want to use the output in another function. I found two earlier questions on stackoverflow, which adress the same topic, and seem to confirm that this is not possible.
Skipping outputs with anonymous function in MATLAB
How to elegantly ignore some return values of a MATLAB function?
The reason why the ~ operator was added to MATLAB some versions ago was to prevent you from saving variables you do not need. If there would be a syntax like the one you are searching for, this would not have been necessary.

How to correctly get current loop count from a Iterator in scala

I am looping over the following lines from a csv file to parse them. I want to identify the first line since its the header. Whats the best way of doing this instead of making a var counter holder.
var counter = 0
for (line <- lines) {
println(CsvParser.parse(line, counter))
counter++
}
I know there is got to be a better way to do this, newbie to Scala.
Try zipWithIndex:
for (line <- lines.zipWithIndex) {
println(CsvParser.parse(line._1, line._2))
}
#tenshi suggested the following improvement with pattern matching:
for ((line, count) <- lines.zipWithIndex) {
println(CsvParser.parse(line, count))
}
I totally agree with the given answer, still that I've to point something important out and initially I planned to put in a simple comment.
But it would be quite long, so that, leave me set it as a variant answer.
It's prefectly true that zip* methods are helpful in order to create tables with lists, but they have the counterpart that they loop the lists in order to create it.
So that, a common recommendation is to sequence the actions required on the lists in a view, so that you combine all of them to be applied only producing a result will be required. Producing a result is considered when the returnable isn't an Iterable. So is foreach for instance.
Now, talking about the first answer, if you have lines to be the list of lines in a very big file (or even an enumeratee on it), zipWithIndex will go through all of 'em and produce a table (Iterable of tuples). Then the for-comprehension will go back again through the same amount of items.
Finally, you've impacted the running lenght by n, where n is the length of lines and added a memory footprint of m + n*16 (roughtly) where m is the lines' footprint.
Proposition
lines.view.zipWithIndex map Function.tupled(CsvParser.parse) foreach println
Some few words left (I promise), lines.view will create something like scala.collection.SeqView that will hold all further "mapping" function producing new Iterable, as are zipWithIndex and map.
Moreover, I think the expression is more elegant because it follows the reader and logical.
"For lines, create a view that will zip each item with its index, the result as to be mapped on the result of the parser which must be printed".
HTH.