473,657 Members | 2,447 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

NumPy arrays that use memory allocated from other libraries or tools


I wanted to point anybody interested to a blog post that describes a
useful pattern for having a NumPy array that points to the memory
created by a different memory manager than the standard one used by
NumPy. The pattern shows how to create a NumPy array that points to
previously allocated memory and then shows how to construct an object
that allows the correct deallocator to be called when the NumPy array is
freed.

This may be useful if you are wrapping code that has it's own memory
management scheme. Comments and feedback is welcome.

The post is

http://blog.enthought.com/?p=62
Best regards,

-Travis Oliphant

Sep 10 '08 #1
2 2778
On Sep 10, 6:39*am, Travis Oliphant <oliphant.tra.. .@ieee.orgwrote :
I wanted to point anybody interested to a blog post that describes a
useful pattern for having a NumPy array that points to the memory
created by a different memory manager than the standard one used by
NumPy.

Here is something similar I have found useful:

There will be a new module in the standard library called
'multiprocessin g' (cf. the pyprocessing package in cheese shop). It
allows you to crerate multiple processes (as opposed to threads) for
concurrency on SMPs (cf. the dreaded GIL).

The 'multiprocessin g' module let us put ctypes objects in shared
memory segments (processing.Arr ay and processing.Valu e). It has it's
own malloc, so there is no 4k (one page) lower limit on object size.
Here is how we can make a NumPy ndarray view the shared memory
referencey be these objects:

try:
import processing
except:
import multiprocessing as processing

import numpy, ctypes

_ctypes_to_nump y = {
ctypes.c_char : numpy.int8,
ctypes.c_wchar : numpy.int16,
ctypes.c_byte : numpy.int8,
ctypes.c_ubyte : numpy.uint8,
ctypes.c_short : numpy.int16,
ctypes.c_ushort : numpy.uint16,
ctypes.c_int : numpy.int32,
ctypes.c_uint : numpy.int32,
ctypes.c_long : numpy.int32,
ctypes.c_ulong : numpy.int32,
ctypes.c_float : numpy.float32,
ctypes.c_double : numpy.float64
}

def shmem_as_ndarra y( array_or_value ):

""" view processing.Arra y or processing.Valu e as ndarray """

obj = array_or_value. _obj
buf = obj._wrapper.ge tView()
try:
t = _ctypes_to_nump y[type(obj)]
return numpy.frombuffe r(buf, dtype=t, count=1)
except KeyError:
t = _ctypes_to_nump y[obj._type_]
return numpy.frombuffe r(buf, dtype=t)

With this simple tool we can make processes created by multiprocessing
work with ndarrays that reference the same shared memory segment. I'm
doing some scalability testing on this. It looks promising :)





Sep 10 '08 #2
sturlamolden wrote:
On Sep 10, 6:39 am, Travis Oliphant <oliphant.tra.. .@ieee.orgwrote :
>I wanted to point anybody interested to a blog post that describes a
useful pattern for having a NumPy array that points to the memory
created by a different memory manager than the standard one used by
NumPy.


Here is something similar I have found useful:

There will be a new module in the standard library called
'multiprocessin g' (cf. the pyprocessing package in cheese shop). It
allows you to crerate multiple processes (as opposed to threads) for
concurrency on SMPs (cf. the dreaded GIL).

The 'multiprocessin g' module let us put ctypes objects in shared
memory segments (processing.Arr ay and processing.Valu e). It has it's
own malloc, so there is no 4k (one page) lower limit on object size.
Here is how we can make a NumPy ndarray view the shared memory
referencey be these objects:

try:
import processing
except:
import multiprocessing as processing

import numpy, ctypes

_ctypes_to_nump y = {
ctypes.c_char : numpy.int8,
ctypes.c_wchar : numpy.int16,
ctypes.c_byte : numpy.int8,
ctypes.c_ubyte : numpy.uint8,
ctypes.c_short : numpy.int16,
ctypes.c_ushort : numpy.uint16,
ctypes.c_int : numpy.int32,
ctypes.c_uint : numpy.int32,
ctypes.c_long : numpy.int32,
ctypes.c_ulong : numpy.int32,
ctypes.c_float : numpy.float32,
ctypes.c_double : numpy.float64
}

def shmem_as_ndarra y( array_or_value ):

""" view processing.Arra y or processing.Valu e as ndarray """

obj = array_or_value. _obj
buf = obj._wrapper.ge tView()
try:
t = _ctypes_to_nump y[type(obj)]
return numpy.frombuffe r(buf, dtype=t, count=1)
except KeyError:
t = _ctypes_to_nump y[obj._type_]
return numpy.frombuffe r(buf, dtype=t)

With this simple tool we can make processes created by multiprocessing
work with ndarrays that reference the same shared memory segment. I'm
doing some scalability testing on this. It looks promising :)

Hey, that is very neat.

Thanks for pointing me to it. I was not aware of this development in
multiprocessing .
-Travis

Sep 11 '08 #3

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

Similar topics

29
4384
by: keredil | last post by:
Hi, Will the memory allocated by malloc get released when program exits? I guess it will since when the program exits, the OS will free all the memory (global, stack, heap) used by this process. Is it correct?
16
4855
by: Ankit Raizada | last post by:
Is there a way to know how much memory has being allocated(dynamically) to a pointer. Related to this, can we find out has a pointer already been freed? I am using VC++
6
2309
by: lovecreatesbeauty | last post by:
Hello experts, 1. Does C guarantee the data layout of the memory allocated by malloc function on the heap. I mean, for example, if I allocate a array of 100 elements of structure, can I always reference a correct/valid structure member upon that allocated memory? If I allocate memory, for example like this way:
4
2653
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
1
2388
by: Rolf Wester | last post by:
Hi, I want to concatenate two numpy arrays with shape (n1,n2) and (n1,n3) into a single array with shape (n1,n2+n3). I guess there is an elegant way to do this but I couldn't figure it out. So any help is very much appreciated. Regards Rolf
13
2516
by: pratap | last post by:
how could i find out how much memory is blocked(or has been allocated to a pointer) consider, int *p=new int; or int *p=new int; suppose i dont know the right hand side of the statement i.e. new int or new int or new int (where n is calculated during
2
4263
by: rathankar | last post by:
dear friends thanks for the mail sent today i have one more question: 1. since in perl arrays need not be declared, , what is the maximum limit of elements an array could have? 2. in java/ c/ c++, if we declare an array with 5 elements it can have utmost 5 elements, and we could also know what is the memory allocated for an array. how do we know it in perl 3. how many bytes does a scalar , array, list and hashes occupy. though most of the...
6
2032
by: Praetorian | last post by:
This is actually 2 questions: The first one: I have a function (FuncA) calling another (FuncB) with a set of parameters which also includes an int * initialized to NULL before the call. Now FuncB looks at the other parameters and decides whether or not to allocated memory to the int * passed to it (using calloc()). One of the other parameters passed is a structure and if FuncB does allocate memory it'll point one of the members of this...
1
4957
by: csgirlie | last post by:
I'm trying to store or arrange three sets of two-dimensional data into three 2xN matrices that are stored as NumPy arrays. import os # for file handling functions import numpy as np # for array/matrix processing import matplotlib.pyplot as plt # for general plotting from mpl_toolkits.mplot3d import axes3d # for 3d plotting wordList= numFiles = 0 numDataSets = numVectors = sizeVector = 0
6
3149
by: ayatsynych | last post by:
Hi, Is there any way to determine at run-time if block of memory allocated on stack or on heap? For example: BYTE* pData = new BYTE; BYTE data; BYTE* pData1 = &data; //Hot to determine that pData is on heap, and pData1 is //on stack?
0
8397
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
8732
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
8503
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
8605
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
7333
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
6167
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
5632
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();...
0
4158
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
1620
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.