Beispiel #1
0
def first_time_step():

    # compute first time step
    # estimate the minimum time step
    if not system.DAE.nx:
        freq = 1.0
    elif system.DAE.nx == 1:
        B = matrix(system.DAE.Gx)
        linsolve(system.DAE.Gy, B)
        As = system.DAE.Fx - system.DAE.Fy * B
        freq = abs(As[0, 0])
    else:
        freq = 40.0

    if freq > system.Settings.freq:
        freq = float(system.Settings.freq)
    if not freq: freq = 40.0
    # set the minimum time step
    deltaT = abs(system.Settings.tf - system.Settings.t0)
    Tstep = 1 / freq
    system.Settings.deltatmax = min(5 * Tstep, deltaT / 100.0)
    system.Settings.deltat = min(Tstep, deltaT / 100.0)
    system.Settings.deltatmin = min(Tstep / 64, system.Settings.deltatmax / 20)
    if system.Settings.fixt:
        if system.Settings.tstep <= 0:
            print('Fixed time step is negative or zero')
            print('Automatic time step has been set')
            system.Settings.fixt = False
        elif system.Settings.tstep < system.Settings.deltatmin:
            print('Fixed time step is less than estimated minimum time step')
            system.Settings.deltat = system.Settings.tstep
        else:
            system.Settings.deltat = system.Settings.tstep
    return system.Settings.deltat
Beispiel #2
0
def test_pcg():
    'Test function for projected CG.'
    n = 10
    m = 4
    H = sprandsym(n,n)
    A = sp_rand(m,n,0.9)
    x0 = matrix(1,(n,1))
    b = A*x0
    c = matrix(1.0,(n,1))

    x_pcg = pcg(H,c,A,b,x0)


    Lhs1 = sparse([H,A])
    Lhs2 = sparse([A.T,spmatrix([],[],[],(m,m))])
    Lhs = sparse([[Lhs1],[Lhs2]])
    rhs = -matrix([c,spmatrix([],[],[],(m,1))])
    rhs2 = copy(rhs)
    linsolve(Lhs,rhs)
    #print rhs[:10]


    sol = solvers.qp(H,c,A=A,b=b)
    print ' cvxopt qp|   pCG'
    print matrix([[sol['x']],[x_pcg]])
    print 'Dual variables:'
    print sol['y']
    print 'KKT equation residuals:'
    print H*sol['x'] + c + A.T*sol['y']
Beispiel #3
0
def linsolve(A,b):
    aLocal = A.tocoo()
    AC = cvxopt.spmatrix(aLocal.data.tolist(),aLocal.row.tolist(), aLocal.col.tolist())
    bLocal = cvxopt.matrix(copy.deepcopy(b))
    umfpack.linsolve(AC,bLocal)
    bLocal = np.array(bLocal).flatten()
    return bLocal
Beispiel #4
0
def test_pcg():
    'Test function for projected CG.'
    n = 10
    m = 4
    H = sprandsym(n, n)
    A = sp_rand(m, n, 0.9)
    x0 = matrix(1, (n, 1))
    b = A * x0
    c = matrix(1.0, (n, 1))

    x_pcg = pcg(H, c, A, b, x0)

    Lhs1 = sparse([H, A])
    Lhs2 = sparse([A.T, spmatrix([], [], [], (m, m))])
    Lhs = sparse([[Lhs1], [Lhs2]])
    rhs = -matrix([c, spmatrix([], [], [], (m, 1))])
    rhs2 = copy(rhs)
    linsolve(Lhs, rhs)
    #print rhs[:10]

    sol = solvers.qp(H, c, A=A, b=b)
    print ' cvxopt qp|   pCG'
    print matrix([[sol['x']], [x_pcg]])
    print 'Dual variables:'
    print sol['y']
    print 'KKT equation residuals:'
    print H * sol['x'] + c + A.T * sol['y']
Beispiel #5
0
def minG(A, r, G=None):
    'Find y that minimize the norm(r - A.T*y)'
    if G is None:
        Lhs = A * A.T
        rhs = A * r
        cp = copy(rhs)
        linsolve(Lhs, rhs)
        return rhs
Beispiel #6
0
def minG(A,r,G= None):
    'Find y that minimize the norm(r - A.T*y)'
    if G is None:
        Lhs = A*A.T
        rhs = A*r
        cp = copy(rhs)
        linsolve(Lhs,rhs)
        return rhs
Beispiel #7
0
 def state_matrix():
     Gyx = matrix(system.DAE.Gx)
     linsolve(sparse(system.DAE.Gy), Gyx)
     I = []
     J = []
     for i in range(system.DAE.nx):
         I.append(i)
         J.append(i)
     return system.DAE.Fx - system.DAE.Fy * Gyx - spmatrix(1e-6, I, J)
Beispiel #8
0
def project(A,r,G = None, fA = None):
    'Project r to null(A) by solving the normal equation AA.t v = Ar.'
    m,n = A.size
    if G is None:
        G = spmatrix([1]*n,range(n),range(n))
    Lhs1 = sparse([G,A])
    Lhs2 = sparse([A.T, spmatrix([],[],[],(m,m))])
    Lhs = sparse([[Lhs1],[Lhs2]])
    rhs = matrix([r,spmatrix([],[],[],(m,1))])
    linsolve(Lhs,rhs)
    return rhs[:n]
Beispiel #9
0
def project(A, r, G=None, fA=None):
    'Project r to null(A) by solving the normal equation AA.t v = Ar.'
    m, n = A.size
    if G is None:
        G = spmatrix([1] * n, range(n), range(n))
    Lhs1 = sparse([G, A])
    Lhs2 = sparse([A.T, spmatrix([], [], [], (m, m))])
    Lhs = sparse([[Lhs1], [Lhs2]])
    rhs = matrix([r, spmatrix([], [], [], (m, 1))])
    linsolve(Lhs, rhs)
    return rhs[:n]
Beispiel #10
0
    def linsolve(self, A, b):
        """
        Solve linear equation set ``Ax = b`` and store the solutions in ``b``.

        Parameters
        ----------
        A
            Sparse matrix

        b
            RHS of the equation

        Returns
        -------
        None
        """
        if self.sparselib == 'umfpack':
            umfpack.linsolve(A, b)
            return b

        elif self.sparselib == 'klu':
            klu.linsolve(A, b)
            return b

        elif self.sparselib in ('spsolve', 'cupy'):
            ccs = A.CCS
            size = A.size
            data = np.array(ccs[2]).reshape((-1, ))
            indices = np.array(ccs[1]).reshape((-1, ))
            indptr = np.array(ccs[0]).reshape((-1, ))

            A = csc_matrix((data, indices, indptr), shape=size)

            if self.sparselib == 'spsolve':
                x = spsolve(A, b)
                return matrix(x)

            elif self.sparselib == 'cupy':
                # delayed import for startup speed
                import cupy as cp  # NOQA
                from cupyx.scipy.sparse import csc_matrix as csc_cu  # NOQA
                from cupyx.scipy.sparse.linalg.solve import lsqr as cu_lsqr  # NOQA

                cu_A = csc_cu(A)
                cu_b = cp.array(np.array(b).reshape((-1, )))
                x = cu_lsqr(cu_A, cu_b)

                return matrix(cp.asnumpy(x[0]))
Beispiel #11
0
    def linsolve(self, A, b):
        """
        Solve linear equation set ``Ax = b`` and store the solutions in ``b``.

        Parameters
        ----------
        A
            Sparse matrix

        b
            RHS of the equation

        Returns
        -------
        None
        """
        if self.sparselib == 'umfpack':
            return umfpack.linsolve(A, b)

        elif self.sparselib == 'klu':
            return klu.linsolve(A, b)
Beispiel #12
0
def spike_inference(fluor, sigma=None, gamma=None, mode="correct",
                    verbose=False):
    """
    Infer the most likely discretized spike train underlying a fluorescence
    trace.

    Parameters
    ----------
    fluor : ndarray
        One dimensional array containing the fluorescence intensities with
        one entry per time-bin.
    sigma : float, optional
        Standard deviation of the noise distribution.  If no value is given,
        then sigma is estimated from the data.
    gamma : float, optional
        Gamma is 1 - timestep/tau, where tau is the time constant of the AR(1)
        process.  If no value is given, then gamma is estimated from the data.
    mode : {'correct', 'robust'}, optional
        The method for estimating sigma. The 'robust' method overestimates the
        noise by assuming that gamma = 1. Default: 'correct'.
    verbose : bool, optional
        Whether to print status updates. Default: False.

    Returns
    -------
    inference : ndarray of float
        The inferred normalized spike count at each time-bin.  Values are
        normalized to the maximium value over all time-bins.
    fit : ndarray of float
        The inferred denoised fluorescence signal at each time-bin.
    parameters : dict
        Dictionary with values for 'sigma', 'gamma', and 'baseline'.

    References
    ----------
    * Pnevmatikakis et al. 2015. Submitted (arXiv:1409.2903).
    * Machado et al. 2015. Submitted.
    * Vogelstein et al. 2010. Journal of Neurophysiology. 104(6): 3691-3704.

    """
    try:
        import cvxopt.umfpack as umfpack
        from cvxopt import matrix, spdiag
        import picos
    except ImportError:
        raise ImportError('Spike inference requires picos package.')

    if verbose:
        sys.stdout.write('Spike inference...')

    if sigma is None or gamma is None:
        gamma, sigma = estimate_parameters([fluor], gamma, sigma, mode)

    # Make spike generating matrix (eye, but with -g on diag below main diag)
    gen = spdiag([1 for step in range(fluor.size)])
    for step in range(fluor.size):
        if step > 0:
            gen[step, step - 1] = -gamma

    # Use spike generating matrix to initialize other constraint variables
    gen_vec = gen * matrix(np.ones(fluor.size))
    gen_ones = matrix(np.ones(fluor.size))
    umfpack.linsolve(gen, gen_ones)

    # Initialize variables in our problem
    prob = picos.Problem()
    calcium_fit = prob.add_variable('calcium_fit', fluor.size)
    init_calcium = prob.add_variable('init_calcium', 1)
    baseline = prob.add_variable('baseline', 1)

    # Define constraints and objective
    prob.add_constraint(init_calcium > 0)
    prob.add_constraint(gen * calcium_fit > 0)
    res = abs(matrix(fluor.astype(float)) - calcium_fit - baseline - gen_ones *
              init_calcium)
    prob.add_constraint(res < sigma * np.sqrt(fluor.size))
    prob.set_objective('min', calcium_fit.T * gen_vec)

    # Run solver
    start_time = time.time()
    try:
        prob.solve(solver='mosek', verbose=False)
    except ImportError:
        warn('MOSEK is not installed. Spike inference may be VERY slow!')
        prob.solver_selection()
        prob.solve(verbose=False)

    if verbose:
        sys.stdout.write("done!\n" +
                         "Status: " + prob.status +
                         "; Value: " + str(prob.obj_value()) +
                         "; Time: " + str(time.time() - start_time) +
                         "; Baseline = " + str(baseline.value) + "\n")

    # Return calcium model fit and spike inference
    fit = np.squeeze(np.asarray(calcium_fit.value)[np.arange(0, fluor.size)] +
                     baseline.value)
    inference = np.squeeze(np.asarray(gen * matrix(fit)))
    parameters = {'gamma': gamma, 'sigma': sigma,
                  'baseline': baseline.value[0]}
    return inference, fit, parameters
Beispiel #13
0
def spike_inference(fluor,
                    sigma=None,
                    gamma=None,
                    mode="correct",
                    verbose=False):
    """
    Infer the most likely discretized spike train underlying a fluorescence
    trace.

    Parameters
    ----------
    fluor : ndarray
        One dimensional array containing the fluorescence intensities with
        one entry per time-bin.
    sigma : float, optional
        Standard deviation of the noise distribution.  If no value is given,
        then sigma is estimated from the data.
    gamma : float, optional
        Gamma is 1 - timestep/tau, where tau is the time constant of the AR(1)
        process.  If no value is given, then gamma is estimated from the data.
    mode : {'correct', 'robust'}, optional
        The method for estimating sigma. The 'robust' method overestimates the
        noise by assuming that gamma = 1. Default: 'correct'.
    verbose : bool, optional
        Whether to print status updates. Default: False.

    Returns
    -------
    inference : ndarray of float
        The inferred normalized spike count at each time-bin.  Values are
        normalized to the maximium value over all time-bins.
    fit : ndarray of float
        The inferred denoised fluorescence signal at each time-bin.
    parameters : dict
        Dictionary with values for 'sigma', 'gamma', and 'baseline'.

    References
    ----------
    * Pnevmatikakis et al. 2015. Submitted (arXiv:1409.2903).
    * Machado et al. 2015. Submitted.
    * Vogelstein et al. 2010. Journal of Neurophysiology. 104(6): 3691-3704.

    """
    try:
        import cvxopt.umfpack as umfpack
        from cvxopt import matrix, spdiag
        import picos
    except ImportError:
        raise ImportError('Spike inference requires picos package.')

    if verbose:
        sys.stdout.write('Spike inference...')

    if sigma is None or gamma is None:
        gamma, sigma = estimate_parameters([fluor], gamma, sigma, mode)

    # Make spike generating matrix (eye, but with -g on diag below main diag)
    gen = spdiag([1 for step in range(fluor.size)])
    for step in range(fluor.size):
        if step > 0:
            gen[step, step - 1] = -gamma

    # Use spike generating matrix to initialize other constraint variables
    gen_vec = gen * matrix(np.ones(fluor.size))
    gen_ones = matrix(np.ones(fluor.size))
    umfpack.linsolve(gen, gen_ones)

    # Initialize variables in our problem
    prob = picos.Problem()
    calcium_fit = prob.add_variable('calcium_fit', fluor.size)
    init_calcium = prob.add_variable('init_calcium', 1)
    baseline = prob.add_variable('baseline', 1)

    # Define constraints and objective
    prob.add_constraint(init_calcium > 0)
    prob.add_constraint(gen * calcium_fit > 0)
    res = abs(
        matrix(fluor.astype(float)) - calcium_fit - baseline -
        gen_ones * init_calcium)
    prob.add_constraint(res < sigma * np.sqrt(fluor.size))
    prob.set_objective('min', calcium_fit.T * gen_vec)

    # Run solver
    start_time = time.time()
    try:
        prob.solve(solver='mosek', verbose=False)
    except ImportError:
        warn('MOSEK is not installed. Spike inference may be VERY slow!')
        prob.solver_selection()
        prob.solve(verbose=False)

    if verbose:
        sys.stdout.write("done!\n" + "Status: " + prob.status + "; Value: " +
                         str(prob.obj_value()) + "; Time: " +
                         str(time.time() - start_time) + "; Baseline = " +
                         str(baseline.value) + "\n")

    # Return calcium model fit and spike inference
    fit = np.squeeze(
        np.asarray(calcium_fit.value)[np.arange(0, fluor.size)] +
        baseline.value)
    inference = np.squeeze(np.asarray(gen * matrix(fit)))
    parameters = {
        'gamma': gamma,
        'sigma': sigma,
        'baseline': baseline.value[0]
    }
    return inference, fit, parameters
        # 计算雅可比矩阵
        if system.Settings.method == 1:  # 采用欧拉法
            system.DAE.Ac = sparse([[identica - h * system.DAE.Fx, system.DAE.Gx], [-h * system.DAE.Fy, system.DAE.Gy]])
            system.DAE.tn = system.DAE.x - xa - h * system.DAE.f
        elif system.Settings.method == 2:  # 采用隐式梯形法

            system.DAE.Ac = sparse(
                [[identica - h * 0.5 * system.DAE.Fx, system.DAE.Gx], [-h * 0.5 * system.DAE.Fy, system.DAE.Gy]])

            system.DAE.tn = system.DAE.x - xa - h * 0.5 * (system.DAE.f + fn)

        # 限幅器
        system.Avr2.windup('td')

        gg = -matrix([system.DAE.tn, system.DAE.g])
        linsolve(system.DAE.Ac, gg)
        inc = gg

        # if system.DAE.factorize:
        #     F = symbolic(system.DAE.Ac)
        #     system.DAE.factorize = False
        # inc = -matrix([system.DAE.tn, system.DAE.g])
        # try:
        #     umfsolve(system.DAE.Ac, numeric(system.DAE.Ac, F), inc)
        # except ArithmeticError:
        #     print('Singular matrix')
        #     iteration = iter_max+1
        # except ValueError:
        #     F = symbolic(system.DAE.Ac)
        #     try:
        #         umfsolve(system.DAE.Ac, numeric(system.DAE.Ac, F), inc)
Beispiel #15
0
def sssa(datafile):

    start = clock()
    system.Bus._init_data()
    system.PV._init_data()
    system.PQ._init_data()
    system.SW._init_data()
    system.Shunt._init_data()
    system.Line._init_data()
    system.Syn6._init_data()
    system.Avr1._init_data()
    system.Avr2._init_data()
    system.Tg1._init_data()
    system.Ind3._init_data()
    # system.Pss1._init_data()

    case = open(datafile)
    for each_line in case:

        data = each_line.split()

        if data[0] == 'Bus':
            bus = data[0] + '_' + str(data[1])
            Vb = float(data[2])
            bus_case = {'bus': bus, 'Vb': Vb}
            system.Bus.add(idx=bus, **bus_case)

        if data[0] == 'PV':
            bus = 'Bus_' + str(data[1])
            Sn = float(data[2])
            Vn = float(data[3])
            Pg = float(data[4])
            V0 = float(data[5])
            qgmax = float(data[6])
            qgmin = float(data[7])
            Vmax = float(data[8])
            Vmin = float(data[9])
            PV_case = {
                'bus': bus,
                'Sn': Sn,
                'Vn': Vn,
                'Pg': Pg,
                'V0': V0,
                'qgmax': qgmax,
                'qgmin': qgmin,
                'Vmax': Vmax,
                'Vmin': Vmin
            }
            system.PV.add(**PV_case)

        if data[0] == 'PQ':
            bus = 'Bus_' + str(data[1])
            Sn = float(data[2])
            Vn = float(data[3])
            Pl = float(data[4])
            Ql = float(data[5])
            Vmax = float(data[6])
            Vmin = float(data[7])
            z = float(data[8])
            PQ_case = {
                'bus': bus,
                'Sn': Sn,
                'Vn': Vn,
                'Pl': Pl,
                'Ql': Ql,
                'Vmax': Vmax,
                'Vmin': Vmin,
                'z': z
            }
            system.PQ.add(**PQ_case)

        if data[0] == 'SW':
            bus = 'Bus_' + str(data[1])
            Sn = float(data[2])
            Vn = float(data[3])
            V0 = float(data[4])
            Va = float(data[5])
            qgmax = float(data[6])
            qgmin = float(data[7])
            Vmax = float(data[8])
            Vmin = float(data[9])
            SW_case = {
                'bus': bus,
                'Sn': Sn,
                'Vn': Vn,
                'V0': V0,
                'Va': Va,
                'qgmax': qgmax,
                'qgmin': qgmin,
                'Vmax': Vmax,
                'Vmin': Vmin
            }
            system.SW.add(**SW_case)

        if data[0] == 'Shunt':
            bus = 'Bus_' + str(data[1])
            Sn = float(data[2])
            Vn = float(data[3])
            fn = float(data[4])
            g = float(data[5])
            b = float(data[6])
            Shunt_case = {
                'bus': bus,
                'Sn': Sn,
                'Vn': Vn,
                'fn': fn,
                'g': g,
                'b': b
            }
            system.Shunt.add(**Shunt_case)

        if data[0] == 'Line':
            f_bus = 'Bus_' + str(data[1])
            to_bus = 'Bus_' + str(data[2])
            Sn = float(data[3])
            Vn = float(data[4])
            fn = float(data[5])
            l = float(data[6])
            kT = float(data[7])
            r = float(data[8])
            x = float(data[9])
            b = float(data[10])
            tap_ratio = float(data[11])
            theta = float(data[12])
            Imax = float(data[13])
            Pmax = float(data[14])
            Smax = float(data[15])
            Line_case = {
                'f_bus': f_bus,
                'to_bus': to_bus,
                'Sn': Sn,
                'Vn': Vn,
                'fn': fn,
                'l': l,
                'kT': kT,
                'r': r,
                'x': x,
                'b': b,
                'tap_ratio': tap_ratio,
                'theta': theta,
                'Imax': Imax,
                'Pmax': Pmax,
                'Smax': Smax
            }
            system.Line.add(**Line_case)
        if data[0] == 'Syn6':
            bus = 'Bus_' + str(data[1])
            Sn = float(data[2])
            Vn = float(data[3])
            fn = float(data[4])
            m_model = float(data[5])
            xl = float(data[6])
            ra = float(data[7])
            xd = float(data[8])
            xd1 = float(data[9])
            xd2 = float(data[10])
            Td01 = float(data[11])
            Td02 = float(data[12])
            xq = float(data[13])
            xq1 = float(data[14])
            xq2 = float(data[15])
            Tq01 = float(data[16])
            Tq02 = float(data[17])
            M = float(data[18])  # M = 2H
            D = float(data[19])
            Syn6_case = {
                'bus': bus,
                'Sn': Sn,
                'Vn': Vn,
                'fn': fn,
                'm_model': m_model,
                'xl': xl,
                'ra': ra,
                'xd': xd,
                'xd1': xd1,
                'xd2': xd2,
                'Td01': Td01,
                'Td02': Td02,
                'xq': xq,
                'xq1': xq1,
                'xq2': xq2,
                'Tq01': Tq01,
                'Tq02': Tq02,
                'M': M,
                'D': D
            }
            system.Syn6.add(**Syn6_case)

        if data[0] == 'Avr2':
            bus = 'Bus_' + str(data[1])
            Type = float(data[2])
            vrmax = float(data[3])
            vrmin = float(data[4])
            Ka = float(data[5])
            Ta = float(data[6])
            Kf = float(data[7])
            Tf = float(data[8])
            Ke = float(data[9])
            Te = float(data[10])
            Tr = float(data[11])
            Ae = float(data[12])
            Be = float(data[13])
            Avr2_case = {
                'bus': bus,
                'Type': Type,
                'vrmax': vrmax,
                'vrmin': vrmin,
                'Ka': Ka,
                'Ta': Ta,
                'Kf': Kf,
                'Tf': Tf,
                'Ke': Ke,
                'Te': Te,
                'Tr': Tr,
                'Ae': Ae,
                'Be': Be
            }
            system.Avr2.add(**Avr2_case)

        if data[0] == 'Avr1':
            bus = 'Bus_' + str(data[1])
            Type = float(data[2])
            vrmax = float(data[3])
            vrmin = float(data[4])
            K0 = float(data[5])
            T1 = float(data[6])
            T2 = float(data[7])
            T3 = float(data[8])
            T4 = float(data[9])
            Te = float(data[10])
            Tr = float(data[11])
            Ae = float(data[12])
            Be = float(data[13])
            Avr1_case = {
                'bus': bus,
                'Type': Type,
                'vrmax': vrmax,
                'vrmin': vrmin,
                'K0': K0,
                'T1': T1,
                'T2': T2,
                'T3': T3,
                'T4': T4,
                'Te': Te,
                'Tr': Tr,
                'Ae': Ae,
                'Be': Be
            }
            system.Avr1.add(**Avr1_case)

        if data[0] == 'Tg1':
            bus = 'Bus_' + str(data[1])
            Type = float(data[2])
            wref0 = float(data[3])
            R = float(data[4])
            Pmax = float(data[5])
            Pmin = float(data[6])
            Ts = float(data[7])
            Tc = float(data[8])
            T3 = float(data[9])
            T4 = float(data[10])
            T5 = float(data[11])
            Tg1_case = {
                'bus': bus,
                'Type': Type,
                'wref0': wref0,
                'R': R,
                'Pmax': Pmax,
                'Pmin': Pmin,
                'Ts': Ts,
                'Tc': Tc,
                'T3': T3,
                'T4': T4,
                'T5': T5
            }
            system.Tg1.add(**Tg1_case)

        if data[0] == 'Ind3':
            bus = 'Bus_' + str(data[1])
            Sn = float(data[2])
            Vn = float(data[3])
            fn = float(data[4])
            type = float(data[5])
            rs = float(data[7])
            xs = float(data[8])
            rr1 = float(data[9])
            xr1 = float(data[10])
            rr2 = float(data[11])
            xr2 = float(data[12])
            xm = float(data[13])
            Hm = float(data[14])
            a1 = float(data[15])
            b = float(data[16])
            c = float(data[17])
            tup = float(data[18])
            sup = float(data[6])
            allow = float(data[19])
            Ind3_case = {
                'bus': bus,
                'Sn': Sn,
                'Vn': Vn,
                'fn': fn,
                'type': type,
                'sup': sup,
                'xs': xs,
                'rs': rs,
                'rr1': rr1,
                'xr1': xr1,
                'rr2': rr2,
                'xr2': xr2,
                'xm': xm,
                'Hm': Hm,
                'a1': a1,
                'b': b,
                'c': c,
                'allow': allow
            }
            system.Ind3.add(**Ind3_case)

    case.close()

    # Bus
    system.Bus._xy_index()
    system.Bus._bus_index()
    system.Bus._list2matrix()
    system.Bus.yinit(system.DAE)

    # PV
    system.PV._bus_index()
    system.PV._list2matrix()
    system.PV.base(Vb=system.Bus.Vb[system.PV.a])
    system.PV.yinit(system.DAE)
    system.PV._matrix2list()

    # PQ
    system.PQ._bus_index()
    system.PQ._list2matrix()
    system.PQ.base(Vb=system.Bus.Vb[system.PQ.a])
    system.PQ.yinit(system.DAE)
    system.PQ._matrix2list()

    # SW
    system.SW._bus_index()
    system.SW.yinit(system.DAE)

    # Shunt
    system.Shunt._bus_index()
    system.Shunt._list2matrix()
    system.Shunt.base(Vb=system.Bus.Vb[system.Shunt.a])
    system.Shunt._matrix2list()

    # Line
    system.Line._bus_index()

    system.Line.build_y()

    # 测试Ind3
    system.Ind3._bus_index()
    system.Ind3._list2matrix()
    system.Ind3.base(Sb=system.Settings.mva, Vb=system.Bus.Vb[system.Ind3.a])
    system.Ind3.setdata()
    # print(system.Ind3.__dict__)

    system.Ind3._dxy_index()

    # system.Ind3._matrix2list()
    # print(system.Ind3.__dict__)

    # system.DAE.Y = sparse(system.DAE.Y)
    # print(system.DAE.Y)
    # system.Line.gcall()
    # system.PQ.gcall()
    # system.Shunt.gcall()
    # system.PV.gcall()
    # system.SW.gcall()

    # print(system.DAE.g)
    # print(system.DAE.y)

    def calcInc():
        global F
        system.Line.gcall()
        system.PQ.gcall()
        system.Shunt.gcall()
        system.PV.gcall()
        system.SW.gcall()
        system.Ind3.gcall()
        system.Line.Gycall()
        system.Shunt.Gycall()
        system.PV.Gycall()
        system.SW.Gycall()
        system.Ind3.Gycall()

        system.Ind3.fcall()

        system.DAE.Fx = matrix(0.0, (system.DAE.nx, system.DAE.nx))
        system.DAE.Fy = matrix(0.0, (system.DAE.nx, system.DAE.ny))
        system.DAE.Gx = matrix(0.0, (system.DAE.ny, system.DAE.nx))
        system.Ind3.Fxcall()

        system.PV.Fxcall()
        system.SW.Fxcall()

        system.DAE.Gy = sparse(system.DAE.Gy)
        system.DAE.Fx = sparse(system.DAE.Fx)
        system.DAE.Fy = sparse(system.DAE.Fy)
        system.DAE.Gx = sparse(system.DAE.Gx)

        A = sparse([[system.DAE.Fx, system.DAE.Gx],
                    [system.DAE.Fy, system.DAE.Gy]])
        inc = matrix([system.DAE.f, system.DAE.g])
        if system.DAE.factorize:
            F = symbolic(
                A
            )  # 重新排列A矩阵以减少填充并执行LU分解,返回为可以传递的不透明 C object到umfpack.numeric()。
            system.DAE.factorize = False
        try:
            N = numeric(A, F)
            solve(A, N, inc)
        except:
            print('unexpect')
            F = symbolic(A)
            solve(A, numeric(A, F), inc)

        return inc

    if system.DAE.nx != 0:
        system.DAE.f = matrix(1.0, (system.DAE.nx, 1))
        system.DAE.x = matrix(1.0, (system.DAE.nx, 1))
        system.DAE.Fx = matrix(0.0, (system.DAE.nx, system.DAE.nx))
        system.DAE.Fy = matrix(0.0, (system.DAE.nx, system.DAE.ny))
        system.DAE.Gx = matrix(0.0, (system.DAE.ny, system.DAE.nx))

    system.DAE.Gy = matrix(0.0, (system.DAE.ny, system.DAE.ny))

    system.Ind3.xinit()

    system.DAE.g = np.array(system.DAE.g)

    iteration = 1
    iter_max = system.Settings.iter
    convergence = True  # 收敛
    tol = system.Settings.error
    cycle = True
    err = []

    # main loop
    while cycle or (max(abs(system.DAE.g)) > tol and iteration <= iter_max):
        inc = calcInc()
        cycle = False
        for i in range(system.DAE.nx):
            system.DAE.x[i] = system.DAE.x[i] - inc[i]
        for i in range(system.DAE.ny):
            system.DAE.y[i] = system.DAE.y[i] - inc[i + system.DAE.nx]

        err.append(max(abs(system.DAE.g)))
        print('第%i次迭代最大误差为:<%f>' % (iteration, err[iteration - 1]))

        iteration += 1

        system.DAE.g = np.array(system.DAE.g)

        # stop if the error increases too much
    if iteration > iter_max:
        print('Reached maximum number of iterations')
        convergence = False

    # 结束时间

    finish = clock()

    t = finish - start

    print('潮流计算运行时间:%f' % t)

    for i in range(system.DAE.ny):
        system.DAE.y[i] = round(system.DAE.y[i], 5)

    # 计算Pl和Ql
    system.DAE.g = matrix(0.0, (system.DAE.ny, 1))
    # print(system.DAE.g)
    system.PQ.gcall()
    system.Shunt.gcall()
    system.DAE._list2matrix()
    system.Bus.Pl = system.DAE.g[system.Bus.a]
    # print(system.Bus.Pl)
    system.Bus.Ql = system.DAE.g[system.Bus.v]
    # print(system.Bus.Ql)

    # 计算Pg 和 Qg
    system.Line.gcall()
    system.PQ.gcall()
    system.Shunt.gcall()
    system.DAE._list2matrix()
    system.Bus.Pg = system.DAE.g[system.Bus.a]
    system.Bus.Qg = system.DAE.g[system.Bus.v]
    # print('Bus.Pg、Qg')
    # print(system.Bus.Pg)
    # print(system.Bus.Qg)

    nx_old = system.DAE.nx

    # 测试Syn6
    system.Syn6._bus_index()
    system.Syn6._dxy_index()

    # 测试Avr
    system.Avr1._bus_index()
    system.Avr2._bus_index()
    system.Avr1.getbus()
    system.Avr2.getbus()
    system.Avr2._dxy_index()
    system.Avr1._dxy_index()

    # 测试Tg1
    system.Tg1._bus_index()
    system.Tg1._dxy_index()
    system.Tg1.getbus()

    # 重新生成对应维度的x, y, g, f
    newx = [0] * (system.DAE.nx - nx_old)
    system.DAE.x = list(system.DAE.x)
    system.DAE.f = list(system.DAE.f)
    system.DAE.x.extend(newx)
    system.DAE.f.extend(newx)
    system.DAE.y = list(system.DAE.y)
    system.DAE.g = list(system.DAE.g)

    # 重新生成雅可比矩阵
    system.DAE.Gy = matrix(0.0, (system.DAE.ny, system.DAE.ny))
    system.DAE.Fx = matrix(0.0, (system.DAE.nx, system.DAE.nx))
    system.DAE.Fy = matrix(0.0, (system.DAE.nx, system.DAE.ny))
    system.DAE.Gx = matrix(0.0, (system.DAE.ny, system.DAE.nx))

    newy = [0] * (system.DAE.ny - system.Bus.n * 2)
    system.DAE.y.extend(newy)
    system.DAE.g.extend(newy)
    system.DAE.y = matrix(system.DAE.y)

    # 测试Syn6 setx0
    system.Syn6._list2matrix()
    system.Syn6.base(Vb=system.Bus.Vb[system.Syn6.a])
    system.Syn6.setx0()
    # print('Syn6 setx0')
    # print(system.DAE.x)
    # 测试Avr setx0

    system.Avr1._list2matrix()
    system.Avr2._list2matrix()
    # system.Avr1.base(Vb=system.Bus.Vb[system.Avr1.a])
    # system.Avr2.base(Vb=system.Bus.Vb[system.Avr2.a])
    system.Avr1.setx0()
    system.Avr2.setx0()
    # print('Avr setx0')
    # print(system.DAE.y)

    # 测试Tg1
    system.Tg1._list2matrix()
    system.DAE._list2matrix()
    system.Tg1.base()
    system.Tg1.setx0()
    # system.Tg1._matrix2list()
    # system.Tg1.pmech = matrix(system.Tg1.pmech)
    # print(system.Tg1.pmech)
    # print(system.Tg1.__dict__)
    # print(system.DAE.f)
    # print(system.DAE.x)
    # print(system.DAE.y)

    # 重新生成微分代数方程和雅可比矩阵

    system.DAE.g = matrix(0.0, (system.DAE.ny, 1))

    # call
    system.DAE._list2matrix()
    system.Line.gcall()
    system.PQ.gcall()
    system.Shunt.gcall()
    system.Syn6.gcall()
    system.Avr1.gcall()
    system.Avr2.gcall()
    system.Tg1.gcall()
    system.Ind3.gcall()
    system.PV.gcall()
    system.SW.gcall()

    system.Line.Gycall()
    system.PQ.Gycall()
    system.Shunt.Gycall()
    system.Syn6.Gycall()
    system.Avr1.Gycall()
    system.Avr2.Gycall()
    system.Tg1.Gycall()
    system.Ind3.Gycall()
    system.PV.Gycall()
    system.SW.Gycall()

    system.Syn6.fcall()
    system.Avr1.fcall()
    system.Avr2.fcall()
    system.Tg1.fcall()
    system.Ind3.fcall()

    # print(system.DAE.f)
    system.Syn6.Fxcall()
    system.Avr1.Fxcall()
    system.Avr2.Fxcall()
    system.Tg1.Fxcall()
    system.Ind3.Fxcall()

    system.DAE.Gy = sparse(system.DAE.Gy)
    system.DAE.Fx = sparse(system.DAE.Fx)
    system.DAE.Fy = sparse(system.DAE.Fy)
    system.DAE.Gx = sparse(system.DAE.Gx)

    # print(system.DAE.Fx.V)

    # print(system.DAE.Fx.V)
    # 生成状态矩阵

    def state_matrix():
        Gyx = matrix(system.DAE.Gx)
        linsolve(sparse(system.DAE.Gy), Gyx)
        I = []
        J = []
        for i in range(system.DAE.nx):
            I.append(i)
            J.append(i)
        return system.DAE.Fx - system.DAE.Fy * Gyx - spmatrix(1e-6, I, J)

    Gyx = matrix(system.DAE.Gx)
    linsolve(sparse(system.DAE.Gy), Gyx)

    # state_matrix()
    As = state_matrix()

    # print(As)
    # As = sparse(As)
    # 计算特征值

    # cvxopt
    def eigs():
        As = state_matrix()
        return eigvals(As)

    eigen = eigs()

    # print(matrix(eigs()))

    # numpy
    # w = np.linalg.eigvals(As)
    # w = matrix(w)
    # print(np.linalg.eigvals(As))

    # scipy
    w, v = linalg.eig(As)
    # w = matrix(w)
    # a = w[0]
    # print(matrix(w))
    # print(a)
    for i in range(system.DAE.nx):
        w[i] = round(w[i], 5)
        print(w[i])

    # 计算参与因子

    # set_printoptions(threshold = 'nan')

    def compute_eig(As):

        mu, N = eig(matrix(As))
        N = matrix(N)
        n = len(mu)
        idx = range(n)
        W = matrix(spmatrix(1.0, idx, idx, (n, n), N.typecode))
        gesv(N, W)
        pf = mul(abs(W.T), abs(N))
        b = matrix(1.0, (1, n))
        WN = b * pf
        pf = pf.T
        for item in idx:
            mur = mu[item].real
            mui = mu[item].imag
            mu[item] = complex(round(mur, 5), round(mui, 5))
            pf[item, :] /= WN[item]

        return pf
        # print(pf)

    return As, Gyx

    pf = compute_eig(As)
    # print(pf)
    w = w.T
    sio.savemat('eig.mat', {'eig': w, 'pf': pf})
    f = open('indpf.txt', 'w+')
    for i in range(system.DAE.nx):
        pfrow = []
        for j in range(system.DAE.nx):
            p = str(round(pf[i, j], 12))
            # pfrow.append(round(pf[i, j], 12))
            f.write(p + ' ')
        f.write('\n')
        # f.writelines(pfrow)
        # print(pfrow)
    f.close()
Beispiel #16
0
def spike_inference(fluor, sigma=None, gamma=None, mode="correct",
                    ar_order=2, psd_opts=None, verbose=False):
    """
    Infer the most likely discretized spike train underlying a fluorescence
    trace.

    Parameters
    ----------
    fluor : ndarray
        One dimensional array containing the fluorescence intensities with
        one entry per time-bin.
    sigma : float, optional
        Standard deviation of the noise distribution.  If no value is given,
        then sigma is estimated from the data.
    gamma : float, optional
        Gamma is 1 - timestep/tau, where tau is the time constant of the AR(1)
        process.  If no value is given, then gamma is estimated from the data.
    mode : {'correct', 'robust', 'psd'}, optional
        The method for estimating sigma. The 'robust' method overestimates
        the noise by assuming that gamma = 1. The 'psd' method estimates
        sigma from the PSD of the fluorescence data. Default: 'correct'.
    ar_order : int, optional
        Autoregressive model order. Only implemented for 'psd' method.
        Default: 2
    psd_opts : dictionary
        Dictionary of options for the psd method; if None, default options
        will be used. Default: None
    verbose : bool, optional
        Whether to print status updates. Default: False.

    Returns
    -------
    inference : ndarray of float
        The inferred normalized spike count at each time-bin.  Values are
        normalized to the maximium value over all time-bins.
    fit : ndarray of float
        The inferred denoised fluorescence signal at each time-bin.
    parameters : dict
        Dictionary with values for 'sigma', 'gamma', and 'baseline'.

    References
    ----------
    * Pnevmatikakis et al. 2015. Submitted (arXiv:1409.2903).
    * Machado et al. 2015. Submitted.
    * Vogelstein et al. 2010. Journal of Neurophysiology. 104(6): 3691-3704.

    """
    try:
        import cvxopt.umfpack as umfpack
        from cvxopt import matrix, spdiag, spmatrix, solvers
        import picos
    except ImportError:
        raise ImportError('Spike inference requires picos package.')

    if verbose:
        sys.stdout.write('Spike inference...')

    if psd_opts is None:
        opts = default_psd_opts()
    else:
        opts = psd_opts

    if sigma is None or gamma is None:
        gamma, sigma = estimate_parameters(
            [fluor], gamma, sigma, mode, ar_order, psd_opts)

    # Initialize variables in our problem
    prob = picos.Problem()

    if mode == "psd":
        T = len(fluor)
        # construct deconvolution matrix  (sp = gen*c)
        gen = spmatrix(1., range(T), range(T), (T, T))

        for i in range(ar_order):
            gen = gen + spmatrix(
                float(-gamma[i]), range(i+1, T), range(T-i-1), (T, T))

        gr = np.roots(np.concatenate([np.array([1]), -gamma.flatten()]))
        # decay vector for initial fluorescence
        gd_vec = np.max(gr)**np.arange(T)
        gen_vec = gen * matrix(np.ones(fluor.size))

        # Define variables
        calcium_fit = prob.add_variable('calcium_fit', fluor.size)
        baseline = prob.add_variable('baseline', 1)
        if opts['bas_nonneg']:
            b_lb = 0
        else:
            b_lb = np.min(fluor)

        prob.add_constraint(baseline >= b_lb)

        init_calcium = prob.add_variable('init_calcium', 1)
        prob.add_constraint(init_calcium >= 0)

        # Add constraints
        prob.add_constraint(gen * calcium_fit >= 0)
        res = abs(matrix(fluor.astype(float)) - calcium_fit -
                  baseline*matrix(np.ones(fluor.size)) -
                  matrix(gd_vec) * init_calcium)

    else:
        # Make spike generating matrix
        # (eye, but with -g on diag below main diag)
        gen = spdiag([1 for step in range(fluor.size)])
        for step in range(fluor.size):
            if step > 0:
                gen[step, step - 1] = -gamma

        # Use spike generating matrix to initialize other constraint variables
        gen_vec = gen * matrix(np.ones(fluor.size))
        gen_ones = matrix(np.ones(fluor.size))
        umfpack.linsolve(gen, gen_ones)

        # Initialize variables in our problem
        calcium_fit = prob.add_variable('calcium_fit', fluor.size)
        init_calcium = prob.add_variable('init_calcium', 1)
        baseline = prob.add_variable('baseline', 1)

        # Define constraints and objective
        prob.add_constraint(init_calcium > 0)
        prob.add_constraint(gen * calcium_fit > 0)
        res = abs(matrix(fluor.astype(float)) - calcium_fit -
                  baseline -
                  gen_ones * init_calcium)

    prob.add_constraint(res < sigma * np.sqrt(fluor.size))
    prob.set_objective('min', calcium_fit.T * gen_vec)

    # Run solver
    start_time = time.time()
    try:
        prob.solve(solver='mosek', verbose=False)
    except ImportError:
        warn('MOSEK is not installed. Spike inference may be VERY slow!')
        prob.solver_selection()
        prob.solve(verbose=False)

    if verbose:
        sys.stdout.write("done!\n" +
                         "Status: " + prob.status +
                         "; Value: " + str(prob.obj_value()) +
                         "; Time: " + str(time.time() - start_time) +
                         "; Baseline = " + str(baseline.value) + "\n")

    # if problem in infeasible due to low noise value then project onto the
    # cone of linear constraints with cvxopt
    if mode == "psd" and prob.status in [
            'prim_infeas_cer', 'dual_infeas_cer', 'primal infeasible']:
        warn("Original problem infeasible. "
             "Adjusting noise level and re-solving")
        # setup quadratic problem with cvxopt
        solvers.options['show_progress'] = verbose
        ind_rows = range(T)
        ind_cols = range(T)
        vals = np.ones(T)

        cnt = 2  # no of constraints (init_calcium and baseline)
        ind_rows += range(T)
        ind_cols += [T]*T
        vals = np.concatenate((vals, np.ones(T)))

        ind_rows += range(T)
        ind_cols += [T+cnt-1]*T
        vals = np.concatenate((vals, np.squeeze(gd_vec)))

        P = spmatrix(vals, ind_rows, ind_cols, (T, T+cnt))
        H = P.T*P
        Py = P.T*matrix(fluor.astype(float))
        sol = solvers.qp(
            H, -Py, spdiag([-gen, -spmatrix(1., range(cnt), range(cnt))]),
            matrix(0., (T+cnt, 1)))
        xx = sol['x']
        fit = np.array(xx[:T])
        inference = np.array(gen*matrix(fit))
        fit = np.squeeze(fit)

        baseline = np.array(xx[T+1]) + b_lb
        init_calcium = np.array(xx[-1])
        sigma = np.linalg.norm(
            fluor-fit-init_calcium*gd_vec-baseline)/np.sqrt(T)
        parameters = {'gamma': gamma, 'sigma': sigma,
                      'baseline': baseline}
    else:
        # Return calcium model fit and spike inference
        fit = np.squeeze(
            np.asarray(calcium_fit.value)[np.arange(0, fluor.size)] +
            baseline.value)
        inference = np.squeeze(np.asarray(gen * matrix(fit)))
        parameters = {'gamma': gamma, 'sigma': sigma,
                      'baseline': baseline.value[0]}

    return inference, fit, parameters
Beispiel #17
0
def state_matrix():
    Gyx = matrix(system.DAE.Gx)
    linsolve(system.DAE.Gy, Gyx)
    return system.DAE.Fx - system.DAE.Fy * Gyx
Beispiel #18
0
    def setx0(self):
        if self.n == 0:
            return
        check = 1

        Pc = system.Bus.Pg[self.a]
        Qc = system.Bus.Qg[self.a]
        Vc = system.DAE.y[self.v]
        ac = system.DAE.y[self.a]

        vds = mul(-Vc, sin(ac))  # 角度还是弧度
        vqs = mul(Vc, cos(ac))

        rho = system.Wind.rho[self.wind]

        ones = matrix(1, (self.n, 1))
        # 常数
        # xs + xm
        self.dat1 = self.xs + self.xm
        self.dat2 = self.xr + self.xm
        self.dat3 = div(ones, mul(2 * ones, self.Hm))
        self.dat4 = div(
            mul(4 * math.pi * system.Settings.freq * self.R, self.nGB),
            self.np)
        self.dat5 = math.pi * mul(self.R, self.R)
        self.dat6 = Vc
        self.dat8 = mul(div(-self.pmin, self.xm), self.dat1)
        self.dat9 = mul(div(-self.pmax, self.xm), self.dat1)
        self.dat10 = -mul(div(div(ones, self.xm) + self.qmin, self.xm),
                          self.dat1)
        self.dat11 = -mul(div(div(ones, self.xm) + self.qmax, self.xm),
                          self.dat1)

        # 初始化状态变量
        for i in range(self.n):
            # 参数
            Vds = vds[i]
            Vqs = vqs[i]
            Rs = self.rs[i]
            Rr = self.rr[i]
            Xm = self.xm[i]
            x1 = self.dat1[i]
            x2 = self.dat2[i]
            Pg = Pc[i]
            Qg = Qc[i]

            # 转子速度
            Pci = Pc[i] * system.Settings.mva
            if (Pci < self.Sn[i]) & (Pc[i] > 0):
                omega = 0.5 * Pc[i] * system.Settings.mva / self.Sn + 0.5
            elif Pci >= self.Sn[i]:
                omega = 1
            else:
                omega = 0.5

            slip = 1 - omega

            iqr = -x1 * self.Sn * (
                2 * omega - 1) / Vc[i] / Xm / system.Settings.mva / omega
            A = [[-Rs, Vqs], [x1, -Vds]]
            B = [Vds - Xm * iqr, Qg]
            A = sparse(A)
            B = matrix(B)
            umfpack.linsolve(A, B)

            # B = numpy.array(B)
            # Is = numpy.linalg.solve(A, B)
            ids = B[0]
            iqs = B[1]
            idr = -(Vqs + Rs * iqs + x1 * ids) / Xm
            vdr = -Rr * idr + slip * (x2 * iqr + Xm * iqs)
            vqr = -Rr * iqr - slip * (x2 * idr + Xm * ids)

            jac = matrix(0.0, (6, 6))
            eqn = matrix(1.0, (6, 1))
            inc = matrix(1.0, (6, 1))

            x = matrix(0.0, (6, 1))

            x[0] = ids
            x[1] = iqs
            x[2] = idr
            x[3] = iqr
            x[4] = vdr
            x[5] = vqr

            rows = [0, 0, 0, 1, 1, 1, 2, 2, 3, 3, 4, 4, 5]
            cols = [0, 1, 3, 0, 1, 2, 2, 4, 3, 5, 0, 1, 2]
            vals = [
                -Rs, x1, Xm, -x1, -Rs, -Xm, -Rr, -1, -Rr, -1, Vds, Vqs,
                -Xm * Vc[i] / x1
            ]
            jac0 = spmatrix(vals, rows, cols, (6, 6), 'd')

            # jac0 = jac + spmatrix(-Rs, [0], [0], (6, 6))
            # jac0 = jac + spmatrix(x1, [0], [1], (6, 6))
            # jac0 = jac + spmatrix(Xm, [0], [3], (6, 6))
            # jac0 = jac + spmatrix(-x1, [1], [0], (6, 6))
            # jac0 = jac + spmatrix(-Rs, [1], [1], (6, 6))
            # jac0 = jac + spmatrix(-Xm, [1], [2], (6, 6))
            # jac0 = jac + spmatrix(-Rr, [2], [2], (6, 6))
            # jac0 = jac + spmatrix(-1, [2], [4], (6, 6))
            # jac0 = jac + spmatrix(-Rr, [3], [3], (6, 6))
            # jac0 = jac + spmatrix(-1, [3], [5], (6, 6))
            # jac0 = jac + spmatrix(Vds, [4], [0], (6, 6))
            # jac0 = jac + spmatrix(Vqs, [4], [1], (6, 6))
            # jac0 = jac + spmatrix(-Xm*Vc[i]/x1, [5], [2], (6, 6))

            k = x1 * self.Sn[i] / Vc[i] / Xm / system.Settings.mva

            iter = 0

            while max(abs(eqn)) > 1e-8:
                if iter > 20:
                    print('双馈风力发电机%i初始化失败' % i)
                    check = 0
                    break
                eqn[0] = -Rs * x[0] + x1 * x[1] + Xm * x[3] - Vds
                eqn[1] = -Rs * x[1] - x1 * x[0] - Xm * x[2] - Vqs
                eqn[2] = -Rr * x[2] + slip * (x2 * x[3] + Xm * x[1]) - x[4]
                eqn[3] = -Rr * x[3] - slip * (x2 * x[2] + Xm * x[0]) - x[5]
                eqn[4] = Vds * x[0] + Vqs * x[1] + x[4] * x[2] + x[5] * x[
                    3] - Pg
                eqn[5] = -Xm * Vc[i] * x[2] / x1 - Vc[i] * Vc[i] / x1 - Qg

                rows = [2, 2, 3, 3, 4, 4, 4, 4]
                cols = [1, 3, 0, 2, 2, 3, 4, 5]
                vals = [
                    slip[i] * Xm, slip[i] * x2, -slip[i] * Xm, -slip[i] * x2,
                    x[4], x[5], x[2], x[3]
                ]

                jac = jac0 + spmatrix(vals, rows, cols, (6, 6), 'd')

                # jac = jac + spmatrix(slip * Xm, [2], [1], (6, 6))
                # jac = jac + spmatrix(slip * x2, [2], [3], (6, 6))
                # jac = jac + spmatrix(-slip * Xm, [3], [0], (6, 6))
                # jac = jac + spmatrix(-slip * x2, [3], [2], (6, 6))
                # jac = jac + spmatrix(x[4], [4], [2], (6, 6))
                # jac = jac + spmatrix(x[5], [4], [3], (6, 6))
                # jac = jac + spmatrix(x[2], [4], [4], (6, 6))
                # jac = jac + spmatrix(x[3], [4], [5], (6, 6))

                jac = sparse(jac)
                umfpack.linsolve(jac, eqn)
                #inc = -numpy.linalg.solve(jac, eqn)
                x = x - eqn
                iter = iter + 1

            ids = x[0]
            iqs = x[1]
            idr = x[2]
            iqr = x[3]
            vdr = x[4]
            vqr = x[5]

            if iqr > self.dat8[i]:
                print(
                    'Warning: Dfig %i at Bus %s : iqr is over its max limit' %
                    (i, self.a[i]))
                check = 0
            if iqr < self.dat9[i]:
                print(
                    'Warning: Dfig %i at Bus %s : iqr is under its min limit' %
                    (i, self.a[i]))
                check = 0
            if idr > self.dat10[i]:
                print(
                    'Warning: Dfig %i at Bus %s : idr is over its max limit' %
                    (i, self.a[i]))
                check = 0
            if idr < self.dat11[i]:
                print(
                    'Warning: Dfig %i at Bus %s : idr is under its min limit' %
                    (i, self.a[i]))
                check = 0

            # theta_p
            contex = decimal.getcontext()
            contex.rounding = decimal.ROUND_05UP
            theta = self.Kp * round(Decimal(1000 * (omega[i] - 1))) / 1000
            theta = max([theta[0], 0])

            # wind turbine state variables
            system.DAE.x[self.idr[i]] = idr
            system.DAE.x[self.iqr[i]] = iqr
            system.DAE.x[self.omega_m[i]] = omega
            system.DAE.x[self.theta_p[i]] = theta
            # Vref
            Kv = self.Kv[i]
            if Kv == 0:  # 没有电压控制
                self.dat6 = 0
            else:
                self.dat6 = Vc[i] - (idr + Vc[i] / Xm) / Kv

            self.dat7 = -k * max([min([2 * omega[i] - 1, 1]), 0
                                  ]) / omega[i] - iqr

            # electric torque
            Tel = Xm * (iqr * ids - idr * iqs)
            if Pg < 0:
                print('** Turbine power is negative at Bus %i' % self.a[i])
                print('Wind speed % i can not be initialized.' % self.wind[i])
                system.DAE.x[system.Wind.vw[self.wind[i]]] = 1
                continue
            # wind power [MW]

            Pw = Tel * omega * system.Settings.mva * 1e6 / self.ng

            # wind speed
            iter = 0
            incvw = matrix(1.0, (1, 1))
            eqnvw = [1]
            R = self.dat4[i]
            AA = self.dat5[i]
            # initial guess wind speed
            vw = 0.9 * system.Wind.vwn[self.wind[i]]
            while abs(incvw[0]) > 1e-7:

                if iter > 50:
                    print(
                        '**Initialization of wind speed %i failed(converge problem)'
                        % self.wind[i])
                    print('Tip: Try increasing the nominal wind speed')
                    check = 0
                    break
                output = system.Dfig.windpower(rho[i], vw, AA, R, omega, theta,
                                               1)
                eqnvw = output - Pw
                jacvw = system.Dfig.windpower(rho[i], vw, AA, R, omega, theta,
                                              2)
                # incvw = -numpy.linalg.solve(jacvw[2], eqnvw)
                incvw = -eqnvw / jacvw[1]
                vw = vw + incvw[0]
                iter = iter + 1
            # average initial wind speed
            system.DAE.x[system.Wind.vw[
                self.wind[i]]] = vw / system.Wind.vwn[self.wind[i]]

            # find and delete static generators
            for bj in range(self.n):
                for bk in range(system.PV.n):
                    if self.u[bj] * self.a[bj] == system.PV.a[bk]:
                        idx = 'PV_' + str(bk + 1)
                        system.PV.remove(idx)
                for bk in range(system.SW.n):
                    if self.u[bj] * self.a[bj] == system.SW.a[bk]:
                        system.SW.remove(idx='SW_1')
        system.DAE.x[self.idr] = mul(self.u, system.DAE.x[self.idr])
        system.DAE.x[self.iqr] = mul(self.u, system.DAE.x[self.iqr])
        system.DAE.x[self.omega_m] = mul(self.u, system.DAE.x[self.omega_m])
        system.DAE.x[self.theta_p] = mul(self.u, system.DAE.x[self.theta_p])
        system.DAE.y[self.vref] = mul(self.u, self.dat6)
        xomega = system.DAE.x[self.omega_m]
        xomega1 = matrix(0.0, (self.n, 1))
        for i in range(self.n):
            xomega1[i] = max([min([2 * xomega[i] - 1, 1]), 0])
        system.DAE.y[self.pwa] = mul(self.Sn, div(xomega1,
                                                  system.Settings.mva))

        if not check:
            print('双馈风力发电机初始化失败')
        else:
            print('双馈风力发电机初始化完成')
Beispiel #19
0
        K.V = Kn.V

    return K


A = spmatrix([10, 3, 5, -2, 5, 2], [0, 2, 1, 2, 2, 3], [0, 0, 1, 1, 2, 3])
P = amd.order(A)
print(P)

V = [2, 3, 3, -1, 4, 4, -3, 1, 2, 2, 6, 1]
I = [0, 1, 0, 2, 4, 1, 2, 3, 4, 2, 1, 4]
J = [0, 0, 1, 1, 1, 2, 2, 2, 2, 3, 4, 4]
A = spmatrix(V, I, J)
B = matrix(1.0, (5, 1))
umfpack.linsolve(A, B)
print(B)

VA = [2, 3, 3, -1, 4, 4, -3, 1, 2, 2, 6, 1]
VB = [4, 3, 3, -1, 4, 4, -3, 1, 2, 2, 6, 2]
I = [0, 1, 0, 2, 4, 1, 2, 3, 4, 2, 1, 4]
J = [0, 0, 1, 1, 1, 2, 2, 2, 2, 3, 4, 4]
A = spmatrix(VA, I, J)
B = spmatrix(VB, I, J)
x = matrix(1.0, (5, 1))
Fs = umfpack.symbolic(A)
FA = umfpack.numeric(A, Fs)
FB = umfpack.numeric(B, Fs)
umfpack.solve(A, FA, x)
umfpack.solve(B, FB, x)
umfpack.solve(A, FA, x, trans='T')