This file is indexed.

/usr/share/pyshared/ferari/binary.py is in python-ferari 1.0.0-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
# Copyright (C) 2006 Robert C. Kirby
#
# This file is part of FErari.
#
# FErari is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# FErari is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with FErari. If not, see <http://www.gnu.org/licenses/>.
#
# First added:  2005-04-01
# Last changed: 2006-04-05

import sigdig, numpy, string, graph, pg, util
from xpermutations import xuniqueCombinations

eps = util.eps


# This are distance measures used in the (hopefully)
# now obsolete brute-force O(n^2) method of forming
# the graph

def edplus( u , v ):
    """Returns the Hamming distance (number of nonzero vectors)
    between u and v, after rounding both vectors to 5 significant
    digits"""
    ur = sigdig.vec_round_sig( u , 5 )
    vr = sigdig.vec_round_sig( v , 5 )
    return util.nnz( ur - vr )

def edminus( u , v ):
    """Returns the Hamming distance (number of nonzero vectors)
    between u and -v, after rounding both vectors to 5 significant
    digits"""
    ur = sigdig.vec_round_sig( u , 5 )
    vr = sigdig.vec_round_sig( v , 5 )
    return util.nnz( ur + vr )

def colinear( u , v ):
    """Returns 0 if both vectors are 0, 1 if they are colinear,
    and the length of the vectors if they are not."""
    d = len( u )
    z = numpy.zeros( u.shape , "d" )
    uzhuh = numpy.alltrue( numpy.allclose( u , z ) )
    vzhuh = numpy.alltrue( numpy.allclose( v , z ) )
    if uzhuh and vzhuh:
        return 0
    elif uzhuh or vzhuh:
        return d
    else:
        uhat = util.unit_vector( u )
        vhat = util.unit_vector( v )
        if numpy.alltrue( numpy.allclose( uhat , vhat ) ) \
           or numpy.alltrue( numpy.allclose( uhat , -vhat ) ):
            return 1
        else:
            return d

def rho( u , v ):
    """Amalgamates several complexity-reducing relations into
    a single function for the purposes of the brute-force
    graph construction"""
    ep = edplus( u , v )
    em = edminus( u , v )
    c = colinear( u , v )
    m = min( em , ep , c )
    if ep == m:
        l = "edp"
    elif em == m:
        l = "edm"
    else:
        l = "c"
    return (m,l)

def get_graph( vecs , dist ):
    """Brute force construction of the CRR graph."""
    G = dict(  [ (v,{}) for v in vecs ] )
    for (u,v) in xuniqueCombinations( vecs.keys() , 2 ):
        (w,l) = dist( vecs[u] , vecs[v] )
        G[u][v] = (w,l)
        G[v][u] = (w,l)
    return G

def get_graph_clever( vecs ):
    """This builds a (possibly unconnected) graph based on
    Hamming distance and colinearity, but it typically works in
    O(n log n) time.  Lack of connectedness is not a problem,
    as we can apply Prim's algorithm to each connected component."""
    digits = 11
    n = len( vecs )
    d = len( vecs.itervalues().next() )
    vecs = dict( [ (i,sigdig.vec_round_sig(v,digits)) \
		   for (i,v) in vecs.iteritems() ] )

    G = dict( [ (i,{}) for i in vecs ] )

    # compute positive/negative Hamming distance between all the vectors

    # need to set up array of hash tables of unique entries in
    # position i to keys of vectors with that value in position i

    Gbig = dict( [ ((1,i),{}) for i in vecs ] + \
		 [ ((-1,i),{}) for i in vecs ] )

    tables = [ {} for i in range(d)]

    for i in vecs:
	for j in range(d):
	    vj = vecs[i][j]
	    if vj in tables[j]:
		tables[j][vj].append( (1,i) )
	    else:
		tables[j][vj] = [(1,i)]
	    mvj = -vecs[i][j]
	    if mvj in tables[j]:
		tables[j][mvj].append( (-1,i) )
	    else:
		tables[j][mvj] = [(-1,i)]

    sgncode = { 1:"edp" , -1:"edm" }

    # create the graph mapping \pm each vector to \pm each other
    # vector, *if* they share a common entry
    for j in range(d):
	for vj in tables[j]:
	    for (tup1,tup2) in \
		    xuniqueCombinations( tables[j][vj] , 2 ):
		if tup2 in Gbig[tup1]:
		    Gbig[tup1][tup2] -= 1
		    Gbig[tup2][tup1] -= 1
		else:
		    Gbig[tup1][tup2] = d-1
		    Gbig[tup2][tup1] = d-1

    # this extracts the minimum Hamming distance between
    # +v1,+v2 and +v1,-v2 and writes it into the graph
    for i1 in vecs:
	nbs = [ i2 for (sgn,i2) in Gbig[(1,i1)] if i2 > i1 ]
	for i2 in nbs:
	    wp = Gbig[(1,i1)].get((1,i2),d)
	    wm = Gbig[(1,i1)].get((-1,i2),d)
	    if wp <= wm:
		G[i1][i2] = (wp,"edp")
		G[i2][i1] = (wp,"edp")
	    else:
		G[i1][i2] = (wm,"edm")
		G[i2][i1] = (wm,"edm")


    # now I need to write in colinear vectors.
    # first, filter out zeros

    z = numpy.zeros( (d,),"d" )
    remaining = dict( [ x for x in vecs.iteritems() \
			if not numpy.alltrue( \
		numpy.allclose( x[1] , z , eps ) ) ] )

    # then, call pg to get colinear terms

    Ls = pg.rp_line_finder( remaining , 1 )
    for L in Ls:
	for (i1,i2) in xuniqueCombinations( list(L) , 2 ):
	    if i2 in G[i1]:
		if G[i1][i2][0] >= 1:
		    G[i1][i2] = (1,"c")
		    G[i2][i1] = (1,"c")


    # this is a sanity check to make sure I didn't screw up
    for i in G:
        for j in G[i]:
            if G[i][j][0] != rho(vecs[i],vecs[j])[0]:
                print "foo"
                print G[i][j],rho(vecs[i],vecs[j])
                print vecs[i], vecs[j]
                print

    return G

def process_bf( vecs ):
    """Takes a dictionary mapping vector labels to the numpy.array
    objects, and returns the minimum spanning tree of the associated
    CRR graph.  This runs in something like O(n^2) plus the cost
    of forming the minimum spanning tree.  Officically, it's O(n^3)
    because I'm doing a suboptimal MST implementation, but the cost
    seems dominated by building the graph rather than the MST in
    the regime I've considered.  Eventually I should implement
    a better MST algorithm if this is a bottleneck"""
    return graph.prim( get_graph( vecs , rho ) )

def process( vecs ):
    """Uses efficient graph construction algorithm then
    returns the minimum spanning forest."""
#    G = get_graph_clever( vecs )
    G = get_graph( vecs , rho )
    return reduce( lambda a,b: graph.merge_disjoint( a , b ) , \
		   map( graph.prim , \
			graph.connectedComponents( G ) ) )


def snip( mst , Adict ):
    """Takes the mst as input.  For each node, if the cost of
    doing the dot product by brute force is less than or equal to the
    cost of using the parent, remove that dependency.  This transforms
    the tree to a forest, which is actually good for data dependency
    and locality"""
    forest = {}
    for v in mst:
	if not mst[v]:
	    forest[v] = {}
	else:
	    num_nz = util.nnz( Adict[v] )
	    mst_cost = mst[v].values()[0][0]
	    if num_nz <= mst_cost:
		forest[v] = {}
	    else:
		forest[v] = mst[v]

    return forest


def cost( g , vecs ):
    """Takes a MST graph constructed in process and returns
    the sum of edge weights plus the number of nonzeros in the root;
    this is the total MAPs needed to form an element stiffness matrix."""
    w = 0
    for u in g:
        if g[u]:
            v = g[u].keys()[0]
            w += g[u][v][0]
        else:
            w += util.nnz( vecs[u] )
    return w

def nodep_code( u ):
    """Abstract code for a dot product performed by brute force"""
    return [ (u[i],1,i) for i in range(len(u)) \
	     if abs(u[i]) > 1.e-6 ]

# returns the abstract code
# associated with various dependencies
# u^t g is assumed known, v^t is to be computed.
# v^t g = u^t g + ( v - u )^t g
def ep_code( Adict , i1 , i2 ):
    """Returns abstract code for computing the dot product
    of Adict[i2] from Adict[i1] using positive Hamming distance"""
    u = Adict[i1]
    v = Adict[i2]
    diff = v - u
    diffinds = []
    # which indices matter?
    for i in range( len( diff ) ):
        if abs( diff[i] ) >= 1.e-4:
            diffinds.append(i)

    oplist = [ (1.0,0,i1) ]
    for i in diffinds:
        oplist.append( (diff[i],1,i) )

    return oplist

# returns the abstract code
# associated with various dependencies
# u^t g is assumed known, v^t is to be computed.
# v^t g = -u^t g + ( v + u )^t g
def em_code( Adict , i1 , i2 ):
    """Returns abstract code for computing the dot product
    of Adict[i2] from Adict[i1] using negative Hamming distance"""
    u = Adict[i1]
    v = Adict[i2]
    diff = v + u
    diffinds = []
    # which indices matter?
    for i in range( len( diff ) ):
        if abs( diff[i] ) >= 1.e-4:
            diffinds.append(i)

    oplist = [ (-1.0,0,i1) ]
    for i in diffinds:
        oplist.append( (diff[i],1,i) )

    return oplist


# v^t g = v[0]/u[0] ( u^t g )
def c_code( A , i1 , i2 ):
    """Returns abstract code for computing Adict[i2]^t g from
    Adict[i1]^t g using colinearity."""
    u = numpy.reshape( A[i1] , (-1,) )
    v = numpy.reshape( A[i2] , (-1,) )
    i=0
    while abs(u[i]) < 1.e-6 and i<len(u):
	i+=1

    alpha = v[i] / u[i]

    return [ ( alpha , 0 , i1 ) ]

def abstract_code( mst , A0 , Adict , foo ):
    """Takes the MST as input and returns a list modeling
    primitive abstract syntax for the optimized code """
    if foo == 1:
        Afoo = numpy.reshape( A0 , (A0.shape[0],-1) )
    elif foo == 2:
        Afoo = numpy.reshape( A0 , (A0.shape[0],A0.shape[1],-1) )
    else:
        raise Exception, "foo barfed"

    A = Afoo
    ts = graph.topsort( mst )
    ops = []
    for k in ts:
        if mst[k]:
            if len( mst[k] ) == 1:
                p = mst[k].iterkeys().next()
                if mst[k][p][1] == 'c':
                    ops.append( ( k , c_code( A , p , k ) ) )
                elif mst[k][p][1] == 'edp':
                    ops.append( ( k , ep_code( A , p , k ) ) )
                elif mst[k][p][1] == 'edm':
                    ops.append( ( k , em_code( A , p , k ) ) )
                else:
                    ops.append( ( k , nodep_code(A[k]) ) )

        else:
            ops.append( ( k , nodep_code( A[k] ) ) )
    return ops

def opt_code( A0 , p , Adict ):
    """Constructs optimized code from the original reference
    tensor, the minimimum spanning tree, and the dictionary."""
    if len( Adict.keys()[0] ) != 2:
        raise RuntimeError, "Illegal input"
    cs = abstract_code( p , A0 , Adict , 2)
    code_list = []
    def flatten(iota):
        return iota[0]*A0.shape[0] + iota[1]

    def convert( a ):
        if a[1] == 0:
            return (a[0],a[1],flatten(a[2]))
        else:
            return a

    for c in cs:
        lvalue = (0,flatten(c[0]))
        rvalue = map( convert , c[1] )
        code_list.append( (lvalue,rvalue) )

    return code_list

def opt_code_action( A0 , p , Adict ):
    """Constructs optimized code from the original reference
    tensor, the minimimum spanning tree, and the dictionary."""
    if len( Adict.keys()[0] ) != 1:
        raise RuntimeError, "Illegal input"
    cs = abstract_code( p , A0 , Adict , 1)

    code_list = []

    def flatten( iota ): return iota[0]

    def convert( a ):
        if a[1] == 0:
            return (a[0],a[1],flatten(a[2]))
        else:
            return a
    for c in cs:
        lvalue = (0,flatten(c[0]))
        rvalue = map(convert,c[1])
        code_list.append( (lvalue,rvalue) )

    return code_list

def optimize( A0 ):
    """Takes the reference tensor as input and returns
    abstract code for forming the element tensor."""
    Adict = {}
    for i in range( A0.shape[0] ):
        for j in range( A0.shape[1] ):
            Adict[i,j] = sigdig.vec_round_sig( \
				numpy.reshape( A0[i,j] , (-1,) ) , 10 )
    p = process( Adict )
    p = snip( p , Adict )
#    print cost( p , Adict )
    return opt_code(A0,p,Adict )

def optimize_action( A0 ):
    """Takes the reference tensor as input and
    returns abstract code for forming the action of the
    element matrix on a vector."""
    Adict = {}
    for i in range( A0.shape[0] ):
        Adict[(i,)] = sigdig.vec_round_sig( numpy.reshape( A0[i],(-1,) ), \
                                            10 )

    p = process( Adict )
    p = snip( p , Adict )
    return opt_code_action( A0 , p , Adict )

def main():
    import build_tensors
    shape = "tetrahedron"
    degree = 1
    A0 = build_tensors.laplacianform(shape,degree)
    for c in optimize_action( A0 ):
        print c
    print
#    for c in optimize( A0 ):
#        print c

if __name__ == "__main__":
    main()