changeset 69:4954c14457f2

implement stripdict, narrowlist and simplify
author Jaroslav Hajek <highegg@gmail.com>
date Wed, 17 Jun 2009 11:49:14 +0200
parents 2f4d6286fb36
children e3de0f6f1552
files ChangeLog package/pytave.py
diffstat 2 files changed, 63 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/ChangeLog	Wed Jun 17 11:05:20 2009 +0200
+++ b/ChangeLog	Wed Jun 17 11:49:14 2009 +0200
@@ -1,3 +1,9 @@
+2009-06-17  Jaroslav Hajek  <highegg@gmail.com>
+
+	* package/pytave.py (stripdict): New function.
+	(narrowlist): New function.
+	(simplify): New function.
+
 2009-06-16  Jaroslav Hajek  <highegg@gmail.com>
 
 	* octave_to_python.cc 
--- a/package/pytave.py	Wed Jun 17 11:05:20 2009 +0200
+++ b/package/pytave.py	Wed Jun 17 11:49:14 2009 +0200
@@ -146,6 +146,63 @@
 
 	return _pytave.eval(nargout, code, silent)
 
+def stripdict(dictarray):
+    """A helper function to convert structures obtained from Octave.
+    Because in Octave, all structs are also arrays, they are returned
+    as dicts of object arrays. In the common case of a 1x1 struct, 
+    stripdict strips the values."""
+    
+    sdict = {}
+    for key in dictarray:
+	sdict[key] = dictarray[key][0,0]
+    return sdict
+
+def narrowlist(objarray):
+    """A helper function to convert cell arrays obtained from Octave.
+    Octave cells are returned as Numeric object arrays. This function
+    will flatten the array and convert it into a 1D list."""
+
+    return Numeric.ravel(objarray).tolist()
+
+def simplify(obj):
+    """A helper function to convert results obtained from Octave.
+    This will convert all 1x1 arrays to scalars, vectors to 1D arrays,
+    1xN and 0x0 character arrays to strings, 1xN, Nx1 and 0x0 cell
+    arrays to lists, and strip scalar dicts. It will work recursively."""
+
+    def vectordims(dims,column_allowed = True):
+	return (len(dims) == 2 and 
+		((dims[0] == 1 or (column_allowed and dims[1] == 1)) or
+		(dims[0] == 0 and dims[1] == 0)))
+
+    if isinstance(obj,Numeric.ArrayType):
+	tc = obj.typecode()
+	if tc == 'O':
+	    if vectordims(Numeric.shape(obj)):
+		return map(simplify,narrowlist(obj))
+	elif tc == 'c':
+	    if vectordims(Numeric.shape(obj), False):
+		return obj.tostring()
+	else:
+	    dims = Numeric.shape(obj)
+	    if dims == (1,1):
+		return obj.toscalar()
+	    elif vectordims(dims):
+		return Numeric.ravel(obj)
+    elif isinstance(obj,dict):
+	sobj = {}
+	for key in obj:
+	    sval = simplify(obj[key])
+	    if isinstance(sval,list) and len(sval) == 1:
+		sval = sval[0]
+	    sobj[key] = sval
+	return sobj
+    elif isinstance(obj,tuple):
+	return tuple(map(simplify,obj))
+    ## default.
+    return obj
+
+
 def addpath(*arguments):
 	"""See Octave documentation"""
 	return _pytave.feval(1, "addpath", arguments)[0]