2
from scipy_base import *
4
def abut (source, *args):
5
"""\nLike the |Stat abut command. It concatenates two arrays column-wise
6
and returns the result. CAUTION: If one array is shorter, it will be
7
repeated until it is as long as the other.
9
Format: abut (source, args) where args=any # of arrays
10
Returns: an array as long as the LONGEST array past, source appearing on the
11
'left', arrays in <args> attached on the 'right'.\n"""
13
source = asarray(source)
14
if len(source.shape)==1:
16
source = N.resize(source,[source.shape[0],width])
18
width = source.shape[1]
20
if len(addon.shape)==1:
22
addon = N.resize(addon,[source.shape[0],width])
24
width = source.shape[1]
25
if len(addon) < len(source):
26
addon = N.resize(addon,[source.shape[0],addon.shape[1]])
27
elif len(source) < len(addon):
28
source = N.resize(source,[addon.shape[0],source.shape[1]])
29
source = N.concatenate((source,addon),1)
34
"""Returns unique items in the FIRST dimension of the passed array. Only
35
works on arrays NOT including string items (e.g., type 'O' or 'c').
37
inarray = asarray(inarray)
38
uniques = N.array([inarray[0]])
39
if len(uniques.shape) == 1: # IF IT'S A 1D ARRAY
40
for item in inarray[1:]:
41
if N.add.reduce(N.equal(uniques,item).flat) == 0:
43
uniques = N.concatenate([uniques,N.array[N.NewAxis,:]])
45
uniques = N.concatenate([uniques,N.array([item])])
46
else: # IT MUST BE A 2+D ARRAY
47
if inarray.typecode() != 'O': # not an Object array
48
for item in inarray[1:]:
49
if not N.sum(N.alltrue(N.equal(uniques,item),1)):
51
uniques = N.concatenate( [uniques,item[N.NewAxis,:]] )
52
except TypeError: # the item to add isn't a list
53
uniques = N.concatenate([uniques,N.array([item])])
55
pass # this item is already in the uniques array
56
else: # must be an Object array, alltrue/equal functions don't work
57
for item in inarray[1:]:
59
for unq in uniques: # NOTE: cmp --> 0=same, -1=<, 1=>
60
test = N.sum(abs(N.array(map(cmp,item,unq))))
61
if test == 0: # if item identical to any 1 row in uniques
62
newflag = 0 # then not a novel item to add
66
uniques = N.concatenate( [uniques,item[N.NewAxis,:]] )
67
except TypeError: # the item to add isn't a list
68
uniques = N.concatenate([uniques,N.array([item])])
71
def colex (a,indices,axis=1):
72
"""\nExtracts specified indices (a list) from passed array, along passed
73
axis (column extraction is default). BEWARE: A 1D array is presumed to be a
74
column-array (and that the whole array will be returned as a column).
76
Returns: the columns of a specified by indices\n"""
78
if type(indices) not in [ListType,TupleType,N.ArrayType]:
80
if len(N.shape(a)) == 1:
81
cols = N.resize(a,[a.shape[0],1])
83
cols = N.take(a,indices,axis)
86
def printcc (lst,extra=2):
87
"""\nPrints a list of lists in columns, customized by the max size of items
88
within the columns (max size of items in col, plus 'extra' number of spaces).
89
Use 'dashes' or '\n' in the list(oflists) to print dashes or blank lines,
92
Format: printcc (lst,extra=2)
96
if type(x) <> StringType:
100
if type(lst[0]) not in [ListType,TupleType]:
103
list2print = copy.deepcopy(lst)
104
for i in range(len(lst)):
105
if lst[i] == ['\n'] or lst[i]=='\n' or lst[i]=='dashes':
106
rowstokill = rowstokill + [i]
107
rowstokill.reverse() # delete blank rows from the end
108
for row in rowstokill:
110
maxsize = [0]*len(list2print[0])
111
for col in range(len(list2print[0])):
112
items = colex(list2print,col)
113
items = map(makestr,items)
114
maxsize[col] = max(map(len,items)) + extra
116
if row == ['\n'] or row == '\n':
118
elif row == ['dashes'] or row == 'dashes':
119
dashes = [0]*len(maxsize)
120
for j in range(len(maxsize)):
121
dashes[j] = '-'*(maxsize[j]-2)
122
print lineincustcols(dashes,maxsize)
124
print lineincustcols(row,maxsize)
127
def linexand (a,columnlist,valuelist):
128
"""Returns the rows of an array where col (from columnlist) = val
129
(from valuelist). One value is required for each column in columnlist.
131
Returns: the rows of a where columnlist[i]=valuelist[i] for ALL i\n"""
134
if type(columnlist) not in [ListType,TupleType,N.ArrayType]:
135
columnlist = [columnlist]
136
if type(valuelist) not in [ListType,TupleType,N.ArrayType]:
137
valuelist = [valuelist]
139
for i in range(len(columnlist)):
140
if type(valuelist[i])==StringType:
141
critval = '\'' + valuelist[i] + '\''
143
critval = str(valuelist[i])
144
criterion = criterion + ' x['+str(columnlist[i])+']=='+critval+' and'
145
criterion = criterion[0:-3] # remove the "and" after the last crit
146
return adm(a,criterion)
149
def collapse (a,keepcols,collapsecols,stderr=0,ns=0,cfcn=None):
150
"""Averages data in collapsecol, keeping all unique items in keepcols
151
(using unique, which keeps unique LISTS of column numbers), retaining
152
the unique sets of values in keepcols, the mean for each. If the sterr or
153
N of the mean are desired, set either or both parameters to 1.
155
Returns: unique 'conditions' specified by the contents of columns specified
156
by keepcols, abutted with the mean(s) of column(s) specified by
163
avgcol = colex(a,collapsecols)
167
if type(keepcols) not in [ListType,TupleType,N.ArrayType]:
168
keepcols = [keepcols]
169
values = colex(a,keepcols) # so that "item" can be appended (below)
170
uniques = unique(values) # get a LIST, so .sort keeps rows intact
174
if type(item) not in [ListType,TupleType,N.ArrayType]:
176
tmprows = linexand(a,keepcols,item)
177
for col in collapsecols:
178
avgcol = colex(tmprows,col)
179
item.append(cfcn(avgcol))
182
item.append(stats.sterr(avgcol))
186
item.append(len(avgcol))
189
new_a = N.array(newlist)
191
new_a = N.array(newlist,'O')
196
if type(item) <> StringType:
200
def lineincustcols (inlist,colsizes):
201
"""\nReturns a string composed of elements in inlist, with each element
202
right-aligned in a column of width specified by a sequence colsizes. The
203
length of colsizes must be greater than or equal to the number of columns in
206
Format: lineincustcols (inlist,colsizes)
207
Returns: formatted string created from inlist\n"""
210
for i in range(len(inlist)):
211
if type(inlist[i]) <> StringType:
212
item = str(inlist[i])
216
if size <= colsizes[i]:
217
for j in range(colsizes[i]-size):
218
outstr = outstr + ' '
219
outstr = outstr + item
221
outstr = outstr + item[0:colsizes[i]+1]
225
def list2string (inlist):
226
"""\nConverts a 1D list to a single long string for file output, using
227
the string.join function.
229
Format: list2string (inlist)
230
Returns: the string created from inlist\n"""
232
stringlist = map(makestr,inlist)
233
return string.join(stringlist)