[cig-commits] r7517 - cs/cigma/branches/cigma-0.9/sandbox/python/cigma

luis at geodynamics.org luis at geodynamics.org
Tue Jun 26 10:14:38 PDT 2007


Author: luis
Date: 2007-06-26 10:14:38 -0700 (Tue, 26 Jun 2007)
New Revision: 7517

Added:
   cs/cigma/branches/cigma-0.9/sandbox/python/cigma/utils.py
Log:
darcs patch:
  * Created cigma.utils python module, and added readfromfile() and readfrom()
  to simplify the process of parsing some column-based ascii data files



Added: cs/cigma/branches/cigma-0.9/sandbox/python/cigma/utils.py
===================================================================
--- cs/cigma/branches/cigma-0.9/sandbox/python/cigma/utils.py	2007-06-26 17:13:37 UTC (rev 7516)
+++ cs/cigma/branches/cigma-0.9/sandbox/python/cigma/utils.py	2007-06-26 17:14:38 UTC (rev 7517)
@@ -0,0 +1,47 @@
+
+def readfromfile(fp, x, **kw):
+    """
+    Given a file object to an ascii file with data in a column-based
+    format. Note that x is assumed to be a numpy array with rank 2.
+    As many rows will be read from the file as can fit along the extent
+    of the first dimension of x.
+
+    The following keyword arguments may be specified
+
+      skip - skip this many lines at beginning
+      factor - conversion factor to apply to each value
+      range - slice representing range of columns to copy into array row
+      dtype - datatype factory for the column data (float or int)
+      offset - whether to apply an index offset (0 or 1)
+    """
+    (n,d) = x.shape
+    skip = kw.get('skip', 0)
+    factor = kw.get('factor', 1.0)
+    range = kw.get('range', slice(1,4))
+    dtype = kw.get('dtype', float)
+    offset = kw.get('offset', 1)
+    # skip the specified number of lines
+    for i in xrange(skip):
+        fp.readline()
+    # read n lines into array
+    for i in xrange(n):
+        line = fp.readline()
+        cols = line.split()
+        k = int(cols[0]) - offset
+        x[k] = map(dtype, cols[range])
+    # finally, apply necessary corrections to x
+    if dtype is int:
+        x -= offset
+    elif dtype is float:
+        x *= factor
+    return
+
+
+def readfrom(filename, x, **kw):
+    print "Reading file", filename
+    fp = open(filename, 'r')
+    readfromfile(fp, x, **kw)
+    fp.close()
+    return
+
+readfrom.__doc__ = readfromfile.__doc__



More information about the cig-commits mailing list