Python numpy.inv() Examples

The following are 5 code examples of numpy.inv(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module numpy , or try the search function .
Example #1
Source File: contact.py    From pyOptimalMotionPlanning with Apache License 2.0 6 votes vote down vote up
def invMassMatrix(obj):
    """Returns the inverse of obj's generalized mass matrix
      [H 0 ]-1
      [0 mI]
    about the origin."""
    Hinv = numpy.zeros((6,6))
    if obj == None or isinstance(obj,TerrainModel):
        #infinite inertia
        return Hinv
    if isinstance(obj,RobotModel):
        return obj.getMassMatrixInv()
    m = obj.getMass()
    minv = 1.0/m.mass
    Hinv[3,3]=Hinv[4,4]=Hinv[5,5]=minv
    #offset the inertia matrix about the COM
    H = numpy.array((3,3))
    H[0,:] = numpy.array(m.inertia[0:3])
    H[1,:] = numpy.array(m.inertia[3:6])
    H[2,:] = numpy.array(m.inertia[6:9])
    H -= skew(m.com)*skew(m.com)*m.mass
    Hinv[0:3,0:3] = numpy.inv(H)
    return Hinv 
Example #2
Source File: reconstruction.py    From soapy with GNU General Public License v3.0 6 votes vote down vote up
def calcCMat(self, callback=None, progressCallback=None):

        nSlopes = self.wfss[0].activeSubaps*2

        self.controlShape = (nSlopes, self.sim_config.totalActs)
        self.controlMatrix = numpy.zeros((nSlopes, self.sim_config.totalActs))
        acts = 0
        for dm in xrange(self.sim_config.nDM):
            dmIMat = self.dms[dm].iMat

            if dmIMat.shape[0]==dmIMat.shape[1]:
                dmCMat = numpy.inv(dmIMat)
            else:
                dmCMat = numpy.linalg.pinv(dmIMat, self.dmConds[dm])

            self.controlMatrix[:,acts:acts+self.dms[dm].n_acts] = dmCMat
            acts += self.dms[dm].n_acts 
Example #3
Source File: regressor.py    From tf-encrypted with Apache License 2.0 5 votes vote down vote up
def estimator_fn(cls, x_p, y_p):
        # Recall beta = np.inv(X.T @ X) * (X.T @ y)
        yy_p = tf.matmul(y_p, y_p, transpose_a=True)  # per-party y.T @ y
        xy_p = tf.matmul(x_p, y_p, transpose_a=True)  # per-party X.T @ y
        xx_p = tf.matmul(x_p, x_p, transpose_a=True)  # per-party X.T @ X
        return yy_p, xy_p, xx_p 
Example #4
Source File: regressor.py    From tf-encrypted with Apache License 2.0 5 votes vote down vote up
def fit(self, training_players, summary=0, validation_split=None):
        """Trains the linear regressor.

    Arguments:
      training_players: Data owners used for joint training. Must implement the
          compute_estimators as a tfe.local_computation.
      summary: Controls what kind of summary statistics are generated after the
          linear regression fit.
      validation_split: Mimics the behavior of the Keras validation_split kwarg.
    """
        if validation_split is not None:
            raise NotImplementedError()

        partial_estimators = [
            player.compute_estimators(self.estimator_fn) for player in training_players
        ]

        for attr, partial_estimator in zip(self.components, zip(*partial_estimators)):
            setattr(self, attr, tfe.add_n(partial_estimator))

        with tfe.Session() as sess:
            for k in self.components:
                op = getattr(self, k)
                setattr(self, k, sess.run(op.reveal()))

        tf_graph = tf.Graph()
        with tf_graph.as_default():
            self._inverted_covariate_square = tf.linalg.inv(self.covariate_square)
            self.coefficients = tf.matmul(
                self._inverted_covariate_square, self.covariate_label_product
            )

        with tf.Session(graph=tf_graph) as sess:
            for k in ["_inverted_covariate_square", "coefficients"]:
                setattr(self, k, sess.run(getattr(self, k)))

        if not summary:
            return self

        return self.summarize(summary_level=summary) 
Example #5
Source File: clutter_removal.py    From passiveRadar with MIT License 4 votes vote down vote up
def LS_Filter(refChannel, srvChannel, filterLen, reg=1.0, peek=10, 
    return_filter=False):
    '''Block least squares adaptive filter. Computes filter taps using the 
    direct matrix inversion method.  
    
    Parameters:
        refChannel:     Array containing the reference channel signal
        srvChannel:     Array containing the surveillance channel signal
        filterLen:      Length of the least squares filter (in samples)
        reg:            L2 regularization parameter for the matrix inversion 
                        (default 1.0)
        peek:           Number of noncausal filter taps. Set to zero for a 
                        causal filter. If nonzero, clutter estimates can depend 
                        on future values of the reference signal (this helps 
                        sometimes)
        return_filter:  Boolean indicating whether to return the filter taps

    Returns:
        srvChannelFiltered: Surveillance channel signal with clutter removed
        filterTaps:     (optional) least squares filter taps

    '''
    if refChannel.shape != srvChannel.shape:
        raise ValueError('Input vectors must have the same length')

    lags = np.arange(-1*peek, filterLen)
    
    # Create a matrix of time-shited copies of the reference channel signal
    A = np.zeros((refChannel.shape[0], filterLen+peek), dtype=np.complex64)
    for k in range(lags.shape[0]):
        A[:, k] = np.roll(refChannel, lags[k])
    
    # compute the autocorrelation matrix of ref
    ATA = A.conj().T @ A

    # create the Tikhonov regularization matrix
    K = np.eye(ATA.shape[0], dtype=np.complex64)

    # solve the least squares problem
    filterTaps = np.linalg.solve(ATA + K*reg, A.conj().T @ srvChannel)

    # direct but slightly slower implementation:
    # filterTaps = np.inv(ATA + K*reg) @ A.conj().T @ srvChannel

    # Apply the least squares filter to the surveillance channel
    srvChannelFiltered = srvChannel - A @ filterTaps

    if return_filter:
        return srvChannelFiltered, filterTaps
    else:
        return srvChannelFiltered