def rotate(self, deg=90):
     """Rotates the entities selected and
     update the selction list
     """
     if len(self.__selection_list) == 0:
         return
     max_ = max(self.__all_selection)
     min_ = min(self.__all_selection)
     pivot = Point(
         min_.x + ((max_.x - min_.x) / 2.),
         min_.y + ((max_.y - min_.y) / 2.),
     )
     new_dict = BaseGrid(int)
     new_selection = list()
     new_all = list()
     for point in self.__selection_list:
         new_pos = rotate_point(point, pivot, deg)
         new_selection.append(new_pos)
         new_dict[new_pos] = ALL_ENTITIES[self._grid[point]].rotate(deg)
         self.delete(point)
     self.__selection_list = new_selection
     self.__all_selection = list()
     for point in self.__all_selection:
         new_all.append(rotate_point(point, pivot, deg))
     self.__all_selection = new_all
     for pos, entity in self._grid.viewitems():
         if pos not in new_dict:
             new_dict[pos] = entity
     self._grid.clear()
     self._grid.update(new_dict)
     self.__update_selection()
    def rotated_points(self) -> tuple:
        # define the points of the ship's triangle and rotate them by the player's rotation    
        point_nose = rotate_point(self.x + self.scale, self.y, self.x, self.y, self.rotation)
        point_right_fin = rotate_point(self.x - self.scale, self.y - (self.scale * 0.8), self.x, self.y, self.rotation)
        point_left_fin = rotate_point(self.x - self.scale, self.y + (self.scale * 0.8), self.x, self.y, self.rotation)

        return point_nose, point_right_fin, point_left_fin
def get_corners(centre, width_scale, start_point):
    horiz_rot = 2*math.atan(width_scale)
    vert_rot = math.pi - horiz_rot

    points = np.vstack((start_point, rotate_point(centre, start_point, horiz_rot)))
    points = np.vstack((points, rotate_point(centre, points[0, :], horiz_rot+vert_rot)))
    points = np.vstack((points, rotate_point(centre, points[0, :], -vert_rot)))
    return points
 def rotate(self, center, angle):
     """Compute new word's bounding box coordinates after rotation. 
     """
     #self.bounding_box = [rotate_point(x,center,angle) for x in self.bounding_box]
     self.relative_bounding_box = [
         rotate_point(x, center, angle) for x in self.relative_bounding_box
     ]
示例#5
0
def motion_update(particles, odom, grid):
    """ Particle filter motion update

        Arguments:
        particles -- input list of particle represents belief p(x_{t-1} | u_{t-1})
                before motion update
        odom -- odometry to move (dx, dy, dh) in *robot local frame*
        grid -- grid world map, which contains the marker information,
                see grid.py and CozGrid for definition
                Can be used for boundary checking
        Returns: the list of particles represents belief \tilde{p}(x_{t} | u_{t})
                after motion update
    """

    motion_particles = []
    dh = odom[2]

    for particle in particles:
        x_coor, y_coor, h_coor = particle.xyh
        dx, dy = utils.rotate_point(odom[0], odom[1], h_coor)

        new_noisy_x, new_noisy_y, new_noisy_h = utils.add_odometry_noise(
            (x_coor + dx, y_coor + dy, h_coor + dh), setting.ODOM_HEAD_SIGMA,
            setting.ODOM_TRANS_SIGMA)
        new_noisy_particle = Particle(new_noisy_x, new_noisy_y, new_noisy_h)
        motion_particles.append(new_noisy_particle)

    # motion_particles = particles
    return motion_particles
示例#6
0
    def plot_position_angle(i, color):
        """
		Plots the position angle for source (i) on the sky as a line with a radius proportional 
		to either the nearest neighbour distance or the major axis of a source.
		"""

        RA = tdata['RA_2'][i]
        DEC = tdata['DEC_2'][i]

        position_angle = tdata['final_PA'][i]
        NN_dist = tdata['new_NN_distance(arcmin)'][i]
        size = 160  # 80  #set fixed X*4 arcsec
        # size = tdata['size_thesis'][i]

        z_best = tdata['z_best'][i]

        radius = size / 3600.  # convert arcsec to deg

        radius *= 4  # enhance radius by a factor

        origin = (RA, DEC)  # (coordinates of the source)

        up_point = (RA, DEC + radius)  # point above the origin (North)
        down_point = (RA, DEC - radius)  # point below the origin (South)

        # rotate the line according to the position angle North through East (counterclockwise)
        x_rot_up, y_rot_up = rotate_point(origin, up_point, position_angle)
        x_rot_down, y_rot_down = rotate_point(origin, down_point,
                                              position_angle)

        x = x_rot_down
        y = y_rot_down
        dx = x_rot_up - x_rot_down
        dy = y_rot_up - y_rot_down

        # ax.arrow(x,y,dx,dy)

        if color:
            # make colorbar with the redshift data
            plt.plot((x_rot_down, x_rot_up), (y_rot_down, y_rot_up),
                     c=color,
                     linewidth=0.4)
        else:
            plt.plot((x_rot_down, x_rot_up), (y_rot_down, y_rot_up),
                     linewidth=0.4,
                     c='k')
示例#7
0
    def update(self, game_map: Map, delta_time):
        vector = utils.rotate_point(
            (0, -config.PROJECTILE_SPEED / config.TILE_SIZE * delta_time),
            self.direction)
        self.x += vector[0]
        self.y += vector[1]

        if self.x < -3 or self.y < -3 or self.x > game_map.width + 3 or self.y > game_map.height + 3:
            self.exists = False
示例#8
0
    def __init__(self, speedvector, game):
        pg.sprite.Sprite.__init__(self)

        # game objects
        self.gm = game
        self.player = game.p
        self.evm = game.evm
        self.evm.add_listener(self)

        # make vector in opposite direction from player
        self.vector = -1 * speedvector

        # spritegroups
        self.gm.allsprites.add(self)
        self.gm.onscreen.add(self)
        self.gm.pvedamage.add(self)
        self.gm.p.allsprites.add(self)
        self.gm.p.brakeshots.add(self)

        # get angle to positive x-axis
        self.angle_d = self.vector.angle_to(pg.math.Vector2((1, 0)))
        self.angle_r = math.radians(self.angle_d)

        # load animation
        self.animation = ani.Animation("brakeblast.png", 64)
        self.image = self.animation.get_frame_no(0).convert_alpha()

        # find center for new rect by rotating a pre-defined center
        # TODO generalize this magic constant to enable scaling
        center_rightx = self.player.rect.centerx + 50
        center_righty = self.player.rect.centery
        center_right = (center_rightx, center_righty)
        newcenter = utils.rotate_point(self.player.rect.center, center_right,
                                       -1 * self.angle_r)

        # get rect from image
        self.rect = pg.transform.rotate(
            self.image, self.angle_d).get_rect(center=newcenter)

        print(str(self.vector.length()))
        print(self.rect)

        # bool to ensure only dealing damage once
        self.damage_dealt = False
示例#9
0
def translate_points_to_origin(p0, p1):
    """Translate to the origin and rotate the points to have both on the x axis
    """
    logg = logging.getLogger(f"c.{__name__}.translate_points_to_origin")
    logg.setLevel("INFO")
    logg.debug(f"Starting translate_points_to_origin")

    # direction from point 0 to 1
    dir_01 = degrees(atan2(p1.y - p0.y, p1.x - p0.x))
    logg.debug(f"dir_01: {dir_01}")

    # rotate the point and translate them in the origin
    rot_p0 = SPoint(0, 0, p0.ori_deg - dir_01)
    # tranlsate p1 towards origin by p0
    tran_p1x = p1.x - p0.x
    tran_p1y = p1.y - p0.y
    # rotate p1 position by dir_01
    rototran_p1 = utils.rotate_point(np.array([tran_p1x, tran_p1y]), dir_01)
    rot_p1 = SPoint(rototran_p1[0], rototran_p1[1], p1.ori_deg - dir_01)
    logg.debug(f"rot_p0: {rot_p0} rot_p1: {rot_p1}")

    return rot_p0, rot_p1, dir_01
示例#10
0
def motion_update(particles, odom, grid):
    """ Particle filter motion update

        Arguments:
        particles -- input list of particle represents belief p(x_{t-1} | u_{t-1})
                before motion update
        odom -- odometry to move (dx, dy, dh) in *robot local frame*
        grid -- grid world map, which contains the marker information,
                see grid.py and CozGrid for definition
                Can be used for boundary checking
        Returns: the list of particles represents belief \tilde{p}(x_{t} | u_{t})
                after motion update
    """
    motion_particles = []
    for p in particles:
        x, y, h = p.xyh
        dx, dy, dh = odom
        dx, dy = rotate_point(dx, dy, h)
        odom_temp = (x + dx, y + dy, h + dh)
        x, y, h = add_odometry_noise(odom_temp, setting.ODOM_HEAD_SIGMA,
                                     setting.ODOM_TRANS_SIGMA)
        motion_particles.append(Particle(x, y, h))
    return motion_particles
示例#11
0
def rototranslate_points(x_sample, y_segment, offset_angle, offset_x, offset_y):
    """Rototranslate the points [x_sample, y_segment]

    Apply first the rotation by offset_angle, then the translation by
    (offset_x, offset_y)
    """
    logg = logging.getLogger(f"c.{__name__}.rototranslate_points")
    logg.setLevel("INFO")
    logg.debug(f"Starting rototranslate_points")

    # rotate the points back
    all_segment = np.array([x_sample, y_segment]).transpose()
    #  logg.debug(f"all_segment.shape: {all_segment.shape}")
    rotated_segment = utils.rotate_point(all_segment, offset_angle)
    #  logg.debug(f"rotated_segment.shape: {rotated_segment.shape}")

    # translate them
    tran_segment = rotated_segment + np.array([offset_x, offset_y])
    tran_segment = tran_segment.transpose()
    #  logg.debug(f"tran_segment.shape: {tran_segment.shape}")
    rototran_x = tran_segment[0]
    rototran_y = tran_segment[1]

    return rototran_x, rototran_y
示例#12
0
 def get_point(self, point: int) -> Tuple[float, float]:
     rotated = utils.rotate_point(self._points[point], self.angle)
     return rotated[0] + self.x, rotated[1] + self.y
示例#13
0
def find_orientationMG(i,
                       fitsim,
                       ra,
                       dec,
                       Maj,
                       Min,
                       s=(3 / 60.),
                       plot=False,
                       head=None,
                       hdulist=None):
    '''	
	Finds the orientation of multiple gaussian single sources 

	To run this function for all sources, use setup_find_orientation_multiple_gaussians() instead.

	A big part of this function is a re-run of the postage function,
	since we need to make a new postage basically, but this time as an array.

	Arguments: 
	i -- The new_Index of the source
	fitsim -- Postage created earlier (if exists)
	ra, dec -- Ra and dec of the source
	Maj -- Major axis of the source
	s -- Width of the image, default 3 arcmin, because it has to be a tiny bit
		lower than the postage created earlier (width 4 arcmin) or NaNs will appear in the image
	plot -- Whether to plot the results. 
	head and hdulist -- the header and hdulist if a postage hasn't been created before.
		(This is so it doesn't open every time in the loop but is opened before the loop.)

	Returns: 
	i -- new_Index of the source
	max_angle -- Angle of the flux line for which flux is maximized.
	len(err_orientations) -- Amount of degrees spread in the angle of the flux line
	len(indx_extrema[0]) -- Amount of extrema along the line
	classification -- 'Large' or 'Small' error, based on cutoff value
	lobe_ratio -- The flux ratio between the two brightest lobes
	position_angle -- Position angle between the two brightest lobes 
	error - Array containing difference in [RA,DEC] between the 80% cutoff value and the maximum flux

	If plot=True, produces the plots of the best orientation and the Flux vs Orientation as well

	'''

    wcs = pw.WCS(hdulist[0].header)

    data_array = extr_array(False,
                            fitsim,
                            ra,
                            dec,
                            s=s,
                            head=head,
                            hdulist=hdulist)

    # use a radius for the line that is the semimajor axis,
    # but with 2 pixels more added to the radius
    # to make sure we do capture the whole source
    radius = Maj / 60. * 40.  #arcsec -- > arcmin --> image units
    radius = int(radius) + 2  # is chosen arbitrarily

    # in the P173+55 1 arcmin = 40 image units
    # this is true for field in FieldNames.

    # check if there are no NaNs in the cutout image, if there are then make smaller cutout
    if True in (np.isnan(data_array)):
        if s < (2 / 60.):
            print "No hope left for this source "
            return i, 0.0, 100.5, 100.5, 'no_hope', 100.5, 100.5

        elif s == (2 / 60.):
            print "Nan in the cutout image AGAIN ", head['OBJECT'], ' i = ', i
            try:
                return find_orientationMG(i,
                                          fitsim,
                                          ra,
                                          dec,
                                          Maj,
                                          Min,
                                          s=(Maj * 2. / 60. / 60.),
                                          plot=plot,
                                          head=head,
                                          hdulist=hdulist)
            except RuntimeError:
                print "No hope left for this source, "
                return i, 0.0, 100.5, 100.5, 'no_hope', 100.5, 100.5

        else:
            print "NaN in the cutout image: ", head['OBJECT'], ' i = ', i
            try:
                return find_orientationMG(i,
                                          fitsim,
                                          ra,
                                          dec,
                                          Maj,
                                          Min,
                                          s=(2 / 60.),
                                          plot=plot,
                                          head=head,
                                          hdulist=hdulist)
            except RuntimeError:
                print "No hope left for this source, "
                return i, 0.0, 100.5, 100.5, 'no_hope', 100.5, 100.5

    # find the cutoff value, dependent on the distance
    cutoff = 2 * np.arctan(Min / Maj) * 180 / np.pi  # convert rad to deg

    # find the max orientation of the flux along a line and '80% flux error'
    (max_angle, err_orientations, min_orientation, max_orientation,
     classification, positions) = flux_along_line(data_array, radius, cutoff,
                                                  hdulist)

    # then find the amount of maxima and the lobe_ratio
    position_angle, lobe_ratio, lobe1, lobe2, indx_extrema = find_lobes(
        data_array, positions, max_angle, hdulist)

    # to make sure the lobes aren't switched
    if (min_orientation < 90 and max_orientation > 90):
        max_orientation -= 180
    elif (min_orientation > 90 and max_orientation < 90):
        min_orientation -= 180

    original_position_angle = position_angle

    try:
        lobe1_min, lobe2_min = find_lobes(data_array, positions,
                                          min_orientation, hdulist)[2:4]
        error = lobe1 - lobe1_min
    except ValueError:
        print 'tja1'
    try:
        lobe1_min, lobe2_min = find_lobes(data_array, positions,
                                          max_orientation, hdulist)[2:4]
        error = lobe1 - lobe1_min
    except ValueError:
        print 'tja2'

    xcenter, ycenter = positions['xcenter'], positions['ycenter']
    x0, y0 = positions['x0'], positions['y0']
    x1, y1 = positions['x1'], positions['y1']
    num = 1000

    if plot:
        # the plot of the rotated source and the flux along the line
        x0_rot, y0_rot = rotate_point((xcenter, ycenter), (x0, y0), max_angle)
        x1_rot, y1_rot = rotate_point((xcenter, ycenter), (x1, y1), max_angle)
        x_rot, y_rot = np.linspace(x0_rot, x1_rot,
                                   num), np.linspace(y0_rot, y1_rot, num)
        zi = map_coordinates(data_array,
                             np.vstack((y_rot, x_rot)),
                             prefilter=True)
        fig, axes = plt.subplots(nrows=2, figsize=(12, 12))
        axes[0].imshow(data_array, origin='lower')
        axes[0].plot([x0_rot, x1_rot], [y0_rot, y1_rot], 'r-', alpha=0.3)
        axes[1].plot(zi)

        # rotate line on the left side of the center with min angle
        x0_rot, y0_rot = rotate_point((xcenter, ycenter), (x0, y0),
                                      min_orientation)
        # rotate line on the right side of the center with min angle
        x1_rot, y1_rot = rotate_point((xcenter, ycenter), (x1, y1),
                                      min_orientation)
        x_rot, y_rot = np.linspace(x0_rot, x1_rot,
                                   num), np.linspace(y0_rot, y1_rot, num)
        axes[0].plot([x0_rot, x1_rot], [y0_rot, y1_rot], 'b-', alpha=0.3)

        # rotate line on the left side of the center with max angle
        x0_rot, y0_rot = rotate_point((xcenter, ycenter), (x0, y0),
                                      max_orientation)
        # rotate line on the right side of the center with max angle
        x1_rot, y1_rot = rotate_point((xcenter, ycenter), (x1, y1),
                                      max_orientation)
        x_rot, y_rot = np.linspace(x0_rot, x1_rot,
                                   num), np.linspace(y0_rot, y1_rot, num)
        axes[0].plot([x0_rot, x1_rot], [y0_rot, y1_rot], 'b-', alpha=0.3)

        axes[0].set_xlabel('pixels')
        axes[0].set_ylabel('pixels')
        axes[1].set_ylabel('Flux (arbitrary units)')
        axes[1].set_xlabel('points')
        plt.suptitle('Field: ' + head['OBJECT'] + ' | Source ' + str(i) +
                     '\n extrema: ' + str(indx_extrema) +
                     '\n lobe ratio: %.3f' % lobe_ratio +
                     ' | Position Angle: %.3f' % position_angle +
                     ' Err orientation: %.1f' % len(err_orientations))

        plt.show()
        plt.clf()
        plt.close()

    return i, max_angle, len(err_orientations), len(
        indx_extrema[0]), classification, lobe_ratio, position_angle, error
示例#14
0
def find_orientationNN(i,
                       fitsim,
                       ra,
                       dec,
                       nn_ra,
                       nn_dec,
                       nn_dist,
                       maj,
                       s=(3 / 60.),
                       plot=False,
                       head=None,
                       hdulist=None):
    '''	
	Finds the orientation of NN

	To run this function for all sources, use setup_find_orientation_NN() instead.

	Arguments: 
	i -- the new_Index of the source
	fitsim -- the postage created earlier 
	ra, dec -- the ra and dec of the source
	maj -- the major axis of the source 
	s: the width of the image, default 3 arcmin, because it has to be a tiny bit
		lower than the postage created earlier (width 4 arcmin) or NaNs will appear in the image
	head and hdulist, the header and hdulist if a postage hasn't been created before.
	(This is so it doesn't open every time in the loop but is opened before the loop.)

	Returns: 
	i -- new_Index of the source
	max_angle -- Angle of the flux line for which flux is maximized.
	len(err_orientations) -- Amount of degrees spread in the angle of the flux line
	len(indx_extrema[0]) -- Amount of extrema along the line
	classification -- 'Large' or 'Small' error, based on cutoff value
	lobe_ratio -- The flux ratio between the two brightest lobes
	position_angle -- Position angle between the two brightest lobes 
	error - Array containing difference in [RA,DEC] between the 80% cutoff value and the maximum flux

	If plot=True, produces the plots of the best orientation and the Flux vs Orientation as well

	'''

    wcs = pw.WCS(hdulist[0].header)

    data_array = extr_array(True,
                            fitsim,
                            ra,
                            dec,
                            nn_ra,
                            nn_dec,
                            nn_dist,
                            maj,
                            s=s,
                            head=head,
                            hdulist=hdulist)

    postfits = './temp.fits'
    print('Creating temporary ./temp.fits file')
    postage(True, fitsim, postfits, ra, dec, s=s, nn_ra=nn_ra, nn_dec=nn_dec)

    # use a radius for the line that is the NN distance,
    # but with 4 pixels more added to the radius
    # to make sure we do capture the whole source
    radius = nn_dist / 2. * 40  #arcmin --> image units
    radius = int(radius) + 4  # is chosen arbitrarily

    # in the P173+55 1 arcmin = 40 image units
    # this is true for field in FieldNames.

    # check if there are no NaNs in the cutout image,
    # if there are then make smaller cutout
    if True in (np.isnan(data_array)):
        if s < (2 / 60.):
            print "No hope left for this source "
            return i, 0.0, 100.5, 100.5, 'no_hope', 100.5, 100.5

        elif s == (2 / 60.):
            print "Nan in the cutout image AGAIN ", head['OBJECT'], ' i = ', i
            try:
                return find_orientationNN(i,
                                          fitsim,
                                          ra,
                                          dec,
                                          nn_ra,
                                          nn_dec,
                                          nn_dist,
                                          maj,
                                          s=(2 * radius + 2) / 40. / 60.,
                                          plot=plot,
                                          head=head,
                                          hdulist=hdulist)
            except RuntimeError:
                print "No hope left for this source, "
                return i, 0.0, 100.5, 100.5, 'no_hope', 100.5, 100.5

        else:
            print "NaN in the cutout image: ", head['OBJECT'], ' i = ', i
            try:
                return find_orientationNN(i,
                                          fitsim,
                                          ra,
                                          dec,
                                          nn_ra,
                                          nn_dec,
                                          nn_dist,
                                          maj,
                                          s=(2 * radius + 4) / 40. / 60.,
                                          plot=plot,
                                          head=head,
                                          hdulist=hdulist)
            except RuntimeError:
                print "No hope left for this source, "
                return i, 0.0, 100.5, 100.5, 'no_hope', 100.5, 100.5

    # find the cutoff value, dependent on the distance, should think about whether i want to use Maj
    cutoff = 2 * np.arctan(
        (maj / 60.) / nn_dist) * 180 / np.pi  # convert rad to deg

    # find the max orientation of the flux along a line and '80% flux error'
    (max_angle, err_orientations, min_orientation, max_orientation,
     classification, positions) = flux_along_line(data_array, radius, cutoff,
                                                  hdulist)

    # then find the amount of maxima and the lobe_ratio
    position_angle, lobe_ratio, lobe1, lobe2, indx_extrema = find_lobes(
        data_array, positions, max_angle, hdulist)

    # to make sure the lobes aren't switched
    if (min_orientation < 90 and max_orientation > 90):
        max_orientation -= 180
    elif (min_orientation > 90 and max_orientation < 90):
        min_orientation -= 180

    original_position_angle = position_angle

    try:
        lobe1_min, lobe2_min = find_lobes(data_array, positions,
                                          min_orientation, hdulist)[2:4]
        error = lobe1 - lobe1_min
    except ValueError:
        print 'tja1'
    try:
        lobe1_min, lobe2_min = find_lobes(data_array, positions,
                                          max_orientation, hdulist)[2:4]
        error = lobe1 - lobe1_min
    except ValueError:
        print 'tja2'

    xcenter, ycenter = positions['xcenter'], positions['ycenter']
    x0, y0 = positions['x0'], positions['y0']
    x1, y1 = positions['x1'], positions['y1']
    num = 1000

    if plot:
        # the plot of the rotated source and the flux along the line
        x0_rot, y0_rot = rotate_point((xcenter, ycenter), (x0, y0), max_angle)
        x1_rot, y1_rot = rotate_point((xcenter, ycenter), (x1, y1), max_angle)
        x_rot, y_rot = np.linspace(x0_rot, x1_rot,
                                   num), np.linspace(y0_rot, y1_rot, num)
        zi = map_coordinates(data_array,
                             np.vstack((y_rot, x_rot)),
                             prefilter=True)
        fig, axes = plt.subplots(nrows=2, figsize=(12, 12))

        from astropy.wcs import WCS
        from astropy.io import fits

        hdu = fits.open(postfits)[0]
        wcs = WCS(hdu.header)
        ax1 = plt.subplot(211, projection=wcs)
        ax1.imshow(hdu.data, origin='lower')

        print('Removing temporary ./temp.fits file')
        os.system('rm ./temp.fits')

        ax2 = plt.subplot(212)
        ax2.imshow(data_array, origin='lower')
        ax1.plot([x0_rot, x1_rot], [y0_rot, y1_rot], 'r-', alpha=0.3)
        ax2.plot(zi)

        # rotate line on the left side of the center with min angle
        x0_rot, y0_rot = rotate_point((xcenter, ycenter), (x0, y0),
                                      min_orientation)
        # rotate line on the right side of the center with min angle
        x1_rot, y1_rot = rotate_point((xcenter, ycenter), (x1, y1),
                                      min_orientation)
        x_rot, y_rot = np.linspace(x0_rot, x1_rot,
                                   num), np.linspace(y0_rot, y1_rot, num)
        ax1.plot([x0_rot, x1_rot], [y0_rot, y1_rot], 'b-', alpha=0.3)

        # rotate line on the left side of the center with max angle
        x0_rot, y0_rot = rotate_point((xcenter, ycenter), (x0, y0),
                                      max_orientation)
        # rotate line on the right side of the center with max angle
        x1_rot, y1_rot = rotate_point((xcenter, ycenter), (x1, y1),
                                      max_orientation)
        x_rot, y_rot = np.linspace(x0_rot, x1_rot,
                                   num), np.linspace(y0_rot, y1_rot, num)
        ax1.plot([x0_rot, x1_rot], [y0_rot, y1_rot], 'b-', alpha=0.3)

        ax1.set_xlabel('pixels')
        ax1.set_ylabel('pixels')
        ax2.set_ylabel('Flux (arbitrary units)')
        ax2.set_xlabel('points')
        plt.suptitle('Field: ' + head['OBJECT'] + ' | Source ' + str(i) +
                     '\n extrema: ' + str(indx_extrema) +
                     ' | nn_dist: %.3f' % nn_dist +
                     '\n lobe ratio: %.3f' % lobe_ratio +
                     ' | Position Angle: %.3f' % position_angle +
                     ' Err orientation: %.1f' % len(err_orientations))

        # plt.savefig('./'+head['OBJECT']+'src_'+str(i)+'.png')
        plt.show()
        plt.clf()
        plt.close()

    return i, max_angle, len(err_orientations), len(
        indx_extrema[0]), classification, lobe_ratio, position_angle, error
示例#15
0
def flux_along_line(data_array, radius, cutoff, hdulist):
    """
	Find the Position angle with the flux along a line method (Better: Gaussian fit.)
	Position angle is defined as the angle between the brightest lobes.

	Arguments:
	data_array -- The Numpy array that contains the source
	radius -- The radius of the line in pixel units.
	cutoff -- The cutoff value for a 'Large' or 'Small' error.
	hdulist -- Necessary to get the coordinates

	Returns:
	position_angle -- The position angle
	err_orientations -- The angles that produce 80% of the flux
	classification -- 'Large' or 'Small' error
	max_angle -- The orientation that produces the maximal flux (assumes source
																is symmetric...)
	lobe_ratio -- Flux ratio between the lobes.

	"""

    # Parse the WCS keywords in the primary HDU
    wcs = pw.WCS(hdulist[0].header)

    #the center of the image is at the halfway point -1 for using array-index
    xcenter = np.shape(data_array)[0] / 2 - 1  # pixel coordinates
    ycenter = np.shape(data_array)[1] / 2 - 1  # pixel coordinates

    # define the start and end points of the line with 'num' points and radius = radius
    x0, y0 = xcenter - radius, ycenter
    x1, y1 = xcenter + radius, ycenter
    num = 1000

    # the final orientation will be max_angle
    max_angle = 0
    max_value = 0
    # flux values for 0 to 179 degrees of rotation (which is also convenietly their index)
    all_values = []
    for angle in range(0, 180):
        # rotate line on the left side of the center
        x0_rot, y0_rot = rotate_point((xcenter, ycenter), (x0, y0), angle)
        # rotate line on the right side of the center
        x1_rot, y1_rot = rotate_point((xcenter, ycenter), (x1, y1), angle)
        # the rotated line
        x_rot, y_rot = np.linspace(x0_rot, x1_rot,
                                   num), np.linspace(y0_rot, y1_rot, num)
        # extract the values along the line,
        zi = map_coordinates(data_array,
                             np.vstack((y_rot, x_rot)),
                             prefilter=True)
        # calc the mean flux
        meanie = np.sum(zi)
        if meanie > max_value:
            max_value = meanie
            max_angle = angle
        all_values.append(meanie)

    # calculate all orientiations for which the average flux lies within
    # 80 per cent of the peak average flux
    err_orientations = np.where(all_values > (0.8 * max_value))[0]
    all_cutoff_values = np.asarray(all_values)[err_orientations]
    minima = np.argsort(all_cutoff_values)

    minimum1 = minima[0]
    minimum2 = minima[1]

    # Orientation can vary between the two flux minima.
    min_orientation = err_orientations[minimum1]
    max_orientation = err_orientations[minimum2]

    if len(err_orientations) > cutoff:
        classification = 'Large err'
    else:
        classification = 'Small err'

    positions = dict()
    positions['xcenter'], positions['ycenter'] = xcenter, ycenter
    positions['x0'], positions['y0'] = x0, y0
    positions['x1'], positions['y1'] = x1, y1

    return (max_angle, err_orientations, min_orientation, max_orientation,
            classification, positions)
示例#16
0
def find_lobes(data_array, positions, angle, hdulist, num=1000):
    # then find the amount of maxima and the lobe_ratio

    xcenter, ycenter = positions['xcenter'], positions['ycenter']
    x0, y0 = positions['x0'], positions['y0']
    x1, y1 = positions['x1'], positions['y1']

    # rotate line on the left side of the center
    x0_rot, y0_rot = rotate_point((xcenter, ycenter), (x0, y0), angle)
    # rotate line on the right side of the center
    x1_rot, y1_rot = rotate_point((xcenter, ycenter), (x1, y1), angle)
    x_rot, y_rot = np.linspace(x0_rot, x1_rot,
                               num), np.linspace(y0_rot, y1_rot, num)

    zi = map_coordinates(data_array, np.vstack((y_rot, x_rot)), prefilter=True)
    # find the local maxima in the flux along the line
    indx_extrema = argrelextrema(zi, np.greater)

    if zi[0] > zi[1]:
        # then there is a maximum (outside of the line range) , namely the first point
        new_indx_extrema = (np.append(indx_extrema, 0), )
        del indx_extrema
        indx_extrema = new_indx_extrema
        del new_indx_extrema

    if zi[len(zi) - 1] > zi[len(zi) - 2]:
        # then there is a maximum (outside of the line range), namely the last point
        new_indx_extrema = (np.append(indx_extrema, len(zi) - 1), )
        del indx_extrema
        indx_extrema = new_indx_extrema
        del new_indx_extrema

    amount_of_maxima = len(indx_extrema[0])
    # calculate the flux ratio of the lobes
    lobe_ratio_bool = False
    lobe_ratio = 0.0  # in case there is only 1 maximum
    position_angle = 1000.0  # in case there is only 1 maximum
    wcs = pw.WCS(hdulist[0].header)
    if amount_of_maxima > 1:
        if amount_of_maxima == 2:
            lobe_ratio = (zi[indx_extrema][0] / zi[indx_extrema][1])
            # calculate the position angle
            lobe1 = np.array(
                [[x_rot[indx_extrema][0], y_rot[indx_extrema][0], 0, 0]])
            lobe2 = np.array(
                [[x_rot[indx_extrema][1], y_rot[indx_extrema][1], 0, 0]])
            lobe1 = wcs.wcs_pix2sky(lobe1, 1)
            lobe2 = wcs.wcs_pix2sky(lobe2, 1)
            position_angle = PositionAngle(lobe1[0][0], lobe1[0][1],
                                           lobe2[0][0], lobe2[0][1])
            if position_angle < 0:
                position_angle += 180.

        else:
            # more maxima, so the lobe_ratio is defined as the ratio between the brightest lobes
            indx_maximum_extrema = np.flip(
                np.argsort(zi[indx_extrema]),
                0)[:2]  #argsort sorts ascending so flip makes it descending
            indx_maximum_extrema = indx_extrema[0][indx_maximum_extrema]
            lobe_ratio = (zi[indx_maximum_extrema[0]] /
                          zi[indx_maximum_extrema][1])

            #find the RA and DEC of the two brightest lobes
            lobe1 = np.array([[
                x_rot[indx_maximum_extrema][0], y_rot[indx_maximum_extrema][0],
                0, 0
            ]])
            lobe2 = np.array([[
                x_rot[indx_maximum_extrema][1], y_rot[indx_maximum_extrema][1],
                0, 0
            ]])
            lobe1 = wcs.wcs_pix2sky(lobe1, 1)
            lobe2 = wcs.wcs_pix2sky(lobe2, 1)
            # then calculate the position angle
            position_angle = PositionAngle(lobe1[0][0], lobe1[0][1],
                                           lobe2[0][0], lobe2[0][1])
            if position_angle < 0:
                position_angle += 180.
    else:
        raise ValueError("This function only works on sources with >1 maximum")

    lobe1 = lobe1[0][:2]
    lobe2 = lobe2[0][:2]

    return position_angle, lobe_ratio, lobe1, lobe2, indx_extrema
示例#17
0
    def move_backward(self, game_map: Map, distance: float):
        vector = utils.rotate_point((0, distance), self.angle)
        self.x += vector[0]
        self.y += vector[1]

        self.resolve_collisions(game_map)
def main():
    args = parser.parse_args()
    env_name = args.env_name
    input_file = args.input_file
    checkpoint_file = args.resume
    test_only = args.test_only
    seed = args.seed
    no_gpu = args.no_gpu
    dir_name = args.dir_name
    visualize = args.visualize
    n_test_steps = args.n_test_steps
    log_perf_file = args.log_perf_file
    min_distance = args.min_distance
    max_distance = args.max_distance
    threshold = args.threshold
    y_range = args.y_range
    n_training_samples = args.n_training_samples
    start_index = args.start_index
    exp_name = args.exp_name
    batch_size = args.batch_size
    learning_rate = args.learning_rate
    n_epochs = args.n_epochs

    # Specific to Humanoid - Pybullet
    if visualize and env_name == 'HumanoidBulletEnv-v0':
        spec = gym.envs.registry.env_specs[env_name]
        class_ = gym.envs.registration.load(spec._entry_point)
        env = class_(**{**spec._kwargs}, **{'render': True})
    else:
        env = gym.make(env_name)

    set_global_seed(seed)
    env.seed(seed)

    input_shape = env.observation_space.shape[0] + 3
    output_shape = env.action_space.shape[0]
    net = Policy(input_shape, output_shape)
    if not no_gpu:
        net = net.cuda()
    optimizer = Adam(net.parameters(), lr=learning_rate)
    criterion = nn.MSELoss()
    epochs = 0

    if checkpoint_file:
        epochs, net, optimizer = load_checkpoint(checkpoint_file, net,
                                                 optimizer)

    if not checkpoint_file and test_only:
        print('ERROR: You have not entered a checkpoint file.')
        return

    if not test_only:
        if not os.path.isfile(input_file):
            raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT),
                                    input_file)

        training_file = open(input_file, 'rb')
        old_states = []
        norms = []
        goals = []
        actions = []
        n_samples = -1

        while n_samples - start_index < n_training_samples:
            try:
                old_s, old_g, new_s, new_g, action = pickle.load(training_file)
                n_samples += 1

                if n_samples < start_index:
                    continue

                old_states.append(np.squeeze(np.array(old_s)))
                norms.append(
                    find_norm(np.squeeze(np.array(new_g) - np.array(old_g))))
                goals.append(
                    preprocess_goal(
                        np.squeeze(np.array(new_g) - np.array(old_g))))
                actions.append(np.squeeze(np.array(action)))
            except (EOFError, ValueError):
                break

        old_states = np.array(old_states)
        norms = np.array(norms)
        goals = np.array(goals)
        actions = np.array(actions)

        normalization_factors = {
            'state': [old_states.mean(axis=0),
                      old_states.std(axis=0)],
            'distance_per_step': [norms.mean(axis=0),
                                  norms.std(axis=0)]
        }
        n_file = open(env_name + '_normalization_factors.pkl', 'wb')
        pickle.dump(normalization_factors, n_file)
        n_file.close()

        old_states = normalize(old_states,
                               env_name + '_normalization_factors.pkl',
                               'state')

        # Summary writer for tensorboardX
        writer = {}
        writer['writer'] = SummaryWriter()

        # Split data into training and validation
        indices = np.arange(old_states.shape[0])
        shuffle(indices)
        val_data = np.concatenate(
            (old_states[indices[:int(old_states.shape[0] / 5)]],
             goals[indices[:int(old_states.shape[0] / 5)]]),
            axis=1)
        val_labels = actions[indices[:int(old_states.shape[0] / 5)]]
        training_data = np.concatenate(
            (old_states[indices[int(old_states.shape[0] / 5):]],
             goals[indices[int(old_states.shape[0] / 5):]]),
            axis=1)
        training_labels = actions[indices[int(old_states.shape[0] / 5):]]
        del old_states, norms, goals, actions, indices

        checkpoint_dir = os.path.join(env_name, 'naive_gcp_checkpoints')
        if dir_name:
            checkpoint_dir = os.path.join(checkpoint_dir, dir_name)
        prepare_dir(checkpoint_dir)

        for e in range(epochs, n_epochs):
            ep_loss = []
            # Train network
            for i in range(int(len(training_data) / batch_size) + 1):
                inp = training_data[batch_size * i:batch_size * (i + 1)]
                out = net(
                    convert_to_variable(inp, grad=False, gpu=(not no_gpu)))
                target = training_labels[batch_size * i:batch_size * (i + 1)]
                target = convert_to_variable(np.array(target),
                                             grad=False,
                                             gpu=(not no_gpu))
                loss = criterion(out, target)
                optimizer.zero_grad()
                ep_loss.append(loss.item())
                loss.backward()
                optimizer.step()

            # Validation
            val_loss = []
            for i in range(int(len(val_data) / batch_size) + 1):
                inp = val_data[batch_size * i:batch_size * (i + 1)]
                out = net(
                    convert_to_variable(inp, grad=False, gpu=(not no_gpu)))
                target = val_labels[batch_size * i:batch_size * (i + 1)]
                target = convert_to_variable(np.array(target),
                                             grad=False,
                                             gpu=(not no_gpu))
                loss = criterion(out, target)
                val_loss.append(loss.item())

            writer['iter'] = e + 1
            writer['writer'].add_scalar('data/val_loss',
                                        np.array(val_loss).mean(), e + 1)
            writer['writer'].add_scalar('data/training_loss',
                                        np.array(ep_loss).mean(), e + 1)

            save_checkpoint(
                {
                    'epochs': (e + 1),
                    'state_dict': net.state_dict(),
                    'optimizer': optimizer.state_dict()
                },
                filename=os.path.join(checkpoint_dir,
                                      str(e + 1) + '.pth.tar'))

            print('Epoch:', e + 1)
            print('Training loss:', np.array(ep_loss).mean())
            print('Val loss:', np.array(val_loss).mean())
            print('')

    # Now we use the trained net to see how the agent reaches a different
    # waypoint from the current one.

    success = 0
    failure = 0

    closest_distances = []
    time_to_closest_distances = []

    f = open(env_name + '_normalization_factors.pkl', 'rb')
    normalization_factors = pickle.load(f)
    average_distance = normalization_factors['distance_per_step'][0]

    for i in range(n_test_steps):
        state = env.reset()
        if env_name == 'Ant-v2':
            obs = env.unwrapped.get_body_com('torso')
            target_obs = [
                obs[0] + np.random.uniform(min_distance, max_distance),
                obs[1] + np.random.uniform(-y_range, y_range), obs[2]
            ]
            target_obs = rotate_point(target_obs, env.unwrapped.angle)
            env.unwrapped.sim.model.body_pos[-1] = target_obs
        elif env_name == 'MinitaurBulletEnv-v0':
            obs = env.unwrapped.get_minitaur_position()
            target_obs = [
                obs[0] + np.random.uniform(min_distance, max_distance),
                obs[1] + np.random.uniform(-y_range, y_range), obs[2]
            ]
            target_obs = rotate_point(
                target_obs, env.unwrapped.get_minitaur_rotation_angle())
            env.unwrapped.set_target_position(target_obs)
        elif env_name == 'HumanoidBulletEnv-v0':
            obs = env.unwrapped.robot.get_robot_position()
            target_obs = [
                obs[0] + np.random.uniform(min_distance, max_distance),
                obs[1] + np.random.uniform(-y_range, y_range), obs[2]
            ]
            target_obs = rotate_point(target_obs, env.unwrapped.robot.yaw)
            env.unwrapped.robot.set_target_position(target_obs[0],
                                                    target_obs[1])
        steps = 0
        done = False
        closest_d = distance(obs, target_obs)
        closest_t = 0
        while distance(obs, target_obs) > threshold and not done:
            goal = preprocess_goal(target_obs - obs)
            state = normalize(np.array(state),
                              env_name + '_normalization_factors.pkl')
            inp = np.concatenate([np.squeeze(state), goal])
            inp = convert_to_variable(inp, grad=False, gpu=(not no_gpu))
            action = net(inp).cpu().detach().numpy()
            state, _, done, _ = env.step(action)
            steps += 1
            if env_name == 'MinitaurBulletEnv-v0':
                obs = env.unwrapped.get_minitaur_position()
            elif env_name == 'HumanoidBulletEnv-v0':
                obs = env.unwrapped.robot.get_robot_position()
            if distance(obs, target_obs) < closest_d:
                closest_d = distance(obs, target_obs)
                closest_t = steps
            if visualize:
                env.render()

        if distance(obs, target_obs) <= threshold:
            success += 1
        elif done:
            failure += 1

        if visualize:
            time.sleep(2)

        closest_distances.append(closest_d)
        time_to_closest_distances.append(closest_t)

    print('Successes: %d, Failures: %d, '
          'Closest distance: %f, Time to closest distance: %d' %
          (success, failure, np.mean(closest_distances),
           np.mean(time_to_closest_distances)))

    if log_perf_file:
        f = open(log_perf_file, 'a+')
        f.write(exp_name + ':Seed-' + str(seed) + ',Success-' + str(success) +
                ',Failure-' + str(failure) + ',Closest_distance-' +
                str(closest_distances) + ',Time_to_closest_distance-' +
                str(time_to_closest_distances) + '\n')
        f.close()