Exemplo n.º 1
0
    def gfactor(self, other_body):
        """
        Computes the g_ij factor between this object and other_body
        g_ij = G * mj / d**3 

        Were G is the gravitational constant, mj is the mass of the other objects and d is the distans.
        
        Parameters
        ---------_
        other_body : Object
                    Another body object.
        """
	    
        # Gravity constant
        G = 0.0374038

        if self.obj_id != other_body.obj_id:
	    
            # Distance beetween objects
            dx = self.obj_position[0] - other_body.obj_position[0]
            dy = self.obj_position[1] - other_body.obj_position[1]
            dist = np_sqrt(dx*dx + dy*dy)
	       
            return G*other_body.obj_mass/(dist*dist*dist)
	        
        else:
            return 0
Exemplo n.º 2
0
    def plotAll(self, timer, coreCut, transform=True, ignoreContigLengths=False):
        """Plot all contigs over a certain length which are unbinned"""
        self.loadData(timer, "((length >= "+str(coreCut)+"))")
        if transform:
            self.transformCP(timer)
        else:
            if self.numStoits == 3:
                self.transformedCP = self.covProfiles
            else:
                print "Number of stoits != 3. You need to transform"
                self.transformCP(timer)

        fig = plt.figure()
        ax1 = fig.add_subplot(111, projection='3d')
        if ignoreContigLengths:
            sc = ax1.scatter(self.transformedCP[:,0],
                             self.transformedCP[:,1],
                             self.transformedCP[:,2],
                             edgecolors='none',
                             c=self.contigGCs,
                             cmap=self.colorMapGC,
                             vmin=0.0,
                             vmax=1.0,
                             marker='.',
                             s=10.
                             )
        else:
            sc = ax1.scatter(self.transformedCP[:,0],
                             self.transformedCP[:,1],
                             self.transformedCP[:,2],
                             edgecolors='k',
                             c=self.contigGCs,
                             cmap=self.colorMapGC,
                             vmin=0.0,
                             vmax=1.0,
                             marker='.',
                             s=np_sqrt(self.contigLengths)
                             )

        sc.set_edgecolors = sc.set_facecolors = lambda *args:None  # disable depth transparency effect
        self.plotStoitNames(ax1)

        cbar = plt.colorbar(sc, shrink=0.5)
        cbar.ax.tick_params()
        cbar.ax.set_title("% GC", size=10)
        cbar.set_ticks([0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8])
        #import IPython; IPython.embed()
        cbar.ax.set_ylim([0.15, 0.85])
        mungeCbar(cbar)

        try:
            plt.show()
            plt.close(fig)
        except:
            print "Error showing image", exc_info()[0]
            raise
        del fig
Exemplo n.º 3
0
def str_to_matrix(_l, _symbols): #_sym_symbols are eg. myMBS.dynamics
    if not type(_symbols) == str:
        _str_symbols = str(_symbols).replace("[","").replace("(t)","").replace("]","").replace(", t", "")
    else:
        _str_symbols = _symbols.replace("[","").replace("(t)","").replace("]","").replace(", t", "")
    rows = cols = np_sqrt(len(_l))
    m = Matrix.zeros(rows,cols)
    for i in range(len(_l)):
        c = int(i%cols)
        r = int(i/cols)
        m[r,c] = str_to_dynexpr(_l[i], _str_symbols)
    return m
Exemplo n.º 4
0
def tmax_pseudo_ellipse_array(phi, theta_x, theta_y):
    """The pseudo-ellipse tilt-torsion polar angle for numpy arrays.

    @param phi:     The azimuthal tilt-torsion angle.
    @type phi:      numpy rank-1 float64 array
    @param theta_x: The cone opening angle along x.
    @type theta_x:  float
    @param theta_y: The cone opening angle along y.
    @type theta_y:  float
    @return:        The array theta max angles for the given phi angle array.
    @rtype:         numpy rank-1 float64 array
    """

    # Zero points.
    if theta_x == 0.0:
        return 0.0 * phi
    elif theta_y == 0.0:
        return 0.0 * phi

    # Return the maximum angle.
    return theta_x * theta_y / np_sqrt((np_cos(phi)*theta_y)**2 + (np_sin(phi)*theta_x)**2)
Exemplo n.º 5
0
    def project(self, w):
        """Linearly project the RTs down to a line using direction w.
        The projected variances are replaced by the projected standard deviations.
        Return the projected statistics.
        
        Input:
            w: the projecting direction.
        Output:
            B: the Stats2e obtained from projecting the RTs.
        """
        w = w.ravel()

        B0 = self.get_stat(0).reshape(self.J, 1)

        M1 = self.get_stat(1).reshape(self.J, self.d)
        B1 = dot(M1, w).reshape(self.J, 1)

        M2 = self.get_stat(2).reshape(self, J, self.d, self.d)
        B2 = np_sqrt(dot(dot(M2, w), w)).reshape(self.J, 1)  # this is actually sqrt(w^T Cov w) for each class
        BB = concatenate((B0, B1, B2), 1)
        return Stats2e(self.J, (1,), BB)
Exemplo n.º 6
0
def liouvillian_normal_form(L, symbolic=False):
    r"""
    Return a Hamilton operator ``H`` and a minimal list of collapse operators ``Ls`` that generate the liouvillian ``L``.

    A Liouvillian defined by a hermitian Hamilton operator :math:`H` and a vector of collapse operators
    :math:`\mathbf{L} = (L_1, L_2, \dots L_n)^T` is invariant under the following two operations:

    .. math::
        \left(H, \mathbf{L}\right) & \mapsto \left(H + {1\over 2i}\left(\mathbf{w}^\dagger \mathbf{L} - \mathbf{L}^\dagger \mathbf{w}\right), \mathbf{L} + \mathbf{w} \right) \\
        \left(H, \mathbf{L}\right) & \mapsto \left(H, \mathbf{U}\mathbf{L}\right)\\

    where :math:`\mathbf{w}` is just a vector of complex numbers and :math:`\mathbf{U}` is a complex unitary matrix.
    It turns out that for quantum optical circuit models the set of collapse operators is often linearly dependent.
    This routine tries to find a representation of the Liouvillian in terms of a Hamilton operator ``H`` with
    as few non-zero collapse operators ``Ls`` as possible.
    Consider the following example, which results from a two-port linear cavity with a coherent input into the first port:

    >>> kappa_1, kappa_2 = symbols('kappa_1, kappa_2', positive = True)
    >>> Delta = symbols('Delta', real = True)
    >>> alpha = symbols('alpha')
    >>> H = Delta * Create(1) * Destroy(1) + (sqrt(kappa_1) / (2 * I)) * (alpha * Create(1) - alpha.conjugate() * Destroy(1))
    >>> Ls = [sqrt(kappa_1) * Destroy(1) + alpha, sqrt(kappa_2) * Destroy(1)]
    >>> LL = liouvillian(H, Ls)
    >>> Hnf, Lsnf = liouvillian_normal_form(LL)
    >>> Hnf
        Delta * Create(1) * Destroy(1) - I *  sqrt(kappa_1) * (alpha * Create(1) - alpha.conjugate() * Destroy(1))
    >>> Lsnf
        [sqrt(kappa_1 + kappa_2) * Destroy(1)]

    In terms of the ensemble dynamics this final system is equivalent.
    Note that this function will only work for proper Liouvillians.

    :param L: The Liouvillian
    :type L: SuperOperator
    :return: ``(H, Ls)``
    :rtype: tuple
    :raises: BadLiouvillianError
    """
    L = L.expand()

    if isinstance(L, SuperOperatorPlus):
        Ls = []
        spres = []
        sposts = []
        collapse_form = defaultdict(lambda: defaultdict(int))
        for s in L.operands:
            coeff, term = s.operands if isinstance(s, ScalarTimesSuperOperator) else (sympyOne, s)

            if isinstance(term, SPre):
                spres.append(coeff * term.operands[0])
            elif isinstance(term, SPost):
                sposts.append((coeff * term.operands[0]))
            else:
                if (
                    not isinstance(term, SuperOperatorTimes)
                    or not len(term.operands) == 2
                    or not (isinstance(term.operands[0], SPre) and isinstance(term.operands[1], SPost))
                ):
                    raise BadLiouvillianError(
                        "All terms of the Liouvillian need to be of form "
                        "SPre(X), SPost(X) or SPre(X)*SPost(X): This term is in violation {!s}".format(term)
                    )
                spreL, spostL = term.operands
                Li, Ljd = spreL.operands[0], spostL.operands[0]

                try:
                    complex(coeff)
                except ValueError:
                    symbolic = True
                    coeff = coeff.simplify()

                collapse_form[Li][Ljd] = coeff

        basis = sorted(collapse_form.keys())

        for ii, Li in enumerate(basis):
            for Lj in basis[ii:]:
                cij = collapse_form[Li][Lj.adjoint()]
                cji = collapse_form[Lj][Li.adjoint()]
                if cij != 0 or cji != 0:
                    diff = cij.conjugate() - cji
                    try:
                        diff = complex(diff)
                        if abs(diff) > 1e-6:
                            print(
                                (
                                    "Warning: the Liouvillian is probably malformed: "
                                    "The coefficients of SPre({!s})*SPost({!s}) and SPre({!s})*SPost({!s}) "
                                    "should be complex conjugates of each other"
                                ).format(Li, Lj.adjoint(), Lj, Li.adjoint())
                            )
                    except ValueError:
                        symbolic = True
                        if diff.simplify():
                            print("Warning: the Liouvillian my be malformed, convert to numerical representation")
        final_Lis = []
        if symbolic:
            if len(basis) == 1:
                l1 = basis[0]
                kappa1 = collapse_form[l1][l1.adjoint()]
                final_Lis = [sqrt(kappa1) * l1]
                sdiff = l1.adjoint() * l1 * kappa1 / 2
                spres.append(sdiff)
                sposts.append(sdiff)
            #            elif len(basis) == 2:
            #                l1, l2 = basis
            #                kappa_1 = collapse_form[l1][l1.adjoint()]
            #                kappa_2 = collapse_form[l2][l2.adjoint()]
            #                kappa_12 = collapse_form[l1][l2.adjoint()]
            #                kappa_21 = collapse_form[l2][l1.adjoint()]
            ##                assert (kappa_12.conjugate() - kappa_21) == 0
            else:
                M = SympyMatrix(len(basis), len(basis), lambda i, j: collapse_form[basis[i]][basis[j].adjoint()])

                # First check if M is already diagonal (sympy does not handle this well, for some reason)
                diag = True
                for i in range(len(basis)):
                    for j in range(i):
                        if M[i, j].simplify() != 0 or M[j, i].simplify != 0:
                            diag = False
                            break
                    if diag == False:
                        break
                if diag:
                    for bj in basis:
                        final_Lis.append(bj * sqrt(collapse_form[bj][bj.adjoint()]))
                        sdiff = bj.adjoint() * bj * collapse_form[bj][bj.adjoint()] / 2
                        spres.append(sdiff)
                        sposts.append(sdiff)

                # Try sympy algo
                else:
                    try:
                        data = M.eigenvects()

                        for evalue, multiplicity, ebasis in data:
                            if not evalue:
                                continue
                            for b in ebasis:
                                new_L = (sqrt(evalue) * sum(cj[0] * Lj for (cj, Lj) in zip(b.tolist(), basis))).expand()
                                final_Lis.append(new_L)
                                sdiff = (new_L.adjoint() * new_L / 2).expand()
                                spres.append(sdiff)
                                sposts.append(sdiff)

                    except NotImplementedError:
                        raise CannotSymbolicallyDiagonalize(
                            (
                                "The matrix {} is too hard to diagonalize symbolically. "
                                "Please try converting to fully numerical representation."
                            ).format(M)
                        )
        else:
            M = np_array([[complex(collapse_form[Li][Lj.adjoint()]) for Lj in basis] for Li in basis])

            vals, vecs = eigh(M)
            for sv, vec in zip(np_sqrt(vals), vecs.transpose()):
                new_L = sum((sv * ci) * Li for (ci, Li) in zip(vec, basis))
                final_Lis.append(new_L)
                sdiff = (0.5 * new_L.adjoint() * new_L).expand()
                spres.append(sdiff)
                sposts.append(sdiff)

        miHspre = sum(spres)
        iHspost = sum(sposts)

        if not (miHspre + iHspost) is ZeroOperator or not (miHspre.adjoint() + miHspre) is ZeroOperator:
            print("Warning, potentially malformed Liouvillian {!s}".format(L))

        final_H = (I * miHspre).expand()
        return final_H, final_Lis

    else:
        if L is ZeroSuperOperator:
            return ZeroOperator, []

        raise BadLiouvillianError(str(L))
Exemplo n.º 7
0
    def renderTransCPData(self,
                          fileName="",
                          show=True,
                          elev=45,
                          azim=45,
                          all=False,
                          showAxis=False,
                          primaryWidth=12,
                          primarySpace=3,
                          dpi=300,
                          format='png',
                          fig=None,
                          highlight=None,
                          restrictedBids=[],
                          alpha=1,
                          ignoreContigLengths=False):
        """Plot transformed data in 3D"""
        del_fig = False
        if(fig is None):
            fig = plt.figure()
            del_fig = True
        else:
            plt.clf()
        if(all):
            myAXINFO = {
                'x': {'i': 0, 'tickdir': 1, 'juggled': (1, 0, 2),
                'color': (0, 0, 0, 0, 0)},
                'y': {'i': 1, 'tickdir': 0, 'juggled': (0, 1, 2),
                'color': (0, 0, 0, 0, 0)},
                'z': {'i': 2, 'tickdir': 0, 'juggled': (0, 2, 1),
                'color': (0, 0, 0, 0, 0)},
            }

            ax = fig.add_subplot(131, projection='3d')
            sc = ax.scatter(self.transformedCP[:,0], self.transformedCP[:,1], self.transformedCP[:,2], edgecolors='k', c=self.contigGCs, cmap=self.colorMapGC, vmin=0.0, vmax=1.0, marker='.')
            sc.set_edgecolors = sc.set_facecolors = lambda *args:None  # disable depth transparency effect
            ax.azim = 0
            ax.elev = 0
            ax.set_xlim3d(0,self.scaleFactor)
            ax.set_ylim3d(0,self.scaleFactor)
            ax.set_zlim3d(0,self.scaleFactor)
            ax.set_xticklabels([])
            ax.set_yticklabels([])
            ax.set_zticklabels([])
            ax.set_xticks([])
            ax.set_yticks([])
            ax.set_zticks([])
            for axis in ax.w_xaxis, ax.w_yaxis, ax.w_zaxis:
                for elt in axis.get_ticklines() + axis.get_ticklabels():
                    elt.set_visible(False)
            ax.w_xaxis._AXINFO = myAXINFO
            ax.w_yaxis._AXINFO = myAXINFO
            ax.w_zaxis._AXINFO = myAXINFO

            ax = fig.add_subplot(132, projection='3d')
            sc = ax.scatter(self.transformedCP[:,0], self.transformedCP[:,1], self.transformedCP[:,2], edgecolors='k', c=self.contigGCs, cmap=self.colorMapGC, vmin=0.0, vmax=1.0, marker='.')
            sc.set_edgecolors = sc.set_facecolors = lambda *args:None  # disable depth transparency effect
            ax.azim = 90
            ax.elev = 0
            ax.set_xlim3d(0,self.scaleFactor)
            ax.set_ylim3d(0,self.scaleFactor)
            ax.set_zlim3d(0,self.scaleFactor)
            ax.set_xticklabels([])
            ax.set_yticklabels([])
            ax.set_zticklabels([])
            ax.set_xticks([])
            ax.set_yticks([])
            ax.set_zticks([])
            for axis in ax.w_xaxis, ax.w_yaxis, ax.w_zaxis:
                for elt in axis.get_ticklines() + axis.get_ticklabels():
                    elt.set_visible(False)
            ax.w_xaxis._AXINFO = myAXINFO
            ax.w_yaxis._AXINFO = myAXINFO
            ax.w_zaxis._AXINFO = myAXINFO

            ax = fig.add_subplot(133, projection='3d')
            sc = ax.scatter(self.transformedCP[:,0], self.transformedCP[:,1], self.transformedCP[:,2], edgecolors='k', c=self.contigGCs, cmap=self.colorMapGC, vmin=0.0, vmax=1.0, marker='.')
            sc.set_edgecolors = sc.set_facecolors = lambda *args:None  # disable depth transparency effect
            ax.azim = 0
            ax.elev = 90
            ax.set_xlim3d(0,self.scaleFactor)
            ax.set_ylim3d(0,self.scaleFactor)
            ax.set_zlim3d(0,self.scaleFactor)
            ax.set_xticklabels([])
            ax.set_yticklabels([])
            ax.set_zticklabels([])
            ax.set_xticks([])
            ax.set_yticks([])
            ax.set_zticks([])
            for axis in ax.w_xaxis, ax.w_yaxis, ax.w_zaxis:
                for elt in axis.get_ticklines() + axis.get_ticklabels():
                    elt.set_visible(False)
            ax.w_xaxis._AXINFO = myAXINFO
            ax.w_yaxis._AXINFO = myAXINFO
            ax.w_zaxis._AXINFO = myAXINFO
        else:
            ax = fig.add_subplot(111, projection='3d')
            if len(restrictedBids) == 0:
                if highlight is None:
                    print "BF:", np_shape(self.transformedCP)
                    if ignoreContigLengths:
                        sc = ax.scatter(self.transformedCP[:,0],
                                   self.transformedCP[:,1],
                                   self.transformedCP[:,2],
                                   edgecolors='none',
                                   c=self.contigGCs,
                                   cmap=self.colorMapGC,
                                   s=10.,
                                   vmin=0.0,
                                   vmax=1.0,
                                   marker='.')
                    else:
                        sc = ax.scatter(self.transformedCP[:,0],
                                   self.transformedCP[:,1],
                                   self.transformedCP[:,2],
                                   edgecolors='none',
                                   c=self.contigGCs,
                                   cmap=self.colorMapGC,
                                   vmin=0.0,
                                   vmax=1.0,
                                   s=np_sqrt(self.contigLengths),
                                   marker='.')
                    sc.set_edgecolors = sc.set_facecolors = lambda *args:None # disable depth transparency effect
                else:
                    #draw the opaque guys first
                    """
                    sc = ax.scatter(self.transformedCP[:,0],
                                    self.transformedCP[:,1],
                                    self.transformedCP[:,2],
                                    edgecolors='none',
                                    c=self.contigGCs,
                                    cmap=self.colorMapGC,
                                    vmin=0.0,
                                    vmax=1.0,
                                    s=100.,
                                    marker='s',
                                    alpha=alpha)
                    sc.set_edgecolors = sc.set_facecolors = lambda *args:None # disable depth transparency effect
                    """
                    # now replot the highlighted guys
                    disp_vals = np_array([])
                    disp_GCs = np_array([])

                    thrower = {}
                    hide_vals = np_array([])
                    hide_GCs = np_array([])

                    num_points = 0
                    for bin in highlight:
                        for row_index in bin.rowIndices:
                            num_points += 1
                            disp_vals = np_append(disp_vals, self.transformedCP[row_index])
                            disp_GCs = np_append(disp_GCs, self.contigGCs[row_index])
                            thrower[row_index] = False
                    # reshape
                    disp_vals = np_reshape(disp_vals, (num_points, 3))

                    num_points = 0
                    for i in range(len(self.indices)):
                        try:
                            thrower[i]
                        except KeyError:
                            num_points += 1
                            hide_vals = np_append(hide_vals, self.transformedCP[i])
                            hide_GCs = np_append(hide_GCs, self.contigGCs[i])
                    # reshape
                    hide_vals = np_reshape(hide_vals, (num_points, 3))

                    sc = ax.scatter(hide_vals[:,0],
                                    hide_vals[:,1],
                                    hide_vals[:,2],
                                    edgecolors='none',
                                    c=hide_GCs,
                                    cmap=self.colorMapGC,
                                    vmin=0.0,
                                    vmax=1.0,
                                    s=100.,
                                    marker='s',
                                    alpha=alpha)
                    sc.set_edgecolors = sc.set_facecolors = lambda *args:None # disable depth transparency effect

                    sc = ax.scatter(disp_vals[:,0],
                                    disp_vals[:,1],
                                    disp_vals[:,2],
                                    edgecolors='none',
                                    c=disp_GCs,
                                    cmap=self.colorMapGC,
                                    vmin=0.0,
                                    vmax=1.0,
                                    s=10.,
                                    marker='.')
                    sc.set_edgecolors = sc.set_facecolors = lambda *args:None # disable depth transparency effect

                    print np_shape(disp_vals), np_shape(hide_vals), np_shape(self.transformedCP)

                # render color bar
                cbar = plt.colorbar(sc, shrink=0.5)
                cbar.ax.tick_params()
                cbar.ax.set_title("% GC", size=10)
                cbar.set_ticks([0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8])
                cbar.ax.set_ylim([0.15, 0.85])
                mungeCbar(cbar)
            else:
                r_trans = np_array([])
                r_cols=np_array([])
                num_added = 0
                for i in range(len(self.indices)):
                    if self.binIds[i] not in restrictedBids:
                        r_trans = np_append(r_trans, self.transformedCP[i])
                        r_cols = np_append(r_cols, self.contigGCs[i])
                        num_added += 1
                r_trans = np_reshape(r_trans, (num_added,3))
                print np_shape(r_trans)
                #r_cols = np_reshape(r_cols, (num_added,3))
                sc = ax.scatter(r_trans[:,0],
                                r_trans[:,1],
                                r_trans[:,2],
                                edgecolors='none',
                                c=r_cols,
                                cmap=self.colorMapGC,
                                s=10.,
                                vmin=0.0,
                                vmax=1.0,
                                marker='.')
                sc.set_edgecolors = sc.set_facecolors = lambda *args:None  # disable depth transparency effect

                # render color bar
                cbar = plt.colorbar(sc, shrink=0.5)
                cbar.ax.tick_params()
                cbar.ax.set_title("% GC", size=10)
                cbar.set_ticks([0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8])
                cbar.ax.set_ylim([0.15, 0.85])
                mungeCbar(cbar)

            ax.azim = azim
            ax.elev = elev
            ax.set_xlim3d(0,self.scaleFactor)
            ax.set_ylim3d(0,self.scaleFactor)
            ax.set_zlim3d(0,self.scaleFactor)
            ax.set_xticklabels([])
            ax.set_yticklabels([])
            ax.set_zticklabels([])
            ax.set_xticks([])
            ax.set_yticks([])
            ax.set_zticks([])
            if(not showAxis):
                ax.set_axis_off()

        if(fileName != ""):
            try:
                if(all):
                    fig.set_size_inches(3*primaryWidth+2*primarySpace,primaryWidth)
                else:
                    fig.set_size_inches(primaryWidth,primaryWidth)
                plt.savefig(fileName,dpi=dpi,format=format)
            except:
                print "Error saving image",fileName, exc_info()[0]
                raise
        elif(show):
            try:
                plt.show()
            except:
                print "Error showing image", exc_info()[0]
                raise
        if del_fig:
            plt.close(fig)
            del fig
Exemplo n.º 8
0
    def plotUnbinned(self, timer, coreCut, transform=True, ignoreContigLengths=False):
        """Plot all contigs over a certain length which are unbinned"""
        self.loadData(timer, "((length >= "+str(coreCut)+") & (bid == 0))")

        if transform:
            self.transformCP(timer)
        else:
            if self.numStoits == 3:
                self.transformedCP = self.covProfiles
            else:
                print "Number of stoits != 3. You need to transform"
                self.transformCP(timer)

        fig = plt.figure()
        ax1 = fig.add_subplot(111, projection='3d')
        if ignoreContigLengths:
            sc = ax1.scatter(self.transformedCP[:,0], self.transformedCP[:,1], self.transformedCP[:,2], edgecolors='none', c=self.contigGCs, cmap=self.colorMapGC, vmin=0.0, vmax=1.0, s=10, marker='.')
        else:
            sc = ax1.scatter(self.transformedCP[:,0], self.transformedCP[:,1], self.transformedCP[:,2], edgecolors='k', c=self.contigGCs, cmap=self.colorMapGC, vmin=0.0, vmax=1.0, s=np_sqrt(self.contigLengths), marker='.')
        sc.set_edgecolors = sc.set_facecolors = lambda *args:None  # disable depth transparency effect
        self.plotStoitNames(ax1)

        try:
            plt.show()
            plt.close(fig)
        except:
            print "Error showing image", exc_info()[0]
            raise
        del fig
Exemplo n.º 9
0
def EyelinkGetGaze(targetLoc, FixLen, dispsize, el=pylink.getEYELINK(),
                   isET=True, PixPerDeg=None, IgnoreBlinks=False,
                   OversamplingBehavior=None):
    """ Online gaze position output and gaze control for Eyelink 1000+.

    **Author** : Wanja Mössing, WWU Münster | [email protected] \n
    *July 2017*

    Parameters
    ----------
    targetLoc : tuple
        two-item tuple x & y coordinates in px; defines where subject should
        look at ([0, 0] is center - just as psychopy assumes it.)
    FixLen : int
        A circle around a specified point is set as area that subjects are
        allowed to look at. ``FixLen`` defines the radius of that circle.
        Can be in degree or pixels. If ``PixPerDeg`` is not empty, assumes
        degree, else pixels.
    el: Eyelink object
        ...as returned by, e.g., ``EyelinkStart()``. You can try to run it
        without passing ``el``. In that case ``EyelinkGetGaze()`` will try to
        find ``el``.
    dispsize : tuple
        Needed because PP thinks (0,0)=center, but EL thinks (0,0)= topleft
    isET: boolean, default=True
        Is Eyetracker connected? If ``False``, returns display center as
        coordinates and ``hsmvd=False``.
    PixPerDeg: float
        How many pixels per one degree of visual angle? If provided, ``FixLen``
        is assumed to be in degree.
    IgnoreBlinks: boolean, default=False
        If True, missing gaze position is replaced by center coordinates.
    OversamplingBehavior: None
        Defines what is returned if nothing new is available.

    Returns
    -------
    GazeInfo: dict
        Dict with elements ``x``,``y``, and ``hsmvd``. ``x`` & ``y`` are gaze
        coordinates in pixels. ``hsmvd`` is boolean and defines whether gaze
        left the circle set with FixLen.
    """
    # IF EYETRACKER IS CONNECTED...
    if isET:
        # This is just for clarity
        RIGHT_EYE = 1
        LEFT_EYE = 0
        BINOCULAR = 2

        # ---------- deprecated but maybe useful later...----------------------
        # check if new data available via link
        # eventType = el.getNextData()
        # if it's a saccade or fixation, get newest gaze data available
        # if eventType in {pylink.STARTFIX, pylink.FIXUPDATE, pylink.ENDFIX,
        #                 pylink.STARTSACC, pylink.ENDSACC}:
        # if it's a blink, adjust output accordingly
        # elif eventType in {pylink.STARTBLINK,pylink.ENDBLINK}:
        # ---------------------------------------------------------------------

        # Get the newest data sample
        sample = el.getNewestSample()
        # get the newest event
        event = el.getNextData()
        # returns none, if no new sample available
        if sample is not None:
            # check which eye has been tracked and retrieve data for this eye
            if el.eyeAvailable() is LEFT_EYE and sample.isLeftSample():
                # getGaze() return Two-item tuple in the format of
                # (float, float). -> (x,y) in px
                # getPupilSize return float in arbitrary units. The meaning of
                # this depends on the settings made (area or diameter)
                gaze = sample.getLeftEye().getGaze()
                pupil = sample.getLeftEye().getPupilSize()
            elif el.eyeAvailable() is RIGHT_EYE and sample.isRightSample():
                gaze = sample.getRightEye().getGaze()
                pupil = sample.getRightEye().getPupilSize()
            elif el.eyeAvailable() is BINOCULAR:
                print 'Binocular mode not yet implemented'
                return None
            else:
                raise Exception('Could not detect which eye has been tracked')

            # Check if subject blinks or if data are just randomly missing
            if pylink.MISSING_DATA in gaze:
                # check how sure we are whether it is a blink
                if event is pylink.STARTBLINK:
                    print('Subject is definitely blinking')  # debugging
                    blinked = True
                elif pupil == 0:
                    print('Subject is probably blinking')  # debugging
                    blinked = True
                else:
                    print('Missing data but no blink?')  # debugging
                    blinked = False
                # assign values accordingly
                if blinked and not IgnoreBlinks:
                    hsmvd = True
                elif blinked and IgnoreBlinks:
                    hsmvd = False
                    gaze = targetLoc
                elif not blinked:
                    hsmvd = True
            else:
                # Eyelink thinks (0,0) = topleft, PsyPy thinks it's center...
                xhalf = dispsize[0]/2
                yhalf = dispsize[1]/2
                x = gaze[0]
                y = gaze[1]
                if x >= xhalf:
                    xout = x - xhalf
                else:
                    xout = (xhalf - x) * -1
                if y >= yhalf:
                    yout = (y - yhalf) * -1
                else:
                    yout = yhalf - y
                gaze = (xout, yout)
                # transform location data to numpy arrays, so we can calculate
                # euclidean distance
                a = np_array(targetLoc)
                b = np_array(gaze)
                # get euclidean distance in px
                dist = np_sqrt(np_sum((a-b)**2))
                # check if we know how many px form one degree.
                # If we do, convert to degree
                if PixPerDeg is not None:
                    dist = dist/PixPerDeg
                # Now check whether gaze is in allowed frame
                hsmvd = dist > FixLen

            # return dict
            return {'x': gaze[0], 'y': gaze[1], 'hsmvd': hsmvd,
                    'pupilSize': pupil}
        # If no new sample is available return None
        elif sample is None:
            return OversamplingBehavior
    # IF EYETRACKER NOT CONNECTED RETURN TARGETLOCATION AND NO PUPIL SIZE
    elif not isET:
        return {'x': targetLoc[0], 'y': targetLoc[1], 'hsmvd': False,
                'pupilSize': None}
Exemplo n.º 10
0
def one2one_matches(known_complex_nodes_list, fin_list_graphs, N_pred_comp,
                    N_test_comp, out_comp_nm, suffix, dir_nm):

    Metric = np_zeros((N_test_comp, N_pred_comp))
    Common_nodes = np_zeros((N_test_comp, N_pred_comp))
    known_comp_lens = np_zeros((N_test_comp, 1))
    pred_comp_lens = np_zeros((1, N_pred_comp))

    fl = 1

    for i, test_complex in enumerate(known_complex_nodes_list):
        T = set(test_complex)
        known_comp_lens[i, 0] = len(T)

        for j, pred_complex in enumerate(fin_list_graphs):
            P = pred_complex[0]

            F1_score, C = f1_similarity(P, T)
            Common_nodes[i, j] = C

            Metric[i, j] = F1_score

            if fl == 1:
                pred_comp_lens[0, j] = len(P)
        fl = 0

    max_indices_i_common = np_argmax(Common_nodes, axis=0)
    ppv_list = [
        float(Common_nodes[i, j]) / pred_comp_lens[0, j]
        for j, i in enumerate(max_indices_i_common)
    ]
    PPV = sum(ppv_list) / len(ppv_list)

    max_indices_j_common = np_argmax(Common_nodes, axis=1)
    sn_list = [
        float(Common_nodes[i, j]) / known_comp_lens[i, 0]
        for i, j in enumerate(max_indices_j_common)
    ]
    Sn = sum(sn_list) / len(sn_list)

    acc_unbiased = np_sqrt(PPV * Sn)

    max_indices_i = np_argmax(Metric, axis=0)
    best_matches_4predicted = [
        (fin_list_graphs[j][0], known_complex_nodes_list[i], Metric[i, j],
         fin_list_graphs[j][1]) for j, i in enumerate(max_indices_i)
    ]

    max_indices_j = np_argmax(Metric, axis=1)
    best_matches_4known = [(fin_list_graphs[j][0], known_complex_nodes_list[i],
                            Metric[i, j], fin_list_graphs[j][1])
                           for i, j in enumerate(max_indices_j)]

    avged_f1_score4known = plot_f1_scores(
        best_matches_4known, out_comp_nm, '_best4known' + suffix,
        'Best predicted match for known complexes - ')
    avged_f1_score4pred = plot_f1_scores(
        best_matches_4predicted, out_comp_nm, '_best4predicted' + suffix,
        'Best known match for predicted complexes - ')

    avg_f1_score = (avged_f1_score4known + avged_f1_score4pred) / 2
    net_f1_score = 2 * avged_f1_score4known * avged_f1_score4pred / (
        avged_f1_score4known + avged_f1_score4pred)

    write_best_matches(best_matches_4known, out_comp_nm, dir_nm,
                       '_best4known' + suffix)
    write_best_matches(best_matches_4predicted, out_comp_nm, dir_nm,
                       '_best4predicted' + suffix)

    prec_MMR, recall_MMR, f1_MMR, max_matching_edges = f1_mmr(Metric)

    plot_pr_curve_mmr(Metric, fin_list_graphs, out_comp_nm + suffix)

    n_matches = int(len(max_matching_edges) / 2)

    return avg_f1_score, net_f1_score, PPV, Sn, acc_unbiased, prec_MMR, recall_MMR, f1_MMR, n_matches
Exemplo n.º 11
0
def FluxRate(pressure,M=117.16,T=300):
    dimerArea_in_cm2 = 0.52918**2*1e-14
    torr2pa = 133.322368
    from numpy import sqrt as np_sqrt
    return (2.63e20*pressure*torr2pa/np_sqrt(M*T))*dimerArea_in_cm2