Python numpy.reciprocal() Examples

The following are 30 code examples for showing how to use numpy.reciprocal(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module numpy , or try the search function .

Example 1
Project: osqp-python   Author: oxfordcontrol   File: _osqp.py    License: Apache License 2.0 7 votes vote down vote up
def update_rho(self, rho_new):
        """
        Update set-size parameter rho
        """
        if rho_new <= 0:
            raise ValueError("rho must be positive")

        # Update rho
        self.work.settings.rho = np.minimum(np.maximum(rho_new,
                                            RHO_MIN), RHO_MAX)

        # Update rho_vec and rho_inv_vec
        ineq_ind = np.where(self.work.constr_type == 0)
        eq_ind = np.where(self.work.constr_type == 1)
        self.work.rho_vec[ineq_ind] = self.work.settings.rho
        self.work.rho_vec[eq_ind] = RHO_EQ_OVER_RHO_INEQ * self.work.settings.rho
        self.work.rho_inv_vec = np.reciprocal(self.work.rho_vec)

        # Factorize KKT
        self.work.linsys_solver = linsys_solver(self.work) 
Example 2
Project: florence   Author: romeric   File: StructuralDynamicIntegrator.py    License: MIT License 6 votes vote down vote up
def ComputeMassMatrixInfo(self, M, formulation, fem_solver):
        """Computes the inverse of lumped mass matrix and so on
        """

        invM = None
        if formulation.fields == "electro_mechanics":
            if fem_solver.mass_type == "lumped":
                M = M.ravel()
                invM = np.zeros_like(M)
                invM[self.mechanical_dofs] = np.reciprocal(M[self.mechanical_dofs])
                M_mech = M[self.mechanical_dofs]
            else:
                M_mech = M[self.mechanical_dofs,:][:,self.mechanical_dofs]
        else:
            if fem_solver.mass_type == "lumped":
                M = M.ravel()
                M_mech = M
                invM = np.reciprocal(M)
            else:
                M_mech = M

        return M_mech, invM 
Example 3
Project: chainer   Author: chainer   File: batch_normalization.py    License: MIT License 6 votes vote down vote up
def forward(self, inputs):
        self.retain_inputs((0, 1, 2, 4))
        x, gamma, mean, var, gy = inputs
        expander = self.expander
        xp = backend.get_array_module(x)

        if self.inv_std is None or self.inv_var is None:
            self.inv_var = xp.reciprocal(var + self.eps)
            self.inv_std = xp.sqrt(self.inv_var, dtype=self.inv_var.dtype)

        self.gamma_over_std = gamma * self.inv_std
        x_hat = _x_hat(x, mean[expander], self.inv_std[expander])

        gx = self.gamma_over_std[expander] * gy
        gbeta = gy.sum(axis=self.axis, dtype=gamma.dtype)
        ggamma = (x_hat * gy).sum(axis=self.axis)
        gmean = -self.gamma_over_std * gbeta
        gvar = - 0.5 * self.inv_var * (
            gamma * ggamma).astype(var.dtype, copy=False)

        gx = gx.astype(dtype=x.dtype)

        self.retain_outputs((0, 1, 2, 3, 4))
        return gx, ggamma, gbeta, gmean, gvar 
Example 4
Project: EpiTator   Author: ecohealthalliance   File: geoname_classifier.py    License: Apache License 2.0 6 votes vote down vote up
def predict_proba(X, classifier):
    """Probability estimation for OvR logistic regression.
    Positive class probabilities are computed as
    1. / (1. + np.exp(-classifier.decision_function(X)));
    multiclass is handled by normalizing that over all classes.
    """
    prob = np.dot(X, classifier['coef_'].T) + classifier['intercept_']
    prob = prob.ravel() if prob.shape[1] == 1 else prob
    prob *= -1
    np.exp(prob, prob)
    prob += 1
    np.reciprocal(prob, prob)
    if prob.ndim == 1:
        return np.vstack([1 - prob, prob]).T
    else:
        # OvR normalization, like LibLinear's predict_probability
        prob /= prob.sum(axis=1).reshape((prob.shape[0], -1))
        return prob 
Example 5
Project: gxpy   Author: GeosoftInc   File: utility.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def vector_normalize(v):
    """
    Normalise (Euclidean) the last axis of a numpy array

    :param v: numpy vector array, any dimension
    :return:  array normalized, 0 vectors will be np.nan

    .. versionadded:: 9.3.1
    """
    if v.ndim < 2:
        return np.array((1.,))
    vs = v.shape
    v = v.reshape((-1, v.shape[-1]))
    mag = np.linalg.norm(v, axis=1)
    mag[mag == 0.] = np.nan
    return (v.T * np.reciprocal(mag)).T.reshape(vs) 
Example 6
Project: demon   Author: lmb-freiburg   File: metrics.py    License: GNU General Public License v3.0 6 votes vote down vote up
def l1_inverse(depth1,depth2):
    """
    Computes the l1 errors between inverses of two depth maps.
    Takes preprocessed depths (no nans, infs and non-positive values)

    depth1:  one depth map
    depth2:  another depth map

    Returns: 
        L1(log)

    """
    assert(np.all(np.isfinite(depth1) & np.isfinite(depth2) & (depth1 > 0) & (depth2 > 0)))
    diff = np.reciprocal(depth1) - np.reciprocal(depth2)
    num_pixels = float(diff.size)
    
    if num_pixels == 0:
        return np.nan
    else:
        return np.sum(np.absolute(diff)) / num_pixels 
Example 7
Project: nettack   Author: danielzuegner   File: nettack.py    License: MIT License 5 votes vote down vote up
def compute_cooccurrence_constraint(self, nodes):
        """
        Co-occurrence constraint as described in the paper.

        Parameters
        ----------
        nodes: np.array
            Nodes whose features are considered for change

        Returns
        -------
        np.array [len(nodes), D], dtype bool
            Binary matrix of dimension len(nodes) x D. A 1 in entry n,d indicates that
            we are allowed to add feature d to the features of node n.

        """

        words_graph = self.cooc_matrix.copy()
        D = self.X_obs.shape[1]
        words_graph.setdiag(0)
        words_graph = (words_graph > 0)
        word_degrees = np.sum(words_graph, axis=0).A1

        inv_word_degrees = np.reciprocal(word_degrees.astype(float) + 1e-8)

        sd = np.zeros([self.N])
        for n in range(self.N):
            n_idx = self.X_obs[n, :].nonzero()[1]
            sd[n] = np.sum(inv_word_degrees[n_idx.tolist()])

        scores_matrix = sp.lil_matrix((self.N, D))

        for n in nodes:
            common_words = words_graph.multiply(self.X_obs[n])
            idegs = inv_word_degrees[common_words.nonzero()[1]]
            nnz = common_words.nonzero()[0]
            scores = np.array([idegs[nnz == ix].sum() for ix in range(D)])
            scores_matrix[n] = scores
        self.cooc_constraint = sp.csr_matrix(scores_matrix - 0.5 * sd[:, None] > 0) 
Example 8
Project: recruit   Author: Frank-qlu   File: test_scalarmath.py    License: Apache License 2.0 5 votes vote down vote up
def test_blocked(self):
        # test alignments offsets for simd instructions
        # alignments for vz + 2 * (vs - 1) + 1
        for dt, sz in [(np.float32, 11), (np.float64, 7), (np.int32, 11)]:
            for out, inp1, inp2, msg in _gen_alignment_data(dtype=dt,
                                                            type='binary',
                                                            max_size=sz):
                exp1 = np.ones_like(inp1)
                inp1[...] = np.ones_like(inp1)
                inp2[...] = np.zeros_like(inp2)
                assert_almost_equal(np.add(inp1, inp2), exp1, err_msg=msg)
                assert_almost_equal(np.add(inp1, 2), exp1 + 2, err_msg=msg)
                assert_almost_equal(np.add(1, inp2), exp1, err_msg=msg)

                np.add(inp1, inp2, out=out)
                assert_almost_equal(out, exp1, err_msg=msg)

                inp2[...] += np.arange(inp2.size, dtype=dt) + 1
                assert_almost_equal(np.square(inp2),
                                    np.multiply(inp2, inp2),  err_msg=msg)
                # skip true divide for ints
                if dt != np.int32 or (sys.version_info.major < 3 and not sys.py3kwarning):
                    assert_almost_equal(np.reciprocal(inp2),
                                        np.divide(1, inp2),  err_msg=msg)

                inp1[...] = np.ones_like(inp1)
                np.add(inp1, 2, out=out)
                assert_almost_equal(out, exp1 + 2, err_msg=msg)
                inp2[...] = np.ones_like(inp2)
                np.add(2, inp2, out=out)
                assert_almost_equal(out, exp1 + 2, err_msg=msg) 
Example 9
Project: PySpice   Author: FabriceSalvaire   File: Unit.py    License: GNU General Public License v3.0 5 votes vote down vote up
def reciprocal(self):
        return self.power(-1)

    ############################################## 
Example 10
Project: PySpice   Author: FabriceSalvaire   File: Unit.py    License: GNU General Public License v3.0 5 votes vote down vote up
def reciprocal(self, prefixed_unit=False):
        si_unit = self._si_unit.reciprocal()
        return self._equivalent_unit_or_power(si_unit, prefixed_unit)

    ############################################## 
Example 11
Project: PySpice   Author: FabriceSalvaire   File: Unit.py    License: GNU General Public License v3.0 5 votes vote down vote up
def reciprocal(self):
        equivalent_unit = self.unit.reciprocal(prefixed_unit=True)
        reciprocal_value = 1. / float(self)
        return equivalent_unit.new_value(reciprocal_value)

    ############################################## 
Example 12
Project: PySpice   Author: FabriceSalvaire   File: Unit.py    License: GNU General Public License v3.0 5 votes vote down vote up
def reciprocal(self):
        equivalent_unit = self.unit.reciprocal(prefixed_unit=True)
        reciprocal_value = 1. / np.as_ndarray(True)
        return self.from_ndarray(reciprocal_value, equivalent_unit)

    ############################################## 
Example 13
Project: PySpice   Author: FabriceSalvaire   File: Unit.py    License: GNU General Public License v3.0 5 votes vote down vote up
def period(self):
        r""" Return the period :math:`T = \frac{1}{f}`. """
        return self.reciprocal()

    ############################################## 
Example 14
Project: ngraph-onnx   Author: NervanaSystems   File: test_ops_unary.py    License: Apache License 2.0 5 votes vote down vote up
def test_reciprocal(input_data):
    expected_output = np.reciprocal(input_data)
    node = onnx.helper.make_node('Reciprocal', inputs=['x'], outputs=['y'])
    ng_results = run_node(node, [input_data])
    assert np.allclose(ng_results, [expected_output]) 
Example 15
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_scalarmath.py    License: MIT License 5 votes vote down vote up
def test_blocked(self):
        # test alignments offsets for simd instructions
        # alignments for vz + 2 * (vs - 1) + 1
        for dt, sz in [(np.float32, 11), (np.float64, 7)]:
            for out, inp1, inp2, msg in _gen_alignment_data(dtype=dt,
                                                            type='binary',
                                                            max_size=sz):
                exp1 = np.ones_like(inp1)
                inp1[...] = np.ones_like(inp1)
                inp2[...] = np.zeros_like(inp2)
                assert_almost_equal(np.add(inp1, inp2), exp1, err_msg=msg)
                assert_almost_equal(np.add(inp1, 1), exp1 + 1, err_msg=msg)
                assert_almost_equal(np.add(1, inp2), exp1, err_msg=msg)

                np.add(inp1, inp2, out=out)
                assert_almost_equal(out, exp1, err_msg=msg)

                inp2[...] += np.arange(inp2.size, dtype=dt) + 1
                assert_almost_equal(np.square(inp2),
                                    np.multiply(inp2, inp2),  err_msg=msg)
                assert_almost_equal(np.reciprocal(inp2),
                                    np.divide(1, inp2),  err_msg=msg)

                inp1[...] = np.ones_like(inp1)
                inp2[...] = np.zeros_like(inp2)
                np.add(inp1, 1, out=out)
                assert_almost_equal(out, exp1 + 1, err_msg=msg)
                np.add(1, inp2, out=out)
                assert_almost_equal(out, exp1, err_msg=msg) 
Example 16
Project: vedaseg   Author: Media-Smart   File: transforms.py    License: Apache License 2.0 5 votes vote down vote up
def __call__(self, image, mask):
        mean = np.reshape(np.array(self.mean, dtype=image.dtype), [1, 1, self.channel])
        std = np.reshape(np.array(self.std, dtype=image.dtype), [1, 1, self.channel])
        denominator = np.reciprocal(std, dtype=image.dtype)

        new_image = (image - mean) * denominator
        new_mask = mask

        return new_image, new_mask 
Example 17
Project: vnpy_crypto   Author: birforce   File: test_scalarmath.py    License: MIT License 5 votes vote down vote up
def test_blocked(self):
        # test alignments offsets for simd instructions
        # alignments for vz + 2 * (vs - 1) + 1
        for dt, sz in [(np.float32, 11), (np.float64, 7), (np.int32, 11)]:
            for out, inp1, inp2, msg in _gen_alignment_data(dtype=dt,
                                                            type='binary',
                                                            max_size=sz):
                exp1 = np.ones_like(inp1)
                inp1[...] = np.ones_like(inp1)
                inp2[...] = np.zeros_like(inp2)
                assert_almost_equal(np.add(inp1, inp2), exp1, err_msg=msg)
                assert_almost_equal(np.add(inp1, 2), exp1 + 2, err_msg=msg)
                assert_almost_equal(np.add(1, inp2), exp1, err_msg=msg)

                np.add(inp1, inp2, out=out)
                assert_almost_equal(out, exp1, err_msg=msg)

                inp2[...] += np.arange(inp2.size, dtype=dt) + 1
                assert_almost_equal(np.square(inp2),
                                    np.multiply(inp2, inp2),  err_msg=msg)
                # skip true divide for ints
                if dt != np.int32 or (sys.version_info.major < 3 and not sys.py3kwarning):
                    assert_almost_equal(np.reciprocal(inp2),
                                        np.divide(1, inp2),  err_msg=msg)

                inp1[...] = np.ones_like(inp1)
                np.add(inp1, 2, out=out)
                assert_almost_equal(out, exp1 + 2, err_msg=msg)
                inp2[...] = np.ones_like(inp2)
                np.add(2, inp2, out=out)
                assert_almost_equal(out, exp1 + 2, err_msg=msg) 
Example 18
Project: DeepRobust   Author: DSE-MSU   File: nettack.py    License: MIT License 5 votes vote down vote up
def compute_cooccurrence_constraint(self, nodes):
        """
        Co-occurrence constraint as described in the paper.

        Parameters
        ----------
        nodes: np.array
            Nodes whose features are considered for change

        Returns
        -------
        np.array [len(nodes), D], dtype bool
            Binary matrix of dimension len(nodes) x D. A 1 in entry n,d indicates that
            we are allowed to add feature d to the features of node n.

        """

        words_graph = self.cooc_matrix.copy()
        D = self.modified_features.shape[1]
        words_graph.setdiag(0)
        words_graph = (words_graph > 0)
        word_degrees = np.sum(words_graph, axis=0).A1

        inv_word_degrees = np.reciprocal(word_degrees.astype(float) + 1e-8)

        sd = np.zeros([self.nnodes])
        for n in range(self.nnodes):
            n_idx = self.modified_features[n, :].nonzero()[1]
            sd[n] = np.sum(inv_word_degrees[n_idx.tolist()])

        scores_matrix = sp.lil_matrix((self.nnodes, D))

        for n in nodes:
            common_words = words_graph.multiply(self.modified_features[n])
            idegs = inv_word_degrees[common_words.nonzero()[1]]
            nnz = common_words.nonzero()[0]
            scores = np.array([idegs[nnz == ix].sum() for ix in range(D)])
            scores_matrix[n] = scores
        self.cooc_constraint = sp.csr_matrix(scores_matrix - 0.5 * sd[:, None] > 0) 
Example 19
Project: onnx-tensorflow   Author: onnx   File: test_node.py    License: Apache License 2.0 5 votes vote down vote up
def _batch_normalization(self, x, mean, variance, bias, scale,
                           variance_epsilon):
    inv = np.reciprocal(np.sqrt(variance + variance_epsilon))
    if scale is not None:
      inv *= scale
    return x * inv + (bias - mean * inv if bias is not None else -mean * inv) 
Example 20
Project: ngraph-python   Author: NervanaSystems   File: test_ops_unary.py    License: Apache License 2.0 5 votes vote down vote up
def test_reciprocal(input_data):
    expected_output = np.reciprocal(input_data)
    node = onnx.helper.make_node('Reciprocal', inputs=['x'], outputs=['y'])
    ng_results = convert_and_calculate(node, [input_data], [expected_output])
    assert np.allclose(ng_results, [expected_output]) 
Example 21
Project: ngraph-python   Author: NervanaSystems   File: cputransform.py    License: Apache License 2.0 5 votes vote down vote up
def generate_op(self, op, out, x):
        self.append("np.reciprocal({}, out={})", x, out) 
Example 22
Project: ngraph-python   Author: NervanaSystems   File: test_execution.py    License: Apache License 2.0 5 votes vote down vote up
def test_reciprocal(input_tensor):
    """TODO."""
    p_u = input_tensor
    u = rng.uniform(.1, 5.0, p_u.axes)

    rec_u_np = np.reciprocal(u)
    rec_u = ng.reciprocal(p_u)

    with ExecutorFactory() as ex:
        rec_u_graph = ex.executor(rec_u, p_u)(u)
    ng.testing.assert_allclose(rec_u_np, rec_u_graph) 
Example 23
Project: ngraph-python   Author: NervanaSystems   File: test_execution.py    License: Apache License 2.0 5 votes vote down vote up
def test_reciprocal_derivative(input_tensor):
    """TODO."""
    p_u = input_tensor

    delta = .001

    u = rng.uniform(.1, 5.0, p_u.axes)

    rec_u = ng.reciprocal(p_u)

    check_derivative(rec_u, p_u, delta, u, atol=1e-2, rtol=1e-2) 
Example 24
Project: ngraph-python   Author: NervanaSystems   File: test_execution.py    License: Apache License 2.0 5 votes vote down vote up
def test_variance_sqrt_inverse(input_tensor):
    inputs = input_tensor
    targets = ng.placeholder(inputs.axes)

    epsilon = 1e-3

    inp_stat = ng.reciprocal(
        ng.sqrt(
            ng.variance(inputs, reduction_axes=inputs.axes.batch_axes()) + epsilon
        )
    )
    err = ng.sum(inp_stat - targets, out_axes=())
    d_inputs = ng.deriv(err, inputs)
    with executor([err, d_inputs], inputs, targets) as comp_func:

        input_value = rng.uniform(-1, 1, inputs.axes)
        target_value = rng.uniform(-1, 1, targets.axes)
        ng_f_res, ng_b_res = comp_func(input_value, target_value)

        npv = np.var(input_value, axis=1, keepdims=True) + epsilon
        np_f_res = 1.0 / np.sqrt(npv)

        npv_delta = 2 * (input_value - np.mean(input_value, axis=1, keepdims=True))

        np_b_res = - 0.5 * np_f_res / npv * npv_delta

        np_f_res = np.sum(np_f_res - target_value)

        ng.testing.assert_allclose(np_f_res, ng_f_res, atol=1e-4, rtol=1e-4)
        ng.testing.assert_allclose(np_b_res, ng_b_res, atol=1e-4, rtol=1e-4) 
Example 25
Project: quaternion   Author: moble   File: test_quaternion.py    License: MIT License 5 votes vote down vote up
def test_as_rotation_matrix(Rs):
    def quat_mat(quat):
        return np.array([(quat * v * quat.inverse()).vec for v in [quaternion.x, quaternion.y, quaternion.z]]).T

    def quat_mat_vec(quats):
        mat_vec = np.array([quaternion.as_float_array(quats * v * np.reciprocal(quats))[..., 1:]
                            for v in [quaternion.x, quaternion.y, quaternion.z]])
        return np.transpose(mat_vec, tuple(range(mat_vec.ndim))[1:-1]+(-1, 0))

    with pytest.raises(ZeroDivisionError):
        quaternion.as_rotation_matrix(quaternion.zero)

    for R in Rs:
        # Test correctly normalized rotors:
        assert allclose(quat_mat(R), quaternion.as_rotation_matrix(R), atol=2*eps)
        # Test incorrectly normalized rotors:
        assert allclose(quat_mat(R), quaternion.as_rotation_matrix(1.1*R), atol=2*eps)

    Rs0 = Rs.copy()
    Rs0[Rs.shape[0]//2] = quaternion.zero
    with pytest.raises(ZeroDivisionError):
        quaternion.as_rotation_matrix(Rs0)

    # Test correctly normalized rotors:
    assert allclose(quat_mat_vec(Rs), quaternion.as_rotation_matrix(Rs), atol=2*eps)
    # Test incorrectly normalized rotors:
    assert allclose(quat_mat_vec(Rs), quaternion.as_rotation_matrix(1.1*Rs), atol=2*eps)

    # Simply test that this function succeeds and returns the right shape
    assert quaternion.as_rotation_matrix(Rs.reshape((2, 5, 10))).shape == (2, 5, 10, 3, 3) 
Example 26
Project: quaternion   Author: moble   File: test_quaternion.py    License: MIT License 5 votes vote down vote up
def test_quaternion_divide(Qs):
    # Check identity between "inverse" and "reciprocal"
    for q in Qs[Qs_finitenonzero]:
        assert q.inverse() == q.reciprocal()

    # Check scalar division
    for q in Qs[Qs_finitenonzero]:
        assert allclose(q / q, quaternion.one)
        assert allclose(1 / q, q.inverse())
        assert allclose(1.0 / q, q.inverse())
        assert 0.0 / q == quaternion.zero
        for s in [-3, -2.3, -1.2, -1.0, 0.0, 0, 1.0, 1, 1.2, 2.3, 3]:
            assert allclose(s / q, s * (q.inverse()))
    for q in Qs[Qs_nonnan]:
        assert q / 1.0 == q
        assert q / 1 == q
        for s in [-3, -2.3, -1.2, -1.0, 1.0, 1, 1.2, 2.3, 3]:
            assert allclose(q / s, q * (1.0/s))

    # Check linearity
    for q1 in Qs[Qs_finite]:
        for q2 in Qs[Qs_finite]:
            for q3 in Qs[Qs_finitenonzero]:
                assert allclose((q1+q2)/q3, (q1/q3)+(q2/q3))

    # Check the multiplication table
    for q in [Qs[q_1], Qs[x], Qs[y], Qs[z]]:
        assert Qs[q_1] / q == q.conj()
        assert q / Qs[q_1] == q
    assert Qs[x] / Qs[x] == Qs[q_1]
    assert Qs[x] / Qs[y] == -Qs[z]
    assert Qs[x] / Qs[z] == Qs[y]
    assert Qs[y] / Qs[x] == Qs[z]
    assert Qs[y] / Qs[y] == Qs[q_1]
    assert Qs[y] / Qs[z] == -Qs[x]
    assert Qs[z] / Qs[x] == -Qs[y]
    assert Qs[z] / Qs[y] == Qs[x]
    assert Qs[z] / Qs[z] == Qs[q_1] 
Example 27
Project: osqp-python   Author: oxfordcontrol   File: _osqp.py    License: Apache License 2.0 5 votes vote down vote up
def set_rho_vec(self):
        """
        Set values of rho vector based on constraint types
        """
        self.work.settings.rho = np.minimum(np.maximum(self.work.settings.rho,
                                            RHO_MIN), RHO_MAX)

        # Find indices of loose bounds, equality constr and one-sided constr
        loose_ind = np.where(np.logical_and(
                            self.work.data.l < -OSQP_INFTY*MIN_SCALING,
                            self.work.data.u > OSQP_INFTY*MIN_SCALING))[0]
        eq_ind = np.where(self.work.data.u - self.work.data.l < RHO_TOL)[0]
        ineq_ind = np.setdiff1d(np.setdiff1d(np.arange(self.work.data.m),
                                loose_ind), eq_ind)

        # Type of constraints
        self.work.constr_type[loose_ind] = -1
        self.work.constr_type[eq_ind] = 1
        self.work.constr_type[ineq_ind] = 0

        self.work.rho_vec[loose_ind] = RHO_MIN
        self.work.rho_vec[eq_ind] = RHO_EQ_OVER_RHO_INEQ * \
            self.work.settings.rho
        self.work.rho_vec[ineq_ind] = self.work.settings.rho

        self.work.rho_inv_vec = np.reciprocal(self.work.rho_vec) 
Example 28
Project: osqp-python   Author: oxfordcontrol   File: _osqp.py    License: Apache License 2.0 5 votes vote down vote up
def update_rho_vec(self):
        """
        Update values of rho_vec and refactor if constraints change.
        """
        # Find indices of loose bounds, equality constr and one-sided constr
        loose_ind = np.where(np.logical_and(
                            self.work.data.l < -OSQP_INFTY*MIN_SCALING,
                            self.work.data.u > OSQP_INFTY*MIN_SCALING))[0]
        eq_ind = np.where(self.work.data.u - self.work.data.l < RHO_TOL)[0]
        ineq_ind = np.setdiff1d(np.setdiff1d(np.arange(self.work.data.m),
                                loose_ind), eq_ind)

        # Find indices of current constraint types
        old_loose_ind = np.where(self.work.constr_type == -1)
        old_eq_ind = np.where(self.work.constr_type == 1)
        old_ineq_ind = np.where(self.work.constr_type == 0)

        # Check if type of any constraint changed
        constr_type_changed = (loose_ind != old_loose_ind).any() or \
                              (eq_ind != old_eq_ind).any() or \
                              (ineq_ind != old_ineq_ind).any()

        # Update type of constraints
        self.work.constr_type[loose_ind] = -1
        self.work.constr_type[eq_ind] = 1
        self.work.constr_type[ineq_ind] = 0

        self.work.rho_vec[loose_ind] = RHO_MIN
        self.work.rho_vec[eq_ind] = RHO_EQ_OVER_RHO_INEQ * \
            self.work.settings.rho
        self.work.rho_vec[ineq_ind] = self.work.settings.rho

        self.work.rho_inv_vec = np.reciprocal(self.work.rho_vec)

        if constr_type_changed:
            self.work.linsys_solver = linsys_solver(self.work) 
Example 29
Project: Computable   Author: ktraunmueller   File: test_scalarmath.py    License: MIT License 5 votes vote down vote up
def test_blocked(self):
        #test alignments offsets for simd instructions
        for dt in [np.float32, np.float64]:
            for out, inp1, inp2, msg in _gen_alignment_data(dtype=dt,
                                                            type='binary',
                                                            max_size=12):
                exp1 = np.ones_like(inp1)
                inp1[...] = np.ones_like(inp1)
                inp2[...] = np.zeros_like(inp2)
                assert_almost_equal(np.add(inp1, inp2), exp1, err_msg=msg)
                assert_almost_equal(np.add(inp1, 1), exp1 + 1, err_msg=msg)
                assert_almost_equal(np.add(1, inp2), exp1, err_msg=msg)

                np.add(inp1, inp2, out=out)
                assert_almost_equal(out, exp1, err_msg=msg)

                inp2[...] += np.arange(inp2.size, dtype=dt) + 1
                assert_almost_equal(np.square(inp2),
                                    np.multiply(inp2, inp2),  err_msg=msg)
                assert_almost_equal(np.reciprocal(inp2),
                                    np.divide(1, inp2),  err_msg=msg)

                inp1[...] = np.ones_like(inp1)
                inp2[...] = np.zeros_like(inp2)
                np.add(inp1, 1, out=out)
                assert_almost_equal(out, exp1 + 1, err_msg=msg)
                np.add(1, inp2, out=out)
                assert_almost_equal(out, exp1, err_msg=msg) 
Example 30
Project: tfdeploy   Author: riga   File: tfdeploy.py    License: MIT License 5 votes vote down vote up
def Inv(a):
    """
    Reciprocal op.
    """
    return np.reciprocal(a),