示例#1
0
def circle_eyes(pos, img8_r, img8_l, roir, roil):
    '''
    Draws circles around eyes and Return coordinates.

    Keyword arguments:
    pos -- list of x,y coordinates of face ROI
    img8_r -- 8-bit right eye (from isolation_methods.color_filter_main())
    img8_l -- 8-bit left eye (from isolation_methods.color_filter_main())
    frame_o -- original frame
    roir -- coordinates of right eye ROI [y, y + h, x, x + w]
    roil -- coordinates of left eye ROI [y, y + h, x, x + w]

    Return:
    frame with circled eyes (numpy ndarray)
    right eye coordinates (tuple)
    left eye coordinates (tuple)
    '''
    right_c = smallestenclosingcircle.make_circle(isolation_methods.get_points(img8_r))
    left_c = smallestenclosingcircle.make_circle(isolation_methods.get_points(img8_l))
    translated_right = None
    translated_left = None
    avg_radius = 0
    if right_c != None:
        translated_right = (int(pos[0] + round(right_c[1] + roir[2])),
                            int(roir[0] + pos[1] + round(right_c[0])))
        avg_radius = right_c[2]
    if left_c != None:
        translated_left = (int(pos[0] + round(left_c[1] + roil[2])),
                           int(roil[0] + pos[1] + round(left_c[0])))
        avg_radius = left_c[2]
    if (left_c != None) and (right_c != None):
        avg_radius = (right_c[2] + left_c[2]) / 2
    return translated_right, translated_left, avg_radius
示例#2
0
    def etatsVoisins(self):

        # les etats voisin seront a une difference de l'etat orginale
        #

        #on enleve un point de chaque antenne
        for position in self.ptsRestants:
            nvAntennePos = make_circle([position])
            nvAntenne = Antenne(nvAntennePos, [position])
            
            nvPtsRestantes = copy.deepcopy(self.ptsRestants)
            
            nvPtsRestantes.remove(position)
            
            nvListeAntennes = copy.deepcopy(self.antennes)
            nvListeAntennes.append(nvAntenne)
            nvEtat = Etat(nvListeAntennes, nvPtsRestantes)
            self.neighbours.append(nvEtat)

        indexAnt = 0 # necessaire pour garder la
        for antenne in self.antennes:
            for position in self.ptsRestants:
                nvListePos = copy.deepcopy(antenne.positions)
                nvListePos.append(position)
                nvAntennePos = make_circle(nvListePos)
                nvAntenne = Antenne(nvAntennePos, nvListePos)
                nvPtsRestantes = copy.deepcopy(self.ptsRestants)
                nvPtsRestantes.remove(position)
                nvListeAntennes = copy.deepcopy(self.antennes)

                del nvListeAntennes[indexAnt]
                nvListeAntennes.append(nvAntenne)
                nvEtat = Etat(nvListeAntennes, nvPtsRestantes)
                self.neighbours.append(nvEtat)
            indexAnt += 1
	def test_scaling(self):
		TRIALS = 100
		CHECKS = 10
		for _ in range(TRIALS):
			points = _make_random_points(random.randint(1, 300))
			reference = smallestenclosingcircle.make_circle(points)
			
			for _ in range(CHECKS):
				scale = random.gauss(0, 1)
				newpoints = [(x * scale, y * scale) for (x, y) in points]
				
				scaled = smallestenclosingcircle.make_circle(newpoints)
				self.assertAlmostEqual(scaled[0], reference[0] * scale     , delta=_EPSILON)
				self.assertAlmostEqual(scaled[1], reference[1] * scale     , delta=_EPSILON)
				self.assertAlmostEqual(scaled[2], reference[2] * abs(scale), delta=_EPSILON)
	def test_translation(self):
		TRIALS = 100
		CHECKS = 10
		for _ in range(TRIALS):
			points = _make_random_points(random.randint(1, 300))
			reference = smallestenclosingcircle.make_circle(points)
			
			for _ in range(CHECKS):
				dx = random.gauss(0, 1)
				dy = random.gauss(0, 1)
				newpoints = [(x + dx, y + dy) for (x, y) in points]
				
				translated = smallestenclosingcircle.make_circle(newpoints)
				self.assertAlmostEqual(translated[0], reference[0] + dx, delta=_EPSILON)
				self.assertAlmostEqual(translated[1], reference[1] + dy, delta=_EPSILON)
				self.assertAlmostEqual(translated[2], reference[2]     , delta=_EPSILON)
示例#5
0
    def on_event(self, event):
        if event.type == QUIT:
            self.running = False
        elif event.type == MOUSEBUTTONUP and event.button in (1, 2, 3):
            print("an event: ", self.points)

            if self.btn_get_box.pressed(event.pos):
                self.box = bounding_box(self.points.copy())
                print("get box:", self.box)
                polyArea = int(self.polygon.area)
                min_x, min_y = self.box[0][0], self.box[0][1]
                max_x, max_y = self.box[2][0], self.box[2][1]
                boxArea = int((max_x - min_x) * (max_y - min_y))
                self.msg = "Polygon area: " + str(
                    polyArea) + "   Bounding Box area: " + str(
                        boxArea) + "    Ratio: " + str(
                            round(polyArea / boxArea, 5))

            elif self.btn_get_circle.pressed(event.pos):
                self.circle = make_circle(self.points.copy())
                print("get circle:", self.circle)
                polyArea = int(self.polygon.area)
                r = self.circle[2]
                circleArea = int(pi * r**2)
                self.msg = "Polygon area: " + str(
                    polyArea) + "    Min circle area: " + str(
                        circleArea) + "    Ratio: " + str(
                            round(polyArea / circleArea, 5))

            elif self.btn_get_convex.pressed(event.pos):
                # send in a copy bc it changes the ordering to sorted
                self.ch_points = convexHull(self.points.copy())
                polyArea = int(self.polygon.area)
                chArea = int(Polygon(self.ch_points).area)
                self.msg = "Polygon area: " + str(
                    polyArea) + "    CH area: " + str(
                        chArea) + "    Ratio: " + str(
                            round(polyArea / chArea, 5))

                print("get hull")


#                 print("convex hull event: ", self.points)
            elif self.btn_reset.pressed(event.pos):
                self.points, self.ch_points, self.circle, self.polygon, self.box = [], [], [], [], []
                self.msg = "Click points in cw or ccw order to add"
                print("reset")
            else:
                # don't add if the point isn't already in there
                # (note: currently linear scan which is ok bc small # of pts. Can be improved later)
                if event.pos not in self.points:
                    self.points.append(event.pos)
                # the polygon must be updated - the only time it is is when you add a point
                if len(self.points) > 2:
                    self.polygon = Polygon(self.points)
                    self.msg = "Added (x,y): " + str(
                        event.pos) + "     Polygon area: " + str(
                            int(self.polygon.area))
                else:
                    self.msg = "Added (x,y): " + str(event.pos)
示例#6
0
 def test_matching_naive_algorithm(self):
     for _ in range(1000):
         points = _make_random_points(random.randint(1, 30))
         reference = _smallest_enclosing_circle_naive(points)
         actual = smallestenclosingcircle.make_circle(points)
         self.assertAlmostEqual(actual[0], reference[0], delta=_EPSILON)
         self.assertAlmostEqual(actual[1], reference[1], delta=_EPSILON)
         self.assertAlmostEqual(actual[2], reference[2], delta=_EPSILON)
示例#7
0
def get_circle_impurity_score(markers, imp_boxes, areas, indices):
    scores = np.full(imp_boxes.shape[0], np.infty)
    for impurity in indices:
        impurity_shape = np.argwhere(markers == impurity + 2)
        circle = make_circle(impurity_shape)
        circle_area = np.pi * circle[2]**2
        scores[impurity] = (circle_area - areas[impurity]) / circle_area
    return scores
示例#8
0
def circumCircle(I):
    """
    this version uses a function provided by Project Nayuki
    under GNU Lesser General Public License
    """
    points = np.argwhere(I > 100)
    c = smallestenclosingcircle.make_circle(points)
    return c
示例#9
0
def solVoisine(etat):
    #Strategy : We randomly take out a point from an antenna and give it randomly to another antenna
    #           if the deprived antenna has 0 points left, then we take it out of the state list
    #           we also need to make sure that the new solution is valid, such as every position is covered

    if len(etat.antennes) <= 1:
        return etat

    #The first antenna is gonna give a position to the second

    etatVoisin = copy.deepcopy(etat)

    antennes = random.sample(etatVoisin.antennes, 2)
    antToDeprive = antennes[0]
    antToGive = antennes[1]
    etatVoisin.antennes.remove(antToDeprive)
    etatVoisin.antennes.remove(antToGive)

    #positionToGive = random.sample(antToDeprive.positions, 1)
    indexPos = randint(0,len(antToDeprive.positions)-1)
    positionToGive = antToDeprive.positions[indexPos]
    antToDeprive.positions.remove(positionToGive)
    antToGive.positions.append(positionToGive)

    etatRetour = None

    nvAntennePos = make_circle(antToGive.positions)
    nvAntenne = Antenne(nvAntennePos, antToGive.positions)

    antenaList = etatVoisin.antennes + [nvAntenne]
    if(len(antToDeprive.positions) == 0):
        #only one position, so we deleted that antenna and we need to reconstruct the list with the new list
        #antToDeprive.


        etatRetour = Etat(antenaList,[])

    else:
        #we need to update the depraved antenna
        nvDepAntennaPos = make_circle(antToDeprive.positions)
        nvDepAntenna = Antenne(nvDepAntennaPos, antToDeprive.positions)
        etatRetour = Etat(antenaList + [nvDepAntenna], [])


    return etatRetour
	def test_matching_naive_algorithm(self):
		TRIALS = 1000
		for _ in range(TRIALS):
			points = _make_random_points(random.randint(1, 30))
			reference = _smallest_enclosing_circle_naive(points)
			actual = smallestenclosingcircle.make_circle(points)
			self.assertAlmostEqual(actual[0], reference[0], delta=_EPSILON)
			self.assertAlmostEqual(actual[1], reference[1], delta=_EPSILON)
			self.assertAlmostEqual(actual[2], reference[2], delta=_EPSILON)
示例#11
0
def solInitiale(Positions):

    antennes = [];

    position = Positions.pop(0)
    antennes.append(Antenne(make_circle([tuple(position)]), [position]))

    etat = Etat(antennes, Positions)

    return etat
示例#12
0
def solInitiale(Positions):

    antennes = [];
    for position in Positions:

        antennes.append(Antenne(make_circle([tuple(position)]), [position]))

    etat = Etat(antennes, [])

    return etat
示例#13
0
def get_polygon_center(pc):
    """
    Estimate object center 
    """
    sample_size = 100
    if len(pc) > sample_size:
        random.sample(np.arange(len(pc)).tolist(), sample_size)

    pc = np.array(pc)
    center = np.sum(pc, axis=0) / len(pc)
    circle = smallestenclosingcircle.make_circle(pc[:, 0:2])

    return np.array([circle[0], circle[1], center[2]])
示例#14
0
def find_neighbour(solution, positions):
    if len(solution) <= 1:
        return solution

    antenna = solution[int(random.random() * len(solution))]
    closest_antenna = min([ant for ant in solution if ant != antenna], key=lambda a : dist_squared(a, antenna))
    ant1_coverage = [p for p in positions if verify_cover(p, antenna)]
    ant2_coverage = [p for p in positions if verify_cover(p, closest_antenna)]

    le_point = min(ant2_coverage, key=lambda pos : dist_squared(pos, antenna))
    ant2_coverage = [p for p in ant2_coverage if p != le_point]
    ant1_coverage.append(le_point)

    new_ant1 = make_circle(ant1_coverage);
    new_ant2 = make_circle(ant2_coverage);

    solution = [ant for ant in solution if (ant != antenna and ant != closest_antenna)]
    if new_ant1:
        solution.append(new_ant1)
    if new_ant2:
        solution.append(new_ant2)

    return solution
示例#15
0
def shoot_for_optim(n_points, cannon, balloon, wind_tbl, ran):

    x_values = []; y_values = [] #착탄점들의 중심점을 구하기 위해 다 저장

    for i in range(n_points):
        np.random.seed(i)
        idland, xy_now, peak_z, theta, direc_now = peak_xy(cannon, balloon, ran)

        # shoot
        #현재 고도보다 바로 위에 있는 테이블 값의 풍향을 사용할 것임
        wind_h = [idx[1] for idx in wind_tbl.index]; wind_h.insert(0,0)
        idx_now = (wind_h >= peak_z).tolist().index(True)
        h_now = peak_z

        #포탄 경로 그리기 준비      
        while idx_now > 0:
            h_down = h_now - wind_h[idx_now - 1] #수직 하강 거리
            one_step = h_down * np.tan(theta) #전진 거리. 풍향의 영향이 없을 때의 방향을 기준으로 거리를 계산함

            wind_vec = np.array(wind_tbl.vec[idx_now-1])
            wind_vel = wind_tbl.wind_vel[idx_now-1]
            interval_now = wind_tbl.index[idx_now - 1]

            
            cossim = cos_sim(direc_now, wind_vec)
            vel_power = (100 + cossim * 100 * wind_vel) / 100
            one_step = one_step * vel_power #전진거리 수정

            if abs(cossim) != 1:
                #풍향과 풍속을 고려하여 방향 수정
                w = np.random.beta(2,20) * vel_power 
                direc_now = (1-w) * direc_now + w * wind_vec.astype('float64')
                direc_now =  (direc_now ) / la.norm(direc_now) #unit vector로 만들기


                
            #계산 종료.

            #포탄의 전진.
            xy_now = xy_now + direc_now * one_step   
            idx_now -=1
            h_now = wind_h[idx_now]

        
        x_values.append(xy_now[0])
        y_values.append(xy_now[1])
      
    cir = sc.make_circle(zip(x_values, y_values))
    return np.array([cir[0], cir[1]])
示例#16
0
def fi_factor(polygon):
    """
    Calculates fi factor (the ratio of the area of the polygon to the area of the circumscribed circle)
    Parameters
    ----------
    polygon : shapely.geometry.Polygon

    Returns
    -------
    fi : float [0,1]
    """
    circle_points = make_circle(np.array(polygon.boundary.xy).T)
    center = shapely.geometry.Point((circle_points[0], circle_points[1]))
    circle = center.buffer(circle_points[2])
    fi = polygon.area / circle.area
    return fi
示例#17
0
def greedy_solution(remaining_positions, k, c):
    positions = list(remaining_positions)
    if not remaining_positions:
        return

    antennas = [(remaining_positions[0][0], remaining_positions[0][1], 1)]
    remaining_positions = remaining_positions[1:]

    for pos in remaining_positions:
        closest_antenna = min(antennas, key=lambda x : dist_squared(pos, (x[0],x[1])))
        covered_points = [p for p in positions if verify_cover(p, closest_antenna)]
        covered_points.append(pos)
        new_antenna = make_circle(covered_points)

        if((k+c*new_antenna[2]**2) > (k+c*closest_antenna[2]**2 + k)):
            new_antenna = (pos[0], pos[1], 1)
        else:
            antennas = [ant for ant in antennas if ant != closest_antenna]

        antennas.append(new_antenna)
        remaining_positions = [p for p in remaining_positions if p != pos]
    return antennas
def is_panning_scene(locs, dirs, scene, MIN_ANGLE, MAX_RADIUS):
    if (scene.end - scene.start) < 1:
        return False

    # if it is panning scene
    if not is_panning_angle(dirs, scene, MIN_ANGLE):
        return False

    points = [(locs[i][0], locs[i][1]) for i in range(scene.start, scene.end + 1, 1)]
    # if radius of the smallest bounding circle of the camera locations are small
    x = make_circle(points)

    if x is not None:
        cx, cy, r = x
        # print cx, cy, r
    else:
        print "xxx"
        cx, cy, r = 0, 0, 0

    # print r/ONE_KM
    if r/ONE_KM <= MAX_RADIUS:
        return True
    return False
示例#19
0
 def childs(self):
     children = []
     if not self.antennas:
         for pos in positions:
             child = State(self.antennas, self.remaining_positions)
             child.add_antenna((pos[0], pos[1], 1))
             child.remaining_positions = tuple([p for p in child.remaining_positions if p != pos])
             children.append(child)
     else:
         child = State(self.antennas, self.remaining_positions)
         pos = min(self.remaining_positions, key=lambda p : dist_squared(p, self.antennas[-1]))
         closest_antenna = min(child.antennas, key=lambda x : dist_squared(pos, (x[0],x[1])))
         #les points couvert par l'antenne
         covered_points = [p for p in positions if child.verify_cover(p, closest_antenna)]
         covered_points.append(pos)
         new_antenna = make_circle(covered_points)
         if((K+C*new_antenna[2]**2) > (K+C*closest_antenna[2]**2 + K)):
            new_antenna = (pos[0], pos[1], 1)
         else:
             child.antennas = tuple([ant for ant in child.antennas if ant != closest_antenna])
         child.add_antenna(new_antenna)
         #child.remaining_positions = tuple([p for p in child.remaining_positions if p != pos])
         children.append(child)
     return children
示例#20
0
def cluster_mc(sp=1.00, Nmax=1000, rs=0):
    # main function that runs the monte carlo code used for creating the clusters
    # sp = sticking probability, = 1 is the classical DLA case, 0 < sp =< 1 are the bounds
    # Nmax = maximum number of particles in the cluster, the functions runs until Nmax is hit
    # rs = random seed (just a number) that set the pseudo-random number generator
    # the random seed is what makes this a Monte Carlo simulation
    
    # some initial checks
    if not 0 < sp <= 1:
        print('ERROR: bounds for sticking probability (sp) are incorrect (must have 0 < sp <= 1). Stopping the simulation.')
        return
    if type(Nmax) is not int:
        print('ERROR: maximum particle number (Nmax) must be type int. Stopping the simulation.')
        return
    rs = int(rs)  # for file saving it is more convenient to have an integer
    random.seed(rs)  # set the random seed
    
    # file opening
    strname = 'cluster_mc_rs%d_n%d_p%0.2f'%(rs, Nmax, sp)
    fh = open(strname + '.csv','w')
    fh.write('number,x,y\n')
    fh.write('1,0,0\n')

    walkdir = [[1,0],[0,1],[-1,0],[0,-1]]       # particles only walk in 4 directions
    seed = [0,0]                                # single frozen seed
    cluster = [seed]                            # just a list of points
    clustsize = len(cluster)

    stickps = []                                # 3D array of sticking points
    cluster_parts = []                          # 3D array of particles in the cluster
    bin_size = 3                                # hard coded value to shape the 3D arrays
    stickdir = [[1,0],[0,1],[-1,0],[0,-1]]      # particle can attach only at 4 sites relative to other particles
    
    for i in range(int(Nmax/bin_size) +10):     # approximation to scale subintervals based on Nmax
        stickps.append([[],[],[],[]])           # 4 lists for the 4 quadrants of the grid
        cluster_parts.append([[],[],[],[]])     # 4 lists for the 4 quadrants of the grid

    # initialize the sublists
    add_to_stickps(stickps, stickdir, bin_size)
    cluster_parts[0][0].append(cluster[0])
    cluster_parts[0][1].append(cluster[0])
    cluster_parts[0][2].append(cluster[0])        
    cluster_parts[0][3].append(cluster[0])

    # circle is a list of three values --> [x_center, y_center, radius]
    circ = smallestenclosingcircle.make_circle(cluster)
    eff_r_check, eff_rl = update_eff_radii(circ[2], 0.5)

    # set some controlling flag
    active_particle = False  # must initialize a random molecule
    rand_walk = False
    
    # now  we can enter the main loop
    while clustsize < Nmax:
        if not active_particle:
            # generate a random particle along the edge
            theta = random.uniform(0,2*math.pi)
            start_x = int(math.ceil(circ[0] + eff_r_check*math.cos(theta)))
            start_y = int(math.ceil(circ[1] + eff_r_check*math.sin(theta)))
            particle = [start_x, start_y]

            # skip random walk step and set active_particle flag
            active_particle = True
            rand_walk = False
            
        # random walk of active particle
        if rand_walk:
            # time to move to a new position, by randomly picking a walk direction
            delta = random.randint(0,3)
            temp_pos = [particle[0] + walkdir[delta][0], particle[1] + walkdir[delta][1]]
            intersectpossibility = build_intersection(temp_pos, cluster_parts, bin_size)

            while temp_pos in intersectpossibility: # keep particle out of cluster (needed when sp < 1)
                delta = random.randint(0,3)
                temp_pos = [particle[0] + walkdir[delta][0], particle[1] + walkdir[delta][1]]
                intersectpossibility = build_intersection(temp_pos, cluster_parts, bin_size)

            if distance(temp_pos, [circ[0], circ[1]]) >= eff_rl:
                # reset particle if too far away fromthe circle
                temp_pos = place_on_cirlce(temp_pos, circ[0], circ[1], eff_r_check)
            
            # if eveything checks out, we can update the position of the particle
            particle = temp_pos

        # check to see if the particle should be added to the cluster
        if distance(particle,[circ[0],circ[1]]) <= eff_r_check: # no need to try if the particle is outside the outside circle

            stickps_intersection = build_intersection(particle, stickps, bin_size)
            
            # if the particle is in a position to attach to the cluster
            if particle in stickps_intersection:
                prob = random.random()  # number between 0 and 1
                if prob < sp:
                    # the particle should be added to the cluster
                    add_to_stickps(stickps, stickdir, bin_size, particle)
                    add_to_cluster(stickps, particle, cluster_parts, cluster, bin_size)
                    circ = smallestenclosingcircle.make_circle(cluster)
                    eff_r_check, eff_rl = update_eff_radii(circ[2], 0.5)
                    # set the flag to make a new a particle
                    active_particle = False
            else:
                rand_walk = True
        else:
            rand_walk = True
            
        # if you have a new particle, add it to the data
        if len(cluster) > clustsize:
            clustsize = len(cluster)
            
            fh.write('%d,%d,%d\n'%(len(cluster),particle[0],particle[1]))
            
            if clustsize%500 == 0:
                # print an update every n particles (as a sanity check)
                print('particle', len(cluster), 'at position:', particle)
            
            if clustsize == Nmax:
                # close the data file and make the picture of the cluster
                fh.close()
                
                fig, ax = plt.subplots(figsize=(10,10))
                for particle in cluster:
                    plt.scatter(particle[0],particle[1], color='k',s=10)
                ax.set_xlim(circ[0]-eff_r_check,circ[0]+eff_r_check)
                ax.set_ylim(circ[1]-eff_r_check,circ[1]+eff_r_check)
                ax.axis('off')
                fig.savefig(fname=strname + '.png', dpi=600, bbox_inches='tight')
示例#21
0
    def get(self, geocast_id):
        """
        Override the standard GET
        """
        global all_data, eps
        parts = geocast_id.split('/')
        dataset = parts[0]
        print parts
        t = map(float, parts[1].split(','))
        print dataset, t
        # if task not in region
        if not is_rect_cover(all_data[dataset][1], t):
            self.write(json.dumps({"error": "invalid task"}))
            return

        q, q_log = geocast(all_data[dataset][0], t, float(eps))
        no_workers, workers, Cells, no_hops, coverage, no_hops2 = post_geocast(t, q, q_log)
        performed, worker, dist = performed_tasks(workers, Params.MTD, t, True)
        x_min, y_min, x_max, y_max = [], [], [], []
        worker_counts, utilities, distances, compactnesses, areas = [], [], [], [], []
        if worker is not None:
            worker = worker.tolist()

        corner_points = Set([])
        for cell in Cells:
            x_min.append(cell[0].n_box[0][0])
            y_min.append(cell[0].n_box[0][1])
            x_max.append(cell[0].n_box[1][0])
            y_max.append(cell[0].n_box[1][1])
            worker_counts.append(cell[0].n_count)
            utilities.append([cell[2][1], cell[2][2]])
            compactnesses.append(cell[2][3])
            distances.append(float("%.3f" % distance_to_rect(t[0], t[1], cell[0].n_box)))
            distances.append(float("%.3f" % distance_to_rect(t[0], t[1], cell[0].n_box)))
            areas.append(float("%.3f" % rect_area(cell[0].n_box)))
            corner_points = corner_points | rect_vertex_set(cell[0].n_box)

        points = list(corner_points)
        x = make_circle(points)
        if x is not None:
            cx, cy, r = x
            print cx, cy, r
        else:
            cx, cy, r = 0, 0, 0
        no_hops2 = math.ceil(no_hops2)
        if performed:
            self.write(
                json.dumps({"is_performed": performed,
                            "notified_workers": {"no_workers": no_workers,
                                                 "x_coords": workers[0].tolist(),
                                                 "y_coords": workers[1].tolist()},
                            "geocast_query": {"no_cell": len(Cells),
                                              "compactness": q_log[-1][3],
                                              "x_min_coords": x_min,
                                              "y_min_coords": y_min,
                                              "x_max_coords": x_max,
                                              "y_max_coords": y_max,
                                              "worker_counts": worker_counts,
                                              "utilities": utilities,
                                              "compactnesses": compactnesses,
                                              "distances": distances,
                                              "areas": areas},
                            "spatial_task": {"location": t},
                            "volunteer_worker": {"location": worker,
                                                 "distance": dist},
                            "hop_count": no_hops2,
                            "bounding_circle": [cx, cy, r]},
                           sort_keys=False)
            )
        else:
            self.write(
                json.dumps({"is_performed": False,
                            "notified_workers": {"no_workers": no_workers,
                                                 "x_coords": workers[0].tolist(),
                                                 "y_coords": workers[1].tolist()},
                            "geocast_query": {"no_cell": len(Cells),
                                              "x_min_coords": x_min,
                                              "y_min_coords": y_min,
                                              "x_max_coords": x_max,
                                              "y_max_coords": y_max,
                                              "worker_counts": worker_counts,
                                              "utilities": utilities,
                                              "compactnesses": compactnesses,
                                              "distances": distances,
                                              "areas": areas},
                            "spatial_task": {"location": t},
                            "volunteer_worker": {"location": worker,
                                                 "distance": dist},
                            "hop_count": no_hops2,
                            "bounding_circle": [cx, cy, r]},
                           sort_keys=False)
            )


        # logging
        if Params.GEOCAST_LOG:
            info = GeocastInfo(int(performed), t, Cells)
            log_str = str(info.logging()) + "\n"
            geocast_log("geocast_server", log_str, eps)
示例#22
0
def shoot_for_optim(n_points, cannon, enemy, degree, direc, wind_tbl):

    x_values = []
    y_values = []  #착탄점들의 중심점을 구하기 위해 다 저장

    h, d_final = theta2hd(degree)
    #print('d_final:', d_final)
    idland_og = cannon[:2] + d_final * direc
    #print('idland:', idland_og)
    d = h / np.tan(degree * (np.pi / 180))

    peak_z_og = cannon[2] + h
    xy_now_og = cannon[:2] + d * direc
    for i in range(n_points):
        idland = idland_og
        xy_now = xy_now_og
        peak_z = peak_z_og
        direc_now = direc
        np.random.seed(i)

        #initialize

        # shoot
        #현재 고도보다 바로 위에 있는 테이블 값의 풍향을 사용할 것임
        wind_h = [idx[1] for idx in wind_tbl.index]
        wind_h.insert(0, 0)
        idx_now = (wind_h >= peak_z).tolist().index(True)
        h_now = peak_z

        #포탄 경로 그리기 준비
        #total_move = 0
        while idx_now > 0:
            h_down = h_now - wind_h[idx_now - 1]  #수직 하강 거리

            one_step = h_down * np.tan(
                degree * (np.pi / 180))  #전진 거리. 풍향의 영향이 없을 때의 방향을 기준으로 거리를 계산함

            wind_vec = np.array(wind_tbl.vec[idx_now - 1])
            wind_vel = wind_tbl.wind_vel[idx_now - 1]
            interval_now = wind_tbl.index[idx_now - 1]

            cossim = cos_sim(direc_now, wind_vec)
            rbeta = np.random.beta(2, 40)
            print('rbeta:', rbeta)
            vel_power = (100 + cossim * 1.5 * wind_vel) / 100
            one_step = one_step * vel_power * (1 + rbeta)  #전진거리 수정
            #print('풍속에 의해 수정된 전진 거리: {}'.format(one_step))
            if abs(cossim) != 1:
                #풍향과 풍속을 고려하여 방향 수정
                w = rbeta * vel_power
                direc_now = (1 -
                             w) * direc_now + w * wind_vec.astype('float64')
                direc_now = (direc_now) / la.norm(direc_now)  #unit vector로 만들기

            #계산 종료.

            #포탄의 전진.
            xy_now = xy_now + direc_now * one_step

            idx_now -= 1
            h_now = wind_h[idx_now]

        x_values.append(xy_now[0])
        y_values.append(xy_now[1])

    #print('실제로 총 {}만큼 전진'.format(total_move))

    cir = sc.make_circle(zip(x_values, y_values))

    return np.array([cir[0], cir[1]])
示例#23
0
def shoot(n_iter, cannon, balloon, wind_tbl, ax, col_id):
    mycol = col_list[col_id]
    ax.scatter(cannon[0], cannon[1], color=mycol)
    ax.text(cannon[0], cannon[1], 'fire')
    ax.scatter(balloon[0], balloon[1], color=mycol, s=300)
    ax.text(balloon[0], balloon[1], 'balloon')

    x_values = []
    y_values = []  #착탄점들의 중심점을 구하기 위해 다 저장
    #x_shootline = []; y_shootline = [] #착탄 경로 저장
    for i in range(n_iter):
        np.random.seed(i)
        #print('iteration {}'.format(i))
        idland, xy_now, peak_z, degree, direc_now = peak_xy(cannon, balloon)
        #print('peak_z:', peak_z)
        if i == 0:
            #ax.scatter(xy_now[0], xy_now[1], color = mycol); ax.text(xy_now[0], xy_now[1], 'peak') #최고점
            ax.scatter(idland[0], idland[1], s=40, alpha=0.7, color=mycol)
            ax.text(idland[0], idland[1], 'theoretical')
            ax.plot([cannon[0], balloon[0]], [cannon[1], balloon[1]],
                    color=mycol)  #cannon to balloon
            ax.plot([balloon[0], xy_now[0]], [balloon[1], xy_now[1]],
                    color=mycol)  #baloon to peak
            ax.plot([xy_now[0], idland[0]], [xy_now[1], idland[1]],
                    linestyle='--',
                    color=mycol)  #peak to ideal landing

        # shoot
        #현재 고도보다 바로 위에 있는 테이블 값의 풍향을 사용할 것임
        wind_h = [idx[1] for idx in wind_tbl.index]
        wind_h.insert(0, 0)
        idx_now = (wind_h >= peak_z).tolist().index(True)
        h_now = peak_z

        #포탄 경로 그리기 준비
        #total_move = 0
        while idx_now > 0:
            h_down = h_now - wind_h[idx_now - 1]  #수직 하강 거리
            #print('고도 {} -> {}. {}만큼 하강하는 동안'.format(h_now, wind_h[idx_now - 1], h_down))

            one_step = h_down * np.tan(
                degree * (np.pi / 180))  #전진 거리. 풍향의 영향이 없을 때의 방향을 기준으로 거리를 계산함
            #total_move += one_step
            #print('x,y좌표 기준으로 {}만큼 전진'.format(one_step))

            wind_vec = np.array(wind_tbl.vec[idx_now - 1])
            wind_vel = wind_tbl.wind_vel[idx_now - 1]
            interval_now = wind_tbl.index[idx_now - 1]
            #print('고도 {} in 구간 {}에서의 바람 방향: {}'.format(wind_h[idx_now], interval_now, wind_vec))
            #print('원래 전진 방향: {}'.format(direc_now))

            cossim = cos_sim(direc_now, wind_vec)
            rbeta = np.random.beta(2, 15)
            #print('rbeta:', rbeta)
            vel_power = (100 + cossim * wind_vel) / 170
            one_step = one_step * vel_power * (1 + rbeta)  #전진거리 수정
            #print('풍속에 의해 수정된 전진 거리: {}'.format(one_step))
            if abs(cossim) != 1:
                #풍향과 풍속을 고려하여 방향 수정
                w = rbeta * vel_power
                direc_now = (1 -
                             w) * direc_now + w * wind_vec.astype('float64')
                direc_now = (direc_now) / la.norm(direc_now)  #unit vector로 만들기
                #print('바람에 의해 수정된 방향: {}'.format(direc_now))
            #else:
            #print('바람의 방향이 포탄의 방향과 정확히 일치(혹은 정확히 반대)하므로, 포탄 진행방향 변화 없음. 속도만 수정')

            #계산 종료.

            #포탄의 전진.
            xy_now = xy_now + direc_now * one_step
            #x_shootline.append(xy_now[0]); y_shootline.append(xy_now[1])  #peak에서 착탄까지 경로 저장
            #print('{},{}에 도착\n'.format(xy_now, wind_h[idx_now - 1]))

            idx_now -= 1
            h_now = wind_h[idx_now]
            #print(xy_now)
        #print(x_shootline)

        x_values.append(xy_now[0])
        y_values.append(xy_now[1])

        ax.scatter(xy_now[0], xy_now[1], s=5, color=mycol)  #착탄지점 그래프에 그리기

    #print('실제로 총 {}만큼 전진'.format(total_move))

    cir = sc.make_circle(zip(x_values, y_values))
    ax.text(cir[0], cir[1], 'center')  #최고점
    ax.add_patch(
        patches.Circle(
            (cir[0], cir[1]),  # (x, y)
            cir[2],  # radius
            alpha=0.4,
            facecolor=mycol,
            edgecolor=mycol,
            linewidth=2,
            linestyle='solid'))

    return idland, np.array([cir[0], cir[1]])
示例#24
0

	col_sys = [ mag_sys[c]-mag_sys[c+1] for c in range(5) ]         
	ug_rest_sys = grouped['ug_rest'][ ug_rest==np.min(ug_rest) ].iloc[0]
	# we put the bluest one as a representative in the catalog
	zs_sys = grouped['zs'][ ug_rest==np.min(ug_rest) ].iloc[0]


	# using i mag as a ref. to find the centroid :: grouped['ra'][0] is ra_m1
	# the separation angle is so small that ra*cos(dec) won't make any difference
	ra_sys  = np.sum(ra *10**(-0.4*mag[:,3])) / np.sum(10**(-0.4*mag[:,3]))
	dec_sys = np.sum(dec*10**(-0.4*mag[:,3])) / np.sum(10**(-0.4*mag[:,3]))

	# this one is fast
	points = [(x,y) for (x,y) in zip(ra,dec)] # pairing up two lists
	gsize_sys = smec.make_circle(points)[2]*3600 # the radius of the smallest enclosing circle (in arcsec)

	A  = 10**(-0.4*mag[:,3]) # actual flux needs a factor because of the zero point, here we just use them as weights
	mu = [ra,dec] #np.array(points).T
	c  = [ra_sys,dec_sys]
	e1_sys, e2_sys = get_shear(A,mu,c,e1,e2,kappa,gsize,reduced=False) # actually no kappa needed fo e!
	gamma1_sys, gamma2_sys = gamma1.mean(), gamma2.mean() #get_shear(A,mu,c,gamma1,gamma2,kappa,gsize,reduced=False)
	g1_sys, g2_sys = g1.mean(), g2.mean() #get_shear(A,mu,c,gamma1,gamma2,kappa,gsize) # reduced by default
	kappa_sys = kappa.mean() # should be checked if it is ok?

	nGoldmem = sum(i<limiting_mag_i_lsst)

#----

	magerr_sys[0] = vec_getMagError(mag_sys[0],'LSST_u')
	magerr_sys[1] = vec_getMagError(mag_sys[1],'LSST_g')
示例#25
0
coeff = list(tck[1])
deg = tck[2]
assert deg == 3
pts_int = [[x, y] for x, y in zip(coeff[0], coeff[1])]
xi, yi = interpolate.splev(np.linspace(0, 1, 1000), tck)

c = NURBS.Curve()
c.degree = 3
c.ctrlpts = pts_int
c.knotvector = knots
'''c.vis = VisMPL.VisCurve2D(axes=False, labels=False, ctrlpts=False, legend=True)
c.render()'''

curves_0 = operations.decompose_curve(c)
base_pts = [(p[0], p[1]) for c in curves_0 for p in c.ctrlpts]
x, y, r = make_circle(base_pts)  # O(n)
center = (x, y)
radius = r

pts_pr = []
for c in curves_0:
    pts_pr.append(project_to_circle(c.ctrlpts[0], center, radius))

curves_1 = []
for i in range(len(pts_pr) - 1):
    c = NURBS.Curve()
    c.degree = 3
    c.ctrlpts = [
        pts_pr[i],
        get_outer_angle_4(pts_pr[i], pts_pr[i + 1], center, radius)[1],
        get_outer_angle_4(pts_pr[i], pts_pr[i + 1], center, radius)[2],
示例#26
0
def get_cent_rad(f_name, coords_flag, cr_file_cols, m_m_n, vor_flag, ra_cent,
                 dec_cent, acp_pts, acp_mags, pts_area, pts_vert,
                 mean_filt_area, area_frac_range):
    '''
    Assign a center and a radius for each overdensity/group identified.

    Use an automatic algorithm based on a Voronoi diagram and grouping neighbor
    stars, or a file with center coordinates and radii already stored.
    '''

    if vor_flag == 'voronoi':

        # Apply maximum area filter.
        pts_area_thres, mag_area_thres, vert_area_thres = area_filter(
            acp_pts, acp_mags, pts_area, pts_vert, mean_filt_area,
            area_frac_range)
        save_to_log(f_name, "\nStars filtered by area range: {}".format(
            len(pts_area_thres)), 'a')

        save_to_log(f_name, 'Detect shared vertex', 'a')
        all_groups = shared_vertex(vert_area_thres)

        # This is a costly process.
        save_to_log(f_name, 'Assign points to groups', 'a')
        neighbors, neig_mags = group_stars(pts_area_thres, mag_area_thres,
                                           vert_area_thres, all_groups)
        save_to_log(f_name, 'Groups found: {}'.format(len(neighbors)), 'a')

        # Keep only those groups with a higher number of members than
        # min_neighbors.
        pts_neighbors, mags_neighbors = neighbors_filter(neighbors, neig_mags,
                                                         m_m_n)
        save_to_log(f_name,
                    '\nGroups filtered by number of members: {}'.format(
                        len(pts_neighbors)), 'a')

        # Check if at least one group was defined with the minimum
        # required number of neighbors.
        if pts_neighbors:
            # Obtain center and radius for each overdensity identified.
            cent_rad = []
            for g in pts_neighbors:

                pts = np.array(zip(*g))
                mean_pts = np.mean(pts, 0)

                # Translate towards origin
                pts -= mean_pts
                result = make_circle(pts)

                # Move back to correct position.
                c_r = (result[0] + mean_pts[0], result[1] + mean_pts[1],
                       result[2])

                cent_rad.append([c_r[0], c_r[1], c_r[2]])
        else:
            cent_rad = []
            save_to_log(f_name, "No groups found with members in range {}".
                        format(m_m_n), 'a')

    else:
        # Get data from file.
        cent_rad = get_cents_rad_file(coords_flag, vor_flag, cr_file_cols,
                                      ra_cent, dec_cent)
        pts_area_thres, mag_area_thres = [[0., 0.], [0., 0.]], [0.]
        pts_neighbors, mags_neighbors = [[[0.], [0.]]], [0]

    return cent_rad, pts_area_thres, mag_area_thres, pts_neighbors,\
        mags_neighbors
示例#27
0
def loop_through_sources(sigma=5, my_directory='/data5/sean/ldr2'):
    """Plot postage stamp images of LDR2 BL Lacs.

    Parameters
    ----------
    sigma : float or integer
        The threshold of the significance to set the mask, as a factor of the
        local RMS. The default is 5.
    my_directory : string
        Working directory.

    Returns
    -------
    string
        The name of the CSV containing the results.
    """
    results_path = f'{my_directory}/measure_point_sources/'
    if Path(results_path).exists() and Path(results_path).is_dir():
        shutil.rmtree(results_path)
    os.mkdir(results_path, 0o755)
    results_csv = (f'{results_path}/measure_point_sources.csv')
    result_header = ('BZB,Name,RA,Dec,S_peak (mJy),RMS (mJy/beam),D (asec)')
    print(result_header)
    with open(results_csv, 'a') as f:
        f.write(f'{result_header}\n')

    df = pd.read_csv(f'{my_directory}/S_Code=S,DC_Maj=0,_1deg - S_Code=S,'
                     'DC_Maj=0,_1deg.csv')
    df = df[(df['PS SNR'] > 10) & (df['Degree separation'] < 0.5)]
    df = df[(df['DC_Maj'] == 0) & (df['DC_Min'] == 0) & (df['S_Code'] == 'S')]

    plt.figure(figsize=(13.92, 8.60)).patch.set_facecolor('white')
    plt.rcParams['font.family'] = 'serif'
    plt.rcParams['mathtext.fontset'] = 'dejavuserif'
    mpl.rcParams['xtick.major.size'] = 10
    mpl.rcParams['xtick.major.width'] = 2
    mpl.rcParams['xtick.minor.size'] = 5
    mpl.rcParams['xtick.minor.width'] = 2
    mpl.rcParams['ytick.major.size'] = 10
    mpl.rcParams['ytick.major.width'] = 2
    mpl.rcParams['ytick.minor.size'] = 5
    mpl.rcParams['ytick.minor.width'] = 2
    mpl.rcParams['axes.linewidth'] = 2
    dummy = 123456
    pix = 1.5  # arcseconds per pixel
    colors = ['#118ab2', '#06d6a0', '#ffd166', '#ef476f']
    for bzb, bzb_mosaic, source_name, ra, dec, mosaic, rms, pf in zip(
        df['BZB name'], df['BZB mosaic'], df['Source_Name'], df['RA'],
            df['DEC'], df['Mosaic_ID'], df['Isl_rms'], df['Peak_flux']):
        if not bzb_mosaic:
            continue  # don't use the source if it is from a different pointing
        threshold = sigma * rms / 1000   # jansky
        hdu = fits.open(f'{my_directory}/mosaics/{mosaic}-mosaic.fits')[0]
        wcs = WCS(hdu.header, naxis=2)
        sky_position = SkyCoord(ra, dec, unit='deg')
        size = [1, 1] * u.arcmin
        cutout = Cutout2D(np.squeeze(hdu.data), sky_position, size=size,
                          wcs=wcs)
        d = cutout.data
        copy_d = np.copy(d)
        last_copy = np.copy(d)
        another_copy_d = np.copy(d)
        d[d < threshold] = 0
        d[d >= threshold] = 1
        rows, cols = d.shape

        d = label(d)
        source_islands = nearest_to_centre(d, percent=0.1)
        for source_island in source_islands:
            d[d == source_island] = dummy
        d[d != dummy] = 0
        copy_d[d != dummy] = 0
        set_to_nil = []  # identify values we can set to zero for being inside
        for r in range(rows):  # set to 0 if surrounded by non nans
            for c in range(cols):
                try:
                    if (d[r - 1, c - 1] != 0 and d[r - 1, c] != 0 and
                        d[r - 1, c + 1] != 0 and d[r, c - 1] != 0 and
                        d[r, c + 1] != 0 and d[r + 1, c - 1] != 0 and
                            d[r + 1, c] != 0 and d[r + 1, c + 1] != 0):
                        set_to_nil.append((r, c))
                except IndexError:
                    print(f'Index error for {source_name}.')
                    continue

        for r, c in set_to_nil:
            d[r, c] = 0  # needs separate loop to avoid checkered pattern

        # d is an outline of the source (one) and everything else is zero
        # copy_d is the source with flux values and everything else is zero
        # another_copy_d has flux values throughout
        good_cells = []
        for r in range(rows):
            for c in range(cols):
                if d[r, c] != 0:
                    good_cells.append([r, c])

        x, y, r = smallestenclosingcircle.make_circle(good_cells)

        ax = plt.subplot(projection=cutout.wcs)
        plt.xlabel('Right ascension', fontsize=20, color='black')
        plt.ylabel('Declination', fontsize=20, color='black')
        ax.tick_params(axis='both', which='major', labelsize=20)
        plt.imshow(another_copy_d, vmin=0, vmax=np.nanmax(another_copy_d),
                   origin='lower', norm=DS9Normalize(stretch='arcsinh'),
                   cmap='cubehelix_r', interpolation='gaussian')
        beam = Circle((6, 6), radius=2, linestyle='dashed', lw=2, fc='none',
                      edgecolor='blue')  # radius=2 pixels -> 3" -> diameter=6"
        diffuse = Circle((y + 0.5, x + 0.5), radius=r, fc='none',
                         edgecolor='k', lw=2)
        ax.add_patch(beam)
        ax.add_patch(diffuse)
        cbar = plt.colorbar()
        cbar.set_label(r'Jy beam$^{-1}$', size=20)
        cbar.ax.tick_params(labelsize=20)
        plt.minorticks_on()
        plt.tick_params(which='minor', length=0)
        levels = [level * threshold for level in [1, 2, 4, 8]]
        plt.contour(another_copy_d, levels=levels, origin='lower',
                    colors=colors)
        plt.contour(last_copy, levels=[-threshold * (3 / 5)], colors='grey',
                    origin='lower', linestyles='dashed')
        saved = f'{results_path}/{source_name}.png'
        plt.savefig(saved)
        plt.clf()
        # os.system(f'convert {saved} -trim {saved}')  # removes whitespace
        result = (f'{bzb},{source_name},{ra},{dec},{pf},{rms},'
                  f'{r * pix * 2:.1f}')
        print(result)
        with open(results_csv, 'a') as f:
            f.write(f'{result}\n')
    return results_csv
示例#28
0
def make_circles(polygons):
    return [make_circle(np.array(poly.boundary.xy).T) for poly in polygons]
示例#29
0
    image[0, 0] = (image[0, 1] + image[1, 0]) / 2.
    image = image - mark
    image = image / 255.
    return image


with open(csvfile, "w") as output:
    writer = csv.writer(output, lineterminator='\n')
    writer.writerow(['X', 'Y', 'R'])
    for i in range(0, nb_samples):
        image = np.array(Image.open(testImagesFolder + imageList[i]))
        label = np.asarray(dfLabels.iloc[i, 1:].values, dtype='float32')

        labelP = world2pixel(label.reshape((21, 3)).copy(), fx, fy, u0, v0)

        circx, circy, radius = make_circle(labelP[:, 0:2].copy())

        center = np.asarray([circx, circy])
        radius = radius + 16
        lefttop_pixel = center - radius
        rightbottom_pixel = center + radius

        new_Xmin = max(lefttop_pixel[0], 0)
        new_Ymin = max(lefttop_pixel[1], 0)
        new_Xmax = min(rightbottom_pixel[0], image.shape[1] - 1)
        new_Ymax = min(rightbottom_pixel[1], image.shape[0] - 1)
        # print([new_Xmin, new_Xmax, new_Ymin, new_Ymax])
        if new_Xmin > 640 or abs(new_Xmin - new_Xmax) < 20:
            continue

        imCrop = image.copy()[int(new_Ymin):int(new_Ymax),
示例#30
0
def loop_through_sources(sigma=4, my_directory='/data5/sean/ldr2'):
    """Plot postage stamp images of LDR2 BL Lacs.

    Parameters
    ----------
    sigma : float or integer
        The threshold of the significance to set the mask, as a factor of the
        local RMS. The default is 4.
    my_directory : string
        Working directory.

    Returns
    -------
    string
        The name of the CSV containing the results.
    """
    df = pd.read_csv(f'{my_directory}/catalogues/pulsars-10asec-match.csv')

    plt.figure(figsize=(13.92, 8.60)).patch.set_facecolor('white')
    plt.rcParams['font.family'] = 'serif'
    plt.rcParams['mathtext.fontset'] = 'dejavuserif'
    mpl.rcParams['xtick.major.size'] = 10
    mpl.rcParams['xtick.major.width'] = 2
    mpl.rcParams['xtick.minor.size'] = 5
    mpl.rcParams['xtick.minor.width'] = 2
    mpl.rcParams['ytick.major.size'] = 10
    mpl.rcParams['ytick.major.width'] = 2
    mpl.rcParams['ytick.minor.size'] = 5
    mpl.rcParams['ytick.minor.width'] = 2
    mpl.rcParams['axes.linewidth'] = 2
    dummy = 123456
    sbar_asec = 30  # desired length of scalebar in arcseconds
    pix = 1.5  # arcseconds per pixel

    for source_name, ra, dec, mosaic, rms in zip(df['NAME'], df['RAJD'],
                                                 df['DECJD'], df['Mosaic_ID'],
                                                 df['Isl_rms']):

        threshold = sigma * rms / 1000  # jansky
        hdu = fits.open(f'{my_directory}/mosaics/{mosaic}-mosaic.fits')[0]
        wcs = WCS(hdu.header, naxis=2)
        sky_position = SkyCoord(ra, dec, unit='deg')
        size = [2, 2] * u.arcmin
        p = 6

        cutout = Cutout2D(np.squeeze(hdu.data),
                          sky_position,
                          size=size,
                          wcs=wcs)
        d = cutout.data
        copy_d = np.copy(d)
        another_copy_d = np.copy(d)
        d[d < threshold] = 0
        d[d >= threshold] = 1
        rows, cols = d.shape

        d = label(d)  # label islands of emission
        source_islands = nearest_to_centre(d, percent=0.1)
        for source_island in source_islands:
            d[d == source_island] = dummy

        d[d != dummy] = 0
        copy_d[d != dummy] = 0
        set_to_nil = []  # identify values we can set to zero for being inside
        for r in range(rows):  # set to 0 if surrounded by non nans
            for c in range(cols):
                try:
                    if (d[r - 1, c - 1] != 0 and d[r - 1, c] != 0
                            and d[r - 1, c + 1] != 0 and d[r, c - 1] != 0
                            and d[r, c + 1] != 0 and d[r + 1, c - 1] != 0
                            and d[r + 1, c] != 0 and d[r + 1, c + 1] != 0):
                        set_to_nil.append((r, c))
                except IndexError:
                    print(f'Index error for {source_name}.')
                    continue

        for r, c in set_to_nil:
            d[r, c] = 0  # needs separate loop to avoid checkered pattern

        # d is an outline of the source (one) and everything else is zero
        # copy_d is the source with flux values and everything else is zero
        # another_copy_d has flux values throughout
        good_cells = []
        for r in range(rows):
            for c in range(cols):
                if d[r, c] != 0:
                    good_cells.append([r, c])

        x, y, r = smallestenclosingcircle.make_circle(good_cells)

        ax = plt.subplot(projection=cutout.wcs)
        plt.xlabel('Right ascension', fontsize=20, color='black')
        plt.ylabel('Declination', fontsize=20, color='black')
        ax.tick_params(axis='both', which='major', labelsize=20)
        plt.imshow(another_copy_d,
                   vmin=0,
                   vmax=np.nanmax(another_copy_d),
                   origin='lower',
                   norm=DS9Normalize(stretch='arcsinh'),
                   cmap='plasma_r')  # interpolation='gaussian'
        beam = Circle((6, 6),
                      radius=2,
                      linestyle='dashed',
                      lw=2,
                      fc='none',
                      edgecolor='blue')
        diffuse = Circle((y + 0.5, x + 0.5),
                         radius=r,
                         fc='none',
                         edgecolor='k',
                         lw=2)
        ax.add_patch(beam)
        ax.add_patch(diffuse)

        sbar = sbar_asec / pix  # length of scalebar in pixels
        s = cutout.data.shape[1]  # plot scalebar
        plt.plot([p, p + sbar], [s - p, s - p], marker='None', lw=2, color='b')
        plt.text(p,
                 s - (5 * p / 6),
                 f'{sbar_asec:.0f}"',
                 fontsize=20,
                 color='b')

        cbar = plt.colorbar()
        cbar.set_label(r'Jy beam$^{-1}$', size=20)
        cbar.ax.tick_params(labelsize=20)
        plt.minorticks_on()
        plt.tick_params(which='minor', length=0)
        plt.contour(another_copy_d,
                    levels=[threshold],
                    origin='lower',
                    colors='w')
        plt.contour(another_copy_d - copy_d,
                    levels=[threshold],
                    colors='grey',
                    origin='lower')
        plt.savefig(f'{my_directory}/images/pulsar-{source_name}.png')
        plt.clf()

        print(f'{source_name}: {r * 1.5 * 2:.1f}"')
示例#31
0
def find_rp(r, p, constraints, point_sets, mapping):
    """Function returns the smallest disc that contains p on its boundary."""
    #print(f"Computing rp for {p}...")
    all_points = [p for point_set in point_sets for p in point_set]
    all_points = [
        q for q in all_points if q != p and euclid_dist(p, q) < 2 * r
    ]  # Compute I(p, r)
    c_depth = [0 for ps in point_sets]
    open_discs = [p]
    valid_configs = []

    intersections = []

    c_depth[mapping[p]] += 1

    intersection_mapping = {}

    for q in all_points:
        midpoint = ((p[0] + q[0]) / 2), ((p[1] + q[1]) / 2)
        a = euclid_dist(p, q) / 2
        h = math.sqrt(r**2 - a**2)

        p1 = (midpoint[0] + h * ((q[1] - p[1]) / (2 * a)),
              midpoint[1] - h * ((q[0] - p[0]) / (2 * a)))
        p2 = (midpoint[0] - h * ((q[1] - p[1]) / (2 * a)),
              midpoint[1] + h * ((q[0] - p[0]) / (2 * a)))

        intersection_mapping[p1] = q
        intersection_mapping[p2] = q

        intersections.append(p1)
        intersections.append(p2)

        if abs((math.atan2(p1[1] - p[1], p1[0] - p[0]) + 2 * math.pi) %
               (2 * math.pi) -
               (math.atan2(p2[1] - p[1], p2[0] - p[0]) + 2 * math.pi) %
               (2 * math.pi)) > math.pi:
            open_discs.append(q)
            c_depth[mapping[q]] += 1

    intersections = sorted(
        intersections,
        key=lambda q: (math.atan2(q[1] - p[1], q[0] - p[0]) + 2 * math.pi) %
        (2 * math.pi))

    for i in range(0, len(intersections)):
        intersection = intersections[i]
        if intersection_mapping[intersection] in open_discs:
            c_depth[mapping[intersection_mapping[intersection]]] -= 1
            open_discs.remove(intersection_mapping[intersection])
        else:
            c_depth[mapping[intersection_mapping[intersection]]] += 1
            open_discs.append(intersection_mapping[intersection])

        valid = True
        for d, (c, op) in zip(c_depth, constraints):
            if (op == 1 or op == 0) and d < c:  # >=
                valid = False
                break
            '''elif op == 0 and d != c: # =
                valid = False
                break
            elif op == -1 and d > c: # <=
                valid = False
                break'''

        if valid:
            valid_configs.append(list(open_discs))

    circles = []
    for v in valid_configs:  # O(n^2)
        x, y, r = make_circle(v)  # O(n)
        valid = True
        for point_set, (c, op) in zip(point_sets, constraints):  # O(n)
            if op == 1:
                continue
            no_points = len(
                [p for p in point_set if euclid_dist(p, (x, y)) <= r])
            if op == 0 and no_points != c:
                valid = False
                break
            elif op == -1 and no_points > c:
                valid = False
                break
        if valid:
            circles.append((x, y, r))

    if len(circles) == 0:
        min_disc = (0, 0, math.inf)
    else:
        min_disc = min(circles, key=lambda c: c[2])

    return min_disc
示例#32
0
def find_best_cylinder(list_atoms, coord_matrix):
    """Find the thinnest cylinder dimesions where the molecule could fit add clouds of points around the atoms before the PCA (pi/3 in every direction with atomic radius)
	x = r*sin(theta)*cos(theta)
	y = r*sin(theta)*sin(theta)        theta is inclination from top (0 to pi) and phi is azimuth (0 to 2pi)
	z = r*cos(theta)
	"""
    # import numpy as np
    # import scipy
    # from sklearn.decomposition import PCA
    # from smallestenclosingcircle import make_circle
    index_of_volumes = {
        'H': 7.24,
        'C': 20.58,
        'N': 15.60,
        'O': 14.71,
        'F': 13.31,
        'Cl': 22.45,
        'Br': 26.52,
        'I': 32.52,
        'P': 24.43,
        'S': 24.43,
        'As': 26.52,
        'B': 40.48,
        'Si': 38.79,
        'Se': 28.73,
        'Te': 36.62
    }
    index_of_radii = {
        'H': 1.2,
        'C': 1.7,
        'N': 1.55,
        'O': 1.52,
        'F': 1.47,
        'Cl': 1.75,
        'Br': 1.85,
        'I': 1.98,
        'P': 1.8,
        'S': 1.8,
        'As': 1.85,
        'B': 2.13,
        'Si': 2.1,
        'Se': 1.9,
        'Te': 2.06
    }
    angle_nbs = 6  # for angle_nbs = 3 there will be points spaced by pi/3 so three sections in inclinations and six in azimutal
    sphere_points = []
    for i in xrange(len(list_atoms)):
        radius = index_of_radii[list_atoms[i]]
        top_sphere_point = [
            coord_matrix[i][0], coord_matrix[i][1],
            coord_matrix[i][2] + radius * np.cos(0)
        ]
        bottom_sphere_point = [
            coord_matrix[i][0], coord_matrix[i][1],
            coord_matrix[i][2] + radius * np.cos(np.pi)
        ]
        sphere_points.append(top_sphere_point)
        sphere_points.append(bottom_sphere_point)
        for inclination_angle in np.linspace(0, np.pi, angle_nbs + 1)[1:-1]:
            for azymuth_angle in np.linspace(0, np.pi * 2, angle_nbs * 2):
                new_sphere_point = [
                    coord_matrix[i][0] +
                    radius * np.sin(inclination_angle) * np.cos(azymuth_angle),
                    coord_matrix[i][1] +
                    radius * np.sin(inclination_angle) * np.sin(azymuth_angle),
                    coord_matrix[i][2] + radius * np.cos(inclination_angle)
                ]
                sphere_points.append(new_sphere_point)
    # print len(sphere_points)
    # print len(coord_matrix[:])
    # print np.array(sphere_points)
    total_matrix = np.concatenate((coord_matrix, sphere_points), axis=0)
    pca = PCA(n_components=3)

    transform = pca.fit_transform(total_matrix)
    transform_coord = pca.transform(coord_matrix)

    point_cloud = zip(transform.T[1][:], transform.T[2][:])
    height = np.max(transform.T[0][:]) - np.min(transform.T[0][:])
    rad = make_circle(point_cloud)

    return [rad[2], height]
示例#33
0
def show_cylinder(smiles):
    conf, energ = get_best_conformation(smiles)
    check_for_invalid_ = compose_matrix_from_raw_xyz(conf)
    print 'this is the python plot coordinate string'
    print conf
    list_atoms, coord_matrix = check_for_invalid_

    index_of_volumes = {
        'H': 7.24,
        'C': 20.58,
        'N': 15.60,
        'O': 14.71,
        'F': 13.31,
        'Cl': 22.45,
        'Br': 26.52,
        'I': 32.52,
        'P': 24.43,
        'S': 24.43,
        'As': 26.52,
        'B': 40.48,
        'Si': 38.79,
        'Se': 28.73,
        'Te': 36.62
    }
    index_of_radii = {
        'H': 1.2,
        'C': 1.7,
        'N': 1.55,
        'O': 1.52,
        'F': 1.47,
        'Cl': 1.75,
        'Br': 1.85,
        'I': 1.98,
        'P': 1.8,
        'S': 1.8,
        'As': 1.85,
        'B': 2.13,
        'Si': 2.1,
        'Se': 1.9,
        'Te': 2.06
    }
    angle_nbs = 6  # for angle_nbs = 3 there will be points spaced by pi/3 so three sections in inclinations and six in azimutal
    sphere_points = []
    for i in xrange(len(list_atoms)):
        radius = index_of_radii[list_atoms[i]]
        top_sphere_point = [
            coord_matrix[i][0], coord_matrix[i][1],
            coord_matrix[i][2] + radius * np.cos(0)
        ]
        bottom_sphere_point = [
            coord_matrix[i][0], coord_matrix[i][1],
            coord_matrix[i][2] + radius * np.cos(np.pi)
        ]
        sphere_points.append(top_sphere_point)
        sphere_points.append(bottom_sphere_point)
        for inclination_angle in np.linspace(0, np.pi, angle_nbs + 1)[1:-1]:
            for azymuth_angle in np.linspace(0, np.pi * 2, angle_nbs * 2):
                new_sphere_point = [
                    coord_matrix[i][0] +
                    radius * np.sin(inclination_angle) * np.cos(azymuth_angle),
                    coord_matrix[i][1] +
                    radius * np.sin(inclination_angle) * np.sin(azymuth_angle),
                    coord_matrix[i][2] + radius * np.cos(inclination_angle)
                ]
                sphere_points.append(new_sphere_point)
    # print len(sphere_points)
    # print len(coord_matrix[:])
    # print np.array(sphere_points)
    total_matrix = np.concatenate((coord_matrix, sphere_points), axis=0)
    pca = PCA(n_components=3)

    transform = pca.fit_transform(total_matrix)
    transform_coord = pca.transform(coord_matrix)

    point_cloud = zip(transform.T[1][:], transform.T[2][:])
    height = np.max(transform.T[0][:]) - np.min(transform.T[0][:])
    rad = make_circle(point_cloud)

    top = np.max(transform.T[0][:])
    bottom = np.min(transform.T[0][:])
    # print height
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    # print [index_of_radii[atom]**2*np.pi for atom in list_atoms]

    ### Not transformed coordinates scatter plot
    ### ax.scatter(coord_matrix.T[0][:],coord_matrix.T[1][:], coord_matrix.T[2][:], s=[(index_of_radii[atom]*5)**2*np.pi for atom in list_atoms], c=[index_of_radii[atom] for atom in list_atoms], alpha=0.75)
    ### ax.scatter(total_matrix.T[0][:],total_matrix.T[1][:], total_matrix.T[2][:], s = 2, alpha=0.75)

    #### Transformed coordinates scatter plot
    ax.scatter(transform_coord.T[0][:],
               transform_coord.T[1][:],
               transform_coord.T[2][:],
               s=[(index_of_radii[atom] * 5)**2 * np.pi
                  for atom in list_atoms],
               c=[index_of_radii[atom] for atom in list_atoms],
               alpha=0.75)
    ax.scatter(transform.T[0][:],
               transform.T[1][:],
               transform.T[2][:],
               s=2,
               alpha=0.75)

    ### Visual indications, mostly circles to outline the perimeter of the cylinder

    n_circles = 6
    zs = np.linspace(bottom, top, n_circles)
    for i in xrange(n_circles):
        circle = plt.Circle((rad[0], rad[1]),
                            rad[2],
                            fill=(i == 0 or i == n_circles - 1),
                            alpha=0.2)
        ax.add_patch(circle)
        art3d.pathpatch_2d_to_3d(circle, z=zs[i], zdir="x")
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('z')
    ax.set_title('{} ({})'.format(smiles, rad[2]))
    plt.axis('equal')
    plt.show()
示例#34
0
def loop_through_sources(sigma=5, my_directory='/data5/sean/ldr2'):
    """Plot postage stamp images of LDR2 BL Lacs.

    Parameters
    ----------
    sigma : float or integer
        The threshold of the significance to set the mask, as a factor of the
        local RMS. The default is 4.
    my_directory : string
        Working directory.

    Returns
    -------
    string
        The name of the CSV containing the results.
    """
    results_csv = f'{my_directory}/images/ldr2.csv'
    try:
        os.remove(results_csv)
    except OSError:
        pass
    df = pd.read_csv(f'{my_directory}/catalogues/final.csv')
    result_header = ('Name,RA,Dec,RMS (uJy),Redshift,Width ("),Width (kpc),'
                     'Peak flux (mJy)\n')

    with open(results_csv, 'a') as f:
        f.write(result_header)

    plt.figure(figsize=(13.92, 8.60)).patch.set_facecolor('white')
    plt.rcParams['font.family'] = 'serif'
    plt.rcParams['mathtext.fontset'] = 'dejavuserif'
    mpl.rcParams['xtick.major.size'] = 10
    mpl.rcParams['xtick.major.width'] = 2
    mpl.rcParams['xtick.minor.size'] = 5
    mpl.rcParams['xtick.minor.width'] = 2
    mpl.rcParams['ytick.major.size'] = 10
    mpl.rcParams['ytick.major.width'] = 2
    mpl.rcParams['ytick.minor.size'] = 5
    mpl.rcParams['ytick.minor.width'] = 2
    mpl.rcParams['axes.linewidth'] = 2
    dummy = 123456
    sbar_asec = 30  # desired length of scalebar in arcseconds
    pix = 1.5  # arcseconds per pixel
    colors = ['#118ab2', '#06d6a0', '#ffd166', '#ef476f']
    print('Name, asec, kpc, threshold, UL?')
    for source_name, ra, dec, mosaic, rms, z, pf, comp in zip(
            df['Name'], df['BZCAT RA'], df['BZCAT Dec'], df['Mosaic_ID'],
            df['Isl_rms'], df['redshift'], df['Peak_flux'], df['Compact']):
        source_name = '5BZB' + source_name
        source_name = source_name.replace(' ', '')
        threshold = sigma * rms / 1000  # jansky
        thresh_ans = f'{sigma}sigma'
        # if threshold < (pf / 50) / 1000:
        #     # see 2.2 of https://arxiv.org/pdf/1907.03726.pdf
        #     four_sigma = threshold
        #     threshold = (pf / 50) / 1000
        #     thresh_ans = '1/50 S_peak'
        hdu = fits.open(f'{my_directory}/mosaics/{mosaic}-mosaic.fits')[0]
        wcs = WCS(hdu.header, naxis=2)
        sky_position = SkyCoord(ra, dec, unit='deg')
        if source_name == '5BZBJ1202+4444' or source_name == '5BZBJ1325+4115':
            size = [3, 3] * u.arcmin
            p = 9
        elif (source_name == '5BZBJ1419+5423'
              or source_name == '5BZBJ0945+5757'):
            size = [4, 4] * u.arcmin
            p = 12
        else:
            size = [2, 2] * u.arcmin
            p = 6

        cutout = Cutout2D(np.squeeze(hdu.data),
                          sky_position,
                          size=size,
                          wcs=wcs)
        d = cutout.data
        copy_d = np.copy(d)
        last_copy = np.copy(d)
        another_copy_d = np.copy(d)
        d[d < threshold] = 0
        d[d >= threshold] = 1
        rows, cols = d.shape

        d = label(d)  # label islands of emission
        source_islands = nearest_to_centre(d, percent=0.1)
        if source_name == '5BZBJ1000+5746':
            source_islands = [1, 2, 3, 4]
        elif source_name == '5BZBJ1202+4444':
            source_islands = [1, 2, 3]
        elif (source_name == '5BZBJ1203+5430'
              or source_name == '5BZBJ1419+5423'):
            source_islands = [1, 2]
        elif source_name == '5BZBJ1409+5939':
            source_islands = [2, 3]
        elif source_name == '5BZBJ1203+5430':
            source_islands = [1, 2]

        for source_island in source_islands:
            d[d == source_island] = dummy
        d[d != dummy] = 0
        copy_d[d != dummy] = 0
        set_to_nil = []  # identify values we can set to zero for being inside
        for r in range(rows):  # set to 0 if surrounded by non nans
            for c in range(cols):
                try:
                    if (d[r - 1, c - 1] != 0 and d[r - 1, c] != 0
                            and d[r - 1, c + 1] != 0 and d[r, c - 1] != 0
                            and d[r, c + 1] != 0 and d[r + 1, c - 1] != 0
                            and d[r + 1, c] != 0 and d[r + 1, c + 1] != 0):
                        set_to_nil.append((r, c))
                except IndexError:
                    print(f'Index error for {source_name}.')
                    continue

        for r, c in set_to_nil:
            d[r, c] = 0  # needs separate loop to avoid checkered pattern

        # d is an outline of the source (one) and everything else is zero
        # copy_d is the source with flux values and everything else is zero
        # another_copy_d has flux values throughout
        good_cells = []
        for r in range(rows):
            for c in range(cols):
                if d[r, c] != 0:
                    good_cells.append([r, c])

        x, y, r = smallestenclosingcircle.make_circle(good_cells)

        ax = plt.subplot(projection=cutout.wcs)
        plt.xlabel('Right ascension', fontsize=20, color='black')
        plt.ylabel('Declination', fontsize=20, color='black')
        ax.tick_params(axis='both', which='major', labelsize=20)
        plt.imshow(another_copy_d,
                   vmin=0,
                   vmax=np.nanmax(another_copy_d),
                   origin='lower',
                   norm=DS9Normalize(stretch='arcsinh'),
                   cmap='cubehelix_r',
                   interpolation='gaussian')
        beam = Circle((6, 6),
                      radius=2,
                      linestyle='dashed',
                      lw=2,
                      fc='none',
                      edgecolor='blue')  # radius=2 pixels -> 3" -> diameter=6"
        # diffuse = Circle((y + 0.5, x + 0.5), radius=r, fc='none',
        #                  edgecolor='k', lw=2)
        ax.add_patch(beam)
        # if comp == False:  # noqa
        #     ax.add_patch(diffuse)

        kpc_per_asec = get_kpc_per_asec(z=z)
        sbar = sbar_asec / pix  # length of scalebar in pixels
        kpc_per_pixel = kpc_per_asec * pix
        s = cutout.data.shape[1]  # plot scalebar
        plt.plot([p, p + sbar], [s - p, s - p], marker='None', lw=2, color='b')
        plt.text(p,
                 s - (5 * p / 6), f'{sbar_asec:.0f}" = '
                 f'{kpc_per_pixel * sbar:.0f} kpc',
                 fontsize=20,
                 color='b')

        cbar = plt.colorbar()
        cbar.set_label(r'Jy beam$^{-1}$', size=20)
        cbar.ax.tick_params(labelsize=20)
        plt.minorticks_on()
        plt.tick_params(which='minor', length=0)
        # levels = [level * threshold for level in [1, 2, 4, 8]]
        levels = [level * threshold for level in [1, 2, 4, 8]]
        plt.contour(another_copy_d,
                    levels=levels,
                    origin='lower',
                    colors=colors)
        plt.contour(last_copy,
                    levels=[-threshold * (3 / 5)],
                    colors='grey',
                    origin='lower',
                    linestyles='dashed')
        # plt.contour(another_copy_d - copy_d, levels=[threshold],
        #             colors='grey', origin='lower')
        saved = f'{my_directory}/images/ldr2-{source_name}.png'
        # if thresh_ans == '1/50 S_peak':
        #     plt.contour(last_copy, levels=[-four_sigma], colors='grey',
        #                 origin='lower', linestyles='dashed')
        #     plt.contour(last_copy, levels=[four_sigma], colors='grey',
        #                 origin='lower', linestyles='solid')
        print('view me: gpicview ' + saved)
        plt.savefig(saved)
        plt.clf()
        os.system(f'convert {saved} -trim {saved}')  # removes whitespace

        width = r * kpc_per_pixel * 2  # radius to diameter
        result = (f'{source_name},{ra},{dec},{rms * 1e3},{z},'
                  f'{r * pix * 2:.1f}, {width:.1f}, {pf}\n')
        print(f'{source_name[4:]}, {r * pix * 2:.4f}, {width:.4f}, '
              f'{thresh_ans}, {comp}')

        with open(results_csv, 'a') as f:
            f.write(result)
    return results_csv