[MATRIX-SIG] Data import into Numeric arrays

Konrad Hinsen hinsen@ibs.ibs.fr
Mon, 2 Feb 1998 20:53:20 +0100


> The data are stored as ordinary ASCII files with each line being one
> timepoint and its associated data.  Currently, the only ways I know to get
> this data into NumPy  all involve reading the data into a Python list (say,
> via readline or readlines), splitting each line into fields, converting the
> string representations of numbers to actual numbers, then using the array()
> function to build an array.  This seems really inefficient.  What I'd like

Right; someone should write a nice C module for ASCII I/O of arrays.
In the meantime, I can offer a ready and working "slow" version, so
you can at least check how bad it is for you:

---------------------------------------------------------------------------
# Array I/O to text files
#
# Written by Konrad Hinsen <hinsen@ibs.ibs.fr>
# last revision: 1998-1-29
#

from TextFile import TextFile
import string, Numeric

def readArray(filename):
    data = []
    for line in TextFile(filename):
	data.append(map(eval, string.split(line)))
    a = Numeric.array(data)
    if a.shape[0] == 1 or a.shape[1] == 1:
	a = Numeric.ravel(a)
    return a

def writeArray(a, filename):
    file = TextFile(filename, 'w')
    if len(a.shape) == 1:
	a = a[:, Numeric.NewAxis]
    for line in a:
	for element in line:
	    file.write(`element` + ' ')
	file.write('\n')
    file.close()
---------------------------------------------------------------------------

-- 
-------------------------------------------------------------------------------
Konrad Hinsen                          | E-Mail: hinsen@ibs.ibs.fr
Laboratoire de Dynamique Moleculaire   | Tel.: +33-4.76.88.99.28
Institut de Biologie Structurale       | Fax:  +33-4.76.88.54.94
41, av. des Martyrs                    | Deutsch/Esperanto/English/
38027 Grenoble Cedex 1, France         | Nederlands/Francais
-------------------------------------------------------------------------------

_______________
MATRIX-SIG  - SIG on Matrix Math for Python

send messages to: matrix-sig@python.org
administrivia to: matrix-sig-request@python.org
_______________