Ejemplo n.º 1
0
 def __mul__(self, other):
     if isinstance(other,(N.ndarray, list, tuple)) :
         # This promotes 1-D vectors to row vectors
         return N.dot(self, asmatrix(other))
     if N.isscalar(other) or not hasattr(other, '__rmul__') :
         return N.dot(self, other)
     return NotImplemented
Ejemplo n.º 2
0
 def __mul__(self, other):
     if isinstance(other,(N.ndarray, list, tuple)) :
         # This promotes 1-D vectors to row vectors
         return N.dot(self, asmatrix(other))
     if isscalar(other) or not hasattr(other, '__rmul__') :
         return N.dot(self, other)
     return NotImplemented
Ejemplo n.º 3
0
    def text(self,v,threshold=0.1,minimum_count=1,include_pairs=True,join='+',maximum_count=5,terms=None,normalize=False):
        if isinstance(v,HRR): v=v.v
        if v is None or self.vectors is None: return ''        
        if normalize:
            nrm=norm(v)
            if nrm>0: v/=nrm
        
        m=numeric.dot(self.vectors,v)
        matches=[(m[i],self.keys[i]) for i in range(len(m))]
        if include_pairs:
            if self.vector_pairs is None: self.generate_pairs()
            # vector_pairs may still be none after generate_pairs (if there is only 1 vector)
            if self.vector_pairs is not None:
                m2=numeric.dot(self.vector_pairs,v)
                matches.extend([(m2[i],self.key_pairs[i]) for i in range(len(m2))])
        if terms is not None:
            matches=[m for m in matches if m[1] in terms]
        matches.sort()
        matches.reverse()

        r=[]        
        for m in matches:
            if threshold is None or (m[0]>threshold and len(r)<maximum_count): r.append(m)
            elif len(r)<minimum_count: r.append(m)
            else: break
            
        return join.join(['%0.2f%s'%(c,k) for (c,k) in r])
Ejemplo n.º 4
0
    def __getitem__(self, key):
        if key not in self.hrr:
            if self.randomize:
                count = 0
                v = HRR(self.dimensions)
                while count < 100 and self.vectors is not None:
                    similarity = numeric.dot(self.vectors, v.v)
                    if max(similarity) < self.max_similarity:
                        break
                    v = HRR(self.dimensions)
                    count += 1
                if count >= 100:
                    print 'Warning: Could not create an HRR with max_similarity=%1.2f (D=%d, M=%d)' % (
                        self.max_similarity, self.dimensions, len(self.hrr))

                # Check and make HRR vector unitary if needed
                if self.unitary is True or (isinstance(self.unitary, list)
                                            and key in self.unitary):
                    v.make_unitary()
            else:
                ov = [0] * self.dimensions
                ov[len(self.hrr)] = 1.0
                v = HRR(data=ov)

            self.add(key, v)
        return self.hrr[key]
Ejemplo n.º 5
0
 def addDecodedTermination(self,name,matrix,pstc,modulatory):
     M=nef.convolution.input_transform(self.dimension,self.first,self.invert)
     if self.invert:
         conv=self.memory.net.network.getNode('deconv')
     else:
         conv=self.memory.net.network.getNode('conv')
     return conv.addDecodedTermination(name,numeric.dot(M,matrix),pstc,modulatory)
Ejemplo n.º 6
0
def conv2neuron( A, B ):
    ra,ca = A.shape
    rb,cb = B.shape
    FFTshape = (ra+rb, ca+cb)        # determine padded FFT size

    AT = input_transform( A.shape, B.shape, FFTshape, True )
    BT = input_transform( A.shape, B.shape, FFTshape, False )

    C = dot( AT, ravel( A ) ) + dot( BT, ravel( B ) )
    print "Max D before multiplication %0.3f" % max( ravel( C ) )

    C = C[0::2] * C[1::2]
    print "Max D after multiplication %0.3f" % max( ravel( C ) )

    T = output_transform( A.shape, B.shape, FFTshape )
    return dot( T, C )
Ejemplo n.º 7
0
 def addDecodedTermination(self, name, matrix, pstc, modulatory):
     M = nef.convolution.input_transform(self.dimension, self.first,
                                         self.invert)
     if self.invert:
         conv = self.memory.net.network.getNode('deconv')
     else:
         conv = self.memory.net.network.getNode('conv')
     return conv.addDecodedTermination(name, numeric.dot(M, matrix), pstc,
                                       modulatory)
Ejemplo n.º 8
0
def conv2dftmatrix( A, B, DM, DN, ZM, ZN ):
    ra,ca = A.shape
    rb,cb = B.shape
    rao,cao = ((DM.shape[0] - ra) // 2, (DN.shape[0] - ca) // 2)
    X = dot( dot( DM[:,:ra], A ), DN[:ca,:] )
    Y = dot( dot( DM[:,:rb], B ), DN[:cb,:] )
    return dot( dot( ZM[rao:rao+ra,:], X * Y ), ZN[:,cao:cao+ca] ).real
 def tick(self):
     self.counter += 1
     if self.counter % LEARNING_PERIOD == 0: #10 FIXME
         #t_start = time.time()
         delta = -rho * np.array(self.s.get())*0.00001 *.1
         Y = np.array(list(self.Y.get()))
         Y.shape = 300,1
         #Y.shape = 150,1
         da = np.dot(Y, delta)
         da.shape = 300,1 #Bug fix
         ###decoder = np.array(self.origin.decoders)
         ###self.origin.decoders = decoder + da #FIXME: this line takes 50ms to run
         self.origin.decoders += da #FIXME: attempt to make it faster
 def tick(self):
     self.counter += 1
     if self.counter%10 == 0:
         delta = -rho * np.array(self.s.get())*0.00001 * .1
         Y = np.array(list(self.Y.get()))
         Y.shape = 300,1
         da = np.dot(Y, delta)
         da.shape = 300,1 #Bug fix
         decoder = np.array(self.origin.decoders)
         #print( "%.9f, %.9f, %.9f, %.9f" % ( decoder[0][0], decoder[13][0],
         #                                   decoder[26][0], decoder[85][0] ) )
         #print( decoder.shape )
         #print( da.shape )
         #print( (decoder + da).shape )
         self.origin.decoders = decoder + da
Ejemplo n.º 11
0
Archivo: match.py Proyecto: w6hu/nengo
    def connect(self):
        self.bg.rules.initialize(self.spa)
        N=self.p.match_neurons
        for (a,b) in self.bg.rules.get_lhs_matches():
            t=self.bg.rules.lhs_match(a,b)
            name='%s_%s'%(a,b)
            dim=self.spa.sources[a].dimensions

            if N==0:
                m=self.net.make(name,1,dim*2,quick=True,mode='direct')
                def dotproduct(x):
                    return sum([x[2*i]*x[2*i+1] for i in range(len(x)/2)])
                funcs=[nef.functions.PythonFunction(dotproduct)]                
                m.addDecodedOrigin('product',funcs,'AXON')
            else:            
                m=self.net.make_array(name,N,dim,dimensions=2,encoders=[[1,1],[1,-1],[-1,-1],[-1,1]],quick=True,radius=1.4,storage_code="%d")
                def product(x): return x[0]*x[1]
                m.addDecodedOrigin('product',[nef.functions.PythonFunction(product,dim)],'AXON')
            self.net.network.exposeOrigin(m.getOrigin('product'),name)

            t1=numeric.zeros((dim*2,dim),typecode='f')
            t2=numeric.zeros((dim*2,dim),typecode='f')
            for i in range(dim):
                t1[i*2,i]=1.0
                t2[i*2+1,i]=1.0

            va=self.spa.vocab(a)
            vb=self.spa.vocab(b)
            if va is not vb:
                t2=numeric.dot(t2,vb.transform_to(va))
            m.addDecodedTermination(a,t1,self.p.pstc_match,False)
            m.addDecodedTermination(b,t2,self.p.pstc_match,False)
            self.net.network.exposeTermination(m.getTermination(a),name+'_1')
            self.net.network.exposeTermination(m.getTermination(b),name+'_2')

            self.spa.net.connect(self.spa.sources[a],self.net.network.getTermination(name+'_1'))
            self.spa.net.connect(self.spa.sources[b],self.net.network.getTermination(name+'_2'))

            if N==0:
                transform=[t for i in range(1)]
            else:
                transform=[t for i in range(dim)]

            self.bg.add_input(self.net.network.getOrigin(name),numeric.array(transform).T)
Ejemplo n.º 12
0
def conv2dft( A, B ):
    ra,ca = A.shape
    rb,cb = B.shape
    M,N = (ra+rb, ca+cb)        # determine padded FFT size

    DM = DFT( M )               # get DFT matrix for rows
    DN = DFT( N )               # get DFT matrix for cols
    ZM = DFTinverse( M )        # get inverse DFT matrix
    ZN = DFTinverse( N )        # get inverse DFT matrix

    X = dot( dot( DM[:,:ra], A ), DN[:ca,:] )   # determine FFT of A (with padding)
    Y = dot( dot( DM[:,:rb], B ), DN[:cb,:] )   # determine FFT of B (with padding)

    rao,cao = ((M - ra) // 2, (N - ca) // 2)
    return (M*N) * dot( dot( ZM[rao:rao+ra,:], X * Y ), ZN[:,cao:cao+ca] ).real
Ejemplo n.º 13
0
    def __init__(self,view,name,config,func,args=(),label=None):
        core.DataViewComponent.__init__(self,label)
        self.view=view
        self.name=name
        self.func=func
        self.data=self.view.watcher.watch(name,func,args=args)

        self.border_top=20
        self.border_left=20
        self.border_right=20
        self.border_bottom=20
        self.config=config
        self.start = 0

        # self.setSize(440,440+self.label_offset)
        self.setSize(240,240+self.label_offset)

        self.max = 0.0001
        self.min = -0.0001
        self.grid_size = 50
        self.image = None
        self.counter = 0
        
        ######################################
        ## initialize function input grid
        
        grid_size = self.grid_size
                
        # construct input grid
        row = array([map(float,range(grid_size))])
        row = row / (self.grid_size-1) * 2 - 2  # normalized to [-1, 1]
        gridX = dot(ones([grid_size,1]), row)
        gridY = transpose(gridX)
        
        # get function value
        x1 = reshape(gridX,[1, grid_size*grid_size])
        x2 = reshape(gridY,[1, grid_size*grid_size])
        self.func_input = concatenate([x1, x2], 0)
Ejemplo n.º 14
0
    def __getitem__(self,key):
        if key not in self.hrr:
            if self.randomize:  
                count=0
                v=HRR(self.dimensions)
                while count<100 and self.vectors is not None:
                    similarity=numeric.dot(self.vectors,v.v)
                    if max(similarity)<self.max_similarity:
                        break
                    v=HRR(self.dimensions)
                    count+=1
                if count>=100:        
                    print 'Warning: Could not create an HRR with max_similarity=%1.2f (D=%d, M=%d)'%(self.max_similarity,self.dimensions,len(self.hrr))
                
                # Check and make HRR vector unitary if needed
                if self.unitary is True or (isinstance(self.unitary,list) and key in self.unitary):
                    v.make_unitary()
            else:
                ov=[0]*self.dimensions
                ov[len(self.hrr)]=1.0
                v = HRR(data = ov)

            self.add(key,v)
        return self.hrr[key]        
Ejemplo n.º 15
0
 def __rmul__(self, other):
     return N.dot(other, self)
Ejemplo n.º 16
0
 def dot_pairs(self,v):
     if len(self.keys)<2: return None # There are no pairs.
     if isinstance(v,HRR): v=v.v
     if self.vector_pairs is None: self.generate_pairs()
     return numeric.dot(self.vector_pairs,v)
Ejemplo n.º 17
0
 def compare(self,other):
     scale=norm(self.v)*norm(other.v)
     if scale==0: return 0
     return dot(self.v,other.v)/(scale)
Ejemplo n.º 18
0
 def dot(self,other):
     return dot(self.v,other.v)
Ejemplo n.º 19
0
    def run(self, start, end):
        # Check if file exists, if it doesn't, create it
        if (start == 0 and not os.path.isfile(self.filename)):
            self.reset(False)

        nef.SimpleNode.run(self, start, end)
        if (start < self.start or end > self.end):
            return

        for msg_time in self.message_list.keys():
            print(msg_time)
            if (msg_time <= self.t_end and msg_time >= self.t_start):
                self.log_file = open(self.filename, 'a')
                self.log_file.write("# (%.5f) - " % (msg_time) +
                                    self.message_list[msg_time] + "\n")
                self.log_file.close()

        if (self.t_end + self.epsilon >= self.next_log):
            self.log_file = open(self.filename, 'a')
            self.log_file.write("%.5f" % (self.next_log) + self.delimiter)
            for n in range(len(self.term_list)):
                termination = self.getTermination(self.term_list[n])
                term_name = termination.getName()
                term_output = array(termination._filtered_values)

                if (term_name in self.vocab_list.keys()):
                    # Termination is a vocabTermination
                    vocab = self.vocabs[term_name]
                    vocab_list = self.vocab_list[term_name]
                    vocab_list_len = len(vocab_list)
                    vocab_threshold = self.vocab_threshold[term_name]
                    vocab_list_range = range(vocab_list_len)
                    dot_prods = [
                        dot(vocab.hrr[vocab_list[n]].v, term_output, False)
                        for n in vocab_list_range
                    ]
                    max_dot = max(dot_prods)
                    if (max_dot >= vocab_threshold):
                        dot_prods = [
                            dot_prods[n] * (dot_prods[n] > vocab_threshold)
                            for n in vocab_list_range
                        ]
                    else:
                        dot_prods = [
                            dot_prods[n] * (dot_prods[n] == max_dot)
                            for n in vocab_list_range
                        ]
                    dot_prods_out = []
                    vocab_list_out = []
                    for n in range(vocab_list_len):
                        if (dot_prods[n] > 0):
                            dot_prods_out.append(dot_prods[n])
                            vocab_list_out.append(vocab_list[n])
                    str_output = "+"
                    str_output = str_output.join([
                        "%0.2f%s" % (dot_prods_out[n], vocab_list_out[n])
                        for n in range(len(dot_prods_out))
                    ])
                    if (len(str_output) == 0):
                        str_output = "0"
                else:
                    # Termination is a valueTermination
                    term_dim = termination.getDimensions()

                    def min_val(input):
                        if (abs(input) < self.epsilon):
                            return 0
                        else:
                            return input

                    term_output = [
                        min_val(term_output[d]) for d in range(term_dim)
                    ]
                    str_output = str(term_output)
                    str_output = str_output.replace(self.delimiter,
                                                    self.delim_replace)
                self.log_file.write(str(str_output) + self.delimiter)
            self.log_file.write("\n")
            self.log_file.close()
            self.next_log += self.log_interval


#### EXAMPLE USAGE ####
#def test_w2fnode():
#    num_dim = 256
#
#    network = nef.Network("Test W2FNode")
#
#    file_path = "FILEPATH HERE"
#    func_in = FunctionInput("Func In", [ConstantFunction(1,0)], Units.UNK)
#    network.add(func_in)
#
#    vocab = hrr.Vocabulary(num_dim, max_similarity = 0.05, include_pairs = False)
#    vocab_strs = ["ZER", "ONE", "TWO", "THR", "FOR", "FIV", "SIX", "SEV", "EIG", "NIN"]
#    for item in vocab_strs:
#        vocab.parse(item)
#
#    class ControlInput(nef.SimpleNode):
#        def __init__(self, name, num_dim, vocab = None, output_str = None):
#            self.dimension = num_dim
#            self.vocab = vocab
#            self.output_str = output_str
#            nef.SimpleNode.__init__(self, name)
#
#        def origin_X(self):
#            if( self.vocab is None or self.output_str is None ):
#                return util_funcs.zeros(1, self.dimension)
#            else:
#                return self.vocab.hrr[self.output_str].v
#
#    vocab_in = ControlInput("Func In", num_dim, vocab, "ZER")
#    network.add(vocab_in)
#
#    # Let the w2fnode automatically connect stuff
#    w2f = w2fnode.WriteToFileNode("W2F AutoAdd+Connect", file_path + "test.csv", network, overwrite = True)
#    w2f.addVocabTermination("Func In", "origin", vocab = vocab, vocab_strs = vocab_strs)
#    w2f.addValueTermination("Vocab In", "X")
#
#    # Do the stuff yourself
#    w2f2 = w2fnode.WriteToFileNode("W2F ManualStuff", file_path + "test2.csv", overwrite = True)
#    w2f2.addVocabTermination("Func In", func_in.getOrigin("origin"), vocab = vocab, vocab_strs = vocab_strs)
#    w2f2.addValueTermination("Vocab In", vocab_in.getOrigin("X"))
#    network.add(w2f2)
#    network.connect(func_in.getOrigin("origin"), w2f2.getTermination("Func In"))
#    network.connect(vocab_in.getOrigin("X"), w2f2.getTermination("Vocab In"))
#
#    # Add messages
#    w2f.addMessages(["Message @ 0.5s","Message @ 1.0s"], [0.5,1])
#
#    network.add_to_nengo()
Ejemplo n.º 20
0
 def compare(self, other):
     scale = norm(self.v) * norm(other.v)
     if scale == 0: return 0
     return dot(self.v, other.v) / (scale)
Ejemplo n.º 21
0
def matrix_power(M,n):
    """Raise a square matrix to the (integer) power n.

    For positive integers n, the power is computed by repeated matrix
    squarings and matrix multiplications. If n=0, the identity matrix
    of the same type as M is returned. If n<0, the inverse is computed
    and raised to the exponent.

    Parameters
    ----------
    M : array-like
        Must be a square array (that is, of dimension two and with
        equal sizes).
    n : integer
        The exponent can be any integer or long integer, positive
        negative or zero.

    Returns
    -------
    M to the power n
        The return value is a an array the same shape and size as M;
        if the exponent was positive or zero then the type of the
        elements is the same as those of M. If the exponent was negative
        the elements are floating-point.

    Raises
    ------
    LinAlgException
        If the matrix is not numerically invertible, an exception is raised.

    See Also
    --------
    The matrix() class provides an equivalent function as the exponentiation
    operator.

    Examples
    --------
    >>> matrix_power(array([[0,1],[-1,0]]),10)
    array([[-1,  0],
           [ 0, -1]])
    """
    if len(M.shape) != 2 or M.shape[0] != M.shape[1]:
        raise ValueError("input must be a square array")
    if not issubdtype(type(n),int):
        raise TypeError("exponent must be an integer")

    from numpy.linalg import inv

    if n==0:
        M = M.copy()
        M[:] = identity(M.shape[0])
        return M
    elif n<0:
        M = inv(M)
        n *= -1

    result = M
    if n <= 3:
        for _ in range(n-1):
            result=N.dot(result,M)
        return result

    # binary decomposition to reduce the number of Matrix
    # multiplications for n > 3.
    beta = binary_repr(n)
    Z,q,t = M,0,len(beta)
    while beta[t-q-1] == '0':
        Z = N.dot(Z,Z)
        q += 1
    result = Z
    for k in range(q+1,t):
        Z = N.dot(Z,Z)
        if beta[t-k-1] == '1':
            result = N.dot(result,Z)
    return result
Ejemplo n.º 22
0
 def termination(x,self=self,transform=numeric.array(transform)):
     self.input+=numeric.dot(transform,x)
Ejemplo n.º 23
0
    def run(self,start,end):
        # Check if file exists, if it doesn't, create it
        if( start == 0 and not os.path.isfile(self.filename) ):
            self.reset(False)

        nef.SimpleNode.run(self, start, end)
        if( start < self.start or end > self.end ):
            return

        for msg_time in self.message_list.keys():
            print(msg_time)
            if( msg_time <= self.t_end and msg_time >= self.t_start ):
                self.log_file = open(self.filename, 'a')
                self.log_file.write("# (%.5f) - " % (msg_time) + self.message_list[msg_time] + "\n")
                self.log_file.close()

        if( self.t_end + self.epsilon >= self.next_log ):
            self.log_file = open(self.filename, 'a')
            self.log_file.write("%.5f" % (self.next_log) + self.delimiter)
            for n in range(len(self.term_list)):
                termination = self.getTermination(self.term_list[n])
                term_name = termination.getName()
                term_output = array(termination._filtered_values)

                if( term_name in self.vocab_list.keys() ):
                    # Termination is a vocabTermination
                    vocab = self.vocabs[term_name]
                    vocab_list = self.vocab_list[term_name]               
                    vocab_list_len = len(vocab_list)
                    vocab_threshold = self.vocab_threshold[term_name]
                    vocab_list_range = range(vocab_list_len)
                    dot_prods = [dot(vocab.hrr[vocab_list[n]].v, term_output, False) for n in vocab_list_range]
                    max_dot = max(dot_prods)
                    if( max_dot >= vocab_threshold ):
                        dot_prods = [dot_prods[n] * (dot_prods[n] > vocab_threshold) for n in vocab_list_range]
                    else:
                        dot_prods = [dot_prods[n] * (dot_prods[n] == max_dot) for n in vocab_list_range]
                    dot_prods_out = []
                    vocab_list_out = []
                    for n in range(vocab_list_len):
                        if( dot_prods[n] > 0 ):
                            dot_prods_out.append(dot_prods[n])
                            vocab_list_out.append(vocab_list[n])
                    str_output = "+"
                    str_output = str_output.join(["%0.2f%s" % (dot_prods_out[n], vocab_list_out[n]) for n in range(len(dot_prods_out))])
                    if( len(str_output) == 0 ):
                        str_output = "0"
                else:
                    # Termination is a valueTermination
                    term_dim = termination.getDimensions()

                    def min_val(input):
                        if( abs(input) < self.epsilon ):
                            return 0
                        else:
                            return input

                    term_output = [min_val(term_output[d]) for d in range(term_dim)]
                    str_output = str(term_output)
                    str_output = str_output.replace(self.delimiter, self.delim_replace)            
                self.log_file.write(str(str_output) + self.delimiter)
            self.log_file.write("\n")
            self.log_file.close()
            self.next_log += self.log_interval

#### EXAMPLE USAGE ####
#def test_wtfnode():
#    num_dim = 256
#
#    network = nef.Network("Test WTFNode")
#
#    file_path = "FILEPATH HERE"
#    func_in = FunctionInput("Func In", [ConstantFunction(1,0)], Units.UNK)
#    network.add(func_in)
#
#    vocab = hrr.Vocabulary(num_dim, max_similarity = 0.05, include_pairs = False)
#    vocab_strs = ["ZER", "ONE", "TWO", "THR", "FOR", "FIV", "SIX", "SEV", "EIG", "NIN"]
#    for item in vocab_strs:
#        vocab.parse(item)
#    
#    class ControlInput(nef.SimpleNode):
#        def __init__(self, name, num_dim, vocab = None, output_str = None):
#            self.dimension = num_dim
#            self.vocab = vocab
#            self.output_str = output_str
#            nef.SimpleNode.__init__(self, name)
#        
#        def origin_X(self):
#            if( self.vocab is None or self.output_str is None ):
#                return util_funcs.zeros(1, self.dimension)
#            else:
#                return self.vocab.hrr[self.output_str].v
#
#    vocab_in = ControlInput("Func In", num_dim, vocab, "ZER")
#    network.add(vocab_in)
#    
#    # Let the wtfnode automatically connect stuff
#    wtf = wtfnode.WriteToFileNode("WTF AutoAdd+Connect", file_path + "test.csv", network, overwrite = True)
#    wtf.addVocabTermination("Func In", "origin", vocab = vocab, vocab_strs = vocab_strs)
#    wtf.addValueTermination("Vocab In", "X")
#
#    # Do the stuff yourself
#    wtf2 = wtfnode.WriteToFileNode("WTF ManualStuff", file_path + "test2.csv", overwrite = True)
#    wtf2.addVocabTermination("Func In", func_in.getOrigin("origin"), vocab = vocab, vocab_strs = vocab_strs)
#    wtf2.addValueTermination("Vocab In", vocab_in.getOrigin("X"))
#    network.add(wtf2)
#    network.connect(func_in.getOrigin("origin"), wtf2.getTermination("Func In"))
#    network.connect(vocab_in.getOrigin("X"), wtf2.getTermination("Vocab In"))
#
#    # Add messages
#    wtf.addMessages(["Message @ 0.5s","Message @ 1.0s"], [0.5,1])
#    
#    network.add_to_nengo()
Ejemplo n.º 24
0
    def paintComponent(self,g):
        
        f,dimension,minx,maxx,miny,maxy, params, color, time_step = self.config
        
        core.DataViewComponent.paintComponent(self,g)

        width=self.size.width-self.border_left-self.border_right
        height=self.size.height-self.border_top-self.border_bottom-self.label_offset
            
        if width<2: return

        dt_tau=None
        if self.view.tau_filter>0:
            dt_tau=self.view.dt/self.view.tau_filter
        try:    
            data=self.data.get(start=self.view.current_tick,count=1,dt_tau=dt_tau)[0]
        except:
            return
        
        if dimension == 2:   
            if self.image is None :
                self.image = BI(width, height, BI.TYPE_INT_ARGB)
            
            if self.counter != time_step:
                self.counter += 1
                g.drawImage( self.image, self.border_left, self.border_top, None)
            else:
                self.counter = 0
                # currently only for fixed grid
                grid_size = self.grid_size
                # step_size = width / grid_size
                
                coeffs=transpose(array([data]))
                basis = array(f(self.func_input, params))
                value = transpose(dot(transpose(basis),coeffs))
                maxv = max(value[0])
                minv = min(value[0])
                if maxv > self.max:
                    self.max = maxv
                if minv < self.min:
                    self.min = minv
        
                pvalue = (value - self.min) / (self.max - self.min) # normalized pixel value
                
                if color == 'g':
                    ## gray
                    pvalue = array(map(int, array(pvalue[0]) * 0xFF))
                    pvalue = pvalue * 0x10000 + pvalue * 0x100 + pvalue
                elif color == 'c':
                    ##color
                    pvalue = map(int, array(pvalue[0]) * 0xFF * 2) 
                    R = zeros(len(pvalue))
                    G = zeros(len(pvalue))
                    B = zeros(len(pvalue))
                    for i, v in enumerate(pvalue):
                        if v < 0xFF:
                            B[i] = 0xFF - v
                            G[i] = v
                        else:
                            G[i] = 2*0xFF - v
                            R[i] = v - 0xFF
                    pvalue = R * 0x10000 + G * 0x100 + B
                
                pvalue = reshape(pvalue,[grid_size, grid_size])
                rvalue = 0xFF000000 + pvalue
                
                # expand pixel value from grid to raster size
                # ratio = float(width) / grid_size
                # indeces = map(int, (floor(array(range(width)) / ratio)))
                ## Tooooooo slow here!
                # for i, ii in enumerate(indeces): 
                    # for j, jj in enumerate(indeces) :
                        # rvalue[i,j] = pvalue[ii,jj]
            
                for zoom in range(2):
                    zgrid_size = grid_size * (zoom + 1)
                    rvalue = reshape(rvalue, [zgrid_size * zgrid_size, 1])
                    rvalue = concatenate([rvalue, rvalue], 1)
                    rvalue = reshape(rvalue, [zgrid_size, zgrid_size* 2])
                    rvalue = repeat(rvalue, ones(zgrid_size) * 2)
                                
                # draw image
                rvalue = reshape(rvalue, [1, width * height])
                self.image.setRGB(0, 0, width, height, rvalue[0], 0, width)
                g.drawImage( self.image, self.border_left, self.border_top, None)
                
        elif dimension == 1: 
            g.color=Color(0.8,0.8,0.8)
            g.drawRect(self.border_left,self.border_top+self.label_offset,width,height)
            
            g.color=Color.black
            txt='%4g'%maxx
            bounds=g.font.getStringBounds(txt,g.fontRenderContext)
            g.drawString(txt,self.size.width-self.border_right-bounds.width/2,self.size.height-self.border_bottom+bounds.height)

            txt='%4g'%minx
            bounds=g.font.getStringBounds(txt,g.fontRenderContext)
            g.drawString(txt,self.border_left-bounds.width/2,self.size.height-self.border_bottom+bounds.height)

            g.drawString('%6g'%maxy,0,10+self.border_top+self.label_offset)
            g.drawString('%6g'%miny,0,self.size.height-self.border_bottom)

            g.color=Color.black
            
            pdftemplate=getattr(self.view.area,'pdftemplate',None)
            if pdftemplate is not None:
                pdf,scale=pdftemplate
                pdf.setLineWidth(0.5)

                steps=100

                dx=float(maxx-minx)/(width*steps)

                for i in range(width*steps):
                    x=minx+i*dx
                    value=sum([f(j,x)*d for j,d in enumerate(data)])
                    y=float((value-miny)*height/(maxy-miny))
                    
                    xx=self.border_left+i/float(steps)
                    yy=self.height-self.border_bottom-y

                    if i==0:
                        pdf.moveTo((self.x+xx)*scale,800-(self.y+yy)*scale)
                    else:
                        if 0<y<height:
                            pdf.lineTo((self.x+xx)*scale,800-(self.y+yy)*scale)
                pdf.setRGBColorStroke(g.color.red,g.color.green,g.color.blue)        
                pdf.stroke()        
            else:                
                dx=float(maxx-minx)/(width-1)
                px,py=None,None
                for i in range(width):
                    x=minx+i*dx
                    value=sum([f(j,x)*d for j,d in enumerate(data)])

                    y=int((value-miny)*height/(maxy-miny))

                    xx=self.border_left+i
                    yy=self.height-self.border_bottom-y

                    if px is not None and miny<value<maxy:
                        g.drawLine(px,py,xx,yy)
                    px,py=xx,yy
Ejemplo n.º 25
0
 def dot(self, v):
     if isinstance(v, HRR): v = v.v
     return numeric.dot(self.vectors, v)
Ejemplo n.º 26
0
 def dot(self, other):
     return dot(self.v, other.v)
Ejemplo n.º 27
0
 def dot(self,v):
     if isinstance(v,HRR): v=v.v
     return numeric.dot(self.vectors,v)
Ejemplo n.º 28
0
 def __rmul__(self, other):
     return N.dot(other, self)
Ejemplo n.º 29
0
def matrix_power(M,n):
    """
    Raise a square matrix to the (integer) power n.

    For positive integers n, the power is computed by repeated matrix
    squarings and matrix multiplications. If n=0, the identity matrix
    of the same type as M is returned. If n<0, the inverse is computed
    and raised to the exponent.

    Parameters
    ----------
    M : array_like
        Must be a square array (that is, of dimension two and with
        equal sizes).
    n : integer
        The exponent can be any integer or long integer, positive
        negative or zero.

    Returns
    -------
    M to the power n
        The return value is a an array the same shape and size as M;
        if the exponent was positive or zero then the type of the
        elements is the same as those of M. If the exponent was negative
        the elements are floating-point.

    Raises
    ------
    LinAlgException
        If the matrix is not numerically invertible, an exception is raised.

    See Also
    --------
    The matrix() class provides an equivalent function as the exponentiation
    operator.

    Examples
    --------
    >>> np.linalg.matrix_power(np.array([[0,1],[-1,0]]),10)
    array([[-1,  0],
           [ 0, -1]])

    """
    if len(M.shape) != 2 or M.shape[0] != M.shape[1]:
        raise ValueError("input must be a square array")
    if not issubdtype(type(n),int):
        raise TypeError("exponent must be an integer")

    from numpy.linalg import inv

    if n==0:
        M = M.copy()
        M[:] = identity(M.shape[0])
        return M
    elif n<0:
        M = inv(M)
        n *= -1

    result = M
    if n <= 3:
        for _ in range(n-1):
            result=N.dot(result,M)
        return result

    # binary decomposition to reduce the number of Matrix
    # multiplications for n > 3.
    beta = binary_repr(n)
    Z,q,t = M,0,len(beta)
    while beta[t-q-1] == '0':
        Z = N.dot(Z,Z)
        q += 1
    result = Z
    for k in range(q+1,t):
        Z = N.dot(Z,Z)
        if beta[t-k-1] == '1':
            result = N.dot(result,Z)
    return result
Ejemplo n.º 30
0
 def termination(x, self=self, transform=numeric.array(transform)):
     self.input += numeric.dot(transform, x)
Ejemplo n.º 31
0
 def dot_pairs(self, v):
     if len(self.keys) < 2: return None  # There are no pairs.
     if isinstance(v, HRR): v = v.v
     if self.vector_pairs is None: self.generate_pairs()
     return numeric.dot(self.vector_pairs, v)