Example #1
0
 def _create_star(self, star_number, rows):
     star = Star(self)
     star_width, star_height = star.rect.size
     star.x = star_width + 2 * star_width * star_number
     star.rect.x = star.x
     star.rect.y = star_height + 2 * star_height * rows
     self.stars.add(star)
Example #2
0
 def _create_stars(self, star_number, row_number):
     star = Star(self)
     star_width, star_height = star.rect.x, star.rect.y
     star.x = star_width + star_width * star_number
     star.rect.x = star.x
     star.rect.y = star.rect.height + star.rect.height * row_number
     self.stars.add(star)
Example #3
0
 def _create_star(self, star_number, row_number):
     star = Star(self)
     star_width, star_height = star.rect.size
     star.x = star_width + 40*star_width*star_number
     star.rect.x = star.x + 10
     star.rect.y = (5*star.rect.height + 40*star.rect.height*row_number)
     self.stars.add(star)
Example #4
0
def create_star(ai_settings, screen, stars, star_number, row_number):
    star = Star(ai_settings, screen)
    star_width = star.rect.width
    star.x = star_width + 2 * star_width * star_number
    star.rect.x = star.x
    star.rect.y = star.rect.height + 2 * star.rect.height * row_number\
    stars.add(star)
Example #5
0
class Picture:
    def __init__(self, width, height):
        self.mWidth = width
        self.mHeight = height
        self.mSky = Sky(width, height)
        self.mPlanet1 = Planet(200, 210, 215)
        self.mPlanet1.setColor(204, 204, 204)
        self.mMountain1 = Mountain(width, height)
        self.mCrater1 = Crater(40, 130, 100, 100)
        self.mCrater2 = Crater(35, 120, 50, 50)
        self.mCrater3 = Crater(90, 10, 90, 90)
        self.mCrater4 = Crater(250, 90, 100, 100)
        self.mCrack1 = Crack(290, 250)
        self.mCrack2 = Crack(285, 240)
        self.mHill1 = Hill(175, 400)
        self.mHill2 = Hill(300, 380)
        self.mHill3 = Hill(500, 450)
        self.mStar = Star(width, height)
        return

    def draw(self, surface):
        self.mSky.draw(surface)
        self.mPlanet1.draw(surface)
        self.mMountain1.draw(surface)
        self.mCrater1.draw(surface)
        self.mCrater2.draw(surface)
        self.mCrater3.draw(surface)
        self.mCrater4.draw(surface)
        self.mCrack1.draw(surface)
        self.mCrack2.draw(surface)
        self.mHill1.draw(surface)
        self.mHill2.draw(surface)
        self.mHill3.draw(surface)
        self.mStar.draw(surface)
        return
Example #6
0
    def add_new_sprite(self, y_pos):
        LIST_OF_OBSTACLE_TYPES = [
            circle_obstacle.CircleObstacle, plus_obstacle.PlusObstacle
        ]

        # If the last sprite is an obstacle
        if issubclass(type(self.last_sprite), BaseObstacle):
            # Randomize whatever should be another obstacle or a color switcher (1 to 3 chance)
            if random.randint(0, 2) == 0:
                # Choose a random obstacle
                obstacle_type = random.choice(LIST_OF_OBSTACLE_TYPES)

                self.last_sprite = obstacle_type(
                    self.screen, y_pos - obstacle_type.OBSTACLE_SIZE)
                if utils.random_bool():  # Randomize if a star should be drawn
                    self.map_sprites.add(
                        Star(self.screen, self.last_sprite.position_for_star(),
                             self.score.increase))
            else:
                # Add a color switcher
                self.last_sprite = ColorSwitcher(
                    self.screen, y_pos - ColorSwitcher.SWITCHER_BORDER -
                    ColorSwitcher.SWITCHER_DIAMETER)
        else:
            # Choose a random obstacle
            obstacle_type = random.choice(LIST_OF_OBSTACLE_TYPES)

            self.last_sprite = obstacle_type(
                self.screen, y_pos - obstacle_type.OBSTACLE_SIZE)
            if utils.random_bool():  # Randomize if a star should be drawn
                self.map_sprites.add(
                    Star(self.screen, self.last_sprite.position_for_star(),
                         self.score.increase))
Example #7
0
    def __init__(self,
                 star,
                 moment=2016.3,
                 instrument='LDSS3C',
                 npixels=500,
                 **starkw):
        '''produce a finder chart for a given star, at a particular moment
				star = either a star object, or the name of star for Simbad
						(**starkw will be passed to the star creation,
						 if you need custom RA, DEC, proper motions)
				moment = for what epoch (e.g. 2016.3) should the chart show?
				instrument = a string, indicating basic size of the chart
				npixels = how big the image can be; ds9 needs all on screen
		'''

        if type(star) == str:
            # if star is a string, use it (and starkw) to create star object
            self.name = star
            self.star = Star(self.name, **starkw)
        else:
            # if star isn't a string, it must be a zachopy.star.Star object'''
            self.star = star
            self.name = star.name

        # keep track
        self.instrument = instrument
        self.npixels = npixels

        # define the moment this finder should represent
        self.setMoment(moment)

        # use ds9 to create the finder chart
        self.createChart()
Example #8
0
def create_star(screen, stars, star_number, row_number):
    """Create a star and place it in the row."""
    star = Star(screen)
    star.x = randint(0, 1200)
    star.rect.x = star.x
    star.rect.y = randint(0, 800)
    stars.add(star)
Example #9
0
    def _create_stars(self):
        """Create the background of stars"""
        # Make a star
        star = Star(self)

        # Calculate density of stars
        rows = int(0.01 * (1 + 0.1 * self.settings.density) *
                   self.settings.screen_height)
        columns = int(0.01 * (1 + 0.1 * self.settings.density) *
                      self.settings.screen_width)
        vertical_space = self.settings.screen_height // rows
        horizontal_space = self.settings.screen_width // columns

        # Create full background of stars
        for row in range(rows):
            for column in range(columns):
                star = Star(self)

                # Introduce randomness element
                rand_x = randint((-horizontal_space // 2),
                                 (horizontal_space // 2))
                rand_y = randint((-vertical_space // 2), (vertical_space // 2))

                star.x = (horizontal_space //
                          2) + rand_x + horizontal_space * column
                star.rect.x = star.x
                star.rect.y = (vertical_space //
                               2) + rand_y + vertical_space * row
                self.stars.add(star)
Example #10
0
	def __init__(self, config, players, ais):
		self._star_names = StarNamesStack()
		self.stars = []
		for n in range(config.nb_stars):
			star = Star(
				self._star_names.pop(),
				random.randrange(config.window_width - 32) + 16,
				random.randrange(config.window_height - 32) + 16
			)
			self.stars.append(star)

			nb_planets = random.randrange(
				config.min_planets_per_star,
				config.max_planets_per_star + 1)
			for n in range(nb_planets):
				star.add_planet(
					random.randrange(config.window_width - 32) + 16,
					random.randrange(config.window_height - 32) + 16
				)

			self._scatter_planets(config, star)
			self._scatter_planets(config, star)

		self._scatter_stars(config)
		self._scatter_stars(config)

		for p in players:
			colony = self._colonize_random_planet(p)

		for ai in ais:
			colony = self._colonize_random_planet(ai)
Example #11
0
def add_star():
    star = mongo.db.stars

    data = Star.jsonify(request.form)
    star_id = star.insert(data)

    new_star = star.find_one({'_id': star_id})
    return jsonify({'result': Star.jsonify(new_star)})
Example #12
0
def create_stars(ai_settings, screen, stars):
	"""Create a star background."""
	star = Star(ai_settings, screen)
	for star_number in range(ai_settings.star_number):
		star = Star(ai_settings, screen)
		star.rect.x = randint(0, ai_settings.screen_width)
		star.rect.y = randint(0, ai_settings.screen_height)
		stars.add(star)
Example #13
0
 def _create_star(self, star_number):
     #Create a star and place it in the row.
     star = Star(self)
     star_width, star_height = star.rect.size
     star.x = randint(0, self.settings.screen_width - star_width)
     star.rect.x = star.x
     star.rect.y = randint(0, self.settings.screen_height - star_height)
     self.stars.add(star)
def create_star(s_settings, screen, stars, star_number, row_number):
    """Create an stars and place it in the row."""
    star = Star(s_settings, screen)
    star_width = star.rect.width
    star.x = star_width + 2 * star_width * star_number
    star.rect.x = star.x
    star.rect.y = star.rect.height + 2 * star.rect.height * row_number
    stars.add(star)
Example #15
0
 def _create_star(self, star_number, row_number):
     """Create an star and place it in the row."""
     star = Star(self)
     star_width, star_height = star.rect.size
     star.x = star_width + 2 * star_width * star_number
     star.rect.x = star.x
     star.rect.y = star.rect.height + 2 * star.rect.height * row_number
     self.stars.add(star)
Example #16
0
def create_star(ai_settings, screen, stars):
    '''创建一个外星人并将其放在当前行'''
    star = Star(ai_settings, screen)
    star_width = star.rect.width
    star.x = randint(0, 1200) + star_width
    star.rect.x = star.x
    star.rect.y = randint(0, 600) + star.rect.height
    stars.add(star)
def create_star(settings, screen, stars, star_number, row_number):
    """Create a star and place it in the row."""
    star = Star(settings, screen)
    star_width = star.rect.width
    star.x = star_width + 1 * star_width * star_number
    star.rect.x = star.x  # I have to multiplying by 1.5 rather than 2 because image is so big
    star.rect.y = star.rect.height + 1 * star.rect.height * row_number
    stars.add(star)
def create_star(ai_settings, screen, stars, star_number, star_row_number):
    """Создание звезды."""
    star = Star(ai_settings, screen)
    star_width = star.rect.width
    star.x = randint(star_width, ai_settings.screen_width - star_width)
    star.rect.x = star.x
    star.rect.y = star.rect.height + 20 * star.rect.height * star_row_number
    stars.add(star)
Example #19
0
def create_star(screen, stars, star_number, row_number):
    star = Star(screen)
    star_width = star.rect.width
    star.x = star_width + 4 * star_width * star_number
    random_x = randint(-30, 30)
    random_y = randint(-30, 30)
    star.rect.x = star.x + random_x
    star.rect.y = star.rect.height + 4 * star.rect.height * row_number + random_y
    stars.add(star)
Example #20
0
 def _create_star(self, star_number, row_number):
     """Creating star and its placement"""
     star = Star(self)
     star_width, star_height = star.rect.size
     star.x = random.randint(-50, 50) + 5 * star_width * star_number
     star.rect.x = star.x
     star.rect.y = (random.randint(-50, 50) +
                    5 * star.rect.height * row_number)  # noqa
     self.stars.add(star)
def create_stars(settings, screen, stars):
    for index in range(30):
        star = Star(settings, screen)
        x = randint(0, settings.screen_width)
        y = randint(0, settings.screen_height)
        star.x = x
        star.rect.x = x
        star.rect.y = y
        stars.add(star)
Example #22
0
    def _create_star(self, row_number, max_number):
        star = Star(self)
        star_width, star_height = star.rect.size
        star_number = randint(0, max_number)

        star.x = star_width + 2 * star_width * star_number
        star.rect.x = star.x
        star.rect.y = star.rect.height + 2 * star.rect.height * row_number
        self.stars.add(star)
def create_star(screen, stars, star_number, row_number):
	"""Create an alien and place it in the row."""
	star = Star(screen)
	star_width = star.rect.width
	random_number = randint(-15, 15)
	star.x = star_width + random_number * star_width * star_number
	star.rect.x = star.x
	star.rect.y = star.rect.height + random_number * star.rect.height * row_number
	stars.add(star)
def create_star(ai_settings, screen, stars, star_number, row_number):
    """Create a star and place it in the row."""
    star = Star(ai_settings, screen)
    star_width = star.rect.width
    star.x = (star_width * randint(-10, 10)) + 2 * star_width * star_number
    star.rect.x = star.x
    star.rect.y = (star.rect.height *
                   randint(-10, 10)) + 2 * star.rect.height * row_number
    stars.add(star)
Example #25
0
 def _create_star(self, star_number, row_number):
     # Create an star and place it in the row.
     star = Star(self)
     star_width, star_height = star.rect.size
     star.x = star_width + 2 * star_width * star_number
     star.rect.x = star.x + randint(-30, 30)
     star.rect.y = star.rect.height + 2 * star.rect.height * row_number + randint(
         -30, 30)
     self.stars.add(star)
Example #26
0
def create_star(game_set, screen, stars, star_x, star_y):
    """Create a single star and add it to the group of stars with random position"""
    star = Star(game_set, screen)
    star_width = star.rect.width
    star_height = star.rect.height
    star.x = star_width * (1 + 2 * star_x)
    star.rect.x = rand_int(0, game_set.screen_width)
    star.rect.y = rand_int(0, game_set.screen_height)
    stars.add(star)
Example #27
0
def creat_star(myset, screen, stars, number_y, number_x):
    # 根据坐标画星星
    star = Star(myset, screen)
    star_width = star.rect.width
    star.x = randint(-11, 11) + 2 * star_width * number_x
    star.rect.x = star.x
    star.rect.y = randint(-11, 11) + 2 * star.rect.height * number_y
    # print(star.rect, end='\t')
    stars.add(star)
Example #28
0
def test_star_mass():
    specified = Star(0.9)
    assert specified.mass_ratio == 0.9
    masses = set()
    for i in range(0, 100):
        masses.add(Star().mass_ratio)
    assert len(masses) > 1
    assert min(masses) >= 0.6
    assert max(masses) <= 1.3
Example #29
0
 def _create_star(self, star_number, row_star):
     star = Star(self)
     star_width, star_height = star.rect.size
     #Create a line of stars
     star.x = star_width + 2 * star_width * randint(-20, star_number)
     star.rect.x = star.x
     #Create a serie of row of stars
     star.rect.y = star.rect.height + 2 * star_height * randint(
         -20, row_star)
     self.stars.add(star)
def create_star(screen, stars, star_number):
    """创建一个星星并将其放在当前行"""
    star = Star(screen)
    star_width = star.rect.width
    # star.x = star_width + 2 * star_width * star_number
    star.x = randint(0, 1000) + star_width
    star.rect.x = star.x
    # star.y = star.rect.height + 2 * star.rect.height * row_number
    star.rect.y = randint(0, 1000) + star.rect.height
    stars.add(star)
Example #31
0
def solve_all(Data, SolvePars, PlotPars, output_file):
    print '------------------------------------------------------'
    print 'Initializing ...'
    start_time = datetime.datetime.now()
    print '- Date and time: '+start_time.strftime('%d-%b-%Y, %H:%M:%S')
    print '- Star data: '+Data.star_data_fname
    print '------------------------------------------------------'
    fout = open(output_file, 'wb')
    pars = ['age', 'mass', 'logl', 'mv', 'r']
    if SolvePars.key_parameter_known == 'plx':
        pars.append('logg')
    values = ['mp', 'll1s', 'ul1s', 'll2s', 'ul2s', 'mean', 'std']
    hd = 'id'
    for par in pars:
        for value in values:
            hd += ','+par+'_'+value
    fout.write(hd+'\n')
    for star_id in Data.star_data['id']:
        print ''
        print '*'*len(star_id)
        print star_id
        print '*'*len(star_id)
        s = Star(star_id)
        s.get_data_from(Data)
        solve_one(s, SolvePars, PlotPars)
        string = "{0}".format(s.name)
        for par in pars:
            keys = ['most_probable',
                    'lower_limit_1sigma', 'upper_limit_1sigma',
                    'lower_limit_2sigma', 'upper_limit_2sigma']
            try:
                for key in keys:
                      string += ",{0:.3f}".format(getattr(s, 'yy'+par)[key])
            except:
                string += ",,,,,"
            try:
                string += ",{0:.3f},{1:.3f}".\
                          format(getattr(s, 'yy'+par)['mean'],\
                                 getattr(s, 'yy'+par)['std'])
            except:
                string += ",,"
        fout.write(string+"\n")
    fout.close()

    print ''
    print '------------------------------------------------------'
    end_time = datetime.datetime.now()
    print '- Date and time: '+end_time.strftime('%d-%b-%Y, %H:%M:%S')
    delta_t = (end_time - start_time).seconds
    hours, remainder = divmod(delta_t, 3600)
    minutes, seconds = divmod(remainder, 60)
    print '- Time elapsed: %sH %sM %sS' % (hours, minutes, seconds)
    print 'Done!'
    print '------------------------------------------------------'
    print ''
Example #32
0
	def __init__(self, 	star,
						moment=2016.3,
						instrument='LDSS3C',
						npixels=500, **starkw):

		'''produce a finder chart for a given star, at a particular moment
				star = either a star object, or the name of star for Simbad
						(**starkw will be passed to the star creation,
						 if you need custom RA, DEC, proper motions)
				moment = for what epoch (e.g. 2016.3) should the chart show?
				instrument = a string, indicating basic size of the chart
				npixels = how big the image can be; ds9 needs all on screen
		'''

		if type(star) == str:
			# if star is a string, use it (and starkw) to create star object
			self.name = star
			self.star = Star(self.name, **starkw)
		else:
			# if star isn't a string, it must be a zachopy.star.Star object'''
			self.star = star
			self.name = star.name

		# keep track
		self.instrument = instrument
		self.npixels = npixels

		# define the moment this finder should represent
		self.setMoment(moment)


		# use ds9 to create the finder chart
		self.createChart()
Example #33
0
 def __init__(self, x, y, toX, toY):
     Star.__init__(self, x, y, "red")
     self.xspeed = 0
     self.yspeed = 0
     self.fromX = x
     self.fromY = y
     self.toX = toX
     self.toY = toY
     if self.toX > self.fromX:
         self.xspeed = -1
     if self.toX < self.fromX:
         self.xspeed = 1
     if self.toY > self.fromY:
         self.yspeed = -1
     if self.toY < self.fromY:
         self.yspeed = 1
Example #34
0
def load_stars(filename):
    stars = []
    data_file = open("hip_main.dat")
    count = 0
    sys.stdout.write("Loading stars")
    for line in data_file:
        count += 1
        if count % 2000 == 0:
            sys.stdout.write(".")
            sys.stdout.flush()
        star = Star.parse(line)
        if star is not None and star.distance(0, 0, 0) < 100:
            stars.append(star)
    print ""
    data_file.close()
    sun = Star("Sol", 0, 0, 0, 255, 0, 0, 0)
    stars.append(sun)
    return stars
Example #35
0
def main():
    parser = argparse.ArgumentParser(description="Returns photometric tables of catalog stars")

    parser.add_argument('catalog',type=str,help='JSON catalog of sources.')
    parser.add_argument('-WISE',type=str,required=True,help='Directory of WISE tables')
    parser.add_argument('-2MASS',type=str,dest='MASS',required=True,help='Directory of 2MASS tables')

    args = parser.parse_args()

    # Get starlist
    print 'Loading JSON data from: %s' % args.catalog
    theList = Star.load(args.catalog)
    print '\tLoaded %i sources.' % len(theList)


    print
    print 'Getting photometry from catalogs...'
    t = star_photometry(theList)
    
    print 'Locating sources in %s' % args.MASS
    t = add_2MASS(t,theList,args.MASS)

    print 'Locating sources in %s' % args.WISE
    t = add_WISE(t,theList,args.WISE)
    
    print

    #t.write('photometry.tsv',format='ascii.tab')
    #exit()

    outfile = 'photometry_ZOMG'

    colnames = [x for x in t.colnames if 'lam' in x]
    for col in colnames:
        t[col] = [99.99 if ((x is None) or (x is 'None')) else x for x in t[col]]

    #for Roberta
    rTable = Table()
    rTable.add_columns([t[x] for x in ['ID','Gal']])
    for col in ['U','B','V','R','I','J','H','K',
                '3.6','4.5','5.8','8.0',
                'W1','W2','W3','W4',
                'F_U_Jy','F_B_Jy','F_V_Jy','F_R_Jy','F_I_Jy',
                'F_J_Jy','F_H_Jy','F_K_Jy',
                'F_3.6_Jy','F_4.5_Jy','F_5.8_Jy','F_8.0_Jy',
                'F_W1_Jy','F_W2_Jy','F_W3_Jy','F_W4_Jy',
                'F_0.36_um','lam_F_0.36_um','F_0.44_um','lam_F_0.44_um','F_0.55_um','lam_F_0.55_um','F_0.71_um','lam_F_0.71_um','F_0.97_um','lam_F_0.97_um',
                'F_1.24_um','lam_F_1.24_um','F_1.66_um','lam_F_1.66_um','F_2.16_um','lam_F_2.16_um',
                'F_3.55_um','lam_F_3.55_um','F_4.44_um','lam_F_4.44_um','F_5.73_um','lam_F_5.73_um','F_7.87_um','lam_F_7.87_um',
            'F_3.35_um','lam_F_3.35_um','F_4.60_um','lam_F_4.60_um','F_11.56_um','lam_F_11.56_um','F_22.09_um','lam_F_22.09_um']:
        c = Column([np.float(x) if x else 99.99 for x in t[col]],name=col,dtype=np.float)
        rTable.add_column(c)

    rTable = photo_corr(rTable)

    rTable.write(outfile+'.tsv',format='ascii.tab')
    rTable.write(outfile+'.fits')
    exit()
    
        
    newCols = []
    for col in colnames:
        c = Column([np.float(x) for x in t[col]],name=col,dtype=np.float)
        newCols.append(c)
    #print colnames
    eTable = Table()
    eTable.add_column(t['ID'])
    #eTable.add_column(t['lam_F_0.55_um'])
    #c = Column([str(x) for x in t['ID']],name='ID',dtype=str)
    #eTable.add_column(c)
    #eTable.add_columns([t[x] for x in colnames])
    eTable.add_columns(newCols)

    #print eTable['ID'].dtype
    #exit()
               
    #print eTable.colnames
    #for col in eTable.colnames:
    #    print eTable[col]

    #print eTable
    outfile = 'photometry.fits'
    print 'Writing table to %s' % outfile
    eTable.write(outfile)
Example #36
0
 def __init__(self, x, y, color):
     Star.__init__(self, x, y, color)
     self.moveleft = True
Example #37
0
	def __init__(self, x, y):
		Star.__init__(self, x, y, "red")
		self.moveleft = True
Example #38
0
class Finder(object):
	def __init__(self, 	star,
						moment=2016.3,
						instrument='LDSS3C',
						npixels=500, **starkw):

		'''produce a finder chart for a given star, at a particular moment
				star = either a star object, or the name of star for Simbad
						(**starkw will be passed to the star creation,
						 if you need custom RA, DEC, proper motions)
				moment = for what epoch (e.g. 2016.3) should the chart show?
				instrument = a string, indicating basic size of the chart
				npixels = how big the image can be; ds9 needs all on screen
		'''

		if type(star) == str:
			# if star is a string, use it (and starkw) to create star object
			self.name = star
			self.star = Star(self.name, **starkw)
		else:
			# if star isn't a string, it must be a zachopy.star.Star object'''
			self.star = star
			self.name = star.name

		# keep track
		self.instrument = instrument
		self.npixels = npixels

		# define the moment this finder should represent
		self.setMoment(moment)


		# use ds9 to create the finder chart
		self.createChart()

	def setMoment(self, moment):
		self.moment = moment



	def createChart(self):
		self.icrs = self.star.atEpoch(self.moment)
		self.ra, self.dec = self.icrs.ra, self.icrs.dec

		self.camera = Camera(self.instrument)
		self.coordstring = self.icrs.to_string('hmsdms')
		for letter in 'hmdm':
			self.coordstring = self.coordstring.replace(letter, ':')
		self.coordstring = self.coordstring.replace('s', '')

		self.w = pyds9.DS9('finders')
		toremove=[ 'info','panner','magnifier','buttons']
		for what in toremove:
			self.w.set('view {0} no'.format(what))
		self.w.set("frame delete all")
		self.size = self.camera.size
		self.inflate = self.camera.inflate
		#try:
		#	self.addImage('poss1_red')
		#except:
		#	print "poss1 failed"
		#try:
		self.addImage('poss2ukstu_red')
		#except:
		#	print "poss2 failed"

		self.addRegions()

		try:
			slit_mask_regions(self.star.attributes['slits'], 'slits')
			self.w.set("regions load {0}".format('slits.reg'))
		except KeyError:
			print "no slits found!"

		self.tidy()
		self.save()
	def tidy(self):
		self.w.set("tile mode column")
		self.w.set("tile yes")

		self.w.set("single")
		self.w.set("zoom to fit")
		self.w.set("match frame wcs")

	def save(self):
		utils.mkdir('finders')
		for d in [finderdir, 'finders/']:
			print "saveimage " + d + self.name.replace(' ', '') + ".png"
			self.w.set("saveimage " + d + self.name.replace(' ', '') + ".png")


	def addImage(self, survey='poss2_red'):
		self.w.set("frame new")
		self.w.set('single')
		self.w.set( "dssstsci survey {0}".format(survey))
		self.w.set("dssstsci size {0} {1} arcmin ".format(self.size*self.inflate, self.size*self.inflate))
		self.w.set("dssstsci coord {0} sexagesimal ".format(self.coordstring))

	def addRegions(self):
		xpixels = self.w.get('''fits header keyword "'NAXIS1'" ''')
		ypixels = self.w.get('''fits header keyword "'NAXIS1'" ''')
		self.scale = np.minimum(int(xpixels), self.npixels)/float(xpixels)
		self.w.set("width {0:.0f}".format(self.npixels))
		self.w.set("height {0:.0f}".format(self.npixels))

		# add circles centered on the target position
		r = regions.Regions("LDSS3C", units="fk5", path=finderdir )


		imageepoch = float(self.w.get('''fits header keyword "'DATE-OBS'" ''').split('-')[0])

		old = self.star.atEpoch(imageepoch)
		print imageepoch
		print self.star.posstring(imageepoch)

		current = self.star.atEpoch(self.moment)
		print self.moment
		print self.star.posstring(self.moment)
		r.addLine(old.ra.degree, old.dec.degree, current.ra.degree, current.dec.degree, line='0 1', color='red')
		print old.ra.degree, old.dec.degree, current.ra.degree, current.dec.degree
		r.addCircle(current.ra.degree, current.dec.degree, "{0}'".format(self.size/2), text="{0:.1f}' diameter".format(self.size), font="bold {0:.0f}".format(np.round(self.scale*14.0)))

		r.addCircle(current.ra.degree, current.dec.degree, "{0}'".format(2.0/60.0))

		# add a compass
		radius = self.size/60/2
		r.addCompass(current.ra.degree + 0.95*radius, current.dec.degree + 0.95*radius, "{0}'".format(self.size*self.inflate/10))
		r.addText(current.ra.degree, current.dec.degree - 1.1*radius, self.name + ', ' + self.star.posstring(self.moment), font='bold {0:.0f}'.format(np.round(self.scale*16.0)), color='red')

		r.addText(current.ra.degree - 1.04*radius, current.dec.degree + 1.02*radius, 'd(RA)={0:+3.0f}, d(Dec)={1:+3.0f} mas/yr'.format(self.star.pmra, self.star.pmdec), font='bold {0:.0f}'.format(np.round(self.scale*12.0)),  color='red')

		r.addText(current.ra.degree - 1.04*radius, current.dec.degree + 0.95*radius, '(image from {0})'.format(imageepoch), font='bold {0:.0f}'.format(np.round(self.scale*10.0)),  color='red')
		# load regions into image
		print(r)
		r.write()
		self.w.set("cmap invert yes")
		self.w.set("colorbar no")

		#self.w.set("rotate to {0}".format(int(np.round(90 -63 - self.star['rot'][0]))))
		self.w.set("regions load {0}".format(r.filename))
Example #39
0
'''
MasseyXLongFile = "tables/MASSEYXLFINAL.dat"
MasseyXLongDat = np.genfromtxt(MasseyXLongFile,skip_header=1,delimiter=';',names=['Gal','LGGS','n_LGGS','Name','V','B_V','U_B','V_R','R_I','Type','rType','RA','DEC'],dtype=['a5','a20','a1','a20','f8','f8','f8','f8','f8','a10','a5','f8','f8'],autostrip=True)
MXLtab = Table(MasseyXLongDat,meta={'title':'mXL','include':False,'num':len(MasseyXLongDat)})
ra,dec = zip(*[Star.sex2deg(ra,dec) for ra,dec in zip(MXLtab['RA'],MXLtab['DEC'])])
MXLtab.add_column(Column(ra,name='RAd'))
MXLtab.add_column(Column(dec,name='DECd'))
MXLtab.write("tables/MasseyXL.fit")
'''
McQuinn = 'tables/McQuinn_dl.fit'
McQuinnDat = Table.read(McQuinn)
RA = [np.float(x.split('+')[0][1:]) for x in McQuinnDat['SSTM3307']]
DEC = [np.float(x.split('+')[1]) for x in McQuinnDat['SSTM3307']]
RAc = Column(RA,name='RA',dtype=np.float)
DECc = Column(DEC,name='DEC',dtype=np.float)

McQuinnDat.rename_column('SSTM3307','Name')
McQuinnDat.add_column(RAc)
McQuinnDat.add_column(DECc)

McQuinnDat.meta['title'] = 'mcqS'
McQuinnDat.meta['include'] = False
McQuinnDat.meta['num'] = len(McQuinnDat)
ra,dec = zip(*[Star.sex2deg(ra,dec) for ra,dec in zip(McQuinnDat['RA'],McQuinnDat['DEC'])])
McQuinnDat.add_column(Column(ra,name='RAd'))
McQuinnDat.add_column(Column(dec,name='DECd'))
McQuinnDat.write('tables/McQuinn.fits')



Example #40
0
def solve_one(Star, SolveParsInit, Ref=object, PlotPars=object):
    sp = SolvePars()
    sp.__dict__ = SolveParsInit.__dict__.copy()
    if not hasattr(Star, 'model_atmosphere_grid'):
        logger.info('Star has no model yet. Calculating.')
        Star.get_model_atmosphere(sp.grid)
    if Star.model_atmosphere_grid != sp.grid:
        logger.info('Inconsistent model atmosphere grids '+
                     '(Star and SolvePars). '+
                     'Fixing problem now.')
        Star.get_model_atmosphere(sp.grid)

    if hasattr(Ref, 'name'):
        if not hasattr(Ref, 'model_atmosphere_grid'):
            logger.info('Ref star has no model yet. Calculating.')
            Ref.get_model_atmosphere(sp.grid)
        if Ref.model_atmosphere_grid != sp.grid:
            logger.info('Inconsistent model atmosphere grids '+
                         '(Ref star and SolvePars). '+
                         'Fixing problem now.')
            Ref.get_model_atmosphere(sp.grid)

    dtv, dgv, dvv, stop_iter = [], [], [], False
    if hasattr(Star, 'converged'):
        if not Star.converged:
            Star.converged = False
    else:
        Star.converged = False
    Star.stop_iter = sp.niter
    if sp.niter == 0:
        Star.converged = True

    print 'it Teff logg [Fe/H]  vt           [Fe/H]'
    print '-- ---- ---- ------ ----      --------------'

    for i in range(sp.niter+1):
        if sp.step_teff <= 1 and sp.step_logg <= 0.01 \
           and sp.step_vt <= 0.01:
            if not stop_iter:
                Star.converged = False
                if SolveParsInit.niter > 0:
                    print '-- Begin final loop'
            stop_iter = True

        if i > 0:
            if Star.iron_stats['slope_ep'] > 0:
                Star.teff += sp.step_teff
            else:
                Star.teff -= sp.step_teff
            if Star.teff > 7000:
                Star.teff = 7000
            if Star.iron_stats['slope_rew'] > 0:
                Star.vt += sp.step_vt
            else:
                Star.vt -= sp.step_vt
            if Star.vt < 0:
                Star.vt = 0
            dfe = Star.iron_stats['afe1'] - Star.iron_stats['afe2']
            if dfe > 0:
                Star.logg += sp.step_logg
            else:
                Star.logg -= sp.step_logg
            if Star.logg > 5.0:
                Star.logg = 5.0

            if hasattr(Ref, 'name'):
                Star.feh = Ref.feh + Star.iron_stats['afe']
            else:
                Star.feh = Star.iron_stats['afe'] - sp.solar_afe
            if Star.feh > 1.0:
                Star.feh = 1.0
            if Star.feh > 0.5 and sp.grid != 'over':
                Star.feh = 0.5

            Star.get_model_atmosphere(sp.grid)

        if i+1 == sp.niter or sp.niter == 0:
            plot = Star.name
            if hasattr(Ref, 'name'):
                plot = Star.name+'-'+Ref.name
                if Star.name == Ref.name:
                    plot = None
                    Star.converged = ''
        else:
            plot = None

        is_done = iron_stats(Star, Ref=Ref, plot=plot, PlotPars=PlotPars)

        print "{0:2d} {1:4d} {2:4.2f} {3:6.3f} {4:4.2f}"\
              " ---> {5:6.3f}+/-{6:5.3f}".\
                format(i, Star.teff, Star.logg, Star.feh, Star.vt,
                          Star.iron_stats['afe'], Star.iron_stats['err_afe'])

        dtv.append(Star.teff)
        dgv.append(Star.logg)
        dvv.append(Star.vt)

        if i >= 4:
            if np.std(dtv[-5:]) <= 0.8*sp.step_teff and \
               np.std(dgv[-5:]) <= 0.8*sp.step_logg and \
               np.std(dvv[-5:]) <= 0.8*sp.step_vt:
                print '-- Converged at iteration '+str(i)+ \
                      ' of '+str(sp.niter)
                if stop_iter:
                    plot = Star.name
                    if hasattr(Ref, 'name'):
                        plot = Star.name+'-'+Ref.name
                    iron_stats(Star, Ref=Ref, plot=plot, PlotPars=PlotPars)
                    Star.converged = True
                    Star.stop_iter = i
                    break
                sp.step_teff = sp.step_teff/2
                sp.step_logg = sp.step_logg/2
                sp.step_vt = sp.step_vt/2
                if sp.step_teff < 1 and sp.step_teff > 0:
                    sp.step_teff = 1
                if sp.step_logg < 0.01 and sp.step_logg > 0:
                    sp.step_logg = 0.01
                if sp.step_vt < 0.01 and sp.step_vt > 0:
                    sp.step_vt = 0.01

    if not Star.converged:
        if hasattr(Ref, 'name'):
            if Star.name == Ref.name or SolveParsInit.niter == 0:
                print '--'
            else:
                print '-- Did not achieve final convergence.'
        else:
            print '-- Did not achieve final convergence.'

    print '------------------------------------------------------'

    if hasattr(Ref, 'name'):
        print '   D[Fe/H]    ||    D[Fe/H] Fe I   |   D[Fe/H] Fe II'
    else:
        print '    A(Fe)     ||      A(Fe I)      |     A(Fe II)   '

    print "{0:6.3f} {1:6.3f} || {2:6.3f} {3:6.3f} {4:3d} "\
          "| {5:6.3f} {6:6.3f} {7:3d}".\
            format(Star.iron_stats['afe'], Star.iron_stats['err_afe'],
                   Star.iron_stats['afe1'], Star.iron_stats['err_afe1'],
                   Star.iron_stats['nfe1'],
                   Star.iron_stats['afe2'], Star.iron_stats['err_afe2'],
                   Star.iron_stats['nfe2'])
    print '------------------------------------------------------'

    Star.sp_err = {'teff': 0, 'logg': 0, 'afe': 0, 'vt': 0}
    if ((Star.converged and sp.errors == True) or \
        (sp.niter == 0 and sp.errors == True and Star.converged != '')):
        errors.error_one(Star, sp, Ref)
        Star.err_teff = int(Star.sp_err['teff'])
        Star.err_logg = Star.sp_err['logg']
        Star.err_feh = Star.sp_err['afe']
        Star.err_vt = Star.sp_err['vt']
        print "Solution with formal errors:"
        print "Teff    = {0:6d} +/- {1:5d}".\
              format(int(Star.teff), int(Star.sp_err['teff']))
        print "log g   = {0:6.3f} +/- {1:5.3f}".\
              format(Star.logg, Star.sp_err['logg'])
        if hasattr(Ref, 'name'):
            print "D[Fe/H] = {0:6.3f} +/- {1:5.3f}".\
                  format(Star.iron_stats['afe'], Star.sp_err['afe'])
        else:
            print "A(Fe)   = {0:6.3f} +/- {1:5.3f}".\
                  format(Star.iron_stats['afe'], Star.sp_err['afe'])
        print "vt      = {0:6.2f} +/- {1:5.2f}".\
              format(Star.vt, Star.sp_err['vt'])
        print '------------------------------------------------------'
Example #41
0
def solve_all(Data, SolveParsInit, output_file, reference_star=None,
              PlotPars=object):
    print '------------------------------------------------------'
    print 'Initializing ...'
    start_time = datetime.datetime.now()
    print '- Date and time: '+start_time.strftime('%d-%b-%Y, %H:%M:%S')
    print '- Model atmospheres: '+SolveParsInit.grid
    print '- Star data: '+Data.star_data_fname
    print '- Line list: '+Data.lines_fname
    print '------------------------------------------------------'
    if reference_star:
        Ref = Star(reference_star)
        Ref.get_data_from(Data)
    else:
        Ref = None
    fout = open(output_file, 'wb')
    if SolveParsInit.errors:
        fout.write('id,teff,logg,feh_model,vt,feh,err_feh_,'+
                   'feh1,err_feh1,nfe1,feh2,err_feh2,nfe2,'
                   'slope_ep,err_slope_ep,slope_rew,err_slope_rew,'
                   'stop_iter,converged,'
                   'err_teff,err_logg,err_feh,err_vt\n')
    else:
        fout.write('id,teff,logg,feh_model,vt,feh,err_feh,'+
                   'feh1,err_feh1,nfe1,feh2,err_feh2,nfe2,'
                   'slope_ep,err_slope_ep,slope_rew,err_slope_rew,'
                   'stop_iter,converged,'
                   'err_teff,err_logg,err_feh_,err_vt\n')
    for star_id in Data.star_data['id']:
        print ''
        print '*'*len(star_id)
        print star_id
        print '*'*len(star_id)
        s = Star(star_id)
        try:
            s.get_data_from(Data)
        except:
            logger.warning('No data found for '+s.name+\
                        '. Excluded from output file.')
            print 'Data not found.'
            #fout.write("{0},,,,,,,,,,"\
            #           ",,,,,,,,,,,,\n".\
            #           format(s.name))
            continue
        if ma.count(Data.lines[star_id]) == 0:
            print 'Line data not found.'
            continue
        sp = SolvePars()
        sp.__dict__ = SolveParsInit.__dict__.copy()
        if reference_star:
            if s.name == Ref.name:
                sp.niter = 0
                print 'Reference star. No calculations needed.'
                #continue
        if hasattr(s, 'converged') and sp.check_converged:
            if s.converged == 'True':
                print 'Already converged.'
                continue
                #sp.niter = 0
                #s.converged = True
        if s.name in sp.ignore:
            print 'Asked to ignore.'
            continue

        solve_one(s, sp, Ref, PlotPars=PlotPars)

        if sp.niter == 0:
            s.converged = ''

        fout.write("{0},{1:4d},{2:5.3f},{3},{4:4.2f},{5},{6:5.3f},"\
                   "{7},{8:5.3f},{9},"\
                   "{10},{11:5.3f},{12},{13:.6f},{14:.6f},"\
                   "{15:.6f},{16:.6f},{17},{18},"\
                   "{19:3d},{20:5.3f},{21:5.3f},{22:4.2f}\n".\
                   format(s.name, s.teff, s.logg, str(round(s.feh,3)), s.vt,
                          str(round(s.iron_stats['afe'],3)),
                          s.iron_stats['err_afe'],
                          str(round(s.iron_stats['afe1'],3)),
                          s.iron_stats['err_afe1'],
                          s.iron_stats['nfe1'],
                          str(round(s.iron_stats['afe2'],3)),
                          s.iron_stats['err_afe2'],
                          s.iron_stats['nfe2'],
                          s.iron_stats['slope_ep'],
                          s.iron_stats['err_slope_ep'],
                          s.iron_stats['slope_rew'],
                          s.iron_stats['err_slope_rew'],
                          s.stop_iter,
                          s.converged,
                          s.sp_err['teff'], s.sp_err['logg'],
                          s.sp_err['afe'], s.sp_err['vt']
                          ))
    fout.close()

    print ''
    print '------------------------------------------------------'
    end_time = datetime.datetime.now()
    print '- Date and time: '+end_time.strftime('%d-%b-%Y, %H:%M:%S')
    delta_t = (end_time - start_time).seconds
    hours, remainder = divmod(delta_t, 3600)
    minutes, seconds = divmod(remainder, 60)
    print '- Time elapsed: %sH %sM %sS' % (hours, minutes, seconds)
    print 'Done!'
    print '------------------------------------------------------'
    print ''
Example #42
0
def error_one(Star_in, SolvePars, Ref=object):

    s = Star()
    s.__dict__ = Star_in.__dict__.copy()
    try:
        Ref.get_model_atmosphere(SolvePars.grid)
        logger.info('Relative abundances')
    except:
        logger.info('Absolute abundances')

    dteff = 20
    dvt = 0.02
    dlogg = 0.02

    s.teff = s.teff + dteff
    s.get_model_atmosphere(SolvePars.grid)
    specpars.iron_stats(s, Ref=Ref)
    fx1  = s.iron_stats['slope_ep']
    efx1 = s.iron_stats['err_slope_ep']
    gx1  = s.iron_stats['slope_rew']
    egx1 = s.iron_stats['err_slope_rew']
    hx1  = s.iron_stats['afe1'] - s.iron_stats['afe2']
    ehx1 = np.sqrt(s.iron_stats['err_afe1']**2+
                   s.iron_stats['err_afe2']**2)/\
           np.sqrt(s.iron_stats['nfe1']+s.iron_stats['nfe2'])
    s.teff = s.teff - 2*dteff
    s.get_model_atmosphere(SolvePars.grid)
    specpars.iron_stats(s, Ref=Ref)
    fx2  = s.iron_stats['slope_ep']
    efx2 = s.iron_stats['err_slope_ep']
    gx2  = s.iron_stats['slope_rew']
    egx2 = s.iron_stats['err_slope_rew']
    hx2  = s.iron_stats['afe1'] - s.iron_stats['afe2']
    ehx2 = np.sqrt(s.iron_stats['err_afe1']**2+
                   s.iron_stats['err_afe2']**2)/\
           np.sqrt(s.iron_stats['nfe1']+s.iron_stats['nfe2'])
    s.teff = s.teff + dteff
    dfx = 1e0*(fx2-fx1)/(2*dteff)
    efx = 1e0*(efx1+efx2)/2
    dgx = 1e0*(gx2-gx1)/(2*dteff)
    egx = 1e0*(egx1+egx2)/2
    dhx = 1e0*(hx2-hx1)/(2*dteff)
    ehx = 1e0*(ehx1+ehx2)/2
    dfdt, dgdt, dhdt = dfx, dgx, dhx
    eft, egt, eht = efx, egx, ehx

    s.vt = s.vt + dvt
    s.get_model_atmosphere(SolvePars.grid)
    specpars.iron_stats(s, Ref=Ref)
    fx1  = s.iron_stats['slope_ep']
    efx1 = s.iron_stats['err_slope_ep']
    gx1  = s.iron_stats['slope_rew']
    egx1 = s.iron_stats['err_slope_rew']
    hx1  = s.iron_stats['afe1'] - s.iron_stats['afe2']
    ehx1 = np.sqrt(s.iron_stats['err_afe1']**2+
                   s.iron_stats['err_afe2']**2)/\
           np.sqrt(s.iron_stats['nfe1']+s.iron_stats['nfe2'])
    s.vt = s.vt - 2*dvt
    s.get_model_atmosphere(SolvePars.grid)
    specpars.iron_stats(s, Ref=Ref)
    fx2  = s.iron_stats['slope_ep']
    efx2 = s.iron_stats['err_slope_ep']
    gx2  = s.iron_stats['slope_rew']
    egx2 = s.iron_stats['err_slope_rew']
    hx2  = s.iron_stats['afe1'] - s.iron_stats['afe2']
    ehx2 = np.sqrt(s.iron_stats['err_afe1']**2+
                   s.iron_stats['err_afe2']**2)/\
           np.sqrt(s.iron_stats['nfe1']+s.iron_stats['nfe2'])
    s.vt = s.vt + dvt
    dfx = 1e0*(fx2-fx1)/(2*dvt)
    efx = 1e0*(efx1+efx2)/2
    dgx = 1e0*(gx2-gx1)/(2*dvt)
    egx = 1e0*(egx1+egx2)/2
    dhx = 1e0*(hx2-hx1)/(2*dvt)
    ehx = 1e0*(ehx1+ehx2)/2
    dfdv, dgdv, dhdv = dfx, dgx, dhx
    efv, egv, ehv = efx, egx, ehx

    s.logg = s.logg + dlogg
    s.get_model_atmosphere(SolvePars.grid)
    specpars.iron_stats(s, Ref=Ref)
    fx1  = s.iron_stats['slope_ep']
    efx1 = s.iron_stats['err_slope_ep']
    gx1  = s.iron_stats['slope_rew']
    egx1 = s.iron_stats['err_slope_rew']
    hx1  = s.iron_stats['afe1'] - s.iron_stats['afe2']
    ehx1 = np.sqrt(s.iron_stats['err_afe1']**2+
                   s.iron_stats['err_afe2']**2)/\
           np.sqrt(s.iron_stats['nfe1']+s.iron_stats['nfe2'])
    s.logg = s.logg - 2*dlogg
    s.get_model_atmosphere(SolvePars.grid)
    specpars.iron_stats(s, Ref=Ref)
    fx2  = s.iron_stats['slope_ep']
    efx2 = s.iron_stats['err_slope_ep']
    gx2  = s.iron_stats['slope_rew']
    egx2 = s.iron_stats['err_slope_rew']
    hx2  = s.iron_stats['afe1'] - s.iron_stats['afe2']
    ehx2 = np.sqrt(s.iron_stats['err_afe1']**2+
                   s.iron_stats['err_afe2']**2)/\
           np.sqrt(s.iron_stats['nfe1']+s.iron_stats['nfe2'])
    s.logg = s.logg + dlogg
    dfx = 1e0*(fx2-fx1)/(2*dlogg)
    efx = 1e0*(efx1+efx2)/2
    dgx = 1e0*(gx2-gx1)/(2*dlogg)
    egx = 1e0*(egx1+egx2)/2
    dhx = 1e0*(hx2-hx1)/(2*dlogg)
    ehx = 1e0*(ehx1+ehx2)/2
    dfdg, dgdg, dhdg = dfx, dgx, dhx
    efg, egg, ehg = efx, egx, ehx
    
    d = matrix( [ [dfdt, dfdv, dfdg],
                  [dgdt, dgdv, dgdg],
                  [dhdt, dhdv, dhdg] ] )
    di = d.I

    s0 = np.mean([eft,efv,efg])
    s1 = np.mean([egt,egv,egg])
    s2 = np.mean([eht,ehv,ehg])

    eteff = np.sqrt ( (s0*di[0, 0])**2 +
                      (s1*di[0, 1])**2 +
                      (s2*di[0, 2])**2  )

    evt   = np.sqrt ( (s0*di[1, 0])**2 +
                      (s1*di[1, 1])**2 +
                      (s2*di[1, 2])**2  )

    elogg = np.sqrt ( (s0*di[2, 0])**2 +
                      (s1*di[2, 1])**2 +
                      (s2*di[2, 2])**2  )

    s.teff = s.teff + eteff
    s.get_model_atmosphere(SolvePars.grid)
    specpars.iron_stats(s, Ref=Ref)
    ap = s.iron_stats['afe']
    s.teff = s.teff - 2*eteff
    s.get_model_atmosphere(SolvePars.grid)
    specpars.iron_stats(s, Ref=Ref)
    am = s.iron_stats['afe']
    s.teff = s.teff + eteff
    eat = (ap-am)/2

    s.logg = s.logg + elogg
    s.get_model_atmosphere(SolvePars.grid)
    specpars.iron_stats(s, Ref=Ref)
    ap = s.iron_stats['afe']
    s.logg = s.logg - 2*elogg
    s.get_model_atmosphere(SolvePars.grid)
    specpars.iron_stats(s, Ref=Ref)
    am = s.iron_stats['afe']
    s.logg = s.logg + elogg
    eag = (ap-am)/2

    s.vt = s.vt + evt
    s.get_model_atmosphere(SolvePars.grid)
    specpars.iron_stats(s, Ref=Ref)
    ap = s.iron_stats['afe']
    s.vt = s.vt - 2*evt
    s.get_model_atmosphere(SolvePars.grid)
    specpars.iron_stats(s, Ref=Ref)
    am = s.iron_stats['afe']
    s.vt = s.vt + evt
    eav = (ap-am)/2

    ea = np.sqrt(eat**2+eag**2+eav**2+s2**2)

    Star_in.sp_err = {'teff': int(eteff), 'logg': elogg, 'afe': ea, 'vt': evt}