~ubuntu-branches/ubuntu/karmic/python-scipy/karmic

« back to all changes in this revision

Viewing changes to Lib/stats/_support.py

  • Committer: Bazaar Package Importer
  • Author(s): Daniel T. Chen (new)
  • Date: 2005-03-16 02:15:29 UTC
  • Revision ID: james.westby@ubuntu.com-20050316021529-xrjlowsejs0cijig
Tags: upstream-0.3.2
ImportĀ upstreamĀ versionĀ 0.3.2

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
import Numeric as N
 
2
from scipy_base import *
 
3
 
 
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.
 
8
 
 
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"""
 
12
 
 
13
    source = asarray(source)
 
14
    if len(source.shape)==1:
 
15
        width = 1
 
16
        source = N.resize(source,[source.shape[0],width])
 
17
    else:
 
18
        width = source.shape[1]
 
19
    for addon in args:
 
20
        if len(addon.shape)==1:
 
21
            width = 1
 
22
            addon = N.resize(addon,[source.shape[0],width])
 
23
        else:
 
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)
 
30
    return source
 
31
 
 
32
 
 
33
def unique(inarray):
 
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').
 
36
    """
 
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:
 
42
                try:
 
43
                    uniques = N.concatenate([uniques,N.array[N.NewAxis,:]])
 
44
                except TypeError:
 
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)):
 
50
                    try:
 
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])])
 
54
                else:
 
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:]:
 
58
                newflag = 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
 
63
                        break
 
64
                if newflag == 1:
 
65
                    try:
 
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])])
 
69
    return uniques
 
70
 
 
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).
 
75
 
 
76
    Returns: the columns of a specified by indices\n"""
 
77
 
 
78
    if type(indices) not in [ListType,TupleType,N.ArrayType]:
 
79
        indices = [indices]
 
80
    if len(N.shape(a)) == 1:
 
81
        cols = N.resize(a,[a.shape[0],1])
 
82
    else:
 
83
        cols = N.take(a,indices,axis)
 
84
    return cols
 
85
 
 
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,
 
90
respectively.
 
91
 
 
92
Format:  printcc (lst,extra=2)
 
93
Returns: None\n"""
 
94
 
 
95
    def makestr (x):
 
96
        if type(x) <> StringType:
 
97
            x = str(x)
 
98
        return x
 
99
 
 
100
    if type(lst[0]) not in [ListType,TupleType]:
 
101
        lst = [lst]
 
102
    rowstokill = []
 
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:
 
109
        del list2print[row]
 
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
 
115
    for row in lst:
 
116
        if row == ['\n'] or row == '\n':
 
117
            print
 
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)
 
123
        else:
 
124
            print lineincustcols(row,maxsize)
 
125
    return None
 
126
 
 
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.
 
130
 
 
131
    Returns: the rows of a where columnlist[i]=valuelist[i] for ALL i\n"""
 
132
 
 
133
    a = asarray(a)
 
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]
 
138
    criterion = ''
 
139
    for i in range(len(columnlist)):
 
140
        if type(valuelist[i])==StringType:
 
141
            critval = '\'' + valuelist[i] + '\''
 
142
        else:
 
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)
 
147
 
 
148
 
 
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.
 
154
 
 
155
    Returns: unique 'conditions' specified by the contents of columns specified
 
156
    by keepcols, abutted with the mean(s) of column(s) specified by
 
157
    collapsecols
 
158
    """
 
159
    if cfcn is None:
 
160
        cfcn = stats.mean
 
161
    a = asarray(a)
 
162
    if keepcols == []:
 
163
        avgcol = colex(a,collapsecols)
 
164
        means = cfcn(avgcol)
 
165
        return means
 
166
    else:
 
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
 
171
        uniques.sort()
 
172
        newlist = []
 
173
        for item in uniques:
 
174
            if type(item) not in [ListType,TupleType,N.ArrayType]:
 
175
                item =[item]
 
176
            tmprows = linexand(a,keepcols,item)
 
177
            for col in collapsecols:
 
178
                avgcol = colex(tmprows,col)
 
179
                item.append(cfcn(avgcol))
 
180
                if sterr:
 
181
                    if len(avgcol)>1:
 
182
                        item.append(stats.sterr(avgcol))
 
183
                    else:
 
184
                        item.append('N/A')
 
185
                if ns:
 
186
                    item.append(len(avgcol))
 
187
                newlist.append(item)
 
188
        try:
 
189
            new_a = N.array(newlist)
 
190
        except TypeError:
 
191
            new_a = N.array(newlist,'O')
 
192
        return new_a
 
193
 
 
194
 
 
195
def makestr (item):
 
196
    if type(item) <> StringType:
 
197
        item = str(item)
 
198
    return item
 
199
 
 
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
 
204
inlist.
 
205
 
 
206
Format:  lineincustcols (inlist,colsizes)
 
207
Returns: formatted string created from inlist\n"""
 
208
 
 
209
    outstr = ''
 
210
    for i in range(len(inlist)):
 
211
        if type(inlist[i]) <> StringType:
 
212
            item = str(inlist[i])
 
213
        else:
 
214
            item = inlist[i]
 
215
        size = len(item)
 
216
        if size <= colsizes[i]:
 
217
            for j in range(colsizes[i]-size):
 
218
                outstr = outstr + ' '
 
219
            outstr = outstr + item
 
220
        else:
 
221
            outstr = outstr + item[0:colsizes[i]+1]
 
222
    return outstr
 
223
 
 
224
 
 
225
def list2string (inlist):
 
226
    """\nConverts a 1D list to a single long string for file output, using
 
227
the string.join function.
 
228
 
 
229
Format:  list2string (inlist)
 
230
Returns: the string created from inlist\n"""
 
231
 
 
232
    stringlist = map(makestr,inlist)
 
233
    return string.join(stringlist)
 
234