473,804 Members | 2,111 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

nDimensional sparse histogram in python.

Hi, I wrote a C++ class that implements an n dimensional histogram in
C++, using stl maps and vectors. I want to code this up now in Python
and would like some input from this group.

The C++ class was VERY simple..

std::map<std::v ector<unsigned short>, unsigned long> histo;

Say for example I want a 3D histogram then std::vector<uns igned short>
would contains
the x, y, and z points in space and the unsigned long is the number of
counts.
If I want to know the value at a specific point in space I pass in a
vector [3,2,1] and if
it is found in the map then the count is returned other wise zero is
returned.
If I want to increment a count then histo[vector]++ will either set the
count to 1 or increment
the count if it is found...

So as you can see this is a very simple way to implement a multi
dimensional sparse histogram.

I'm thinking that in python this must also be as simple as a
dictionary, where the key is the vector x,y,z and the value is the
count.

My python is ok, but not the best and I was hoping some one here might
want to help me out?
This doesn't work for example...

histo = {[0,0,0]:1, [0,0,1]:2}
Would indicate that there is one sample at 0,0,0 and two samples at
0,0,1
but python tells me TypeError: list objects are unhashable

So any suggestions would be welcome.
TIA.

Feb 2 '06 #1
12 2855
KraftDiner <bo*******@yaho o.com> wrote:
...
histo = {[0,0,0]:1, [0,0,1]:2}
Would indicate that there is one sample at 0,0,0 and two samples at
0,0,1
but python tells me TypeError: list objects are unhashable

So any suggestions would be welcome.


Use tuples, not lists, as your keys:

histo = {(0,0,0):1, (0,0,1):2}
Alex
Feb 2 '06 #2
Cool.
Ok so my histogram class had two methods 1) To increment a point and 2)
to get the point.

def class histo:
def __init__(self):
histo = {}
def update(point):
'''searches the dictionary for point and if it exists increment the
value.
if it doesn't exist set the value to 1'''

def get(point):
return self.histo[point]

I'm not sure how to code up the update routine...

Feb 2 '06 #3
On Wed, 2006-02-01 at 19:06 -0800, KraftDiner wrote:
Cool.
Ok so my histogram class had two methods 1) To increment a point and 2)
to get the point.

def class histo:
def __init__(self):
histo = {}
def update(point):
'''searches the dictionary for point and if it exists increment the
value.
if it doesn't exist set the value to 1'''

def get(point):
return self.histo[point]

I'm not sure how to code up the update routine...

--
http://mail.python.org/mailman/listinfo/python-list


def update(point);

if histo.get(point ) != None:
histo[point] = histo[point] + 1

Regards,

John
--
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

Feb 2 '06 #4
KraftDiner <bo*******@yaho o.com> wrote:
Cool.
Ok so my histogram class had two methods 1) To increment a point and 2)
to get the point.

def class histo:
def __init__(self):
histo = {}
def update(point):
'''searches the dictionary for point and if it exists increment the
value.
if it doesn't exist set the value to 1'''
def update(self, point):
self.histo[point] = 1 + self.histo.get( point, 0)

def get(point):
def (self, point):

actually.
return self.histo[point]

I'm not sure how to code up the update routine...


See above.
Alex
Feb 2 '06 #5
The dictionary is sorted by the point key.
Is there a way to sort the dictionary by the value?
Seems to me this goes against the purpose of a dictionary but....
thats what I need to do..

Feb 2 '06 #6
KraftDiner wrote:
The dictionary is sorted by the point key.
Is there a way to sort the dictionary by the value?
Seems to me this goes against the purpose of a dictionary but....
thats what I need to do..


Well, it's probably not all that efficient, but it is simple code:

sortedList = [(v, k) for k, v in self.histo.item s()]
sortedList.sort ()

Should do it...

-Kirk McDonald
Feb 2 '06 #7
Ok so this is nice.. Just one thing.. When you try to get a value from
a dictionary
and it isn't found in the dictionary things go bad...

Take this for example:

class histogram(objec t):
def __init__(self):
self.histo = {}

def update(self, point):
if self.histo.get( point) != None:
self.histo[point] = self.histo[point] + 1
else:
self.histo[point] = 1

def get(self, point):
return self.histo[point]
hist = histogram()
hist.update((0, 0,0))
hist.update((0, 0,1))
hist.update((0, 0,1))
hist.get((0,0,0 ))
hist.get((0,0,1 ))
hist.get((0,0,2 ))

spews out this error:

Traceback (most recent call last):
File "histogram. py", line 21, in ?
hist.get((0,0,2 ))
File "histogram. py", line 12, in get
return self.histo[point]
KeyError: (0, 0, 2)

Feb 2 '06 #8
KraftDiner wrote:
Ok so this is nice.. Just one thing.. When you try to get a value from
a dictionary
and it isn't found in the dictionary things go bad...

Take this for example:

class histogram(objec t):
def __init__(self):
self.histo = {}

def update(self, point):
if self.histo.get( point) != None:
self.histo[point] = self.histo[point] + 1
else:
self.histo[point] = 1

def get(self, point):
return self.histo[point]
hist = histogram()
hist.update((0, 0,0))
hist.update((0, 0,1))
hist.update((0, 0,1))
hist.get((0,0,0 ))
hist.get((0,0,1 ))
hist.get((0,0,2 ))

spews out this error:

Traceback (most recent call last):
File "histogram. py", line 21, in ?
hist.get((0,0,2 ))
File "histogram. py", line 12, in get
return self.histo[point]
KeyError: (0, 0, 2)


Try this:

class histogram(objec t):
def __init__(self):
self.histo = {}

def update(self, point):
self.histo[point] = self.histo.get( point, 0) + 1

def get(self, point):
return self.histo.get( point, 0)

dict.get's default return value is your friend.

-Kirk McDonald
Feb 2 '06 #9
Hi
you can use has_key() to check whether
the particular value is in the key set or not.
a = {}
a[1] = 22
a[2] = 33
a {1: 22, 2: 33} a.has_key(3) False a.has_key(1) True


-raj
KraftDiner wrote: Ok so this is nice.. Just one thing.. When you try to get a value from
a dictionary
and it isn't found in the dictionary things go bad...

Take this for example:

class histogram(objec t):
def __init__(self):
self.histo = {}

def update(self, point):
if self.histo.get( point) != None:
self.histo[point] = self.histo[point] + 1
else:
self.histo[point] = 1

def get(self, point):
return self.histo[point]
hist = histogram()
hist.update((0, 0,0))
hist.update((0, 0,1))
hist.update((0, 0,1))
hist.get((0,0,0 ))
hist.get((0,0,1 ))
hist.get((0,0,2 ))

spews out this error:

Traceback (most recent call last):
File "histogram. py", line 21, in ?
hist.get((0,0,2 ))
File "histogram. py", line 12, in get
return self.histo[point]
KeyError: (0, 0, 2)


Feb 2 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
6702
by: Oracle3001 | last post by:
Hi All, I am trying to use JAI to build a histogram of an image i have. I have posted the code below, and the error I get at runtime. I have taken the code from the offical java examples, so I am really puzzled why it doesn't work public PlanarImage thresholding (PlanarImage source) { // set up the histogram int bins = { 256 }; double low = { 0.0D };
1
3075
by: bleh | last post by:
....to include a removeData(datatoremove) function, to mirror the existing addData(datatoadd) function. If anybody knows of somewhere where this has been done already, if you could point me in that direction I'd be much obliged... TIA
2
2306
by: kevin parks | last post by:
hi. I've been banging my head against this one a while and have asked around, and i am throwing this one out there in the hopes that some one can shed some light on what has turned out to be a tough problem for me (though i am getting closer). i have been mucking with a lot of data in a dictionary that looks like:
6
1834
by: Dan Stromberg | last post by:
Does anyone have a python implementation (or python C/C+ extension) that would allow me to perform set operations (union, intersection, difference, number of elements, &c) over very large collections of integers? Some of the sets may have over 10**11 (probably less than 10**13 though) integers in them, but there will tend to be runs of integers being included or not included, so there might be 10**5 consecutive integers included, then...
10
5694
by: draghuram | last post by:
Hi, Is there any special support for sparse file handling in python? My initial search didn't bring up much (not a thorough search). I wrote the following pice of code: options.size = 6442450944 options.ranges = fd = open("testfile", "w") fd.seek(options.size-1)
13
1974
by: momobear | last post by:
hi, is there a way to let python operate on sequence of int or short? In C, we just need declare a point, then I could get the point value, just like: short* k = buffer, //k is a point to a sequence point of short. short i = *k++, but python is a dynamic language, a = buffer i = ? I don't know how to continue, what's a? a seems to be a str?
2
4281
by: Daniel Nogradi | last post by:
How does one do a histogram on only a part of an image? This is what I found in the PIL documentation about histogram( ): """ im.histogram(mask) =list Returns a histogram for those parts of the image where the mask image is non-zero. The mask image must have the same size as the image, and be either a bi-level image (mode "1") or a greyscale image ("L"). """
5
2923
by: arnuld | last post by:
this is a programme that counts the "lengths" of each word and then prints that many of stars(*) on the output . it is a modified form of K&R2 exercise 1-13. the programme runs without any compile-error BUT it has a semantic BUG: what i WANT: I want it to produce a "horizontal histogram" which tells how many characters were in the 1st word, how many characters were in the second word by writing equal number of stars, *, at the...
13
2372
by: Bruza | last post by:
I need to implement a "random selection" algorithm which takes a list of as input. Each of the (obj, prob) represents how likely an object, "obj", should be selected based on its probability of "prob".To simplify the problem, assuming "prob" are integers, and the sum of all "prob" equals 100. For example, items = The algorithm will take a number "N", and a list as
0
9715
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9595
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10600
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10354
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7642
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6867
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4313
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3835
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3002
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.