473,769 Members | 7,408 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

In-place array modification

Hello everybody,

Say I have an array (Python array, not Numpy) that contains characters
representing a DNA sequence. Something like
from array import array
s = array('c', "ATAGCTGCT" )
Now I want to calculate the reverse complement of this sequence. I could
make a simple loop:
d = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C'}
s.reverse()
s array('c', 'TCGTCGATA') n = len(s)
for i in range(n): .... s[i] = d[s[i]] s array('c', 'AGCAGCTAT')

But usually DNA sequences are very long, so the loop might take a long
time to finish. So I thought I would use the map function instead:
s = map(lambda c: d[c], s)
s = array('c', s)


But then I am creating memory for s from scratch. So what I would really
like to do is to have a function similar to map, but have it modify the
array in place. Does such a function exist in Python?
Many thanks,

Michiel de Hoon
Human Genome Center, U Tokyo.
Jul 18 '05 #1
3 2354
umdehoon wrote:
Say I have an array (Python array, not Numpy) that contains characters
representing a DNA sequence. Something like
from array import array
s = array('c', "ATAGCTGCT" )
Now I want to calculate the reverse complement of this sequence. I could


The following does not meet your spec (it's not in-place), but might be
worth considering as well:
import array, string
a = array.array("c" , "ATAGCTGCT" )
a.reverse()
t = string.maketran s("ATCG", "TAGC")
array.array("c" , a.tostring().tr anslate(t))

array('c', 'AGCAGCTAT')

Peter
Jul 18 '05 #2
umdehoon wrote:
Say I have an array (Python array, not Numpy) that contains characters for i in range(n):
s[i] = d[s[i]]


For large lists 'range' will affect the performance since it
creates another huge list. You might think about using xrange or
enumerate. With xrange I could replace 10 million bases in
20 seconds whereas I had to kill the test program using
range b/c it started gobbling up resources...

I suspected that psyco might do a good job of optimizing
this kind of looping. Indeed, the same job took less than 3
seconds with psyco enabled.

Istvan.

Jul 18 '05 #3
With 2.4's generator expressions and slice assignment, you should be
able to perform these kinds of operations in-place. You would write
something like
s[:] = (d[si] for si in s)
... unfortunately, this doesn't work.
TypeError: can only assign array (not "generator" ) to array slice

I thought that numarray arrays might accept generators, but I get an odd
error there too:
n = numarray.zeros( (5,))
n[:] = iter(range(5)) Traceback (most recent call last):
File "<stdin>", line 1, in ?
libnumarray.err or: Type object lookup returned NULL for type -1

If you can identify a small set of operations that need to be in-place
(like this simple base-to-base mapping), you could code them in C or
Pyrex---as a bonus, they'll be fast, too. The map() variant is not likely
to be very fast (in fact, I'd be surprised if it was faster than the
inplace for-loop version). string.translat e() would work in this case,
very quickly, but create an extra copy just like the map() solution would.
s = map(d.get, s) might beat s = map(lambda c: d[c], s) but probably not by enough to matter.

Here's a run with my implementation of "itranslate " in Pyrex: from array import array
s = array('c', "ATAGCTGCT" )
t = string.maketran s('ATCG', 'TAGC')
itranslate.itra nslate(s, t)
s

array('c', 'TATCGACGA')

And here's the Pyrex source for itranslate:

cdef extern from "Python.h":
int PyObject_AsWrit eBuffer(object, void **, int *) except -1
int PyString_AsStri ngAndSize(objec t, char **, int *) except -1

def itranslate(obje ct obuf, object ot):
cdef int blen, tlen, i
cdef unsigned char *buf, *t

PyObject_AsWrit eBuffer(obuf, <void **>&buf, &blen)
PyString_AsStri ngAndSize(ot, <char **>&t, &tlen)

if tlen != 256:
raise ValueError, "Translatio n must be length-256 string"

for i from 0 <= i < blen:
buf[i] = t[buf[i]]

On my 650MHz x86 machine, a translation of a 1 megabyte buffer with
itranslate takes 15ms according to "timeit" (that's 66 megs per second,
which doesn't seem that great, but probably beats the plain Python code
handily)

Jeff

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.1 (GNU/Linux)

iD8DBQFA+946Jd0 1MZaTXX0RAvvyAJ 4hgupdX+YLxzMGg 2ijRzIF85dzXACd G4YH
vd35MQG+0Vm2dAi nEIZwP58=
=2ELj
-----END PGP SIGNATURE-----

Jul 18 '05 #4

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

Similar topics

3
6771
by: Curious Expatriate | last post by:
Hi- I'm completely stumped. I'm trying to write some code that will parse a file and rewrite it with all URLs replaced by something else. For example: if the file looks like this: <b>click here</b><a href="http://www.cnn.com">click me</a> ... then the output should be this:
0
4938
by: Ben Eisenberg | last post by:
I'm trying to run a php script setuid. I've tried POSIX_setuid but you have to be root to run this. The files are located on a public access unix system and have me as the owner and nobody as the group. Rather than make them group writable where in anybody could make a script and write to my files i would like to make them setuid. I tried making a c prog with the setuid function. I used chmod and made it setuid. I called it with the system...
2
8564
by: Felix | last post by:
Hi, I've a problem: I want to have the result of my Mysql Query in a Table in my php file. Now I've this: <?
1
8706
by: James | last post by:
What is the best way to update a record in a MYSQL DB using a FORM and PHP ? Where ID = $ID ! Any examples or URLS ? Thanks
1
2946
by: Patrick Schlaepfer | last post by:
Why this code is not working on Solaris 2.8 host. Always getting: PHP Fatal error: swfaction() : getURL('http://www.php.net' ^ Line 1: Reason: 'syntax error' in /.../htdocs/ming2.php on line 28
1
3424
by: phpkid | last post by:
Howdy I've been given conflicting answers about search engines picking up urls like: http://mysite.com/index.php?var1=1&var2=2&var3=3 Do search engines pick up these urls? I've been considering converting a site of mine to PHP-Nuke, but if the individual modules aren't picked up in search engines I'm not going to do it. Thanks phpKid
1
2558
by: lawrence | last post by:
What is the PHP equivalent of messaging, as in Java?
3
4918
by: Quinten Carlson | last post by:
Is there a way to conditionally define a function in php? I'm trying to run a php page 10 times using the include statement, but I get an error because my function is already defined. The docs state that a function cannot be undefined and adding "exit" to the included page doesn't free it up either. Any suggestions? B44CCD21
10
3848
by: lawrence | last post by:
I get the impression that most people who are using objects in their PHP projects are mixing them with procedural code. The design, I think, is one where the procedural code is the client code, and the classes are a library of utility code. As such, when I've asked about how to get globals into objects, I've been told that I should pass them in as the parameters to a method. Easy enough if you have some procedural code. This answer I've...
4
18671
by: Matt Schroeder | last post by:
Does anyone know how to count how many rows are in a mysql table? This is what I have, but it doesn't work right: <? $db = mysql_connect("localhost", "username", "password"); mysql_select_db("database",$db); $sql = "SELECT COUNT(*) FROM table"; $result = mysql_query($sql); echo "$result"; ?>
0
9589
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
10214
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
9996
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
9865
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...
1
7410
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
6674
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
5304
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...
0
5447
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2815
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.