473,756 Members | 1,969 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

numpy migration (also posted to numpy-discussion)

Hello,
Since moving to numpy I've had a few problems with my existing
code. It basically revolves around the numpy scalar types. e.g.

------------------------------------------------
>>import Numeric as N
a = N.array([[0,1],[2,3]])
a
array([[0, 1],
[2, 3]])
>>i = a[0,0]
1/i
Traceback (most recent call last):
File "<pyshell#3 0>", line 1, in -toplevel-
1/i
ZeroDivisionErr or: integer division or modulo by zero
>>b = a * 1.5
b
array([[ 0. , 1.5],
[ 3. , 4.5]])
>>N.floor(b)
array([[ 0., 1.],
[ 3., 4.]])
>>============= =============== ==== RESTART
=============== =============== ==
>>import numpy as N
a = N.array([[0,1],[2,3]])
a
array([[0, 1],
[2, 3]])
>>i = a[0,0]
1/i
0
>>b = a * 1.5
b
array([[ 0. , 1.5],
[ 3. , 4.5]])
>>N.floor(b)
array([[ 0., 1.],
[ 3., 4.]])
>>a = N.array([[0,1],[2,3]], dtype='O')
a
array([[0, 1],
[2, 3]], dtype=object)
>>i = a[0,0]
1/i
Traceback (most recent call last):
File "<pyshell#4 5>", line 1, in -toplevel-
1/i
ZeroDivisionErr or: integer division or modulo by zero
>>b = a * 1.5
b
array([[0.0, 1.5],
[3.0, 4.5]], dtype=object)
>>N.floor(b)
Traceback (most recent call last):
File "<pyshell#4 8>", line 1, in -toplevel-
N.floor(b)
AttributeError: 'float' object has no attribute 'floor'
>>>
----------------------------------------------

An additional problem involves classes that have e.g. __rmul__ methods
defined and are sufficiently similar to numpy arrays that my classes'
__rmul__ methods are not invoked when using numpy scalars.
Using the 'O' dtype gives me Python types that raise zero division
errors appropriately (for my code) and the desired calls to e.g.
__rmul__ methods, but reduced functionality in other repects.

I might (I hope) be missing something obvious; but it seems like, to be
safe, I'm going to have to do a lot of explicit conversions to Python
types (or abandon catching zero division errors, and documenting some of
my classes to highlight that whether scalar * a equals a * scalar
depends on whether a.__rmul__ is called, which depends on the type of
scalar).

I suppose I might get round both issues by subclassing existing numpy
dtypes. Any ideas? Cheers. TIA.

Duncan
Apr 23 '07 #1
3 2207
Duncan Smith wrote:
Hello,
Since moving to numpy I've had a few problems with my existing
code. It basically revolves around the numpy scalar types. e.g.
You will probably get more help on the numpy discussion list:

nu************* *@scipy.org
You are encountering problems because numpy scalar types don't raise
errors (unless you have set the appropriate hardware flag using
numpy.seterr).

You can get Python scalars out of NumPy arrays if you really want them
using (for example...)

a.item(0,0)

>
An additional problem involves classes that have e.g. __rmul__ methods
defined and are sufficiently similar to numpy arrays that my classes'
__rmul__ methods are not invoked when using numpy scalars.
Could you please post an example showing the problem?
>
I might (I hope) be missing something obvious; but it seems like, to be
safe, I'm going to have to do a lot of explicit conversions to Python
types (or abandon catching zero division errors, and documenting some of
my classes to highlight that whether scalar * a equals a * scalar
depends on whether a.__rmul__ is called, which depends on the type of
scalar).
numpy scalars are try a lot more things before giving up on
multiplication and letting the other class have a stab at it.

Post your problems to the numpy discussion list for better help and more
discussion.
-Travis

Apr 24 '07 #2
Travis E. Oliphant wrote:
Duncan Smith wrote:
>Hello,
Since moving to numpy I've had a few problems with my existing
code. It basically revolves around the numpy scalar types. e.g.

You will probably get more help on the numpy discussion list:

nu************* *@scipy.org
You are encountering problems because numpy scalar types don't raise
errors (unless you have set the appropriate hardware flag using
numpy.seterr).
Aha!
You can get Python scalars out of NumPy arrays if you really want them
using (for example...)

a.item(0,0)

>>
An additional problem involves classes that have e.g. __rmul__ methods
defined and are sufficiently similar to numpy arrays that my classes'
__rmul__ methods are not invoked when using numpy scalars.

Could you please post an example showing the problem?
I'll try to post a minimal example tomorrow. But they are classes that
have an ndarray as an attribute, and with __getitem__ and __setitem__
methods which simply call the corresponding array methods. Maybe that's
enough to account for the behaviour? I'll check tomorrow.
>>
I might (I hope) be missing something obvious; but it seems like, to be
safe, I'm going to have to do a lot of explicit conversions to Python
types (or abandon catching zero division errors, and documenting some of
my classes to highlight that whether scalar * a equals a * scalar
depends on whether a.__rmul__ is called, which depends on the type of
scalar).

numpy scalars are try a lot more things before giving up on
multiplication and letting the other class have a stab at it.

Post your problems to the numpy discussion list for better help and more
discussion.
Yes, I have done. But it's awaiting moderation; presumably because I
posted using a different e-mail address than the one I registered with
(I wasn't thinking). Thanks for the reply.

Duncan
Apr 24 '07 #3
Travis E. Oliphant wrote:
Duncan Smith wrote:
>Hello,
Since moving to numpy I've had a few problems with my existing
code. It basically revolves around the numpy scalar types. e.g.

You will probably get more help on the numpy discussion list:

nu************* *@scipy.org
You are encountering problems because numpy scalar types don't raise
errors (unless you have set the appropriate hardware flag using
numpy.seterr).
Unfortunately it seems to raise a FloatingPointEr ror.
>>import numpy as N
N.__version __
'1.0.1'
>>a = N.array([[0,1],[2,3]])
a
array([[0, 1],
[2, 3]])
>>i = a[0,0]
1/i
0
>>N.seterr(divi de='raise')
{'over': 'print', 'divide': 'print', 'invalid': 'print', 'under': 'ignore'}
>>1/i
Traceback (most recent call last):
File "<pyshell#9 >", line 1, in <module>
1/i
FloatingPointEr ror: divide by zero encountered in long_scalars
You can get Python scalars out of NumPy arrays if you really want them
using (for example...)

a.item(0,0)

>>
An additional problem involves classes that have e.g. __rmul__ methods
defined and are sufficiently similar to numpy arrays that my classes'
__rmul__ methods are not invoked when using numpy scalars.

Could you please post an example showing the problem?
[snip]

-----------------example.py--------------------

from __future__ import division

import numpy

class MyClass(object) :

def __init__(self, arr, labels):
self.arr = arr
self.labels = labels

def __repr__(self):
return numpy.array2str ing(self.arr, separator=', ') +
repr(self.label s)

def __len__(self):
return len(self.labels )

def __getitem__(sel f, key):
return self.arr[key]

def __setitem__(sel f, key, item):
self.arr[key] = item

def __mul__(self, other):
return self.__class__( self.arr * other, self.labels)

__rmul__ = __mul__

----------------------------------------------------
>>import example
import numpy as N
ex = example.MyClass (N.array([[6,7],[8,9]]), ['axis0', 'axis1'])
i = ex.arr[0,0]
ex
[[6, 7],
[8, 9]]['axis0', 'axis1']
>>ex * i
[[36, 42],
[48, 54]]['axis0', 'axis1']
>>i * ex
array([[36, 42],
[48, 54]])
>>>

It seems that it requires having __len__, __setitem__ and __getitem__
defined to get the undesired behaviour. Cheers.

Duncan
Apr 25 '07 #4

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

Similar topics

2
2157
by: neilmcguigan | last post by:
this is more of a text parsing/regex kind of question, but i figured i'd start here. please let me know if this should go somewhere else. I'd like to implement google-like search syntax, a la http://www.google.ca/help/refinesearch.html so a text query like this: ("google search" "regular expressions") OR (syntax text) aSpecificField:somevalue
20
2584
by: mclaugb | last post by:
Has anyone recompiled the Scientific Computing package using NumPy instead of Numeric? I need a least squares algorithm and a Newton Rhaphson algorithm which is contained in Numeric but all the documentation out there says that Numeric is crap and all code should be using NumPy. Thanks, Bryan
2
1277
by: Boris Borcic | last post by:
after a while trying to find the legal manner to file numpy bug reports, since it's a simple one, I thought maybe a first step is to describe the bug here. Then maybe someone will direct me to the right channel. So, numpy appears not to correctly compute bitwise_and.reduce and bitwise_or.reduce : instead of reducing over the complete axis, these methods only take the extremities into account. Illustration : >>> from numpy import * >>>...
4
2659
by: sonjaa | last post by:
Hi last week I posted a problem with running out of memory when changing values in NumPy arrays. Since then I have tried many different approaches and work-arounds but to no avail. I was able to reduce the code (see below) to its smallest size and still have the problem, albeit at a slower rate. The problem appears to come
15
2525
by: greg.landrum | last post by:
After using numeric for almost ten years, I decided to attempt to switch a large codebase (python and C++) to using numpy. Here's are some comments about how that went. - The code to automatically switch python stuff over just kind of works. But it was a 90% solution, I could do the rest by hand. Of course, the problem is that then the code is still using the old numeric API, so it's not a long term solution. Unfortunately, to switch to...
2
2796
by: robert | last post by:
in Gnuplot (Gnuplot.utils) the input array will be converted to a Numeric float array as shown below. When I insert a numpy array into Gnuplot like that below, numbers 7.44 are cast to 7.0 Why is this and what should I do ? Is this bug in numpy or in Numeric? >>m #numpy array array(, , , ..., ,
2
3969
by: Chris Smith | last post by:
Howdy, I'm a college student and for one of we are writing programs to numerically compute the parameters of antenna arrays. I decided to use Python to code up my programs. Up to now I haven't had a problem, however we have a problem set where we are creating a large matrix and finding it's inverse to solve the problem. To invert the matrix I've tried using numpy.numarray.linear_algebra.inverse and...
7
1929
by: vj | last post by:
I've tried to post this to the numpy google group but it seems to be down. My migration seems to be going well. I currently have one issue with using scipy_base.insert. array() array() array(, dtype=int8) array() array()
1
3749
by: Slaunger | last post by:
Hi, This is my first post here, I am looking forward to being here. I have actually posted almost the same question on comp.lang.python: http://groups.google.dk/group/comp.lang.python/browse_thread/thread/2f0e7ee3ad76d5a3/e2eae3719c6e3fe8?hl=en#e2eae3719c6e3fe8 and got some hints at what i could do, but it is a little bit too complicated for me (yet), and i was wondering if there is a simpler way to do this.
0
9455
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
9271
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
10031
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...
0
9869
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9838
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,...
0
9708
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8709
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7242
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...
3
2665
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.