コード例 #1
0
ファイル: solvefilt.py プロジェクト: a1k0n/303
def FilterCoeffs(x):
    """ return filter coefficients """
    p1i = x[0] < 0 and -x[0] * 1j or x[0]
    p1 = np.exp(p1i + x[1])
    p1c = np.exp(-p1i + x[1])
    p2i = x[2] < 0 and -x[2] * 1j or x[2]
    p2 = np.exp(p2i + x[3])
    p2c = np.exp(-p2i + x[3])

    if np.imag(p1) == 0 and np.real(p1) > 1.0:
        p1 = 1.0 - p1
    if np.imag(p1c) == 0 and np.real(p1c) > 1.0:
        p1c = 1.0 - p1c
    if np.imag(p2) == 0 and np.real(p2) > 1.0:
        p2 = 1.0 - p2
    if np.imag(p2c) == 0 and np.real(p2c) > 1.0:
        p2c = 1.0 - p2c
    z1 = np.exp(x[4])
    # first biquad:
    # (z - z1) / [(z - p1) (z - p1*)]
    a1 = np.real(p1 + p1c)
    b1 = -np.real(p1 * p1c)

    # second:
    # 1.0 / [(z - p2) (z - p3)]
    # (1 - p2 z^-1) (1 - p3 z^-1)
    a2 = np.real(p2 + p2c)
    b2 = -np.real(p2 * p2c)

    z = np.exp(2j * np.pi / T)
    gain = 1.0 / np.abs(FilterResponse(z, x))
    return np.array([gain, -z1, a1, b1, a2, b2])
コード例 #2
0
ファイル: solvefilt.py プロジェクト: a1k0n/303
def FilterResponse(z, x):
    ''' -b +- sqrt(b^2 - 4c) / 2
    so we want to independently control b and the discriminant
    which really just turns out to be + -> real, - -> imag
    so we allow the "frequency" component to go positive or negative
    if it's negative we use complex conjugates
    if it's positive we use "real conjugates"
    s^2 + bs + c = (s-p1)(s-p2)
    p1,p2 = b/2 +- sqrt(b^2 - 4ac)/2 = x1 +- sqrt(x2))
    b = x1*2
    sqrt(b^2 - 4c)/2 = sqrt(x2)
    b^2/4 - c = x2
    c = b^2/4 - x2
    wait, the quadratic form isn't all that useful though; we need to map the
    poles and zeros so we might as well just make it a distance either in real
    or in imag
    '''
    p1i = x[0] < 0 and -x[0] * 1j or x[0]
    p1 = np.exp(p1i + x[1])
    p1c = np.exp(-p1i + x[1])
    p2i = x[2] < 0 and -x[2] * 1j or x[2]
    p2 = np.exp(p2i + x[3])
    p2c = np.exp(-p2i + x[3])
    z1 = np.exp(x[4])
    if np.imag(p1) == 0 and np.real(p1) > 1.0:
        p1 = 1.0 - p1
    if np.imag(p1c) == 0 and np.real(p1c) > 1.0:
        p1c = 1.0 - p1c
    if np.imag(p2) == 0 and np.real(p2) > 1.0:
        p2 = 1.0 - p2
    if np.imag(p2c) == 0 and np.real(p2c) > 1.0:
        p2c = 1.0 - p2c
    h = (z - z1) / ((z - p1) * (z - p1c) * (z - p2) * (z - p2c))
    return h
コード例 #3
0
ファイル: track_opt.py プロジェクト: a1k0n/autorustler
def TrackCurvature(x):
    # use quadratic b-splines at each point to estimate curvature
    # i get almost the same formula i had before but it's off by a factor of 4!

    xx = np.concatenate([x[-1:], x, x[:1]])
    p0 = xx[:-2]
    p1 = xx[1:-1]
    p2 = xx[2:]
    T = p2 - p0  # track derivative
    uT = np.abs(T)
    TT = 4*(p0 - 2*p1 + p2)
    k = (np.real(T)*np.imag(TT) - np.imag(T)*np.real(TT)) / (uT**3)
    return k
コード例 #4
0
def TrackCurvature(x):
    # use quadratic b-splines at each point to estimate curvature
    # i get almost the same formula i had before but it's off by a factor of 4!

    xx = np.concatenate([x[-1:], x, x[:1]])
    p0 = xx[:-2]
    p1 = xx[1:-1]
    p2 = xx[2:]
    T = p2 - p0  # track derivative
    uT = np.abs(T)
    TT = 4 * (p0 - 2 * p1 + p2)
    k = (np.real(T) * np.imag(TT) - np.imag(T) * np.real(TT)) / (uT**3)
    return k
コード例 #5
0
    def constraint(x):
        arr_Y_pos, arr_Y_neg, arr_a_pos, arr_a_neg = expand(x)
        arr_C_pos = list()
        arr_C_neg = list()

        def conj(z):
            return np.real(z) - 1j * np.imag(z)

        for i in range(n_decomp):
            arr_C_pos.append(conj(arr_Y_pos[i].T) @ arr_Y_pos[i])
            arr_C_neg.append(conj(arr_Y_neg[i].T) @ arr_Y_neg[i])

        retvec = np.array([])

        # TP constraint
        for i in range(n_decomp):
            pt = anp_partial_trace(arr_C_pos[i], [2**n_qubits, 2**n_qubits], 1)
            vec = (pt - arr_a_pos[i] * np.identity(2**n_qubits)).flatten()
            retvec = np.hstack([retvec, vec])

            pt = anp_partial_trace(arr_C_neg[i], [2**n_qubits, 2**n_qubits], 1)
            vec = (pt - arr_a_neg[i] * np.identity(2**n_qubits)).flatten()
            retvec = np.hstack([retvec, vec])

        # equality constraint
        C_sum = np.zeros_like(target_choi)
        for i in range(n_decomp):
            C_sum += arr_C_pos[i] - arr_C_neg[i]
        vec = (C_sum - target_choi).flatten()
        retvec = np.hstack([retvec, vec])

        # separate complex and real part
        retvec = np.hstack([np.real(retvec), np.imag(retvec)])
        return retvec
コード例 #6
0
def imvoigt_vjp(g, ans, x, y):
    from scipy.special import wofz
    z = x + 1j*y
    zw = z*wofz(z)
    dx = -2*np.imag(zw) + 2/np.sqrt(np.pi)
    dy = -2*np.real(zw)
    return g*dx, g*dy
コード例 #7
0
ファイル: core.py プロジェクト: ssolson/WecOptTool
    def dynamic_residual(self,
                         x: np.ndarray,
                         f_exc: np.ndarray,                     # TODO: make this a property of WEC
                         f_pto_fun: types.FunctionType,
                         f_ext_fun: types.FunctionType) -> np.ndarray:
        """
        Solves WEC dynamics in residual form so that they may be enforced through
        a nonlinear constraint within an optimization problem
    
        Parameters
        ----------
        x : np.ndarray
            Decision variable for optimization problem
        f_exc : np.ndarray
            Time history of excitation forcing at collocation points in body 
            coordinate system
        f_pto_fun : types.FunctionType
            Function that acceps decision variable and WEC, returns PTO forcing at 
            collocation points in body coordinate system
        f_ext_fun : types.FunctionType
            Function that acceps decision variable and WEC, returns other forcing at 
            collocation points in body coordinate system

        Returns
        -------
        np.ndarray
            Residuals at collocation points
    
        """
        
        assert isinstance(x, np.ndarray)
        assert isinstance(f_exc, np.ndarray)
        assert isinstance(f_pto_fun, types.FunctionType)
        assert isinstance(f_ext_fun, types.FunctionType)
             
    
        # WEC position
        x_wec, _, nf, nm = self.decompose_decision_var(x)
        
        # WEC velocity (each row is a mode, each column is a Fourier component)
        X = np.reshape(x_wec, (nm, -1))
        
        # complex velocity with position at beginning
        X_hat = np.concatenate((np.reshape(X[:,0],(-1,1)), X[:,1::2] - X[:,2::2]*1j ), axis=1)
        
        Gi_block_scaled = self.num_scale * self.Gi_block.toarray() # TODO: do this only once
    
        Fi = np.squeeze(np.reshape(Gi_block_scaled @ X_hat.flatten(), (nm, -1)))
        Fi_fs_tmp_0 = np.real(Fi[0])
        Fi_fs_tmp_1 = np.vstack([np.real(Fi[1::]), -np.imag(Fi[1::])]).ravel('F')
        Fi_fs = np.hstack((np.array(Fi_fs_tmp_0), Fi_fs_tmp_1))
        fi = Fi_fs @ self.Phi
        
        residual = f_exc + f_pto_fun(x) + f_ext_fun(x) - fi

        return residual.flatten()
コード例 #8
0
ファイル: solve2.py プロジェクト: a1k0n/303
def PlotPoles(x, n):
    Q, p3, p4, z1, w0, w1, wdecay = x
    w = w1 * np.exp(-np.arange(n) * wdecay) + w0
    p1 = (w * (-1.0 / Q + 1j))
    p2 = np.conj(p1)
    p3 = (w * p3 / Q)
    p4 = (w * p4)
    z1 = (w * z1)

    a = np.vstack((p1, p2, p3, p4, z1))
    plt.axvline(0)
    plt.plot(np.real(a), np.imag(a), 'x')
コード例 #9
0
ファイル: wrappers.py プロジェクト: zhenchen16/adorym
def ifft2(var_real, var_imag, axes=(-2, -1), backend='autograd', normalize=False):
    if backend == 'autograd':
        var = var_real + 1j * var_imag
        norm = None if not normalize else 'ortho'
        var = anp.fft.ifft2(var, axes=axes, norm=norm)
        return anp.real(var), anp.imag(var)
    elif backend == 'pytorch':
        var = tc.stack([var_real, var_imag], dim=-1)
        var = tc.ifft(var, signal_ndim=2, normalized=normalize)
        var_real, var_imag = tc.split(var, 1, dim=-1)
        slicer = [slice(None)] * (len(var_real.shape) - 1) + [0]
        return var_real[tuple(slicer)], var_imag[tuple(slicer)]
コード例 #10
0
ファイル: confidence_region.py プロジェクト: tw7649116/momi2
    def g_out_antihess(y):
        lp = snp_log_probs(y)
        ret = 0.0
        for l in seg_sites._get_likelihood_sequences(lp):
            L = len(l)
            lc = make_constant(l)

            fft = np.fft.fft(l)
            # (assumes l is REAL)
            assert np.all(np.imag(l) == 0.0)
            fft_rev = np.conj(fft) * np.exp(
                2 * np.pi * 1j * np.arange(L) / float(L))

            curr = 0.5 * (fft * fft_rev - fft * make_constant(fft_rev) -
                          make_constant(fft) * fft_rev)
            curr = np.fft.ifft(curr)[(L - 1)::-1]

            # make real
            assert np.allclose(np.imag(curr / L), 0.0)
            curr = np.real(curr)
            curr = curr[0] + 2.0 * np.sum(curr[1:int(np.sqrt(L))])
            ret = ret + curr
        return ret
コード例 #11
0
def QuadFitCurvatureMap(x):
    curv = []

    for i in range(len(x)):
        # do a look-ahead quadratic fit, just like the car would do
        pts = x[(np.arange(6) + i) % len(x)] / 100  # convert to meters
        basis = (pts[1] - pts[0]) / np.abs(pts[1] - pts[0])

        # project onto forward direction
        pts = (np.conj(basis) * (pts - pts[0]))

        p = np.polyfit(np.real(pts), np.imag(pts), 2)
        curv.append(p[0] / 2)

    return np.float32(curv)
コード例 #12
0
ファイル: track_opt.py プロジェクト: a1k0n/autorustler
def QuadFitCurvatureMap(x):
    curv = []

    for i in range(len(x)):
        # do a look-ahead quadratic fit, just like the car would do
        pts = x[(np.arange(6) + i) % len(x)] / 100  # convert to meters
        basis = (pts[1] - pts[0]) / np.abs(pts[1] - pts[0])

        # project onto forward direction
        pts = (np.conj(basis) * (pts - pts[0]))

        p = np.polyfit(np.real(pts), np.imag(pts), 2)
        curv.append(p[0] / 2)

    return np.float32(curv)
コード例 #13
0
def ifft2(var_real,
          var_imag,
          axes=(-2, -1),
          override_backend=None,
          normalize=False):
    bn = override_backend if override_backend is not None else global_settings.backend
    if bn == 'autograd':
        var = var_real + 1j * var_imag
        norm = None if not normalize else 'ortho'
        var = anp.fft.ifft2(var, axes=axes, norm=norm)
        return anp.real(var), anp.imag(var)
    elif bn == 'pytorch':
        var = tc.stack([var_real, var_imag], axis=-1)
        var = tc.ifft(var, signal_ndim=2, normalized=normalize)
        var_real, var_imag = tc.split(var, 1, dim=-1)
        slicer = [slice(None)] * (var_real.ndim - 1) + [0]
        return var_real[tuple(slicer)], var_imag[tuple(slicer)]
コード例 #14
0
ファイル: setup_autograd.py プロジェクト: stjordanis/qubiter
def pu2i(*tlist):
    """
    Returns imaginary part of u2, and registers it as being primitive.

    Primitive means that its derivative will be provided in a defvjp (
    def of vector-jacobian-product) so no need for autograd to calculate it
    from the u2 definition.

    Parameters
    ----------
    tlist : list[float]
        len = 4

    Returns
    -------
    np.ndarray
        shape=(2,2)

    """
    return np.imag(u2_alt(*tlist))
コード例 #15
0
def complex_as_matrix(z, n):
    """Represent a complex number as a matrix.
    
    Parameters
    ----------
    z : complex float
    n : int (even)
    
    Returns
    -------
    Z : ndarray (n,n)
        Real-valued n*n tri-diagonal matrix representing z in the ring of n*n matrices.
        
    """

    Z = np.zeros((n, n))
    ld = np.zeros(n - 1)
    ld[0::2] = np.imag(z)
    np.fill_diagonal(Z[1:], ld)
    Z = Z - Z.T
    np.fill_diagonal(Z, np.real(z))
    return Z
コード例 #16
0
def realify(Y):
    """Convert data in k-dimensional complex space to 2k-dimensional
    real space.

    Parameters
    ----------
    Y : ndarray (k,n)
        Real-valued array of data, `k` must be even.

    Returns
    -------
    Yreal : ndarray (2k,n)
        Complex-valued array of data.

    """

    if Y.ndim == 1:
        Yreal = np.zeros(2 * Y.shape[0])
    else:
        Yreal = np.zeros((2 * Y.shape[0], Y.shape[1]))
    Yreal[0::2] = np.real(Y)
    Yreal[1::2] = np.imag(Y)
    return Yreal
コード例 #17
0
    def serialize_recurrent_layer(self, weights):

        evals, evecs = np.linalg.eig(weights[1])
        diagonal_evals = np.real(np.diag(evals))
        real_parts = evals.real
        img_parts = evals.imag
        evecs_c = np.real(evecs)
        #reconstructed_matrices = []
        for i in range(len(weights[1])):

            #diagonal_evals = np.zeros((24, 24))
            #diagonal_evals[i, i] = evals[i]**(1/24)

            #reconstructed_weights = evecs @ diagonal_evals @ np.linalg.pinv(evecs)
            if img_parts[i] > 0:
                diagonal_evals[i, i + 1] = img_parts[i]
                diagonal_evals[i + 1, i] = img_parts[i + 1]
                evecs_c[:, i] = np.real(evecs[:, i])
                evecs_c[:, i + 1] = np.imag(evecs[:, i])
                i += 2

            #reconstructed_matrices.append(reconstructed_weights)

        return diagonal_evals
コード例 #18
0
ファイル: setup_autograd.py プロジェクト: stjordanis/qubiter
defvjp(
    pu2r,
    # defines vector-jacobian-product of pu2r
    # g.shape == pu2r.shape
    lambda ans, *tlist: lambda g: np.sum(g * np.real(d_u2(0, *tlist))),
    lambda ans, *tlist: lambda g: np.sum(g * np.real(d_u2(1, *tlist))),
    lambda ans, *tlist: lambda g: np.sum(g * np.real(d_u2(2, *tlist))),
    lambda ans, *tlist: lambda g: np.sum(g * np.real(d_u2(3, *tlist))),
    argnums=range(4))

defvjp(
    pu2i,
    # defines vector-jacobian-product of pu2i
    # g.shape == pu2i.shape
    lambda ans, *tlist: lambda g: np.sum(g * np.imag(d_u2(0, *tlist))),
    lambda ans, *tlist: lambda g: np.sum(g * np.imag(d_u2(1, *tlist))),
    lambda ans, *tlist: lambda g: np.sum(g * np.imag(d_u2(2, *tlist))),
    lambda ans, *tlist: lambda g: np.sum(g * np.imag(d_u2(3, *tlist))),
    argnums=range(4))


def d_auto_pu2(dwrt, *tlist):
    """
    Returns the automatic derivative of pu2. We have defined things so that
    this derivative is stipulated analytically a priori rather than being
    calculated by autograd from def of u2.

    Parameters
    ----------
    dwrt : int
コード例 #19
0
ファイル: utils.py プロジェクト: juliaprocess/chieh_libs
def polyinterp(points, doPlot=None, xminBound=None, xmaxBound=None):
    """ polynomial interpolation
    Parameters
    ----------
    points: shape(pointNum, 3), three columns represents x, f, g
    doPolot: set to 1 to plot, default 0
    xmin: min value that brackets minimum (default: min of points)
    xmax: max value that brackets maximum (default: max of points)
    
    set f or g to sqrt(-1)=1j if they are not known
    the order of the polynomial is the number of known f and g values minus 1

    Returns
    -------
    minPos:
    fmin:
    """
    
    if doPlot == None:
        doPlot = 0

    nPoints = points.shape[0]
    order = np.sum(np.imag(points[:, 1:3]) == 0) -1
    
    # code for most common case: cubic interpolation of 2 points
    if nPoints == 2 and order == 3 and doPlot == 0:
        [minVal, minPos] = [np.min(points[:,0]), np.argmin(points[:,0])]
        notMinPos = 1 - minPos
        d1 = points[minPos,2] + points[notMinPos,2] - 3*(points[minPos,1]-\
                points[notMinPos,1])/(points[minPos,0]-points[notMinPos,0])

        t_d2 =  d1**2 - points[minPos,2]*points[notMinPos,2]
        if t_d2 > 0:
            d2 = np.sqrt(t_d2)
        else:
            d2 = np.sqrt(-t_d2) * np.complex(0,1)
        if np.isreal(d2):
            t = points[notMinPos,0] - (points[notMinPos,0]-points[minPos,0])*\
                    ((points[notMinPos,2]+d2-d1)/(points[notMinPos,2]-\
                    points[minPos,2]+2*d2))
            minPos = np.min([np.max([t,points[minPos,0]]), points[notMinPos,0]])
        else:
            minPos = np.mean(points[:,0])
        fmin = minVal
        return (minPos, fmin)
    
    xmin = np.min(points[:,0])
    xmax = np.max(points[:,0])

    # compute bounds of interpolation area
    if xminBound == None:
        xminBound = xmin
    if xmaxBound == None:
        xmaxBound = xmax

    # constraints based on available function values
    A = np.zeros((0, order+1))
    b = np.zeros((0, 1))
    for i in range(nPoints):
        if np.imag(points[i,1]) == 0:
            constraint = np.zeros(order+1)
            for j in np.arange(order,-1,-1):
                constraint[order-j] = points[i,0]**j
            A = np.vstack((A, constraint))
            b = np.append(b, points[i,1])
    
    # constraints based on availabe derivatives
    for i in range(nPoints):
        if np.isreal(points[i,2]):
            constraint = np.zeros(order+1)
            for j in range(1,order+1):
                constraint[j-1] = (order-j+1)* points[i,0]**(order-j)
            A = np.vstack((A, constraint))
            b = np.append(b,points[i,2])
    
    # find interpolating polynomial
    params = np.linalg.solve(A, b)

    # compute critical points
    dParams = np.zeros(order)
    for i in range(params.size-1):
        dParams[i] = params[i] * (order-i)
    
    if np.any(np.isinf(dParams)):
        cp = np.concatenate((np.array([xminBound, xmaxBound]), points[:,0]))
    else:
        cp = np.concatenate((np.array([xminBound, xmaxBound]), points[:,0], \
                np.roots(dParams)))
    
    # test critical points
    fmin = np.infty;
    minPos = (xminBound + xmaxBound)/2.
    for xCP in cp:
        if np.imag(xCP) == 0 and xCP >= xminBound and xCP <= xmaxBound:
            fCP = np.polyval(params, xCP)
            if np.imag(fCP) == 0 and fCP < fmin:
                minPos = np.double(np.real(xCP))
                fmin = np.double(np.real(fCP))
    
    # plot situation (omit this part for now since we are not going to use it
    # anyway)

    return (minPos, fmin)
コード例 #20
0
ファイル: utils.py プロジェクト: juliaprocess/chieh_libs
def isLegal(v):
    return np.sum(np.any(np.imag(v)))==0 and np.sum(np.isnan(v))==0 and \
            np.sum(np.isinf(v))==0
コード例 #21
0
ファイル: run_sail.py プロジェクト: yuriyelesin/rcw_grad
def emissivity_f(dofold,ctrl):
    ''' ctrl: ctrl's frequency calculation
    average over p/s polarizations, sum over forward and backward directions
    '''
    freq = freqL.flatten()[ctrl]
    theta = thetaL.flatten()[ctrl]
    phi = phiL.flatten()[ctrl]
    # RCWA
    freqcmp = freq*(1+1j/2/Qabs)
    planewave={'p_amp':0,'s_amp':1,'p_phase':0,'s_phase':0}
    obj,dof,epsdiff = rcwa_assembly(dofold,freqcmp,theta,phi,planewave)

    if absmethod == 'V':
        Mv = []
        FMFL=[]
        MtL=[]
        solveinsideL=[]
        for i in range(Nlayer):
            Mv.append(get_conv(1./Nx/Ny,dof[i*Nx*Ny:(i+1)*Nx*Ny].reshape((Nx,Ny)),obj.G))
            FMF,Mt, solveinside = obj.Volume_integralpart1(1+i,Mv[i],Mv[i],Mv[i])
            FMFL.append(FMF)
            MtL.append(Mt)
            solveinsideL.append(solveinside)
    elif absmethod == 'RT':
        fun = obj.RT_Solvepart1()

    # planewave excitation
    p_phase = 0.
    s_phase = 0.

    vals=0.
    if absmethod == 'V':
        for i in range(Nlayer):
            p_amp = 0.
            s_amp = 1.
            obj.MakeExcitationPlanewave(p_amp,p_phase,s_amp,s_phase,order = 0,direction='forward')
            vals = vals + np.real(obj.Volume_integralpart2(obj.a0,obj.bN,FMFL[i],MtL[i], solveinsideL[i], normalize=1))*np.imag(epsdiff[i])*np.real(obj.omega)

            obj.MakeExcitationPlanewave(p_amp,p_phase,s_amp,s_phase,order = 0,direction='backward')
            vals = vals + np.real(obj.Volume_integralpart2(obj.a0,obj.bN,FMFL[i],MtL[i], solveinsideL[i], normalize=1))*np.imag(epsdiff[i])*np.real(obj.omega)
            p_amp = 1.
            s_amp = 0.
            obj.MakeExcitationPlanewave(p_amp,p_phase,s_amp,s_phase,order = 0,direction='forward')
            vals = vals + np.real(obj.Volume_integralpart2(obj.a0,obj.bN,FMFL[i],MtL[i], solveinsideL[i], normalize=1))*np.imag(epsdiff[i])*np.real(obj.omega)

            obj.MakeExcitationPlanewave(p_amp,p_phase,s_amp,s_phase,order = 0,direction='backward')
            vals = vals + np.real(obj.Volume_integralpart2(obj.a0,obj.bN,FMFL[i],MtL[i], solveinsideL[i], normalize=1))*np.imag(epsdiff[i])*np.real(obj.omega)
    elif absmethod == 'RT':
        p_amp = 0.
        s_amp = 1.
        obj.MakeExcitationPlanewave(p_amp,p_phase,s_amp,s_phase,order = 0,direction='forward')
        R,T = obj.RT_Solvepart2(fun,normalize=1) 
        vals = vals + 1-R-T

        obj.MakeExcitationPlanewave(p_amp,p_phase,s_amp,s_phase,order = 0,direction='backward')
        R,T = obj.RT_Solvepart2(fun,normalize=1) 
        vals = vals + 1-R-T

        p_amp = 1.
        s_amp = 0.
        obj.MakeExcitationPlanewave(p_amp,p_phase,s_amp,s_phase,order = 0,direction='forward')
        R,T = obj.RT_Solvepart2(fun,normalize=1) 
        vals = vals + 1-R-T

        obj.MakeExcitationPlanewave(p_amp,p_phase,s_amp,s_phase,order = 0,direction='backward')
        R,T = obj.RT_Solvepart2(fun,normalize=1) 
        vals = vals + 1-R-T

    val = vals*np.sin(theta)*np.cos(theta)/np.pi
    val = val * dtheta*dphi*prefactorT

    return val
コード例 #22
0
ファイル: absopt.py プロジェクト: yuriyelesin/rcw_grad
def fun_owen(ep):
    sigma = np.imag(ep)/np.abs(ep-1)**2
    fun = lambda h:h-2/np.pi*sigma/(1-np.sinc(2*h)**2)
    init = 1/np.imag(np.sqrt(ep))/2/np.pi
    return solve(fun,init)[0]
コード例 #23
0
ファイル: test_graphs.py プロジェクト: HIPS/autograd
 def fun(a):
     r, i = np.real(a), np.imag(a)
     a = np.abs(r)**1.4 + np.abs(i)**1.3
     return np.sum(np.sin(a))
コード例 #24
0
 def norm(x):
     return np.mean(np.square(np.real(x)) + np.square(np.imag(x)))
コード例 #25
0
ファイル: generic.py プロジェクト: wesselb/lab
def imag(a: Numeric):
    return anp.imag(a)
コード例 #26
0
ファイル: track_opt.py プロジェクト: a1k0n/autorustler
    Nr = TrackNormal(rx)

    # psie is sort of backwards: higher angles go to the left
    return np.angle(Nx) - np.angle(Nr)


if __name__ == '__main__':
    TRACK_SPACING = 19.8  # cm
    x = SVGPathToTrackPoints("oakwarehouse.path", TRACK_SPACING)[:-1]

    xm = np.array(x)[:, 0] / 50  # 50 pixels / meter
    track_k = TrackCurvature(xm)
    Nx = TrackNormal(xm)
    u = 1j * Nx
    np.savetxt("track_x.txt",
               np.vstack([np.real(xm), np.imag(xm)]).T.reshape(-1),
               newline=",\n")
    np.savetxt("track_u.txt",
               np.vstack([np.real(u), np.imag(u)]).T.reshape(-1),
               newline=",\n")
    np.savetxt("track_k.txt", track_k, newline=",\n")

    ye, val, stuff = OptimizeTrack(xm, 1.4, 0.1)
    psie = RelativePsie(ye, xm)

    rx = u*ye + xm
    raceline_k = TrackCurvature(rx)

    np.savetxt("raceline_k.txt", raceline_k, newline=",\n")
    np.savetxt("raceline_ye.txt", ye, newline=",\n")
    np.savetxt("raceline_psie.txt", psie, newline=",\n")
コード例 #27
0
 def nonlinearity(value):
     return np.tanh(np.real(value)) + np.tanh(np.imag(value))
コード例 #28
0
ファイル: test_complex.py プロジェクト: AugustLONG/autograd
def test_imag_type():
    fun = lambda x: np.sum(np.imag(x))
    df = grad(fun)
    assert base_class(type(df(1.0 ))) == float
    assert base_class(type(df(1.0j))) == complex
コード例 #29
0
 def fun(a):
     r, i = np.real(a), np.imag(a)
     a = np.abs(r)**1.4 + np.abs(i)**1.3
     return to_scalar(a)
コード例 #30
0
ファイル: absopt.py プロジェクト: yuriyelesin/rcw_grad
def p_abs(dofold,nG,bproj,method='RT'):
    dof = b_filter(dofold,bproj)
    
    planewave={'p_amp':0,'s_amp':1,'p_phase':0,'s_phase':0}
    theta = 0.
    phi = 0.
    
    t1 = time.time()
    obj= rcwa_assembly(dof,nG,bproj,theta,phi,planewave)

    vals = 0.
    R = 0.
    T = 0.
    
    if method == 'V':
        for i in range(Nlayer):
            Mv=get_conv(1./Mx/My,dof[i*Mx*My:(i+1)*Mx*My].reshape((Mx,My)),obj.G)
            vals = vals + np.real(obj.Volume_integral(1+i,Mv,Mv,Mv,normalize=1))*np.real(obj.omega)*np.imag(epsdiff)
    elif method == 'RT':
        R,T = obj.RT_Solve(normalize=1) 
        vals = 1-R-T
    t2 = time.time()
    if 'autograd' not in str(type(vals)):
        global ctrl
        np.savetxt('dof.txt',dof)
        if ctrl<=1:
            print(t2-t1)
        if method == 'V':
            print(ctrl,vals)
        elif method == 'RT':
            print(ctrl, 'R =',R,'T =',T,'Abs=',vals,'time=',t2-t1)
            
        ctrl +=1
    return vals
コード例 #31
0
ファイル: setup_autograd.py プロジェクト: stjordanis/qubiter
 def u2i(*tlist1):
     return np.imag(u2_alt(*tlist1))
コード例 #32
0
def run_lf(load_p, net, tol=1e-9, comp_tol=1e-3, max_iter=10000):
    """ Perform Gauss-Seidel power flow on the given pandapower network.

    The ``load_p`` array is an iterable of additional real power load to add
    to each bus. By providing this as an input, this python function becomes
    the function ``slack_power = f(load_power)`` and thus the derivative of
    slack power with respect to load power can be calculated.

    By restricting the values of `load_p` to be very small we can ensure that
    this function is solving the load flow correctly by comparing it to the
    results in the pandapower network. Restricting to very small does not interfere
    with calculation of the derivative - that is, the derivative of
    x (the small value given as input) plus a constant (the load power specified
    in the pandapower network object) is equal to the derivative of x alone.

    Args:
        load_p (iterable): Iterable of additional loads to add to network.
            Index i will add load to bus i.
            These should be very small values so that the consistency
            assertion with pandapower succeeeds.
        net (pp.Network): Solved Pandapower network object that defines the
            elements of the network and contains the ybus matrix.
        tol (float): Convergence tolerance (voltage).
        comp_tol (float): Tolerance for comparison check against pandapower.
        max_iter(int): Max iterations to solve load flow.

    Returns:
        float: Sum of real power injected by slack buses in the network.
    """
    ybus = np.array(net._ppc["internal"]["Ybus"].todense())
    pd2ppc = net._pd2ppc_lookups["bus"]  # Pandas bus num --> internal bus num.
    n = ybus.shape[0]  # Number of buses.
    slack_buses = set(pd2ppc[net.ext_grid['bus']])
    gen_buses = set([pd2ppc[b] for b in net.gen['bus']])
    ybus_hollow = ybus * (1 - np.eye(n))  # ybus with diagonal elements zeroed.
    v = init_v(net, n, pd2ppc)
    psch, qsch = scheduled_p_q(net, n, pd2ppc)
    # Incorporate the variables we are differentiating with respect to:
    psch = {b: p - load_p[b] for b, p in psch.items()}

    it = 0
    while it < max_iter:
        old_v, v = v, [x for x in v]
        for b in [b for b in range(n) if b not in slack_buses]:
            qsch_b = (-1 *
                      np.imag(np.conj(old_v[b]) * np.sum(ybus[b, :] * old_v))
                      if b in gen_buses else qsch[b])
            v[b] = (1 / ybus[b, b]) * (
                (psch[b] - 1j * qsch_b) / np.conj(old_v[b]) -
                np.sum(ybus_hollow[b, :] * old_v))
            if b in gen_buses:
                v[b] = np.abs(old_v[b]) * v[b] / np.abs(
                    v[b])  # Only use angle.
        it += 1
        v = np.array(v)
        if np.allclose(v, old_v, rtol=tol, atol=0):
            break
    p_slack = sum((np.real(np.conj(v[b]) * np.sum(ybus[b, :] * v)) - psch[b])
                  for b in slack_buses)
    # Assert convergence and consistency with pandapower.
    assert it < max_iter, f'Load flow not converged in {it} iterations.'
    assert np.allclose(v, net._ppc["internal"]["V"], atol=comp_tol, rtol=0),\
           f'Voltage\npp:\t\t{net._ppc["internal"]["V"]}\nsolved:\t{v}'
    assert np.allclose(p_slack, net.res_ext_grid['p_mw'].sum(), atol=comp_tol, rtol=0),\
           f'Slack Power\npp:\t\t{net.res_ext_grid["p_mw"].sum()}\nsolved:\t{p_slack}'
    return p_slack
コード例 #33
0
 def complex_to_real(self,
                     z):  # complex vector of length n -> real of length 2n
     return np.real(np.concatenate((np.real(z), np.imag(z))))
コード例 #34
0
    Nr = TrackNormal(rx)

    # psie is sort of backwards: higher angles go to the left
    return np.angle(Nx) - np.angle(Nr)


if __name__ == '__main__':
    TRACK_SPACING = 19.8  # cm
    x = SVGPathToTrackPoints("oakwarehouse.path", TRACK_SPACING)[:-1]

    xm = np.array(x)[:, 0] / 50  # 50 pixels / meter
    track_k = TrackCurvature(xm)
    Nx = TrackNormal(xm)
    u = 1j * Nx
    np.savetxt("track_x.txt",
               np.vstack([np.real(xm), np.imag(xm)]).T.reshape(-1),
               newline=",\n")
    np.savetxt("track_u.txt",
               np.vstack([np.real(u), np.imag(u)]).T.reshape(-1),
               newline=",\n")
    np.savetxt("track_k.txt", track_k, newline=",\n")

    ye, val, stuff = OptimizeTrack(xm, 1.4, 0.1)
    psie = RelativePsie(ye, xm)

    rx = u * ye + xm
    raceline_k = TrackCurvature(rx)

    np.savetxt("raceline_k.txt", raceline_k, newline=",\n")
    np.savetxt("raceline_ye.txt", ye, newline=",\n")
    np.savetxt("raceline_psie.txt", psie, newline=",\n")
コード例 #35
0
ファイル: run_sail.py プロジェクト: yuriyelesin/rcw_grad
def p_abs(dofold,ctrl):
    ''' ctrl: ctrl's frequency calculation
    '''
    # RCWA
    freqcmp = freq_list[ctrl]*(1+1j/2/Qabs)
    planewave={'p_amp':0,'s_amp':1,'p_phase':0,'s_phase':0}
    theta = 0.
    phi = 0.
    obj,dof,epsdiff = rcwa_assembly(dofold,freqcmp,theta,phi,planewave)
    vals = 0.0
    # volume integration
    if absmethod == 'V':
        for i in range(Nlayer):
            Mv=get_conv(1./Nx/Ny,dof[i*Nx*Ny:(i+1)*Nx*Ny].reshape((Nx,Ny)),obj.G)
            vals = vals + np.real(obj.Volume_integral(1+i,Mv,Mv,Mv,normalize=1))*np.real(obj.omega)*np.imag(epsdiff[i])

        vals = vals*laserP
    elif absmethod == 'RT':
        R,T = obj.RT_Solve(normalize=1)
        vals = (1-R-T)*laserP
    else:
        raise Exception('absmethod undefined')

    vals = vals * (1-beta[ctrl])/(1+beta[ctrl]) # relativistic correction
    return vals
コード例 #36
0
    def calculate_loss(obj_delta, obj_beta, probe_real, probe_imag, probe_defocus_mm, probe_pos_offset, this_i_theta, this_pos_batch, this_prj_batch):

        if optimize_probe_defocusing:
            h_probe = get_kernel(probe_defocus_mm * 1e6, lmbda_nm, voxel_nm, probe_size, fresnel_approx=fresnel_approx)
            probe_complex = probe_real + 1j * probe_imag
            probe_complex = np.fft.ifft2(np.fft.ifftshift(np.fft.fftshift(np.fft.fft2(probe_complex)) * h_probe))
            probe_real = np.real(probe_complex)
            probe_imag = np.imag(probe_complex)

        if optimize_probe_pos_offset:
            this_pos_batch = this_pos_batch + probe_pos_offset[this_i_theta]
        if not shared_file_object:
            obj_stack = np.stack([obj_delta, obj_beta], axis=3)
            if not two_d_mode:
                obj_rot = apply_rotation(obj_stack, coord_ls[this_i_theta])
                # obj_rot = sp_rotate(obj_stack, theta, axes=(1, 2), reshape=False)
            else:
                obj_rot = obj_stack
            probe_pos_batch_ls = []
            exiting_ls = []
            i_dp = 0
            while i_dp < minibatch_size:
                probe_pos_batch_ls.append(this_pos_batch[i_dp:min([i_dp + n_dp_batch, minibatch_size])])
                i_dp += n_dp_batch

            # Pad if needed
            obj_rot, pad_arr = pad_object(obj_rot, this_obj_size, probe_pos, probe_size)

            for k, pos_batch in enumerate(probe_pos_batch_ls):
                subobj_ls = []
                for j in range(len(pos_batch)):
                    pos = pos_batch[j]
                    pos = [int(x) for x in pos]
                    pos[0] = pos[0] + pad_arr[0, 0]
                    pos[1] = pos[1] + pad_arr[1, 0]
                    subobj = obj_rot[pos[0]:pos[0] + probe_size[0], pos[1]:pos[1] + probe_size[1], :, :]
                    subobj_ls.append(subobj)

                subobj_ls = np.stack(subobj_ls)
                exiting = multislice_propagate_batch_numpy(subobj_ls[:, :, :, :, 0], subobj_ls[:, :, :, :, 1], probe_real,
                                                           probe_imag, energy_ev, psize_cm * ds_level, kernel=h, free_prop_cm=free_prop_cm,
                                                           obj_batch_shape=[len(pos_batch), *probe_size, this_obj_size[-1]],
                                                           fresnel_approx=fresnel_approx, pure_projection=pure_projection)
                exiting_ls.append(exiting)
            exiting_ls = np.concatenate(exiting_ls, 0)
            loss = np.mean((np.abs(exiting_ls) - np.abs(this_prj_batch)) ** 2)

        else:
            probe_pos_batch_ls = []
            exiting_ls = []
            i_dp = 0
            while i_dp < minibatch_size:
                probe_pos_batch_ls.append(this_pos_batch[i_dp:min([i_dp + n_dp_batch, minibatch_size])])
                i_dp += n_dp_batch

            pos_ind = 0
            for k, pos_batch in enumerate(probe_pos_batch_ls):
                subobj_ls_delta = obj_delta[pos_ind:pos_ind + len(pos_batch), :, :, :]
                subobj_ls_beta = obj_beta[pos_ind:pos_ind + len(pos_batch), :, :, :]
                exiting = multislice_propagate_batch_numpy(subobj_ls_delta, subobj_ls_beta, probe_real,
                                                           probe_imag, energy_ev, psize_cm * ds_level, kernel=h,
                                                           free_prop_cm=free_prop_cm,
                                                           obj_batch_shape=[len(pos_batch), *probe_size,
                                                                            this_obj_size[-1]],
                                                           fresnel_approx=fresnel_approx,
                                                           pure_projection=pure_projection)
                exiting_ls.append(exiting)
                pos_ind += len(pos_batch)
            exiting_ls = np.concatenate(exiting_ls, 0)
            loss = np.mean((np.abs(exiting_ls) - np.abs(this_prj_batch)) ** 2)
            # dxchange.write_tiff(abs(exiting_ls._value[0]), output_folder + '/det/det', dtype='float32', overwrite=True)
            # raise

        # Regularization
        if reweighted_l1:
            if alpha_d not in [None, 0]:
                loss = loss + alpha_d * np.mean(weight_l1 * np.abs(obj_delta))
            if alpha_b not in [None, 0]:
                loss = loss + alpha_b * np.mean(weight_l1 * np.abs(obj_beta))
        else:
            if alpha_d not in [None, 0]:
                loss = loss + alpha_d * np.mean(np.abs(obj_delta))
            if alpha_b not in [None, 0]:
                loss = loss + alpha_b * np.mean(np.abs(obj_beta))
        if gamma not in [None, 0]:
            if shared_file_object:
                loss = loss + gamma * total_variation_3d(obj_delta, axis_offset=1)
            else:
                loss = loss + gamma * total_variation_3d(obj_delta, axis_offset=0)

        # Write convergence data
        global current_loss
        current_loss = loss._value
        f_conv.write('{},{},{},'.format(i_epoch, i_batch, current_loss))
        f_conv.flush()

        return loss
コード例 #37
0
ファイル: absopt.py プロジェクト: yuriyelesin/rcw_grad
L1 = [Lx,0.]
L2 = [0.,Ly]
epsuniform = 1.
epsbkg = 1.
epsdiff = silicon.epsilon(lam0/freq,'lambda')-epsbkg

thick0 = 1.
thickN = 1.

def fun_owen(ep):
    sigma = np.imag(ep)/np.abs(ep-1)**2
    fun = lambda h:h-2/np.pi*sigma/(1-np.sinc(2*h)**2)
    init = 1/np.imag(np.sqrt(ep))/2/np.pi
    return solve(fun,init)[0]

print('epsilon=',epsdiff+epsbkg,'skin deptph=',1/np.imag(np.sqrt(epsdiff+epsbkg))/2/np.pi,'owen=',fun_owen(epsdiff+epsbkg))

def b_filter(dof,bproj):
    eta = 0.5
    dofnew = np.where(dof<=eta,eta*(np.exp(-bproj*(1-dof/eta))-(1-dof/eta)*np.exp(-bproj)),(1-eta)*(1-np.exp(-bproj*(dof-eta)/(1-eta)) + (dof - eta)/(1-eta) * np.exp(-bproj)) + eta)
    return dofnew

def rcwa_assembly(dof,nG,bproj,theta,phi,planewave):
    '''
    planewave:{'p_amp',...}
    '''
    freqcmp = freq*(1+1j/2/Qabs)
    obj = rcwa.RCWA_obj(nG,L1,L2,freqcmp,theta,phi,verbose=0)
    obj.Add_LayerUniform(thick0,epsuniform)
    for i in range(Nlayer):
        obj.Add_LayerGrid(thickness[i],epsdiff,epsbkg,Mx,My)