Question

I am trying to build a list with the following format:

(t,dt,array)

Where t is time -float-, dt is also a float an array is an array of ints that represents the state of my system. I want to have elements ordered in an array by the first element, that is t. So my take on it is to use the heap structure provided by Python.

What I am trying is:

import numpy as np 
import scipy as sp
import matplotlib.pyplot as plt
import heapq

popsize = 10

populat = [ (0,0,np.random.randint(0,2,Nsize)) for count in range(popsize)]
heapq.heapify(populat)  # Structure to order efficiently 

However this returns the following:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

So does anybody knows how could it do that? or where does the error comes from?

I am using Ubuntu 12.04, running python 2.7 and also ipython 1.1.

I will be very grateful, thanks a lot.

Was it helpful?

Solution

(0,0,np.random.randint(0,2,Nsize))

The first two elements there aren't t or dt. They're both 0. As such, the tuple comparison tries to compare the arrays in the 3rd slot and finds that that doesn't produce a meaningful boolean result. Did you mean to have something meaningful in the first two slots?

OTHER TIPS

As far as where the error comes from:

>>> a = (0, 0, np.random.randint(0, 2, 3))
>>> a
(0, 0, array([0, 0, 1]))
>>> b = (0, 0, np.random.randint(0, 2, 3))
>>> a
(0, 0, array([0, 0, 1]))
>>> a == b

The reason for this is that numpy overrides comparison operators in a non-standard way. Rather than returning a boolean result, it returns a numpy boolean array.

So what I ended up doing was to add another element in the list to make the intial comparison possible:

populat = [ (0,0,i,np.random.randint(0,2,Nsize)) for i in range(popsize)]

As pointed above if the two first elements are equal the comparison goes to the third element (the array) which returns an error due to the bolean logic arrays.

The way around is to create an element that is different for each members of the list that inhibits comparisons at that level of the array (that's what the i is doing).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top