Beispiel #1
0
    def action(self, fields, canvas, side):
        if (side == 'Right'):
            if ((self.location.x + 40) / 40 < 20):
                new_coords = Coords((self.location.x + 40) / 40,
                                    (self.location.y) / 40)
            else:
                return canvas
        elif (side == 'Left'):
            if ((self.location.x + 40) / 40 > 1):
                new_coords = Coords((self.location.x - 40) / 40,
                                    (self.location.y) / 40)
            else:
                return canvas
        elif (side == 'Up'):
            if ((self.location.y + 40) / 40 > 1):
                new_coords = Coords((self.location.x) / 40,
                                    (self.location.y - 40) / 40)
            else:
                return canvas
        elif (side == 'Down'):
            if ((self.location.y + 40) / 40 < 20):
                new_coords = Coords((self.location.x) / 40,
                                    (self.location.y + 40) / 40)
            else:
                return canvas

        canvas = self.move(new_coords, fields, canvas)

        return canvas
Beispiel #2
0
 def clear_data(self):
     self.score = 0
     self.bird = Bird.Bird(self.window, self.fpsClock, self.FPS,
                           Coords.Coords((100, int(480 / 2))))
     self.curTime = self.prevTime = pg.time.get_ticks()
     self.time_diff = 3500
     self.grass = Grass.Grass(self.window, Coords.Coords((640, 480)))
     self.cloud = Cloud.Cloud(self.window, Coords.Coords((640, 480)))
     self.pipes = [Pipe.Pipe(self.window, Coords.Coords((640, 480)))]
 def __init__(self, game):
     Sprite.__init__(self, game)
     # Малюнки бігаючого чоловічка
     self.images_left = [
         PhotoImage(file="figure-L1.gif"),
         PhotoImage(file="figure-L2.gif"),
         PhotoImage(file="figure-L3.gif")
     ]
     self.images_right = [
         PhotoImage(file="figure-R1.gif"),
         PhotoImage(file="figure-R2.gif"),
         PhotoImage(file="figure-R3.gif")
     ]
     self.image = game.canvas.create_image(200,
                                           470,
                                           image=self.images_left[0],
                                           anchor='nw')
     self.x = -2
     self.y = 0
     self.current_image = 0
     self.current_image_add = 1
     self.jump_count = 0
     self.last_time = time.time()
     self.coordinates = Coords()
     game.canvas.bind_all('<KeyPress-Left>', self.turn_left)
     game.canvas.bind_all('<KeyPress-Right>', self.turn_right)
     game.canvas.bind_all('<KeyPress-Up>', self.jump)
     game.canvas.bind_all('<KeyPress-Down>', self.stop)
 def __init__(self, game, photo_image, x, y, width, height):
     Sprite.__init__(self, game)
     self.photo_image = photo_image
     self.image = game.canvas.create_image(x,
                                           y,
                                           image=self.photo_image,
                                           anchor="nw")
     self.coordinates = Coords(x, y, x + width, y + height)
Beispiel #5
0
 def startScreen(self):
     startCloud = pg.transform.scale(
         pg.image.load('objects/startscreen/cloud.jpg'), (640, 480))
     startbird = pg.transform.scale(
         pg.image.load("objects/startscreen/bird.png"), (64, 64))
     startPlayButton = pg.transform.scale(
         pg.image.load('objects/startscreen/play.png'), (128, 128))
     c = None
     startFlappyBird = TypeFaces.Draws(dispSurf=self.window,
                                       typeface="./fonts/CHLORINR.TTF",
                                       string="FLaPpY Wings",
                                       fontsize=72,
                                       coords=Coords.Coords(
                                           (int(640 / 2), int(480 / 5))),
                                       use_center=True,
                                       color_left=pg.Color(0, 120, 0))
     startCloudRect = startCloud.get_rect()
     startCloudRect.top = startCloudRect.left = 0
     startbirdRect = startbird.get_rect()
     startbirdRect.centerx = 60
     startbirdRect.centery = int(480 / 2)
     startPlayButtonRect = startPlayButton.get_rect()
     startPlayButtonRect.centerx = int(640 / 2)
     startPlayButtonRect.centery = int(480 / 2)
     mouseClicked = False
     while True:
         self.window.fill((0, 0, 0))
         self.window.blit(startCloud, startCloudRect)
         self.window.blit(startbird, startbirdRect)
         self.window.blit(startPlayButton, startPlayButtonRect)
         startFlappyBird.drawFont()
         self.checkForQuit()
         for event in pg.event.get():
             if event.type == pglcl.MOUSEBUTTONUP:
                 c = Coords.Coords(event.pos)
                 mouseClicked = True
         if mouseClicked == True and startPlayButtonRect.colliderect(
                 pg.Rect(c.x, c.y, startPlayButtonRect.width,
                         startPlayButtonRect.height)) == True:
             return
         pg.display.update()
         self.fpsClock.tick(self.FPS)
 def __init__(self, game, x, y, width, height):
     Sprite.__init__(self, game)
     self.closed_door = PhotoImage(file='door1.gif')
     self.open_door = PhotoImage(file='door2.gif')
     #зберігаємо індетифікатор який повертає функція creat_image в змінну image
     self.image = game.canvas.create_image(x,
                                           y,
                                           image=self.closed_door,
                                           anchor='nw')
     # Координати дверей
     self.coordinates = Coords(x, y, x + (width / 2), y + height)
     self.endgame = True  # ця змінна є тру поки чоловічок не торкнеться спрайту дверей
 def __init__(self,
              dispSurf=None,
              typeface="./fonts/PG_Roof Runners_active.ttf",
              string="test",
              fontsize=40,
              coords=Coords.Coords((int(640 / 2), 60)),
              color_left=pg.Color(128, 128, 128),
              use_center=False):
     self.dispSurf = dispSurf
     self.fontObj = pg.font.Font(typeface, fontsize)
     self.fontObj = self.fontObj.render(str(string), True, color_left)
     self.textSurf = self.fontObj.get_rect()
     if use_center == False:
         self.textSurf.top, self.textSurf.left = coords.y, coords.x
     else:
         self.textSurf.center = (coords.x, coords.y)
Beispiel #8
0
 def gameOver(self):
     GameOverSurface = pg.Surface((640, 480))
     GameOverSurface = GameOverSurface.convert_alpha()
     GameOverSurface.fill((0, 0, 0, 50))
     gameOverGameOver = TypeFaces.Draws(dispSurf=self.window,
                                        typeface="./fonts/CHLORINR.TTF",
                                        string="Game Over",
                                        fontsize=72,
                                        coords=Coords.Coords(
                                            (int(640 / 2), int(480 / 2))),
                                        use_center=True,
                                        color_left=pg.Color(0, 120, 0))
     self.window.blit(GameOverSurface, (0, 0))
     gameOverGameOver.drawFont()
     pg.display.update()
     while True:
         self.checkForQuit()
         for event in pg.event.get():
             if event.type == pglcl.KEYUP:
                 return
Beispiel #9
0
 def mainGame(self):
     self.runGame = True
     while self.runGame == True:
         if len(self.pipes) > 0 and self.pipes[0].visible == False:
             del self.pipes[0]
         for i in self.pipes:
             if i.inrange(self.bird.getCoords()) == True:
                 return
         for i in self.pipes:
             if i.passed_pipe(self.bird.getCoords()) == True:
                 self.score += 1
                 break
         self.window.fill((0, 0, 0))
         self.checkForQuit()
         for event in pg.event.get():
             if event.type == pglcl.KEYDOWN and event.key == pglcl.K_UP:
                 self.bird.MakeJump()
         self.curTime = pg.time.get_ticks()
         if self.curTime - self.prevTime > self.time_diff:
             self.pipes.append(
                 Pipe.Pipe(self.window, Coords.Coords((640, 480))))
             self.prevTime = self.curTime
         self.cloud.drawCloud()
         self.grass.drawGrass()
         for i in self.pipes:
             i.drawPipe()
         TypeFaces.Draws(dispSurf=self.window,
                         string="{!s}".format(self.score),
                         use_center=True).drawFont()
         self.bird.showAnimation()
         if self.grass.inrange(
                 self.bird.getCoords()) or self.checkOutOfFrame(
                     self.bird.getCoords()):
             break
         pg.display.update()
         self.fpsClock.tick(self.FPS)
Beispiel #10
0

def Escape(event):
    menuStack.pop()


window = Tk()

canvas = Canvas(window, width=800, height=1000, bg='green')

first_menu = []
menu_settings = []
menuStack = MenuStack(first_menu)

first_menu.append(
    UIInformation("temperature °C ", Coords(0, 0), 400, 100, "", canvas))
first_menu.append(
    UIButton("light on", Coords(0, 100), 400, 100, "", canvas,
             lambda: print('light on')))
first_menu.append(
    UIMenu("settings", Coords(0, 200), 400, 100, "", canvas, menu_settings,
           menuStack))  #//uimenu (4,5,6)
first_menu.append(UIElement("4", Coords(0, 300), 400, 100, "", canvas))
first_menu.append(UIElement("5", Coords(0, 400), 400, 100, "",
                            canvas))  #// uimenu (1,2,3)
first_menu.append(UIElement("6", Coords(400, 100), 400, 100, "", canvas))
first_menu.append(UIElement("7", Coords(400, 200), 400, 100, "", canvas))
first_menu.append(UIElement("9", Coords(400, 300), 400, 100, "", canvas))
first_menu.append(UIElement("10", Coords(400, 400), 400, 100, "", canvas))

menu_settings.append(UIInformation("11", Coords(0, 0), 400, 100, "", canvas))
Beispiel #11
0
 def get_center(self):
     x = self.coords.x + self.width / 2
     y = self.coords.y + self.height / 2
     return Coords(x, y)
Beispiel #12
0
def makeScriptobsLine(name,
                      row,
                      do_flag,
                      t,
                      decker="W",
                      I2="Y",
                      owner='Vogt',
                      focval=0):
    """ given a name, a row in a star table and a do_flag, will generate a scriptobs line as a string
    line = makeScriptobsLine(name, row, do_flag, t, decker="W",I2="Y")
    name - name of star, first column in line
    row - star_table row for star that begins with name, cotains all of the data needed for the line except
    do_flag - a string for whether or not scriptob needs to do a pointing check before slewing to the target
    t - a datetime object, this is used to fill in the uth and utm fields,
    decker - one character field for the decker, defaults to "W"
    I2 - one character field for whether or not the Iodine cell is in, must be "Y" or "N"
    """
    """Takes a line from the star table and generates the appropriate line to pass to scriptobs. """
    # Start with the target name
    ret = name + ' '
    # Add the RA as three elements, HR, MIN, SEC
    rastr = Coords.getCoordStr(np.degrees(row[DS_RA]), isRA=True)
    ret += rastr + ' '
    # Add the DEC as three elements, DEG, MIN, SEC
    decstr = Coords.getCoordStr(np.degrees(row[DS_DEC]))
    ret += decstr + ' '
    # Epoch
    ret += '2000 '
    # Proper motion RA and DEC
    ret += 'pmra=' + str(row[DS_PMRA]) + ' '
    ret += 'pmdec=' + str(row[DS_PMDEC]) + ' '
    # V Mag
    ret += 'vmag=' + str(row[DS_VMAG]) + ' '
    # T Exp
    if row[DS_EXPT] > MAX_EXPTIME:
        ret += 'texp=%d ' % (int(MAX_EXPTIME))
    elif row[DS_EXPT] <= MIN_EXPTIME:
        ret += 'texp=%d ' % (int(MIN_EXPTIME))
    else:
        ret += 'texp=' + str(int(row[DS_EXPT])) + ' '
    # I2
    ret += 'I2=%s ' % (I2)
    # lamp
    ret += 'lamp=none '
    # start time
    ret += 'uth=' + str(t.hour) + ' '
    ret += 'utm=' + str(t.minute) + ' '
    # Exp Count
    if row[DS_COUNTS] > 3e9:
        ret += 'expcount=%.3g' % (3e9) + ' '
    else:
        ret += 'expcount=%.3g' % (row[DS_COUNTS]) + ' '
    # Decker
    ret += 'decker=%s ' % (decker)
    # do flag
    if do_flag:
        ret += 'do=Y '
    else:
        ret += 'do= '
    # Count
    ret += 'count=' + str(int(row[DS_NSHOTS]))

    ret += ' foc=' + str(int(focval))

    if owner != '':
        ret += ' owner=' + str(owner)

    return ret
Beispiel #13
0
def parseGoogledex(sheetns=["Bstars"],certificate='UCSC Dynamic Scheduler-5b98d1283a95.json',outfn="googledex.dat",outdir=None,config={'I2': 'Y', 'decker': 'W', 'owner' : '' }):
    """ parseGoogledex parses google sheets and returns the output as a tuple
    This routine downloads the data if needed and saves the output to a file. If the file exists, it just reads in the file.
    
    names, star_table, do_flag, stars = parseGoogledex(sheetn="The Googledex",certificate='UCSC Dynamic Scheduler-5b98d1283a95.json',outfn="googledex.dat")
    names - a list of stars in the starlist
    star_table - a numpy array
    flags - a dictionary of items on whether or not do="y" needs to be set for scriptobs 
    stars - a list of pyEphem objects 

    """
    # Downloading all the values is going slowly.
    # Try to only have to load this once a day
    apflog( "Starting Googledex parse",echo=True)    
    if not outdir :
        outdir = os.getcwd()
    if os.path.exists(os.path.join(outdir,outfn)):
        try:
            f = open(os.path.join(outdir,outfn),'rb')
            full_codex = pickle.load(f)
            f.close()
        except:
            full_codex = make_local_copy(sheetns=sheetns,certificate=certificate,outfn=os.path.join(outdir,outfn))
    else:
        full_codex = make_local_copy(sheetns=sheetns,certificate=certificate,outfn=os.path.join(outdir,outfn))

    col_names = full_codex[0]
    codex = full_codex[1:]

    # These are the columns we need for scheduling
    req_cols = ["Star Name", "RA hr", "RA min", "RA sec", \
                "Dec deg", "Dec min", "Dec sec", "pmRA", "pmDEC", "Vmag", \
                "APFpri", "APFcad", "APFnshots", "lastobs", "APFmin", "APFmax", \
                "B-V", "APF Desired Precision", "Close Companion", \
                "APF decker","I2", "owner", "uth","utm","duration", "Template",
                "Nobs", "Total Obs"
                ]
    didx = findColumns(col_names,req_cols)
    
    names = []
    star_table = []
    flags = { "do" : [], "decker" : [], "I2" : [], "owner" : [], "template" : [] }
    stars = []
    # Build the star table to return to 
    for ls in codex:
        if ls[0] == '':
            continue
        try:
            apfpri = float(ls[didx["APFpri"]])
        except:
            apfpri = 0.0
        try:
            nobs = int(ls[didx["Nobs"]])
        except:
            nobs = 0
        try:
            totobs = int(ls[didx["Total Obs"]])
        except :
            totobs = -1
        if totobs > 0 and nobs >= totobs: continue
        if apfpri < 0.5: continue
        row = []
        # Get the star name
        names.append(parse_starname(ls[didx["Star Name"]]))
        # Get the RA
        raval = Coords.getRARad(ls[didx["RA hr"]], ls[didx["RA min"]], ls[didx["RA sec"]])
        if raval:
            row.append(raval)
        else:
            row.append(-1.)
        # Get the DEC
        decval = Coords.getDECRad(ls[didx["Dec deg"]], ls[didx["Dec min"]], ls[didx["Dec sec"]])
        if decval:
            row.append(decval)
        else:
            row.append(-3.14)

        for coln in ("pmRA", "pmDEC", "Vmag"):
            try:
                row.append(float(ls[didx[coln]]))
            except ValueError:
                if coln == "Vmag":
                    row.append(15.0)
                else:
                    row.append(0.0)
        # For now use the old 1e9 count value - these get recalculated 
        row.append(1200.0)
        row.append(1.e9)
        for coln in ["APFpri", "APFcad","APFnshots"] :
            try:
                row.append(float(ls[didx[coln]]))
            except ValueError:
                if coln in ("APFpri","APFnshots"):
                    row.append(0)
                else:
                    row.append(1000.0)
                    
        
        for coln in ["lastobs", "B-V", "APF Desired Precision" ]:
            try:
                row.append(float(ls[didx[coln]]))
            except ValueError:
                if coln in ("lastobs", "B-V"):
                    row.append(0.0)
                else:
                    row.append(1000.0)

        for coln in ["uth", "utm"]:
            try:
                row.append(int(ls[didx[coln]]))
            except ValueError:
                row.append(0)
            except KeyError:
                row.append(0)
                
        for coln in ["duration"]:
            try:
                row.append(float(ls[didx[coln]]))
            except ValueError:
                row.append(0)
            except KeyError:
                row.append(0)
                
        for coln in ["APFmin"]:
            try:
                row.append(float(ls[didx[coln]]))
            except ValueError:
                row.append(MIN_TOTOBS)
            except KeyError:
                row.append(MIN_TOTOBS)
                
        for coln in ["APFmax"]:
            try:
                row.append(float(ls[didx[coln]]))
            except ValueError:
                row.append(0)
            except KeyError:
                row.append(0)

        for coln in ["Nobs"]:
            try:
                row.append(int(ls[didx[coln]]))
            except ValueError:
                row.append(0)
            except KeyError:
                row.append(0)
                
        for coln in ["Total Obs"]:
            try:
                row.append(int(ls[didx[coln]]))
            except ValueError:
                row.append(0)
            except KeyError:
                row.append(0)
                
                    
        check = checkflag("Close Companion",didx,ls,"\A(n|N)","Y")
        if check == "N" or check == "n":
            flags['do'].append("")
        else:
            flags['do'].append(check)
            
        flags['decker'].append(checkflag("APF decker",didx,ls,"\A(W|N|T|S|O|K|L|M|B)",config["decker"]))
        flags['I2'].append(checkflag("I2",didx,ls,"\A(n|N)",config["I2"]))
        flags['template'].append(checkflag("Template",didx,ls,"\A(n|N)",'Y'))

        flags['owner'].append(checkflag("owner",didx,ls,"\A(\w?\.?\w+)",config["owner"]))

            
        star_table.append(row)
        star = ephem.FixedBody()
        star.name = ls[0]
        star._ra = ephem.hours(":".join([ls[didx["RA hr"]], ls[didx["RA min"]], ls[didx["RA sec"]]]))
        star._dec = ephem.degrees(":".join([ls[didx["Dec deg"]], ls[didx["Dec min"]], ls[didx["Dec sec"]]]))
        stars.append(star)

    return (names, np.array(star_table), flags, stars)
Beispiel #14
0
def parseGoogledex(sheetns=["Bstars"],certificate='UCSC Dynamic Scheduler-4f4f8d64827e.json',outfn="googledex.dat",outdir=None,config={'I2': 'Y', 'decker': 'W', 'owner' : '' },force_download=False,prilim=0.5):
    """ parseGoogledex parses google sheets and returns the output as a tuple
    This routine downloads the data if needed and saves the output to a file. If the file exists, it just reads in the file.
    
    names, star_table, do_flag, stars = parseGoogledex(sheetn="The Googledex",certificate='UCSC Dynamic Scheduler-4f4f8d64827e.json',outfn="googledex.dat")
    names - a list of stars in the starlist
    star_table - a numpy array
    flags - a dictionary of items on whether or not do="y" needs to be set for scriptobs 
    stars - a list of pyEphem objects 

    """

    # These are the columns we need for scheduling
    req_cols = ["Star Name", "RA hr", "RA min", "RA sec", \
                "Dec deg", "Dec min", "Dec sec", "pmRA", "pmDEC", "Vmag", \
                "APFpri", "APFcad", "APFnshots", "lastobs", "APFmin", "APFmax", \
                "B-V", "APF Desired Precision", "Close Companion", \
                "APF decker","I2", "owner", "uth","utm","duration", "Template",
                "Nobs", "Total Obs"
                ]

    
    # Downloading all the values is going slowly.
    # Try to only have to load this once a day
    apflog( "Starting Googledex parse",echo=True)    
    if not outdir :
        outdir = os.getcwd()
    if os.path.exists(os.path.join(outdir,outfn)) and force_download is False:
        try:
            f = open(os.path.join(outdir,outfn),'rb')
            full_codex = pickle.load(f)
            f.close()
        except:
            full_codex = makeLocalCopy(req_cols,sheetns=sheetns,certificate=certificate,outfn=os.path.join(outdir,outfn))
    else:
        full_codex = makeLocalCopy(req_cols,sheetns=sheetns,certificate=certificate,outfn=os.path.join(outdir,outfn))

    col_names = full_codex[0]
    codex = full_codex[1:]

    didx = findColumns(col_names,req_cols)
    
    names = []
    star_table = []
    flags = { "do" : [], "decker" : [], "I2" : [], "owner" : [], "template" : [] }
    stars = []
    # Build the star table to return to 
    for ls in codex:
        row = []
        if ls[0] == '':
            continue
        apfpri = float_or_default(ls[didx["APFpri"]])
        nobs = int_or_default(ls[didx["Nobs"]])
        totobs = int_or_default(ls[didx["Total Obs"]],default=-1)

        if totobs > 0 and nobs >= totobs: continue
        if apfpri < prilim: continue
        # Get the star name
        names.append(parseStarname(ls[didx["Star Name"]]))
        
        # Get the RA
        raval = Coords.getRARad(ls[didx["RA hr"]], ls[didx["RA min"]], ls[didx["RA sec"]])
        if raval:
            row.append(raval)
        else:
            row.append(-1.)
        # Get the DEC
        decval = Coords.getDECRad(ls[didx["Dec deg"]], ls[didx["Dec min"]], ls[didx["Dec sec"]])
        if decval:
            row.append(decval)
        else:
            row.append(-3.14)

        for coln in ("pmRA", "pmDEC"):
            row.append(float_or_default(ls[didx[coln]]))

        # Vmag
        row.append(float_or_default(ls[didx["Vmag"]],default=15.0))
        
        # For now use the old 1e9 count value - these get recalculated 
        row.append(1200.0)
        row.append(1.e9)
        # APFpri
        row.append(apfpri)
        for coln in ["APFcad","APFnshots","lastobs"] :
            row.append(float_or_default(ls[didx[coln]]))

        for coln in [ "B-V", "APF Desired Precision" ]:
            inval = float_or_default(ls[didx[coln]],default=1.0)
            if inval < 0:
                inval = 1.
            if coln is 'B-V' and inval > 2:
                inval = 1
            if coln is 'APF Desired Precision' and inval > 10:
                inval = 10
            row.append(inval)
                    
        for coln in ["uth", "utm"]:
            row.append(int_or_default(ls[didx[coln]]))
                
        # duration:
        row.append(float_or_default(ls[didx["duration"]]))
                
        # APFmin
        row.append(float_or_default(ls[didx["APFmin"]],default=MIN_TOTOBS))
                
        # APFmax
        row.append(float_or_default(ls[didx["APFmax"]]))

        # Nobs
        row.append(nobs)
                
        # Total Obs
        if totobs >= 0:
            row.append(totobs)
        else:
            row.append(0)

        if row[DS_BV] > 1.2:
            i2cnts = ec.getI2_M(row[DS_ERR])
        else:
            i2cnts = ec.getI2_K(row[DS_ERR])
        if i2cnts < 100:
            i2cnts = 100

        row.append(i2cnts)
                
        check = checkflag("Close Companion",didx,ls,"\A(y|Y)","")
        if check == "Y" or check == "y" :
            flags['do'].append(check)
        else:
            flags['do'].append("")
            
        flags['decker'].append(checkflag("APF decker",didx,ls,"\A(W|N|T|S|O|K|L|M|B)",config["decker"]))
        i2select = checkflag("I2",didx,ls,"\A(n|N)",config["I2"])
        flags['I2'].append(i2select.upper())
        tempselect = checkflag("Template",didx,ls,"\A(n|N)",'Y')
        flags['template'].append(tempselect.upper())

        flags['owner'].append(checkflag("owner",didx,ls,"\A(\w?\.?\w+)",config["owner"]))

            
        star_table.append(row)
        star = ephem.FixedBody()
        star.name = ls[0]
        star._ra = ephem.hours(str(":".join([ls[didx["RA hr"]], ls[didx["RA min"]], ls[didx["RA sec"]]])))
        star._dec = ephem.degrees(str(":".join([ls[didx["Dec deg"]], ls[didx["Dec min"]], ls[didx["Dec sec"]]])))
        stars.append(star)

    return (names, np.array(star_table), flags, stars)
def can_order_ingredient(ingredient):
    img = Image.screen_grab(Coords.topping_order_area(ingredient))
    return Image.get_hash(img) == Image.CAN_RESTOCK_HASH[ingredient]
Beispiel #16
0
def parseCodex(config,
               sheetns=["RECUR_A100"],
               certificate='UCSC_Dynamic_Scheduler-4f4f8d64827e.json',
               prilim=1,
               sleep=True,
               hour_constraints=None):
    # These are the columns we need for scheduling
    req_cols = ["Star Name", "RA hr", "RA min", "RA sec", \
                    "Dec deg", "Dec min", "Dec sec", "pmRA", "pmDEC", "Vmag", \
                    "texp", "I2", "expcount", "decker","Close Companion", "APFnshots", \
                    "owner", "APFpri", "APFcad", "lastobs", "B-V", \
                    "cad", "pri", "nexp", "count",
                    "uth","utm","duration", \
                    "Template", "Nobs", "Total Obs", \
                    "mode", "raoff", "decoff", "Bstar", "obsblock",\
                    'sheetn' \
                    ]

    negsearch = re.compile("\-(\d+\.*\d*)")

    full_codex = retrieveCodex(
        req_cols,
        sheetns=sheetns,
        certificate='UCSC_Dynamic_Scheduler-4f4f8d64827e.json',
        sleep=sleep)

    col_names = full_codex[0]
    codex = full_codex[1:]

    didx = findColumns(col_names, req_cols)
    star_table = initStarTable(req_cols)

    if hour_constraints is not None:
        done_names = hour_constraints['runname'][hour_constraints['left'] < 0]
    else:
        done_names = []

    stars = []
    # Build the star table to return to
    for ls in codex:
        row = []
        if ls[0] == '':
            continue
        if "pri" in didx and ls[didx["pri"]] is not None:
            apfpri = intDefault(ls[didx["pri"]], default=-1)
        else:
            apfpri = intDefault(ls[didx["APFpri"]], default=-1)

        nobs = intDefault(ls[didx["Nobs"]])
        totobs = intDefault(ls[didx["Total Obs"]], default=-1)
        csheetn = checkFlag("sheetn", didx, ls, "\A(.*)", 'public')

        if totobs > 0 and nobs >= totobs: continue
        if apfpri < prilim: continue
        if csheetn in done_names: continue
        if apfpri > MAX_PRI: apfpri = MAX_PRI

        name = parseStarname(ls[didx["Star Name"]])
        # Get the RA
        raval, rahr, ramin, rasec = Coords.getRARad(ls[didx["RA hr"]],
                                                    ls[didx["RA min"]],
                                                    ls[didx["RA sec"]])
        if raval is None:
            # alarm
            apflog("Error in RA coordinates for %s" % (name),
                   level='warn',
                   echo=True)
            continue

        # Get the DEC
        decval, decdeg, decmin, decsec = Coords.getDECRad(
            ls[didx["Dec deg"]], ls[didx["Dec min"]], ls[didx["Dec sec"]])
        if decval is None:
            # alarm
            apflog("Error in Dec coordinates for %s" % (name),
                   level='warn',
                   echo=True)
            continue

        # why are we doing this you may ask?
        # we use Google sheets which cannot have -0 for a value
        # but if we pass a value like 00:-16:00 to eostele, it generates
        # an incorrect declination value
        # so, we move the - to the front of the sexagesimal string
        # the radian values above are only used for the scheduler, we still
        # command the telescope in the raw units

        if name and raval and decval:
            star_table["name"].append(name)

            star_table['ra'].append(raval)
            star_table['RA hr'].append(rahr)
            star_table['RA min'].append(ramin)
            star_table['RA sec'].append(rasec)

            star_table['dec'].append(decval)
            star_table["Dec deg"].append(decdeg)
            star_table["Dec min"].append(decmin)
            star_table["Dec sec"].append(decsec)
        else:
            continue

        mode = checkFlag("mode", didx, ls, "\A(b|B|a|A|c|C)", config["mode"])
        if type(mode) == str:
            mode = mode.upper()
        star_table['mode'].append(mode)
        star_table['raoff'].append(
            checkFlag("raoff", didx, ls, "\A((\+|\-)?\d+\.?\d*)",
                      config["raoff"]))
        star_table['decoff'].append(
            checkFlag("decoff", didx, ls, "\A((\+|\-)?\d+\.?\d*)",
                      config["decoff"]))

        for coln in ("pmRA", "pmDEC"):
            star_table[coln].append(floatDefault(ls[didx[coln]]))

        star_table['Vmag'].append(floatDefault(ls[didx["Vmag"]], default=15.0))
        star_table['texp'].append(floatDefault(ls[didx["texp"]], default=1200))
        expcount = floatDefault(ls[didx["expcount"]], default=1e9)
        if expcount > EXP_LIM:
            expcount = EXP_LIM
        star_table['expcount'].append(expcount)
        if "nexp" in didx and ls[didx["nexp"]] is not None:
            star_table['nexp'].append(intDefault(ls[didx["nexp"]], default=1))
        elif "count" in didx and ls[didx['count']] is not None:
            star_table['nexp'].append(intDefault(ls[didx["count"]], default=1))
        else:
            star_table['nexp'].append(
                intDefault(ls[didx["APFnshots"]], default=1))

        # scheduler specific
        if "cad" in didx and ls[didx['cad']] is not None:
            star_table['cad'].append(floatDefault(ls[didx["cad"]],
                                                  default=0.7))
        else:
            star_table['cad'].append(
                floatDefault(ls[didx["APFcad"]], default=0.7))

        star_table['pri'].append(apfpri)
        star_table["lastobs"].append(
            floatDefault(ls[didx["lastobs"]], default=0))

        inval = floatDefault(ls[didx["B-V"]], default=0.7)
        if inval < 0:
            inval = 1.
        if coln is 'B-V' and inval > 2:
            inval = 1
        star_table['B-V'].append(inval)

        # Nobs
        star_table['nobs'].append(nobs)

        # Total Obs
        if totobs >= 0:
            star_table['totobs'].append(totobs)
        else:
            star_table['totobs'].append(0)

        check = checkFlag("Close Companion", didx, ls, "\A(y|Y)", "")
        if check == "Y" or check == "y":
            star_table['do'].append(check)
        else:
            star_table['do'].append("")

        star_table['decker'].append(
            checkFlag("decker", didx, ls, "\A(W|N|T|S|O|K|L|M|B)",
                      config["decker"]))
        i2select = checkFlag("I2", didx, ls, "\A(n|N)", config["I2"])
        star_table['I2'].append(i2select.upper())
        tempselect = checkFlag("Template", didx, ls, "\A(n|N)", 'Y')
        star_table['Template'].append(tempselect.upper())

        star_table['owner'].append(
            checkFlag("owner", didx, ls, "\A(\w?\.?\w+)", config["owner"]))
        star_table['obsblock'].append(
            checkFlag("obsblock", didx, ls, "\A(\w+)", config["obsblock"]))
        #        star_table['inst'].append(checkFlag("inst",didx,ls,"(levy|darts)",config['inst']).lower())

        # need to check raoff and decoff values and alarm on failure

        if 'Bstar' in didx:
            star_table['Bstar'].append(
                checkFlag('Bstar', didx, ls, "(Y|y)", 'N'))
            star_table['sheetn'].append(csheetn)
        else:
            if 'RECUR_A100' in csheetn:
                star_table['Bstar'].append("Y")
                star_table['sheetn'].append('RECUR_A100')
            else:
                star_table['Bstar'].append("N")
                star_table['sheetn'].append(csheetn)

    badkeylist = []
    for k in star_table.keys():
        if len(star_table[k]) == 0:
            badkeylist.append(k)
    for k in badkeylist:
        del star_table[k]

    # This just reorders the columns
    # This way the ascii table has these columns in front to make finding targets by specific programs easier
    star_table_names = list(star_table.keys())
    for n in ('Dec sec', 'Dec min', 'Dec deg', 'RA sec', 'RA min', 'RA hr',
              'APFpri', 'sheetn', 'name'):
        if n in star_table_names:
            star_table_names.remove(n)
            star_table_names = [n] + star_table_names

    star_table = astropy.table.Table(star_table, names=star_table_names)

    return star_table
Beispiel #17
0
X = x, y
xdot, ydot, rdot, phidot = sp.symbols("xdot,ydot,rdot,phidot")
XdotSym = sp.Matrix([xdot, ydot])
xdot = x - y - x * (x**2 + 5 * y**2)
ydot = x + y - y * (x**2 + y**2)
Xdot = sp.Matrix([xdot, ydot])
r = sp.symbols("r", positive=True, real=True)
phi = sp.symbols("phi", real=True)
U = sp.Matrix([r, phi])
## then X(U) is given by:
x = r * sp.cos(phi)
y = r * sp.sin(phi)
XofU = sp.Matrix([x, y])
print("\nThe coordinate transformation:\n")
sp.pprint(XofU)
T1 = Coords(X, U, XofU, sp.trigsimp)
X, Y = T1.trans((R, PHI))
#X,Y=trans((R,PHI),(r,phi),x,y)

print("\nThe Jacobian of the transformation:\n")
sp.pprint(T1.J)
print("\nThe inverse of the Jacobian :\n")
sp.pprint(T1.Jinv)

xdot = x - y - x * (x**2 + 5 * y**2)
ydot = x + y - y * (x**2 + y**2)
Xdot = sp.Matrix([xdot, ydot])
Udot = T1.matSimp(T1.Jinv * Xdot)
print("\nThe system in the new variables:\n")
sp.pprint(sp.Matrix([rdot, phidot]))
sp.pprint(Udot)
Beispiel #18
0
def makeScriptobsLine(name, row, do_flag, t, decker="W",I2="Y",owner='Vogt'):
    """ given a name, a row in a star table and a do_flag, will generate a scriptobs line as a string
    line = makeScriptobsLine(name, row, do_flag, t, decker="W",I2="Y")
    name - name of star, first column in line
    row - star_table row for star that begins with name, cotains all of the data needed for the line except
    do_flag - a string for whether or not scriptob needs to do a pointing check before slewing to the target
    t - a datetime object, this is used to fill in the uth and utm fields,
    decker - one character field for the decker, defaults to "W"
    I2 - one character field for whether or not the Iodine cell is in, must be "Y" or "N"
    """
    focval = 0
    """Takes a line from the star table and generates the appropriate line to pass to scriptobs. """
    # Start with the target name
    ret = name + ' '
    # Add the RA as three elements, HR, MIN, SEC
    rastr = Coords.getCoordStr(np.degrees(row[DS_RA]),isRA=True)
    ret += rastr + ' '
    # Add the DEC as three elements, DEG, MIN, SEC
    decstr = Coords.getCoordStr(np.degrees(row[DS_DEC]))
    ret += decstr + ' '
    # Epoch
    ret += '2000 '
    # Proper motion RA and DEC
    ret += 'pmra=' + str(row[DS_PMRA]) + ' '
    ret += 'pmdec=' + str(row[DS_PMDEC]) + ' '
    # V Mag
    ret += 'vmag=' + str(row[DS_VMAG]) + ' '
    # T Exp
    if row[DS_EXPT] > MAX_EXPTIME:
        ret += 'texp=%d ' % (int(MAX_EXPTIME))
    elif row[DS_EXPT] <= MIN_EXPTIME:
        ret += 'texp=%d ' % (int(MIN_EXPTIME))
    else:
        ret += 'texp=' + str(int(row[DS_EXPT])) + ' '
    # I2
    ret += 'I2=%s ' % (I2)
    # lamp
    ret += 'lamp=none '
    # start time
    ret += 'uth=' + str(t.hour) + ' '
    ret += 'utm=' + str(t.minute) + ' '
    # Exp Count
    if row[DS_COUNTS] > 3e9:
        ret += 'expcount=%.3g' % (3e9) + ' '
    else:
        ret += 'expcount=%.3g' % (row[DS_COUNTS]) + ' '
    # Decker
    ret += 'decker=%s ' % (decker)
    # do flag
    if do_flag:
        ret += 'do=Y '
    else:
        ret += 'do= '
    # Count
    ret += 'count=' + str(int(row[DS_NSHOTS])) 

    ret += ' foc=' + str(int(focval))

    if owner != '':
        ret += ' owner=' + str(owner)
        
    return ret