Returns the power mismatch constraint (B*Va + Pg = Pd).
175649
def _power_mismatch_dc(self, buses, generators, B, Pbusinj, base_mva):
        
        nb, ng = len(buses), len(generators)
        # Negative bus-generator incidence matrix.
        gen_bus = array([g.bus._i for g in generators])
        neg_Cg = csr_matrix((-ones(ng), (gen_bus, range(ng))), (nb, ng))

        Amis = hstack([B, neg_Cg], format="csr")

        Pd = array([bus.p_demand for bus in buses])
        Gs = array([bus.g_shunt for bus in buses])

        bmis = -(Pd - Gs) / base_mva - Pbusinj

        return LinearConstraint("Pmis", Amis, bmis, bmis, ["Va", "Pg"])
1104630
def _select_vs(v, p):
    # This one is is about 30 times faster than
    # the generic algorithm it is replacing.
    """"""

    if v >= 120.:
        return 60, 120, inf
    elif v >= 60.:
        return 40, 60, 120
    elif v >= 40.:
        return 30, 40, 60
    elif v >= 30.:
        return 24, 30, 40
    elif v >= 24.:
        return 20, 24, 30
    elif v >= 19.5:
        return 19, 20, 24

    if p >= .9:
        if v < 2.5:
            return 1, 2, 3
    else:
        if v < 3.5:
            return 2, 3, 4

    vi = int(round(v))
    return vi - 1, vi, vi + 1
1131772
def ph_supconj(b, orbit, solve_for=None, **kwargs):
    
    orbit_ps = _get_system_ps(b, orbit)

    # metawargs = orbit_ps.meta
    #metawargs.pop('qualifier')

    # t0_ph0 and phshift both exist by default, so we don't have to worry about creating either
    # t0_ph0 = orbit_ps.get_parameter(qualifier='t0_ph0')
    # phshift = orbit_ps.get_parameter(qualifier='phshift')
    ph_supconj = orbit_ps.get_parameter(qualifier='ph_supconj')
    per0 = orbit_ps.get_parameter(qualifier='per0')
    ecc = orbit_ps.get_parameter(qualifier='ecc')
    period = orbit_ps.get_parameter(qualifier='period')

    # true_anom_supconj = pi/2 - per0
    # mean_anom_supconj = true_anom_supconj - ecc*sin(true_anom_supconj)
    # ph_supconj = (mean_anom_supconj + per0) / (2 * pi) - 1/4

    if solve_for in [None, ph_supconj]:
        lhs = ph_supconj

        #true_anom_supconj = np.pi/2*u.rad - per0
        true_anom_supconj = -1*(per0 - 360*u.deg)

        rhs = _true_anom_to_phase(true_anom_supconj, period, ecc, per0)

    #elif solve_for in [per0]:
    #    raise NotImplementedError("phshift constraint does not support solving for per0 yet")
    else:
        raise NotImplementedError

    return lhs, rhs, {'orbit': orbit}
1364330
def constraint(self, n=-1, fid=0):
        
        c = self._getval("constr", fid)
        if n < 0 or n > self.deficiency(fid):
            return c
        else:
            raise RuntimeError("Not yet implemented")
832875
def DampedPowerlaw(q, a, alpha, sigma):
    
    return a * q ** alpha * np.exp(-q ** 2 / (2 * sigma ** 2))
33214
def _power(ctx, number, power):
    
    return decimal_pow(conversions.to_decimal(number, ctx), conversions.to_decimal(power, ctx))
454815
def _p_iteration(self, P, Bp_solver, Vm, Va, pvpq):
        
        dVa = -Bp_solver.solve(P)

        # Update voltage.
        Va[pvpq] = Va[pvpq] + dVa
        V = Vm * exp(1j * Va)

        return V, Vm, Va
725150
def pvwatts_ac(self, pdc):
        
        kwargs = _build_kwargs(['eta_inv_nom', 'eta_inv_ref'],
                               self.inverter_parameters)

        return pvwatts_ac(pdc, self.module_parameters['pdc0'], **kwargs)
279919
def _polevl(x, coefs, N):
    
    ans = 0
    power = len(coefs) - 1
    for coef in coefs:
        try:
            ans += coef * x**power
        except OverflowError:
            pass
        power -= 1
    return ans
473909
private int compareMagnitude(BigDecimal val) {
        // Match scales, avoid unnecessary inflation
        long ys = val.intCompact;
        long xs = this.intCompact;
        if (xs == 0)
            return (ys == 0) ? 0 : -1;
        if (ys == 0)
            return 1;

        long sdiff = (long)this.scale - val.scale;
        if (sdiff != 0) {
            // Avoid matching scales if the (adjusted) exponents differ
            long xae = (long)this.precision() - this.scale;   // [-1]
            long yae = (long)val.precision() - val.scale;     // [-1]
            if (xae < yae)
                return -1;
            if (xae > yae)
                return 1;
            BigInteger rb = null;
            if (sdiff < 0) {
                // The cases sdiff <= Integer.MIN_VALUE intentionally fall through.
                if ( sdiff > Integer.MIN_VALUE &&
                      (xs == INFLATED ||
                      (xs = longMultiplyPowerTen(xs, (int)-sdiff)) == INFLATED) &&
                     ys == INFLATED) {
                    rb = bigMultiplyPowerTen((int)-sdiff);
                    return rb.compareMagnitude(val.intVal);
                }
            } else { // sdiff > 0
                // The cases sdiff > Integer.MAX_VALUE intentionally fall through.
                if ( sdiff <= Integer.MAX_VALUE &&
                      (ys == INFLATED ||
                      (ys = longMultiplyPowerTen(ys, (int)sdiff)) == INFLATED) &&
                     xs == INFLATED) {
                    rb = val.bigMultiplyPowerTen((int)sdiff);
                    return this.intVal.compareMagnitude(rb);
                }
            }
        }
        if (xs != INFLATED)
            return (ys != INFLATED) ? longCompareMagnitude(xs, ys) : -1;
        else if (ys != INFLATED)
            return 1;
        else
            return this.intVal.compareMagnitude(val.intVal);
    }
392342
def _constraint(self, params):
        

        # ensure that mass1 > mass2
        if params["mass1"] < params["mass2"]:
            return False

        # constraint for secondary mass
        a = ((4.0 * params["q"]**2 + 3.0 * params["q"])
                 / (4.0 + 3.0 * params["q"]) * params["xi2"])**2
        b = ((1.0 + params["q"]**2) / 4.0
                 * (params["chi_eff"] + params["chi_a"])**2)
        if a + b > 1:
            return False

        # constraint for primary mass
        a = params["xi1"]**2
        b = ((1.0 + params["q"])**2 / (4.0 * params["q"]**2)
                 * (params["chi_eff"] - params["chi_a"])**2)
        if a + b > 1:
            return False

        return True
169894
def relaxation_operators(p):
    
    k0 = np.array([[1.0, 0.0], [0.0, np.sqrt(1 - p)]])
    k1 = np.array([[0.0, np.sqrt(p)], [0.0, 0.0]])
    return k0, k1
54296
def _run_power_flow(self, Ybus, Sbus, V, pv, pq, pvpq):
        
        i = 0
        Va = angle(V)
        Vm = abs(V)

        # FIXME: Do not repeat build for each Q limit loop.
        Bp, Bpp = self.case.makeB(method=self.method)

        # Evaluate initial mismatch.
        P, Q = self._evaluate_mismatch(Ybus, V, Sbus, pq, pvpq)

        if self.verbose:
            logger.info("iteration     max mismatch (p.u.)  \n")
            logger.info("type   #        P            Q     \n")
            logger.info("---- ----  -----------  -----------\n")

        # Check tolerance.
        converged = self._check_convergence(P, Q, i, "P")

        if converged and self.verbose:
            logger.info("Converged!")

        # Reduce B matrices.
        pq_col = [[k] for k in pq]
        pvpq_col = [[k] for k in pvpq]
        Bp = Bp[pvpq_col, pvpq].tocsc() # splu requires a CSC matrix
        Bpp = Bpp[pq_col, pq].tocsc()

        # Factor B matrices.
        Bp_solver = splu(Bp)
        Bpp_solver = splu(Bpp)
#        L = decomp.lu(Bp.todense())
#        LU, P = decomp.lu_factor(Bp.todense())

        # Perform Newton iterations.
        while (not converged) and (i < self.iter_max):
            i += 1
            # Perform P iteration, update Va.
            V, Vm, Va = self._p_iteration(P, Bp_solver, Vm, Va, pvpq)

            # Evalute mismatch.
            P, Q = self._evaluate_mismatch(Ybus, V, Sbus, pq, pvpq)
            # Check tolerance.
            converged = self._check_convergence(P, Q, i, "P")

            if self.verbose and converged:
                logger.info("Fast-decoupled power flow converged in %d "
                    "P-iterations and %d Q-iterations." % (i, i - 1))
                break

            # Perform Q iteration, update Vm.
            V, Vm, Va = self._q_iteration(Q, Bpp_solver, Vm, Va, pq)

            # Evalute mismatch.
            P, Q = self._evaluate_mismatch(Ybus, V, Sbus, pq, pvpq)
            # Check tolerance.
            converged = self._check_convergence(P, Q, i, "Q")

            if self.verbose and converged:
                logger.info("Fast-decoupled power flow converged in %d "
                    "P-iterations and %d Q-iterations." % (i, i))
                break

        if self.verbose and not converged:
            logger.error("FDPF did not converge in %d iterations." % i)

        return V, converged, i
919926
def check_constraint_convergence(X, L, LX, Z, U, R, S, step_f, step_g, e_rel, e_abs):
    

    if isinstance(L, list):
        M = len(L)
        convergence = True
        errors = []
        # recursive call
        for i in range(M):
            c, e = check_constraint_convergence(X, L[i], LX[i], Z[i], U[i], R[i], S[i],
                                                step_f, step_g[i], e_rel, e_abs)
            convergence &= c
            errors.append(e)
        return convergence, errors
    else:
        # check convergence of prime residual R and dual residual S
        e_pri, e_dual = get_variable_errors(X, L, LX, Z, U, step_g, e_rel, e_abs)
        lR = l2(R)
        lS = l2(S)
        convergence = (lR <= e_pri) and (lS <= e_dual)
        return convergence, (e_pri, e_dual, lR, lS)
1264657
def pow2(x: int, p: int) -> int:
    """"""
    while p > 0:
        x = x * x % q
        p -= 1
    return x
1363023
def getV0(self, v_mag_guess, buses, generators, type=CASE_GUESS):
        
        if type == CASE_GUESS:
            Va = array([b.v_angle * (pi / 180.0) for b in buses])
            Vm = array([b.v_magnitude for b in buses])
            V0 = Vm * exp(1j * Va)
        elif type == FLAT_START:
            V0 = ones(len(buses))
        elif type == FROM_INPUT:
            V0 = v_mag_guess
        else:
            raise ValueError

        # Set the voltages of PV buses and the reference bus in the guess.
#        online = [g for g in self.case.generators if g.online]
        gbus = [g.bus._i for g in generators]
        Vg = array([g.v_magnitude for g in generators])

        V0[gbus] = Vg * abs(V0[gbus]) / V0[gbus]

        return V0
301946
def in_constraint(self, node1, node2):
        """"""
        constraint = constraint_table[node2]
        if constraint == 0b0:
            return False

        try:
            value = self.el2bv[node1]
        except KeyError:
            return False

        return constraint & value != 0