def random_info(info2, deny, points_new, k, red):
        i = 0
        final_points = np_ones((np_shape(info2)[0], 5)) * (-1)
        num = []
        while i < red:
            if i == 0:
                num.append(int(points_new[0, -1]))
            else:
                while True:
                    r = randint(0, np_shape(info2)[0] - 1)
                    s = 0
                    for j in xrange(i):
                        s += sum(np_isin(deny[num[j] + 1], r + 1)) * 1
                    if sum(np_isin(num, r) * 1) > 0 or s != 0:
                        continue
                    else:
                        p = int(points_new[np_isin(points_new[:, -1], r),
                                           -1][0])
                        break
                num.append(p)
            i += 1
        pn_68 = points_new[np_isin(points_new[:, -1], num), :]

        final_points[0:len(num), 0] = pn_68[:, 0]
        final_points[0:len(num), 1] = pn_68[:, 1]
        final_points[0:len(num), 2] = info2[k:k + len(num), 0]
        final_points[0:len(num), 3] = info2[k:k + len(num), 1]
        final_points[0:len(num), 4] = pn_68[:, -1]
        f = list(np_isin(final_points[:, 3], [6, 8]) == False)
        pn = points_new[np_isin(points_new[:, -1], num) == False]
        final_points[len(num):, 0:2] = pn[:, 0:2]
        final_points[len(num):, 4] = pn[:, -1]
        final_points[len(num):,
                     2:4] = info2[np_isin(info2[:, 1], [6, 8]) == False, :]
        return final_points
示例#2
0
    def subIncrement3D(self, workingBlock, px, py, pz, vals, offset):
        """AUX: Called from incrementAboutPoint3D does but one slice
        
        multiplier is proportional to the contigs length
        """
        # get the size of the working block
        shape = np_shape(workingBlock)
        if px > 0:
            if py > 0:
                workingBlock[px - 1, py - 1, pz] += vals[offset + 2]  # Top left corner
            workingBlock[px - 1, py, pz] += vals[offset + 1]  # Top
            if py < shape[1] - 1:
                workingBlock[px - 1, py + 1, pz] += vals[offset + 2]  # Top right corner

        if py > 0:
            workingBlock[px, py - 1, pz] += vals[offset + 1]  # Left side
        workingBlock[px, py, pz] += vals[offset]  # Point
        if py < shape[1] - 1:
            workingBlock[px, py + 1, pz] += vals[offset + 1]  # Right side

        if px < shape[0] - 1:
            if py > 0:
                workingBlock[px + 1, py - 1, pz] += vals[offset + 2]  # Bottom left corner
            workingBlock[px + 1, py, pz] += vals[offset + 1]  # Bottom
            if py < shape[1] - 1:
                workingBlock[px + 1, py + 1, pz] += vals[offset + 2]  # Bottom right corner
示例#3
0
def lines(ground, dim_x, dim_y):
    d_small = 60
    d_long = 3 * d_small
    x_c, y_c = dim_x / 2, dim_y / 2
    points = np_array([[y_c - d_small, x_c - d_long],
                       [y_c - d_small, x_c + d_long],
                       [y_c + d_small, x_c - d_long],
                       [y_c + d_small, x_c + d_long],
                       [y_c + d_long, x_c - d_small],
                       [y_c - d_long, x_c - d_small],
                       [y_c - d_long, x_c + d_small],
                       [y_c + d_long, x_c + d_small]])
    for j in xrange(np_shape(points)[0] / 2):
        i = 2 * j
        cv2_line(ground, (points[i, 1], points[i, 0]),
                 (points[i + 1, 1], points[i + 1, 0]), [125, 100, 140], 5)
    out = x_c, y_c, d_small, d_long
    return out
示例#4
0
def pause(time, ground):
    while time >= 1:
        ground[np_shape(ground)[1] / 2 + 70:np_shape(ground)[1] / 2 + 100,
               np_shape(ground)[1] / 2 - 10:np_shape(ground)[1] / 2 +
               40, :] = 255
        cv2_putText(
            ground, str(time),
            (np_shape(ground)[1] / 2 - 5, np_shape(ground)[1] / 2 + 93),
            cv2_FONT_HERSHEY_SIMPLEX, 1, 0)
        cv2_imshow("Tic_Tac_Toe", ground)
        k = cv2_waitKey(1000) & 0xFF
        if k == 27:
            return 1
        elif k != 255:
            return 0
        time -= 1
    return 0
示例#5
0
    def findNewClusterCenters(self, ss=0):
        """Find a putative cluster"""

        inRange = lambda x, l, u: x >= l and x < u

        # we work from the top view as this has the base clustering
        max_index = np_argmax(self.blurredMaps[0])
        max_value = self.blurredMaps[0].ravel()[max_index]

        max_x = int(max_index / self.PM.scaleFactor)
        max_y = max_index - self.PM.scaleFactor * max_x
        max_z = -1

        ret_values = [max_value, max_x, max_y]

        start_span = int(1.5 * self.span)
        span_len = 2 * start_span + 1

        if self.debugPlots:
            self.plotRegion(max_x, max_y, max_z, fileName="Image_" + str(self.imageCounter), tag="column", column=True)
            self.imageCounter += 1

        # make a 3d grid to hold the values
        working_block = np_zeros((span_len, span_len, self.PM.scaleFactor))

        # go through the entire column
        (x_lower, x_upper) = self.makeCoordRanges(max_x, start_span)
        (y_lower, y_upper) = self.makeCoordRanges(max_y, start_span)
        super_putative_row_indices = []
        for p in self.im2RowIndicies:
            if inRange(p[0], x_lower, x_upper) and inRange(p[1], y_lower, y_upper):
                for row_index in self.im2RowIndicies[p]:
                    # check that the point is real and that it has not yet been binned
                    if row_index not in self.PM.binnedRowIndicies and row_index not in self.PM.restrictedRowIndicies:
                        # this is an unassigned point.
                        multiplier = np_log10(self.PM.contigLengths[row_index])
                        self.incrementAboutPoint3D(
                            working_block, p[0] - x_lower, p[1] - y_lower, p[2], multiplier=multiplier
                        )
                        super_putative_row_indices.append(row_index)

        # blur and find the highest value
        bwb = ndi.gaussian_filter(working_block, 8)  # self.blurRadius)
        densest_index = np_unravel_index(np_argmax(bwb), (np_shape(bwb)))
        max_x = densest_index[0] + x_lower
        max_y = densest_index[1] + y_lower
        max_z = densest_index[2]

        # now get the basic color of this dense point
        putative_center_row_indices = []

        (x_lower, x_upper) = self.makeCoordRanges(max_x, self.span)
        (y_lower, y_upper) = self.makeCoordRanges(max_y, self.span)
        (z_lower, z_upper) = self.makeCoordRanges(max_z, 2 * self.span)

        for row_index in super_putative_row_indices:
            p = np_around(self.PM.transformedCP[row_index])
            if inRange(p[0], x_lower, x_upper) and inRange(p[1], y_lower, y_upper) and inRange(p[2], z_lower, z_upper):
                # we are within the range!
                putative_center_row_indices.append(row_index)

        # make sure we have something to go on here
        if np_size(putative_center_row_indices) == 0:
            # it's all over!
            return None

        if np_size(putative_center_row_indices) == 1:
            # get out of here but keep trying
            # the calling function may restrict these indices
            return [[np_array(putative_center_row_indices)], ret_values]
        else:
            total_BP = sum([self.PM.contigLengths[i] for i in putative_center_row_indices])
            if not self.isGoodBin(total_BP, len(putative_center_row_indices), ms=5):  # Can we trust very small bins?.
                # get out of here but keep trying
                # the calling function should restrict these indices
                return [[np_array(putative_center_row_indices)], ret_values]
            else:
                # we've got a few good guys here, partition them up!
                # shift these guys around a bit
                center_k_vals = np_array([self.PM.kmerVals[i] for i in putative_center_row_indices])
                k_partitions = self.partitionVals(center_k_vals)

                if len(k_partitions) == 0:
                    return None
                else:
                    center_c_vals = np_array([self.PM.transformedCP[i][-1] for i in putative_center_row_indices])
                    # center_c_vals = np_array([self.PM.averageCoverages[i] for i in putative_center_row_indices])
                    center_c_vals -= np_min(center_c_vals)
                    c_max = np_max(center_c_vals)
                    if c_max != 0:
                        center_c_vals /= c_max
                    c_partitions = self.partitionVals(center_c_vals)

                    # take the intersection of the two partitions
                    tmp_partition_hash_1 = {}
                    id = 1
                    for p in k_partitions:
                        for i in p:
                            tmp_partition_hash_1[i] = id
                        id += 1

                    tmp_partition_hash_2 = {}
                    id = 1
                    for p in c_partitions:
                        for i in p:
                            try:
                                tmp_partition_hash_2[(tmp_partition_hash_1[i], id)].append(i)
                            except KeyError:
                                tmp_partition_hash_2[(tmp_partition_hash_1[i], id)] = [i]
                        id += 1

                    partitions = [
                        np_array([putative_center_row_indices[i] for i in tmp_partition_hash_2[key]])
                        for key in tmp_partition_hash_2.keys()
                    ]

                    # pcs = [[self.PM.averageCoverages[i] for i in p] for p in partitions]
                    # print pcs
                    return [partitions, ret_values]
示例#6
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
示例#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
                         small_side,
                         edges,
                         0,
                         0,
                         color=[160, 200, 200])
    #print side,small_side
    points, r_c = centers(c, small_side * 2, edges, CATAN)
    points = points.astype('uint16')
    #data = color_number(points,CATAN,r_c)
    data = color_number2(points, CATAN, r_c)

    if catan[0] == CATAN:
        i_y = 55
    elif catan[1] == CATAN:
        i_y = 44
    for p in xrange(np_shape(data)[0]):
        if data[p, 3] >= 10:
            radius = 15
        else:
            radius = 8
        col = [
            int((data[p, 2] / 1000000) % 1000),
            int((data[p, 2] / 1000) % 1000),
            int(data[p, 2] % 1000)
        ]
        if data[p, 3] != 7:
            factor = 0.3
        else:
            factor = 0
        ground, small_side = polygon(ground,
                                     data[p, :2],
示例#9
0
def adsToolkit(searchWidth = 5, debugMode = False, indep_mode = False):
    filetag = pd_ExcelFile('lib.xlsx')
    sheetlist = filetag.sheet_names

    print('adsToolkit| Welcome, adsorption lib is activated. Currently only molecule adsorbs on metal is supported,\n'
         +'            but I will update and add more available dataset in the future.\n'
         +'            Advantage of this program: you can just add any data into lib.xlsx without hestitation such as\n'
         +'            messing up order of data.\n'
         )

    print('adsToolkit| usage: just do what program tells you to do, you will obtain what you want to get.\n'
         +'adsToolkit| adsToolkit is a module belonging to open source SIMUPKGS package, it provides custormize\n'
         +'            usage. Any data you trust and suppose to be useful in your future work can be added in\n'
         +'            database saved in the same directory of this program -> lib.xlsx\n'
         +'            to guarantee program will read your data properly, please read quotes in that file.\n'
         +'            or you can just send email to developer of this tool, lib will be updated at Github\n'
         +'            --->\n'
         +'            For more tools (source codes), visit https://github.com/kirk0830/SIMUPKGS\n\n'
         +'adsToolkit| Developer notes:\n\n'
         +'           *Dipole-dipole coupling, see -> Chin. J. Catal., 2017, 38: 1473–1480, for distinguishing isolated\n'
         +'            atoms and cluster, one important feature is whether CO frequencies are loading-dependent.\n'
         +'            dipole-dipole coupling (actually dynamically correlation) will cause higher vibrational \n'
         +'            frequencies at higher loading. And this correlation will decrease intensity of overall adsorbance.\n\n'
         +'           *Stark effect, which is Zeeman effect in electrostatic version, see -> J. Phys.: Conf. Ser. 117 012003.\n'
         +'            Stark effect is a field-dipole interaction that breaks degeneracy of M-CO vibration frequencies.\n\n'
         +'           *Failure of DFT prediction of CO\n'
         +'            as extraordinary delocalization yielded by DFT, a compensating DFT + molecular U on C 2p and O 2p\n'
         +'            should be used. Also under several circumstances, traditional functionals such as PBE, revPBE, rPBE\n'
         +'            will overestimate adsorption energy, vdw-correction will even make problem worse. So do not blindly\n'
         +'            trust so-called first-principle.\n\n'
         +'           *Chemical environment distinguished by FWHM\n'
         +'            full width of half max, can be used as an qualitative indicator of homogenity of PGM_iso-CO sites\n'
         +'            such as Ir(CO)2 on various supports, FWHM ~5cm-1, similar with organmetallic complexes ~4cm-1, \n'
         +'            indicating an nearly isolated site, see J. Phys. Chem. Lett., 2016, 7, 3854–3860.\n'
         +'----------------------------------------------------------------------------------------------------\n'
         +'adsToolkit| step 1: choose adsorbate:'
        )
    if debugMode:
        exit()
    
    for isheet in range(len(sheetlist)):
        print('            ['+str(isheet)+'] '+str(sheetlist[isheet]))
    mole = input('adsToolkit| (to directly quit program, enter 999) >> ')
    if mole == '999' or mole == '':
        exit()
    else:
        mole = int(mole)
    
    sheetObj = filetag.parse(sheet_name=mole)
    elementlist = set(sheetObj.iloc[:,0].values)
    print('adsToolkit| for molecule you choose, there are '+str(sheetObj.shape[0])+' lines of data available.\n'
         +'----------------------------------------------------------------------------------------------------\n'
         +'adsToolkit| step 2: type-in element symbol of your metal, currently supported metals: '+str([ielement for ielement in elementlist]))
    
    element = input('adsToolkit| (to directly quit program, enter 999) >> ')
    if element == '999' or element == '':
        exit()

    print('----------------------------------------------------------------------------------------------------\n'
         +'adsToolkit| step 3: type-in frequence in cm-1 you want to look up.')

    try:
        freqIn = float(input('adsToolkit| >> '))
    except ValueError:
        print('adsToolkit| ***error*** for no valid input, first five rows of dataset will be printed, quit.')
        # sheetOut = filetag.parse(sheet_name=mole).iloc[[0, 2, 3]] # to print out several specified lines
        print('----------------------------------------SEARCH RESULT-----------------------------------------------')
        print(sheetObj.iloc[:5,:6])
        exit()

    print('----------------------------------------------------------------------------------------------------\n'
         +'adsToolkit| step 4: (press Enter directly or choose \'normal mode\' if you dont know what this step means)\n'
         +'            [1] normal mode (0)\n'
         +'            [2] very tight (0.0001)\n'
         +'            [3] tight (0.001)\n'
         +'            [4] default (0.01)\n'
         +'            [5] loose (0.1)\n'
         +'            [6] very loose (0.3)\n'
         +'            [7] awfully loose (0.5)\n'
         +'            [8] Do you feel lucky? (1.0)\n'
         +'            ----->>> I just salute to Gaussian software :)')
    rescale = input('adsToolkit| >> ')
    if rescale == '' or rescale == '1':
        rescale = 0
    elif rescale == '2':
        rescale = 0.0001
    elif rescale == '3':
        rescale = 0.001
    elif rescale == '4':
        rescale = 0.01
    elif rescale == '5':
        rescale = 0.1
    elif rescale == '6':
        rescale = 0.3
    elif rescale == '7':
        rescale = 0.5
    elif rescale == '8':
        rescale = 1
    else:
        rescale = 0
    
    rescale_min = 1-rescale
    rescale_max = 1+rescale

    sheetdata = sheetObj.iloc[:].values # 2 dimensional list obtained.
    nline = np_shape(sheetdata)[0]
    
    outlist = []
    for iline in range(nline):

        if sheetdata[iline][0] == element:

            freqCheck = re_split(', ', str(sheetdata[iline][2]))
            freqCheck = [ float(freq) for freq in freqCheck ]
            if len(freqCheck) == 1:
                freqmin = freqCheck[0] - searchWidth
                freqmax = freqCheck[0] + searchWidth
                if freqIn >= freqmin and freqIn <= freqmax:
                    outlist.append(iline)
            elif len(freqCheck) == 2:
                freqmin = min(freqCheck[0], freqCheck[1])*rescale_min
                freqmax = max(freqCheck[0], freqCheck[1])*rescale_max
                if freqIn >= freqmin and freqIn <= freqmax:
                    outlist.append(iline)
    print('----------------------------------------SEARCH RESULT-----------------------------------------------')
    print(sheetObj.iloc[outlist, :6])
    #strout = sheetObj.iloc[0].values
    
    # use
    # .loc for label based indexing or
    # .iloc for positional indexing
    # .values for get data from it

    # developer notes:
    # this may be the first time that I use pandas pacakge... So I take note here for future use. Parameters without any explanations
    # are evaluated as parameters that wont be used by me. But you can still find detailed description at website:
    # https://pandas.pydata.org/pandas-docs/stable/reference

    # parameters of ExcelFile.parse(
    # sheet_name=0, : specify sheet you want to read, list is also supported. if not specified, all sheeets will be read in.
    # header=0, : determine which line pandas will start with, header = 0 for a full read
    # names=None, : specify names of column as you like, will overwrite results read-in.
    # index_col=None, : select one column as the first
    # usecols=None, : number of columns you want pandas to parse, there are also other usage, I omit here.
    # squeeze=False, 
    # converters=None, 
    # true_values=None, 
    # false_values=None, 
    # skiprows=None, 
    # nrows=None, : number of rows to skip at the beginning
    # na_values=None, 
    # parse_dates=False, 
    # date_parser=None, 
    # thousands=None, 
    # comment=None, 
    # skipfooter=0, 
    # convert_float=True, 
    # mangle_dupe_cols=True, 
    # **kwds)
    # 
    print('----------------------------------------------------------------------------------------------------')
    print('adsToolkit| thank you, adsorption toolkit will quit. Results above only the first two reference is listed.\n'
         +'            If you need more reference to cite, search the number emerges at head of line, it is the line number\n'
         +'            of datafile lib.xlsx.\n\n'
         +'            If you want to have contribution on this program, \n'
         +'            -> send your customized lib.xlsx to me [email protected]\n'
         +'            -> make comments and report issues at https://github.com/kirk0830/SIMUPKGS\n')
    if indep_mode:
        quitTag = input('adsToolkit| press ENTER to quit. >> ')