Example #1
0
    def pca(self, data_matrix):
        """Perform PCA.

        Principal components are given in self.pca,
        and the variance in self.variance.

        Parameters
        ----------
        data_matrix : list of lists
          List of tetranucleotide signatures
        """

        cols = len(data_matrix[0])
        data_matrix = np_reshape(np_array(data_matrix), (len(data_matrix), cols))

        pca = PCA()
        pc, variance = pca.pca_matrix(data_matrix, 3, bCenter=True, bScale=False)

        # ensure pc matrix has at least 3 dimensions
        if pc.shape[1] == 1:
            pc = np_append(pc, np_zeros((pc.shape[0], 2)), 1)
            variance = np_append(variance[0], np_ones(2))
        elif pc.shape[1] == 2:
            pc = np_append(pc, np_zeros((pc.shape[0], 1)), 1)
            variance = np_append(variance[0:2], np_ones(1))

        return pc, variance
Example #2
0
    def pca(self, data_matrix):
        """Perform PCA.

        Principal components are given in self.pca,
        and the variance in self.variance.

        Parameters
        ----------
        data_matrix : list of lists
          List of tetranucleotide signatures
        """

        cols = len(data_matrix[0])
        data_matrix = np_reshape(np_array(data_matrix),
                                 (len(data_matrix), cols))

        pca = PCA()
        pc, variance = pca.pca_matrix(data_matrix,
                                      3,
                                      bCenter=True,
                                      bScale=False)

        # ensure pc matrix has at least 3 dimensions
        if pc.shape[1] == 1:
            pc = np_append(pc, np_zeros((pc.shape[0], 2)), 1)
            variance = np_append(variance[0], np_ones(2))
        elif pc.shape[1] == 2:
            pc = np_append(pc, np_zeros((pc.shape[0], 1)), 1)
            variance = np_append(variance[0:2], np_ones(1))

        return pc, variance
    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
Example #4
0
def invert_index_list(indexes, length):
    '''
    Inverts indexes list
    indexes: List[Int] of Ndarray flat numpy array
    length: Int. Length of the base list
    '''
    mask = np_ones(length, dtype='bool')
    mask[indexes] = False
    inverted_indexes = np_arange(length)[mask]
    return inverted_indexes
    def set_data(self):
        data_len = self.col_mat.shape[0]*self.col_mat.shape[1]
        self.pos = np_empty((data_len, 3))
        self.size = np_ones((data_len))*.1
        self.color = np_empty((data_len, 4))

        jj = 0
        for ii in range(len(self.y)):
            for zz in range(len(self.z)):
                self.pos[jj,:] = np_array((self.x[ii]/self.kx,self.y[ii]/self.ky,zz/self.kz))
                self.color[jj,:] = self.col_mat[ii,zz]/255.
                jj = jj + 1
Example #6
0
    def set_data(self):
        data_len = self.col_mat.shape[0] * self.col_mat.shape[1]
        self.pos = np_empty((data_len, 3))
        self.size = np_ones((data_len)) * .1
        self.color = np_empty((data_len, 4))

        jj = 0
        for ii in range(len(self.y)):
            for zz in range(len(self.z)):
                self.pos[jj, :] = np_array(
                    (self.x[ii] / self.kx, self.y[ii] / self.ky, zz / self.kz))
                self.color[jj, :] = self.col_mat[ii, zz] / 255.
                jj = jj + 1
Example #7
0
    def get_syms(self):
        """ Gets symmetries with Pymatgen"""
        from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
        # Gets symmetries with pymatgen:
        symprec = 0.1  # symmetry tolerance for the Spacegroup Analyzer
        #used to generate the symmetry operations
        sga = SpacegroupAnalyzer(self.structure, symprec)
        # ([SymmOp]): List of symmetry operations.
        SymmOp = sga.get_symmetry_operations()
        nsym = len(SymmOp)

        # Symmetries directory:
        # dirname=path.dirname(path.abspath(__file__))
        dirname = path.realpath(curdir)
        newdir = "symmetries"
        SYMdir = path.join(dirname, newdir)
        if not path.exists(SYMdir):
            mkdir(SYMdir)

        # symmetries/sym.d file:
        #self.symd_fname=SYMdir+"/sym.d"
        f = open(self.symd_fname, "w")
        f.write("%i\n" % (nsym))
        for isym in range(0, nsym):
            symrel = np_array(SymmOp[isym].rotation_matrix)  #rotations
            # Transpose all symmetry matrices
            symrel = np_linalg.inv(symrel.transpose())
            symrel = np_array(symrel, np_int)
            #translation=SymmOp[isym].translation_vector
            f.write(" ".join(map(str, symrel[0][:])) + " ")
            f.write(" ".join(map(str, symrel[1][:])) + " ")
            f.write(" ".join(map(str, symrel[2][:])) + "\n")
        f.close()
        # Get lattice parameters
        lattice = self.structure.lattice
        rprim = lattice
        ang2bohr = 1.88972613
        acell = np_ones(3) * ang2bohr
        # Write pvectors file
        # symmetries/pvectors file:
        #        self.pvectors_fname=SYMdir+"/pvectors"
        f = open(self.pvectors_fname, "w")
        f.write(str(lattice) + "\n")
        f.write(" ".join(map(str, acell[:])) + "\n")
        f.close()
Example #8
0
def generate_plot(fig,
                  soln,
                  *,
                  linestyle='-',
                  with_slow=False,
                  with_alfven=False,
                  with_fast=False,
                  with_sonic=False,
                  start=0,
                  stop=90,
                  v_θ_scale="linear",
                  use_E_r=False):
    """
    Generate plot, with enough freedom to be able to format fig
    """
    solution = soln.solution
    angles = soln.angles
    cons = soln.initial_conditions
    sonic_angle = soln.sonic_point
    sonic_values = soln.sonic_point_values
    roots_angles = soln.t_roots
    roots_values = soln.y_roots

    wave_speeds = sqrt(
        mhd_wave_speeds(solution[:, MAGNETIC_INDEXES], solution[:, ODEIndex.ρ],
                        1))

    indexes = (start <= degrees(angles)) & (degrees(angles) <= stop)

    ordering = PlotOrdering.E_r if use_E_r else PlotOrdering.B_φ_prime

    param_names = get_common_arguments(ordering,
                                       v_θ_scale=v_θ_scale,
                                       initial_conditions=cons)

    if with_slow:
        param_names[ODEIndex.v_θ]["extras"].append({
            "label":
            "slow",
            "data":
            wave_speeds[MHD_Wave_Index.slow],
        })
    if with_alfven:
        param_names[ODEIndex.v_θ]["extras"].append({
            "label":
            "alfven",
            "data":
            wave_speeds[MHD_Wave_Index.alfven],
        })
    if with_fast:
        param_names[ODEIndex.v_θ]["extras"].append({
            "label":
            "fast",
            "data":
            wave_speeds[MHD_Wave_Index.fast],
        })
    if with_sonic:
        param_names[ODEIndex.v_θ]["extras"].append({
            "label":
            "sound",
            "data":
            np_ones(len(solution)),
        })

    axes = fig.subplots(
        nrows=2,
        ncols=4,
        sharex=True,
        gridspec_kw=dict(hspace=0),
    )

    # only add label to bottom plots
    for ax in axes[1]:
        ax.set_xlabel("angle from plane (°)")

    axes.shape = len(param_names)
    for i, settings in enumerate(param_names):
        ax = axes[i]
        ax.plot(degrees(angles[indexes]),
                (solution[:, i] - settings.get("offset", 0))[indexes],
                linestyle,
                label=settings["name"])
        for extra in settings.get("extras", []):
            ax.plot(degrees(angles[indexes]),
                    extra["data"][indexes],
                    label=extra.get("label"))
        if sonic_angle is not None:
            ax.plot(
                degrees(sonic_angle),
                sonic_values[i] - settings.get("offset", 0),
                linestyle=None,
                marker='.',
                color='red',
            )
        if roots_angles is not None:
            ax.plot(
                degrees(roots_angles),
                roots_values[:, i] - settings.get("offset", 0),
                linestyle=None,
                marker='.',
                color='black',
            )
        ax.set_ylabel(settings["name"])
        ax.set_yscale(settings.get("scale", "linear"))
        if settings.get("legend"):
            ax.legend(loc=0)
    return fig
def create_path_to_point(image, yCurr, xCurr, yDest, xDest, s):
    '''Move to destination without crossing any white spaces
       The algorithm will create new matrix the size of image that has all
       values = 10,000, except the current position will havea a value
       of 0.  Then, every black pixel touching the current position will
       get a value of 1.  Every black pixel touching those pixels will get
       a value of 2, and so on.  Then, the path will be determined by
       starting at the destination and moving to the lowest adjoining value.

       "touching" means sharing an edge, not diagonal.
    '''

    global returnToMain

    if yDest == -1:  #Not looking for a path to a point but just to a connected area
        findConnected = True
    else:
        findConnected = False
    yLimit, xLimit = image.shape
    defaultDist = xLimit * yLimit
    distances = np_ones(
        (yLimit,
         xLimit)) * defaultDist  #Create an array with all values = 100000
    distances[yCurr][xCurr] = 0
    currList = [(yCurr, xCurr, distances[yCurr][xCurr])]
    nextList = []

    atDestination = False
    while not atDestination and currList:  #currList is not empty
        listen(s)
        if returnToMain:
            return ([])
        #Keep moving out one step until reach destination
        #or can not move any more steps
        for (y, x, value) in currList:
            #Check all 4 surrounding cells to see if black (0, or 100)
            #If they are, values = currValue + 1, and add to next list
            if y > 0:
                if image[y - 1][x] != 255 and distances[y -
                                                        1][x] == defaultDist:
                    distances[y - 1][x] = value + 1
                    nextList.append((y - 1, x, value + 1))
                    if findConnected:
                        if image[y - 1][x] == 0:
                            atDestination = True
                            yDest = y - 1
                            xDest = x
                    else:
                        if (y - 1, x) == (yDest, xDest): atDestination = True
            if y + 1 < yLimit:  #Remember, index goes to one value less than the value of shape property
                if image[y + 1][x] != 255 and distances[y +
                                                        1][x] == defaultDist:
                    distances[y + 1][x] = value + 1
                    nextList.append((y + 1, x, value + 1))
                    if findConnected:
                        if image[y + 1][x] == 0:
                            atDestination = True
                            yDest = y + 1
                            xDest = x
                    else:
                        if (y + 1, x) == (yDest, xDest): atDestination = True
            if x > 0:
                if image[y][x - 1] != 255 and distances[y][x -
                                                           1] == defaultDist:
                    distances[y][x - 1] = value + 1
                    nextList.append((y, x - 1, value + 1))
                    if findConnected:
                        if image[y][x - 1] == 0:
                            atDestination = True
                            yDest = y
                            xDest = x - 1
                    else:
                        if (y, x - 1) == (yDest, xDest): atDestination = True
            if x + 1 < xLimit:
                if image[y][x + 1] != 255 and distances[y][x +
                                                           1] == defaultDist:
                    distances[y][x + 1] = value + 1
                    nextList.append((y, x + 1, value + 1))
                    if findConnected:
                        if image[y][x + 1] == 0:
                            atDestination = True
                            yDest = y
                            xDest = x + 1
                    else:
                        if (y, x + 1) == (yDest, xDest): atDestination = True

        #Now, set currList = nextList and nextList = []
        currList = nextList
        nextList = []

    if not atDestination:
        if findConnected:
            print("FAILED TO CREATE A PATH FROM", yCurr, ",", xCurr,
                  "to a connected, unshaded region")
        else:
            print("FAILED TO CREATE A PATH FROM", yCurr, ",", xCurr, "to",
                  yDest, ",", xDest)
        return ([])

    #Now, create the path and return it.  Start at destination and move
    #backwards to lowest value with preference being horizontal, then vertical
    ##and then diagonal until get to (xCurr, yCurr)
    #temp is current position, next is best next position found so far
    #NOTE: Changed so preference is to keep going in a straight line in order to keep the
    #      paths more on the inside of shaded regions instead of along the edges
    nextX = tempX = xDest
    nextY = tempY = yDest
    nextValue = distances[tempY][tempX]
    pathPoint = (yDest, xDest)
    path = [pathPoint]
    preferHorizontal = True  #True means move horizontally instead of vertically if otherwise indifferent

    while pathPoint != (yCurr,
                        xCurr):  #Have not traced path back to current position
        listen(s)
        if returnToMain:
            return ([])
        found = False
        if preferHorizontal:  #Check horizontal first
            #Check adjacent cells to find lowest value
            if tempX > 0:  #Can look to the left
                if distances[tempY][tempX - 1] < nextValue:
                    nextX = tempX - 1
                    nextY = tempY
                    nextValue = distances[nextY][nextX]
                    found = True
                    preferHorizontal = True
            if tempX + 1 < xLimit and not found:  #Can look to the right
                if distances[tempY][tempX + 1] < nextValue:
                    nextX = tempX + 1
                    nextY = tempY
                    nextValue = distances[nextY][nextX]
                    found = True
                    preferHorizontal = True
            if tempY + 1 < yLimit and not found:
                if distances[tempY + 1][tempX] < nextValue:
                    nextX = tempX
                    nextY = tempY + 1
                    nextValue = distances[nextY][nextX]
                    found = True
                    preferHorizontal = False
            if tempY > 0 and not found:
                if distances[tempY - 1][tempX] < nextValue:
                    nextX = tempX
                    nextY = tempY - 1
                    nextValue = distances[nextY][nextX]
                    found = True
                    preferHorizontal = False
        else:  #Prefer vertical
            #Check adjacent cells to find lowest value
            if tempY + 1 < yLimit:
                if distances[tempY + 1][tempX] < nextValue:
                    nextX = tempX
                    nextY = tempY + 1
                    nextValue = distances[nextY][nextX]
                    found = True
                    preferHorizontal = False
            if tempY > 0 and not found:
                if distances[tempY - 1][tempX] < nextValue:
                    nextX = tempX
                    nextY = tempY - 1
                    nextValue = distances[nextY][nextX]
                    found = True
                    preferHorizontal = False
            if tempX > 0 and not found:  #Can look to the left
                if distances[tempY][tempX - 1] < nextValue:
                    nextX = tempX - 1
                    nextY = tempY
                    nextValue = distances[nextY][nextX]
                    found = True
                    preferHorizontal = True
            if tempX + 1 < xLimit and not found:  #Can look to the right
                if distances[tempY][tempX + 1] < nextValue:
                    nextX = tempX + 1
                    nextY = tempY
                    nextValue = distances[nextY][nextX]
                    found = True
                    preferHorizontal = True

        if found:
            tempX = nextX
            tempY = nextY
            pathPoint = (nextY, nextX)
            path.append(pathPoint)
        else:  #Did not find a next point
            print("Error: unable to trace path back to current destination")
            print("Stuck at point", tempY, tempX)
            return []

    return path
Example #10
0
def generate_plot(fig,
                  soln,
                  *,
                  linestyle='-',
                  with_slow=False,
                  with_alfven=False,
                  with_fast=False,
                  with_sonic=False,
                  start=0,
                  stop=90,
                  use_E_r=False):
    """
    Generate plot, with enough freedom to be able to format fig
    """
    solution = soln.solution
    angles = soln.angles
    inp = soln.solution_input
    cons = soln.initial_conditions

    heights, vert_soln = convert_spherical_to_cylindrical(
        angles,
        solution,
        γ=inp.γ,
        c_s_on_v_k=inp.c_s_on_v_k,
        use_E_r=use_E_r,
    )

    wave_speeds = sqrt(
        mhd_wave_speeds(
            vert_soln[:, VERT_MAGNETIC_INDEXES],
            vert_soln[:, CylindricalODEIndex.ρ],
            1,
            index=CylindricalODEIndex.B_z,
        ))

    indexes = (start <= heights) & (heights <= stop)

    ordering = PlotOrdering.E_r_vert if use_E_r else (
        PlotOrdering.B_φ_prime_vert)

    param_names = get_common_arguments(
        ordering,
        initial_conditions=cons,
        v_φ_offset=sqrt(
            cons.norm_kepler_sq /
            get_vertical_scaling(angles, c_s_on_v_k=inp.c_s_on_v_k)),
    )

    if with_slow:
        param_names[CylindricalODEIndex.v_z]["extras"].append({
            "label":
            "slow",
            "data":
            wave_speeds[MHD_Wave_Index.slow],
        })
    if with_alfven:
        param_names[CylindricalODEIndex.v_z]["extras"].append({
            "label":
            "alfven",
            "data":
            wave_speeds[MHD_Wave_Index.alfven],
        })
    if with_fast:
        param_names[CylindricalODEIndex.v_z]["extras"].append({
            "label":
            "fast",
            "data":
            wave_speeds[MHD_Wave_Index.fast],
        })
    if with_sonic:
        param_names[CylindricalODEIndex.v_z]["extras"].append({
            "label":
            "sound",
            "data":
            np_ones(len(vert_soln)),
        })

    axes = fig.subplots(
        nrows=2,
        ncols=4,
        sharex=True,
        gridspec_kw=dict(hspace=0),
    )

    # only add label to bottom plots
    for ax in axes[1]:
        ax.set_xlabel("height from plane ($c_s/v_k$ scale heights)")

    axes.shape = len(param_names)
    for i, settings in enumerate(param_names):
        ax = axes[i]
        ax.plot(heights[indexes],
                (vert_soln[:, i] - settings.get("offset", 0))[indexes],
                linestyle,
                label=settings["name"])
        for extra in settings.get("extras", []):
            ax.plot(heights[indexes],
                    extra["data"][indexes],
                    label=extra.get("label"))
        ax.set_ylabel(settings["name"])
        ax.set_yscale(settings.get("scale", "linear"))
        if settings.get("legend"):
            ax.legend(loc=0)
    return fig
Example #11
0
def generate_plot(soln,
                  *,
                  linestyle='-',
                  with_slow=False,
                  with_alfven=False,
                  with_fast=False,
                  with_sonic=False,
                  stop=90,
                  figargs=None,
                  v_z_scale="linear"):
    """
    Generate plot, with enough freedom to be able to format fig
    """
    if figargs is None:
        figargs = {}

    solution = soln.solution
    heights = soln.heights
    cons = soln.initial_conditions

    wave_speeds = sqrt(
        mhd_wave_speeds(solution[:, MAGNETIC_INDEXES],
                        solution[:, ODEIndex.ln_ρ], 1))

    indexes = heights <= stop

    param_names = [
        {
            "name": "$B_r/B_0$",
            "data": solution[:, ODEIndex.b_r],
        },
        {
            "name": "$B_φ/B_0$",
            "data": solution[:, ODEIndex.b_φ],
        },
        {
            "name": "$v_r/c_s$",
            "data": solution[:, ODEIndex.w_r],
        },
        {
            "name": "$(v_φ - v_k)/c_s$",
            "data": solution[:, ODEIndex.w_φ],
        },
        {
            "name": "$v_z/c_s$",
            "data": cons.ρ_s / exp(solution[:, ODEIndex.ln_ρ]),
            "legend": True,
            "scale": v_z_scale,
            "extras": []
        },
        {
            "name": "$log(ρ/ρ_0)$",
            "data": solution[:, ODEIndex.ln_ρ],
        },
    ]

    if with_slow:
        param_names[5]["extras"].append({
            "label":
            "slow",
            "data":
            wave_speeds[MHD_Wave_Index.slow],
        })
    if with_alfven:
        param_names[5]["extras"].append({
            "label":
            "alfven",
            "data":
            wave_speeds[MHD_Wave_Index.alfven],
        })
    if with_fast:
        param_names[5]["extras"].append({
            "label":
            "fast",
            "data":
            wave_speeds[MHD_Wave_Index.fast],
        })
    if with_sonic:
        param_names[5]["extras"].append({
            "label": "sound",
            "data": np_ones(len(solution)),
        })

    fig, axes = plt.subplots(nrows=2,
                             ncols=3,
                             constrained_layout=True,
                             sharex=True,
                             gridspec_kw=dict(hspace=0),
                             **figargs)

    # only add label to bottom plots
    for ax in axes[1]:
        ax.set_xlabel("height from plane ($z/h$)")

    axes.shape = len(param_names)
    for i, settings in enumerate(param_names):
        ax = axes[i]
        ax.plot(heights[indexes],
                settings["data"][indexes],
                linestyle,
                label=settings["name"])
        for extra in settings.get("extras", []):
            ax.plot(heights[indexes],
                    extra["data"][indexes],
                    label=extra.get("label"))
        ax.set_ylabel(settings["name"])
        ax.set_yscale(settings.get("scale", "linear"))
        if settings.get("legend"):
            ax.legend(loc=0)
    return fig
dim_x = int(dim * 1.3)
#Uncomment the line below and others containing "out" if you need to save results as a video
#out = cv2_VideoWriter('CATAN.avi',1, 10, (dim_x,dim))
side = 11 * dim / 21
edges = 6
name = 0
#Choose the directory to save picture of samples
D_main = "\Users\Hesam\Project Tests\CATAN\CATAN-5000K"
n_k = ""
#t=[]
#Decide the number of samples you want to create here
numbers_to_generate = 500000
while name < numbers_to_generate:
    #t1 = time()
    name += 1
    ground = np_ones((dim, dim_x, 3)) * 255
    ground = ground.astype('uint8')
    c = [int(dim_x / 2.0 + 0.5 + side / 11.0), int(dim / 2.0 + 0.5)]
    ground, small_side = polygon(ground,
                                 c,
                                 side,
                                 edges,
                                 0,
                                 int(side * 0.67 + 0.5),
                                 color=[250, 80, 30])
    ground, ss = polygon(ground,
                         c,
                         small_side,
                         edges,
                         0,
                         0,