コード例 #1
0
def mjdRADec2skyBright(mjd, ra, dec):
    dtObj = convert.mjd2datetime(mjd)

    moon = Moon(dtObj)
    moonRA, moonDec = moon.ra, moon.dec

    sun = Sun(dtObj)
    sunRA, sunDec = sun.ra, sun.dec

    # alpha
    moonSunAngle = geometry.subtends(sunRA,
                                     sunDec,
                                     moonRA,
                                     moonDec,
                                     units="DEGREES")

    # rho
    moonObjectAngle = geometry.subtends(moonRA,
                                        moonDec,
                                        ra,
                                        dec,
                                        units="DEGREES")

    moonAlt, moonAz = convert.raDec2AltAz(moonRA, moonDec, APOLAT, APOLONG,
                                          dtObj)
    objAlt, objAz = convert.raDec2AltAz(ra, dec, APOLAT, APOLONG, dtObj)

    if moonAlt > 0 and objAlt > 0:
        bright = lunskybright(moonSunAngle.degrees, moonObjectAngle.degrees,
                              moonAlt, objAlt)
    else:
        bright = 0

    return bright
コード例 #2
0
def main():
    running = True
    index = 0
    while running:
        if index >= 130:
            index = 0

        clock.tick(20)

        #2s产生一个太阳花
        if index % 40 == 0:
            sun = Sun(sunflower.rect)
            sunList.append(sun)

        screen.blit(bg_img_obj, (0, 0))
        screen.blit(sunbank_img_obj, (250, 0))
        screen.blit(sun_num_surface, (300, 5))

        screen.blit(peashooter.images[index % 13], peashooter.rect)
        screen.blit(sunflower.images[index % 13], sunflower.rect)
        screen.blit(wallnut.images[index % 13], wallnut.rect)

        for sun in sunList:
            screen.blit(sun.images[index % 17], sun.rect)

        index += 1
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        pygame.display.update()
コード例 #3
0
def createAndAnimate():
    ss = SolarSystem(2, 2)

    sun = Sun("SUN", 10)
    ss.addSun(sun)

    m = Planet("Mercury", 1000, 0.2, 1, 0, 2, "orange")
    ss.addPlanet(m)

    e = Planet("Earth", 5000, 0.3, 1.3, 0, 2, "blue")
    ss.addPlanet(e)

    ma = Planet("Mars", 9000, 0.5, 1.2, 0, 1.63, "red")
    ss.addPlanet(ma)

    p = Planet("Pluto", 500, 0.9, .5, 0, .5, "gray")
    ss.addPlanet(p)

    # a = Planet("Asteroid", 500, 1.0, 0, .75, "cyan")
    # ss.addPlanet(a)

    numCycles = 10000
    for i in range(numCycles):
        ss.movePlanets()

    # while True:
    #     ss.movePlanets()
    #     # You can add functionality to break away from the loop given some condition
    #     # use the keyword break
    #     break


    ss.freeze()
コード例 #4
0
def main():
    running = True
    index = 0
    while running:
        if index >= 130:
            index = 0

        clock.tick(20)

        #2s产生一个太阳花
        if index % 40 == 0:
            sun = Sun(sunflower.rect)
            spriteGroup.add(sun)



        screen.blit(bg_img_obj,(0,0))
        screen.blit(sunbank_img_obj,(250,0))
        screen.blit(sun_num_surface,(300,5))

        spriteGroup.update(index)
        spriteGroup.draw(screen)

        index+=1
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        pygame.display.update()
コード例 #5
0
 def calcPos(self, mjd, config):
     """Calculate the moon's ecliptic lon/lat and geocentric RA/Dec, for the given MJD(s)."""
     self.mjd = numpy.copy(mjd)
     self.ra = numpy.zeros(len(mjd), 'float')
     self.dec = numpy.zeros(len(mjd), 'float')
     for i in range(len(mjd)):
         # Calculate moon's position.
         ra_RAD, dec_RAD, diam = slalib.sla_rdplan(
             mjd[i], 3, config['longitude'] * _deg2rad,
             config['latitude'] * _deg2rad)
         self.ra[i] = ra_RAD * _rad2deg
         self.dec[i] = dec_RAD * _rad2deg
     # Calculate the lunar phase.
     eclon = numpy.zeros(len(mjd), 'float')
     eclat = numpy.zeros(len(mjd), 'float')
     for i in range(len(mjd)):
         eclon[i], eclat[i] = slalib.sla_eqecl(self.ra[i] * _deg2rad,
                                               self.dec[i] * _deg2rad,
                                               self.mjd[i])
     # Calculate the solar longitude.
     sun = Sun()
     lon_sun = sun.getLon(self.mjd) * _deg2rad
     # Calculate the solar elongation of the Moon.
     solarelong = numpy.arccos(
         numpy.cos((lon_sun - eclon)) * numpy.cos(eclat))
     # Calculate the phase of the moon. This is the 0-180 degrees phase.
     self.phase = 180.0 - solarelong * _rad2deg
     # Calculate the illumination of the Moon. This is between 0 - 100, and is what Opsim calls 'moonPhase'.
     self.illum = (1 + numpy.cos(self.phase * _deg2rad)) / 2.0 * 100.0
     return
コード例 #6
0
def dusk(scene):
    sun = Sun(pos=Vec3(40, 20, 0), colour=Vec3(0.4, 0.2, 0.4))
    # orient sun
    sun.lookAt(Vec3(0, 0, 0))
    # Add sun to scene
    scene.addLight(sun)
    # Create sky
    sky = Sky()
    # Add sky to scene
    scene.addLight(sky)
コード例 #7
0
def midDay(scene):
    sun = Sun(pos=Vec3(40, 100, 30))
    # orient sun
    sun.lookAt(Vec3(0, 0, 0))
    # Add sun to scene
    scene.addLight(sun)
    # Create sky
    sky = Sky()
    # Add sky to scene
    scene.addLight(sky)
コード例 #8
0
def get_sunset_time():
    global sunset_today
    sun = Sun()
    sunset = sun.getSunsetTime(coords)
    sunset_time = str(sunset['hr']) + ':' + str(int(sunset['min'])) + ' UTC'
    sunset_time_local = parser.parse(sunset_time).astimezone(timezone)
    sunset_today = {
        'hr': int(sunset_time_local.strftime('%H')),
        'min': int(sunset_time_local.strftime('%M'))
    }
    return sunset_today
コード例 #9
0
def isSunRise(coords):
    """
    Check if Sun has risen for the specified Coordinates
    """
    sun = Sun()
    SunRiseTime = sun.getSunriseTime(coords)

    now = datetime.now()
    SunRiseTimeDT = datetime(now.year, now.month, now.day, SunRiseTime['hr'],
                             int(SunRiseTime['min']), 00)

    if now > SunRiseTimeDT + timedelta(minutes=30):
        print "Sun is risen"
        print "Now", now, "SunRise", SunRiseTimeDT
        return True
    else:
        return False
コード例 #10
0
ファイル: project3.py プロジェクト: iErdem1/api_management
def main():
    pprint("asdasdsadasdasd")

    user_obj = User()
    sun_obj = Sun()
    trump_obj = TrumpRavings()

    for i in range(len(user_obj.users)):
        age = int(user_obj.users[i]['Age'])
        pprint("Welcome {name}!".format(name=user_obj.users[i]['Name']))
        pprint("""Here is your current location: {location} 
                    Sun Movement Information:
                    {sun_info}
                    According to your age, a silly Donald Trump tweet to have fun:
                    {trump}""".format(location=user_obj.users[i]['City'],
                                      sun_info=sun_obj.results[i],
                                      trump=trump_obj.quotes[age]))
コード例 #11
0
def timingloop():
    coords = {'latitude': 41, 'longitude': -72}
    sun = Sun()
    didsunset = False
    didsunrise = False
    while True:
        sunrise = sun.getSunriseTime(coords)
        sunset = sun.getSunsetTime(coords)
        now = datetime.datetime.now(tz=datetime.timezone.utc)
        hourdec = now.hour + now.minute / 60

        sr = (hourdec + SUNRISE_DELAY) % 24 > sunrise['decimal']
        if sr and not didsunrise:
            for light in lights.keys():
                setoff(light)
        
        ss = hourdec > (sunset['decimal'] + SUNSET_DELAY) % 24
        if ss and not didsunset:
            for light in lights.keys():
                seton(light)

        didsunset, didsunrise = ss, sr

        time.sleep(10)
コード例 #12
0
def main():
    global text
    global sun_num_surface
    running = True
    index = 0
    while running:
        # if index >= 130:
        #     index = 0

        clock.tick(20)

        #2s产生一个太阳花
        # if index % 40 == 0:
        #     sun = Sun(sunflower.rect)
        #     sunList.add(sun)

        #3s产生一个子弹
        if index % 30 == 0:
            bullet = Bullet(peashooter.rect, backgd_size)
            spriteGroup.add(bullet)


        screen.blit(bg_img_obj,(0,0))
        screen.blit(sunbackImg,(250,0))
        screen.blit(sun_num_surface,(270,60))

        screen.blit(flower_seed, (330, 10))
        screen.blit(wallNut_seed, (380, 10))
        screen.blit(peashooter_seed, (430, 10))


        spriteGroup.update(index)
        spriteGroup.draw(screen)

        sunList.update(index)
        sunList.draw(screen)

        index+=1
        for event in pygame.event.get():
            if event.type == GEN_SUN_EVENT:
                sun = Sun(sunflower.rect)
                sunList.add(sun)
            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.MOUSEBUTTONDOWN:
                pressed_key = pygame.mouse.get_pressed()
                print(pressed_key)
                if pressed_key[0] == 1:
                    pos = pygame.mouse.get_pos()
                    print(pos)
                    x,y = pos
                    if 330<=x<=380 and 10<=y<=80 and int(text) >= 50:
                        print('点中了太阳花卡片')
                        choose = 1
                    elif 380<x<=430 and 10<=y<=80 and int(text) >= 50:
                        print('点中了坚果卡片')
                        choose = 2
                    elif 430 < x <= 480 and 10 <= y <= 80 and int(text) >= 100:
                        print('点中了豌豆射手卡片')
                        choose = 3
                    elif 250 < x < 1200 and 70<y<600:
                        print('#########')
                        print(x,y)
                        pass
                    else:
                        pass
                    for sun in sunList:
                        if sun.rect.collidepoint(pos):
                            sunList.remove(sun)
                            text = str(int(text)+50)
                            sun_font = pygame.font.SysFont('arial', 25)
                            sun_num_surface = sun_font.render(text, True, (0, 0, 0))

        pygame.display.update()
コード例 #13
0
    GPIO.cleanup()
    sys.exit(0)
signal.signal(signal.SIGINT, sign_handler)
# Taster Rauf und Runter
GPIO.setmode(GPIO.BOARD)
GPIO.setup(PIN_SWITCH_UP,GPIO.IN)# pin 7 -> Rauf 
GPIO.setup(PIN_SWITCH_DOWN,GPIO.IN)# Pin 29 zum runterfahren 
# Relais Schaltungen
GPIO.setup(PIN_RELAIS_UP, GPIO.OUT) # pin 3 -> rauf
GPIO.setup(PIN_RELAIS_DOWN, GPIO.OUT) # pin 5 -> runter
GPIO.output(PIN_RELAIS_UP, RELAISOFF) # Relaises auschalten
GPIO.output(PIN_RELAIS_DOWN , RELAISOFF)

#Use GPS Coordinats for morning open and evening close
COORDS = {'longitude' : 11.581981, 'latitude' : 48.135125}
SUN = Sun()
lastUpDay = datetime.datetime.today().day -1 # fur die sonnenstandAbfrage
lastDownDay = datetime.datetime.today().day -1
hochfahren = 0
runterfahren = 0
buttonPressedUp = False
buttonPressedDown = False
buttonsLocked = False
alterStatusHochfahren = False
alterStatusRunterfahren = False
alterStatusStop = False
StartzeitBewegung = 0.0
StartzeitSwitchUp = 0.0
StartzeitSwitchDown = 0.0
stop = False
mynow = 0.0
コード例 #14
0
def main():
    global text,choose
    global sun_num_surface
    running = True
    # index必须初始化为0,否则第一张图片进不去屏幕
    index = 0
    while running:
        # if index >= 130:
        #     index = 0

        clock.tick(20)
        # if not pygame.mixer.music.get_busy():
        #     pygame.mixer.music.play()
        #2s产生一个太阳花
        # if index % 40 == 0:
        #     sun = Sun(sunflower.rect)
        #     sunList.add(sun)

        #3s产生一个子弹
        # if index % 30 == 0:
        #     for sprite in spriteGroup:
        #         if isinstance(sprite, Peashooter):
        #             bullet = Bullet(sprite.rect, backgd_size)
        #             spriteGroup.add(bullet)

        for bullet in bulletGroup:
            for zombie in zombieGroup:
                # 直接使用下列函数实现碰撞检测,
                # 这个函数接收两个精灵作为参数,返回值是一个bool变量。
                if pygame.sprite.collide_mask(bullet,zombie):
                    zombie.energy -= 1
                    bulletGroup.remove(bullet)

        for wallNut in wallNutGroup:
            # 只要僵尸与植物接触就是zombie.isMeetWallNut = True
            # 接触之后将其放入精灵建立的set函数产生的无序列表中
            for zombie in zombieGroup:
                if pygame.sprite.collide_mask(wallNut, zombie):
                    zombie.isMeetWallNut = True
                    wallNut.zombies.add(zombie)

        for peaShooter in peaShooterGroup:
            for zombie in zombieGroup:
                if pygame.sprite.collide_mask(peaShooter, zombie):
                    zombie.isMeetWallNut = True
                    peaShooter.zombies.add(zombie)

        for sunFlower in sunFlowerGroup:
            for zombie in zombieGroup:
                if pygame.sprite.collide_mask(sunFlower, zombie):
                    zombie.isMeetWallNut = True
                    sunFlower.zombies.add(zombie)

        # 图片绘制
        screen.blit(bg_img_obj,(0,0))
        screen.blit(sunbackImg,(250,0))
        # 这个是放植物的框图
        screen.blit(sun_num_surface,(270,60))
        # 绘制种子图片在框框里面
        screen.blit(flower_seed, (330, 10))
        screen.blit(wallNut_seed, (380, 10))
        screen.blit(peashooter_seed, (430, 10))


        # spriteGroup.update(index)
        # spriteGroup.draw(screen)
        bulletGroup.update(index)
        bulletGroup.draw(screen)
        zombieGroup.update(index)
        zombieGroup.draw(screen)


        wallNutGroup.update(index)
        wallNutGroup.draw(screen)
        peaShooterGroup.update(index)
        peaShooterGroup.draw(screen)

        sunFlowerGroup.update(index)
        sunFlowerGroup.draw(screen)

        sunList.update(index)
        sunList.draw(screen)
        # 确定鼠标点击的横纵坐标
        (x,y) = pygame.mouse.get_pos()

        # if choose == 1:
        #     screen.blit(sunFlowerImg,(x,y))
        # elif choose == 2:
        #     screen.blit(wallnutImg, (x, y))
        # elif choose == 3:
        #     screen.blit(peashooterImg, (x, y))


        # 确定好三种植物后绘制图像位置,一般都在鼠标点击点在图片的正中心
        if choose == 1:
            screen.blit(sunFlowerImg, (x - sunFlowerImg.get_rect().width // 2, y - sunFlowerImg.get_rect().height // 2))
        if choose == 2:
            screen.blit(wallnutImg, (x - wallnutImg.get_rect().width // 2, y - wallnutImg.get_rect().height // 2))
        if choose == 3:
            screen.blit(peashooterImg,
                        (x - peashooterImg.get_rect().width // 2, y - peashooterImg.get_rect().height // 2))
        # index控制确定的次数和机会,点了一次,index加一对应刷新一次屏幕
        index+=1




        # 精灵调用以及添加精灵组
        for event in pygame.event.get():
            if event.type == GEN_FLAGZOMBIE_EVENT:
                zombie = FlagZombie()
                zombieGroup.add(zombie)

            if event.type == GEN_ZOMBIE_EVENT:
                zombie = Zombie()
                zombieGroup.add(zombie)

            if event.type == GEN_SUN_EVENT:
                for sprite in sunFlowerGroup:
                    # 返回当前时间的时间戳,控制太阳出现的时间
                    now = time.time()
                    if now - sprite.lasttime >= 5:
                        sun = Sun(sprite.rect)
                        sunList.add(sun)
                        sprite.lasttime = now

            if event.type == GEN_BULLET_EVENT:
                for sprite in peaShooterGroup:
                    bullet = Bullet(sprite.rect, backgd_size)
                    bulletGroup.add(bullet)

            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.MOUSEBUTTONDOWN:
                pressed_key = pygame.mouse.get_pressed()
                print(pressed_key)
                if pressed_key[0] == 1:
                    pos = pygame.mouse.get_pos()
                    print(pos)
                    x,y = pos
                    if 330<=x<=380 and 10<=y<=80 and int(text) >= 50:
                        print('点中了太阳花卡片')
                        choose = 1
                    elif 380<x<=430 and 10<=y<=80 and int(text) >= 50:
                        print('点中了坚果卡片')
                        choose = 2
                    elif 430 < x <= 480 and 10 <= y <= 80 and int(text) >= 100:
                        print('点中了豌豆射手卡片')
                        choose = 3
                    elif 250 < x < 1200 and 70<y<600:
                        #种植植物
                        if choose == 1:
                            current_time = time.time()
                            sunFlower = SunFlower(current_time)
                            sunFlower.rect.top = y
                            sunFlower.rect.left = x
                            sunFlowerGroup.add(sunFlower)
                            choose = 0

                            #扣除分数
                            text = int(text)
                            text -= 50
                            myfont = pygame.font.SysFont('arial',20)
                            sun_num_surface = myfont.render(str(text),True,(0,0,0))
                        elif choose == 2:
                            wallNut = WallNut()
                            wallNut.rect.top = y
                            wallNut.rect.left = x
                            wallNutGroup.add(wallNut)
                            choose = 0

                            # 扣除分数
                            text = int(text)
                            text -= 50
                            myfont = pygame.font.SysFont('arial', 20)
                            sun_num_surface = myfont.render(str(text), True, (0, 0, 0))
                        elif choose == 3:
                            peashooter = Peashooter()
                            peashooter.rect.top = y
                            peashooter.rect.left = x
                            peaShooterGroup.add(peashooter)
                            choose = 0

                            # 扣除分数
                            text = int(text)
                            text -= 50
                            myfont = pygame.font.SysFont('arial', 20)
                            sun_num_surface = myfont.render(str(text), True, (0, 0, 0))

                        print('#########')
                        print(x,y)
                        pass
                    else:
                        pass
                    for sun in sunList:
                        if sun.rect.collidepoint(pos):
                            sunList.remove(sun)
                            text = str(int(text)+50)
                            # 分数变化后循环渲染字体
                            sun_font = pygame.font.SysFont('arial', 20)
                            sun_num_surface = sun_font.render(text, True, (0, 0, 0))

        pygame.display.update()
コード例 #15
0
ファイル: opsimObs.py プロジェクト: rhiannonlynne/OpsimObs
def run(inputobs_file, config):
    
    # Set up a skypos object to hold site information and provide ra/dec -> alt/az/airmass translations.
    skypos = SkyPos()
    skypos.setSite(lat=config['latitude'], lon=config['longitude'], height=config['height'],
                   pressure=config['pressure'], temperature=config['temperature'],
                   relativeHumidity=config['relativeHumidity'], lapseRate=config['lapseRate'])

    # Set up a Weather object to read the site weather data.
    t = time.time()
    weather = Weather()
    weather.readWeather(config)
    dt, t = dtime(t)
    print '# Reading weather required %.2f seconds' %(dt)

    # Set up a Downtime object to read the downtime data.
    downtime = Downtime()
    downtime.readDowntime(config)
    dt, t = dtime(t)
    print '# Reading downtime required %.2f seconds' %(dt)

    # Read observations.
    obs = ObsFields()
    obs.readInputObs(inputobs_file, config)
    nobs = len(obs.ra)
    dt, t = dtime(t)
    print '# Reading %d input observations required %.2f seconds' %(nobs, dt)
    # Check timing of input observations.
    if config['check_observations']:
        obs.checkInputObs(config)
        dt, t = dtime(t)
        print '# Checking %d input observations required %.2f seconds' %(nobs, dt)
    else:
        print '# Did not check input observations for minimum required timing separation!'

    # Calculate alt/az/airmass for all fields.
    obs.getAltAzAirmass(skypos)
    dt, t = dtime(t)
    print '# Calculating alt/az/airmass for %d input observations required %.2f seconds' %(nobs, dt)
    # Calculate weather (cloud/seeing) for all fields.
    dt, t = dtime(t)
    obs.getObsWeather(weather, config)
    dt, t = dtime(t)
    print '# Getting weather information for %d observations required %.2f seconds' %(nobs, dt)
    # Check downtime status for these observations
    obs.getDowntime(downtime, config)

    # Calculate position of sun at the times of these observations.
    sun = Sun()
    dt, t = dtime(t)
    sun.calcPos(obs.mjd)
    sun.getAltAz(skypos)
    dt, t = dtime(t)
    print '# Calculating sun position at %d times required %.2f seconds' %(nobs, dt)

    # Calculate the position, phase and altitude of the Moon. 
    moon = Moon()
    moon.calcPos(obs.mjd, config)
    moon.getAltAz(skypos)
    dt, t = dtime(t)
    print '# Calculating moon position at %d times required %.2f seconds' %(nobs, dt)

    # Will clean this up and put into classes as time is available. 
    # Calculate the sky brightness. 
    skybright = SkyBright(model='Perry', solar_phase='ave')    
    sky = numpy.zeros(len(obs.mjd), 'float')
    filterlist = numpy.unique(obs.filter)
    for f in filterlist:
        condition = (obs.filter == f)
        skybright.setSkyBright(obs.alt[condition], obs.az[condition], moon.alt[condition], moon.az[condition], 
                               moon.phase[condition], bandpass = f)
        sky[condition] = skybright.getSkyBright()
    # Add modification to match 'skybrightness_modified' (which is brighter in twilight)
    sky = numpy.where(sun.alt > -18, 17, sky)
    dt, t = dtime(t)
    print '# Calculating the sky brightness for %d observations required %.2f seconds' %(nobs, dt)

    # Calculate the 5-sigma limiting magnitudes. 
    maglimit = numpy.zeros(len(obs.mjd), 'float')
    m5 = m5calculations()
    # Read the throughput curves for LSST (needed to determine zeropoints). 
    m5.setup_Throughputs(verbose=False)
    # Swap 'y4' for 'y' (or other default y value). 
    tmp_filters = m5.check_filter(obs.filter)
    # Determine the unique exposure times, as have to set up dark current, etc. based on this for telescope ZP's.
    exptimes = numpy.unique(obs.exptime)
    for expT in exptimes:
        condition = [obs.exptime == expT]
        # Calculate telescope zeropoints.        
        # Calculate actual open-sky time, after accounting for readout time, number of exposures per visit, shutter time, etc.
        opentime = ((expT - config['readout_time']*config['nexp_visit'] -  config['nexp_visit']* config['add_shutter']*config['shutter_time']) 
                    / float(config['nexp_visit']))
        print "# Calculating depth for %d exposures of %.2f open shutter time" %(config['nexp_visit'], opentime)
        m5.setup_values(expTime=opentime, nexp=config['nexp_visit'])
        # Calculate 5sigma limiting magnitudes. 
        maglimit[condition] = m5.calc_maglimit(obs.seeing[condition], sky[condition], tmp_filters[condition], obs.airmass[condition], snr=5.0)        
    dt, t = dtime(t)
    print '# Calculating the m5 limit for %d observations required %.2f seconds' %(nobs, dt)
        
    # Print out interesting values. 
    obs.printObs(sun, moon, sky, maglimit,  config)
コード例 #16
0
ファイル: SolarHeating.py プロジェクト: jszmajda/antioch
 def __init__(self):
     self.sun = Sun()
     self.day_offset = timedelta(hours=2)
     self.night_offset = timedelta(hours=3)
     self.cache = dict()
コード例 #17
0
# RenderIt.py
"An example for how to use this program to render"
from Vector3 import Vec3
from Camera import Camera
from Scene import Scene
from Sun import Sun
from Sky import Sky
from Octree import Braunch
from timeit import default_timer as timer
# Create new scene
scene = Scene()
# Load Model and materials
scene.loadModel("models/planet.obj", "models/planet.mtl")
# Create Sun
sun = Sun(pos=Vec3(40, 100, 30))
# orient sun
sun.lookAt(Vec3(0, 0, 0))
# Add sun to scene
scene.addLight(sun)
# Create sky
sky = Sky()
# Add sky to scene
scene.addLight(sky)
# Create Camera (pos, width height)
cam = Camera(Vec3(3.5, 4, 0), int(400), int(200), Fov=1.4, Samples=2)
# Orient camera
cam.lookAt(Vec3(0, 3, 0))
# Render scene
ts = timer()
cam.render(scene, "flower.png")
print("Time elapsed: {}s".format(timer() - ts))
コード例 #18
0
def getloc(year,month,day,sunrise,sunset,altitude=0):
    if sunrise>sunset: #Handle sunrise from day before not being negative, as
                       #it really should be.
        sunrise=sunrise-24.0
    
    tester=Sun()
    daylen=sunset-sunrise
    darc=cosd(7.5*daylen) #diurnal arc

    #Latitude, round I
    days=tester.daysSince2000Jan0(year,month,day) + 0.5 
    rasc,dec,radius=tester.sunRADec(days) #right ascension,declination,radius of sun.
    alt=-35.0/60.0-0.2666/radius

    #Account for altitude.
    alt-=acosd(6378.0/(6378.0+altitude))

    #Precalculated sines
    b=sind(alt)
    c=sind(dec)

    #Cribs
    crib1=darc*darc*c*c-darc*darc
    crib2=c*c-crib1
    crib3=2*b*c

    #Calculation
    uroot=crib3**2-4*(b*b+crib1)*crib2
    if uroot<0: uroot=-uroot
    uroot=math.sqrt(uroot)/(2*crib2)
    rest=crib3/(2*crib2)

    #Choose best of the 2 possible solutions
    try:
        lat_i=asind(rest-uroot)
        i=abs(diff(tester.sunRiseSet(year,month,day,0,lat_i))-daylen)
    except ValueError:
        i=1000
    try:
        lat_ii=asind(rest+uroot)
        ii=abs(diff(tester.sunRiseSet(year,month,day,0,lat_ii))-daylen)
    except ValueError:
        ii=1000
    if i<ii: lat=lat_i
    else: lat=lat_ii

    #Find longitude
    midday=(sunset+sunrise)/2
    gmmid=av(tester.sunRiseSet(year,month,day,0,lat))
    lon=-(midday-gmmid)*15

    #Latitude, round II (using longitude)
    d=tester.daysSince2000Jan0(year,month,day) + 0.5 - lon/360.0
    RA__,dec,radius=tester.sunRADec(d)
    alt=-35.0/60.0-0.2666/radius

    #Account for altitude.
    alt-=acosd(6378.0/(6378.0+altitude))

    #Precalculated sines
    b=sind(alt)
    c=sind(dec)

    #Cribs
    crib1=darc*darc*c*c-darc*darc
    crib2=c*c-crib1
    crib3=2*b*c

    #Calculation
    uroot=crib3**2-4*(b*b+crib1)*crib2
    if uroot<0: uroot=-uroot
    uroot=math.sqrt(uroot)/(2*crib2)
    rest=crib3/(2*crib2)

    #Choose best of the 2 possible solutions
    try:
        lat_i=asind(rest-uroot)
        i=abs(diff(tester.sunRiseSet(year,month,day,0,lat_i))-daylen)
    except ValueError:
        i=1000
    try:
        lat_ii=asind(rest+uroot)
        ii=abs(diff(tester.sunRiseSet(year,month,day,0,lat_ii))-daylen)
    except ValueError:
        ii=1000
    if i<ii: lat=lat_i
    else: lat=lat_ii

    #Return tuple in similar fashion to Sun.sunRiseSet
    return (lon,lat)
コード例 #19
0
ファイル: main.py プロジェクト: DennisHagebrand/cr-smart-home
def main():
    #---------------------------------------------------------------------------#
    # Logging - Rotate log file at midnight and keep for 7 days
    #---------------------------------------------------------------------------#
    handler = logging.handlers.TimedRotatingFileHandler(Config.Log_Filename,
                                                        when="midnight",
                                                        interval=1,
                                                        backupCount=7)
    handler.setFormatter(
        logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s'))

    logger = logging.getLogger('cr-smart-home')
    logger.addHandler(handler)
    logger.setLevel(Config.Log_Level)

    log = Log()
    log.info('Server', 'Starting CR Smart Home %s...' % Config.Version)

    #---------------------------------------------------------------------------#
    # Upgrade
    #---------------------------------------------------------------------------#
    upgrade = Upgrade()
    upgrade.Upgrade()

    #---------------------------------------------------------------------------#
    # Startup
    #---------------------------------------------------------------------------#
    weather = Weather()
    sun = Sun()
    lamp = Lamp()
    sensor = Sensor()

    log.info(
        'Server', 'System is running in %s (Lat=%f, Long=%f)' %
        (weather.city, sun.latitude, sun.longitude))
    bStartUp = True

    #---------------------------------------------------------------------------#
    # Run program
    #---------------------------------------------------------------------------#
    while True:
        # Update current weather on startup or every 30 minutes
        if (datetime.now().minute == 0 or datetime.now().minute == 30
                or bStartUp == True):
            weather.UpdateCurrentWeather()

        # Update sun to database every hour
        if (datetime.now().minute == 0 or bStartUp == True):
            sun.UpdateDb()

        # Lamp schedule
        lamp.Schedule()

        # Sensors
        if (datetime.now().minute % 10 == 0 or bStartUp):
            sensor.readAll()

        #Reset startup bool
        bStartUp = False

        #Sleep one minute
        time.sleep(60 - datetime.now().second)
コード例 #20
0
 def __init__(self):
     self.logger = logging.getLogger('cr-smart-home')
     self.log = Log()
     self.sun = Sun()
コード例 #21
0
 def __init__(self, name, season, latitude, longitude):
     self.name = name
     self.sun = Sun(latitude, longitude)
     self.season = season
     self.rooms = []
     self.dweet = 'ICTBUILDINGPUTINASHADE'
コード例 #22
0
ファイル: octreetest.py プロジェクト: BRENDAN-09/Py-tracer
from Octree import Braunch
from Scene import Scene
from Vector3 import Vec3
from timeit import default_timer as timer
from Sun import Sun
from Sky import Sky
from Camera import Camera

# Create new scene
scene = Scene()
# Load Model and materials
scene.loadModel("untitled.obj", "untitled.mtl")

sun = Sun(pos=Vec3(-20, 30, 30))
sun.lookAt(Vec3(0, 0, 0))
scene.addLight(sun)
sun.size = 3
# Create sky
sky = Sky(colour=Vec3(0.3, 0.2, 0.3))
scene.addLight(sky)
# Create Camera
cam = Camera(Vec3(-4, 3, -5), 256, 256, Fov=1, Samples=7)
cam.lookAt(Vec3(0, 0, 0))
tree = Braunch()
tree.fromScene(scene)
tree.display()
# Render scene
ts = timer()
cam.render(tree)
treeTime = timer() - ts
# print("Render time: {}".format(timer()-ts))
コード例 #23
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec  1 12:05:33 2020

@author: dpetrovykh
"""

from Node import Limb
from Sun import Sun
from Tree import Tree
import matplotlib.pyplot as plt

sun = Sun(5, 0)

node_A = Limb(0, 0)
node_B = Limb(-1, 2)
node_C = Limb(2, 1)
node_A.add_child(node_B)
node_A.add_child(node_C)
node_B.gen_child(-0.5, 0.5)
node_B.gen_child(0.5, 0.5)
node_C.gen_child(-0.5, 0.5)
node_C.gen_child(0.5, 0.5)

for node in [*node_B.children, *node_C.children]:
    node.gen_leaf(-0.2, 0.2)
    node.gen_leaf(0.2, 0.2)

tree = Tree(node_A)
for tstep in range(0, 100):
コード例 #24
0
elif (len(sys.argv) == 3):
    annee = int(sys.argv[2].split('/')[2])
    mois = int(sys.argv[2].split('/')[1])
    jour_mois = int(sys.argv[2].split('/')[0])
    jour_semaine = datetime.datetime(annee, mois, jour_mois, 0, 0,
                                     0).weekday()  #Lundi 0 .... Dimanche 6

minute_journee = plage_proche(
    now.tm_hour * 60 + now.tm_min,
    plage)  #Commence une minute avant un plage existante
site_alpha.actualisation_heure_jour_machine_foyer(
)  #Calcul des horaires pour les différentes machines

# ---------- AJOUTER LATITUDE ET LONGITUDE DE LA VILLE OU VOUS ETES ---------- #
coords = {'longitude': 2.3522, 'latitude': 48.8566}
sun = Sun()
# ---------- AJOUTER LE DECALAGE HORAIRE PAR RAPPORT AU MERIDIEN DE GREENWICH ----------#
decalage_horaire = 1.0

#consommation globale du site
consommation_total = 0

#Gestion de l'affichage
pygame.init()
#Ouverture de la fenêtre Pygame
fenetre = pygame.display.set_mode((largeur_fenetre, longueur_fenetre))
etat_affichage = "menu"

#Stockage
stockage_val = 0
stockage_max = 100000000
コード例 #25
0
    # print(time.time())
    clock.tick(15)
    # 启动消息队列,获取消息并处理
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

        if event.type == GENERATOR_SUN_EVENT:
            # 当前是否有太阳花对象,有几个太阳花对象,就生成几个太阳
            if len(sunFlowerList) > 0:
                timeNow = time.time()
                for sunFlower in sunFlowerList:
                    if timeNow - sunFlower.lasttime >= 5:
                        sunFlower.lasttime = timeNow
                        sun = Sun(sunFlower.rect)
                        sunList.add(sun)

        if event.type == GENERATOR_PEASHOOTER_EVENT:
            # 当前是否有太阳花对象,有几个太阳花对象,就生成几个太阳
            if len(peashooterList) > 0:
                for peashooter in peashooterList:
                    bullet = Bullet(peashooter.rect, size)
                    bulletList.add(bullet)

        if event.type == GENERATOR_ZOMBIE_EVENT:
            randomIndex = random.randrange(0, len(nameList))
            nameOfZombie = nameList[randomIndex]
            zombie = Zombie(nameOfZombie)
            zombieList.add(zombie)
コード例 #26
0
ファイル: data.py プロジェクト: Assaf124/UV_Application
def calculate_sun_angle(latitude, longitude, local_time_unix_format,
                        time_offset, *args):
    """
    This function calculates the Sun actual angle in the sky based on latitude, longitude
    and local time

    Args:
        latitude:               Integer. the latitude of the given location
        longitude:              Integer. the longitude of the given location
        local_time_unix_format: Integer.
        time_offset:            Integer.

    Returns:
        sun_angle:  Integer. The sun actual angle in the sky.

    Raises:
        Exception:     Raises an exception.
    """

    sun_max_angle = calculate_sun_max_angle(latitude)

    time_offset_hours = time_offset / 3600
    sun = Sun()

    sunrise_hour = math.floor(
        sun.get_sunrise_time(latitude, longitude)['decimal'] +
        time_offset_hours)
    sunrise_minutes = 60 * (sun.get_sunrise_time(
        latitude, longitude)['decimal'] + time_offset_hours - sunrise_hour)
    LOGGER.info(f'Sunrise value: {sunrise_hour}:{sunrise_minutes}')

    sunset_hour = math.floor(
        sun.get_sunset_time(latitude, longitude)['decimal'] +
        time_offset_hours)
    sunset_minutes = 60 * (sun.get_sunset_time(latitude, longitude)['decimal']
                           + time_offset_hours - sunset_hour)
    LOGGER.info(f'Sunset value: {sunset_hour}:{sunset_minutes}')

    daylength = sun.get_sunset_time(
        latitude, longitude)['decimal'] - sun.get_sunrise_time(
            latitude, longitude)['decimal']
    daylength_in_minutes = daylength * 60
    LOGGER.info(f'Calculated day length: {daylength} hours')

    local_time_in_minutes = extract_minutes_from_timestamp(
        get_local_time(latitude, longitude)[0], True)
    LOGGER.info(f'Calculated local_time_in_minutes: {local_time_in_minutes}')

    sunrise_in_minutes = sunrise_hour * 60 + sunrise_minutes
    LOGGER.info(f'Calculated sunrise_in_minutes: {sunrise_in_minutes}')

    sunset_in_minutes = sunset_hour * 60 + sunset_minutes
    LOGGER.info(f'Calculated sunrise_in_minutes: {sunset_in_minutes}')

    if local_time_in_minutes < sunrise_in_minutes:
        sun_angle = 0
        LOGGER.info(f'local_time_in_minutes < sunrise_in_minutes. It is night')

    elif local_time_in_minutes > sunset_in_minutes:
        sun_angle = 0
        LOGGER.info(f'local_time_in_minutes > sunset_in_minutes. It is night')

    else:
        m = (local_time_in_minutes -
             sunrise_in_minutes) / (daylength_in_minutes / 2)
        if m <= 1:
            sun_angle = sun_max_angle * m

        else:
            n = (local_time_in_minutes -
                 sunrise_in_minutes) - (daylength_in_minutes / 2)
            a = (daylength_in_minutes / 2) - n
            b = a / (daylength_in_minutes / 2)
            sun_angle = sun_max_angle * b

    LOGGER.info(f'Calculated sun angle is: {sun_angle}')
    return sun_angle
コード例 #27
0
def main():
    global text,choose
    global sun_num_surface
    running = True
    index = 0
    while running:
        # if index >= 130:
        #     index = 0

        clock.tick(20)

        #2s产生一个太阳花
        # if index % 40 == 0:
        #     sun = Sun(sunflower.rect)
        #     sunList.add(sun)

        #3s产生一个子弹
        # if index % 30 == 0:
        #     for sprite in spriteGroup:
        #         if isinstance(sprite, Peashooter):
        #             bullet = Bullet(sprite.rect, backgd_size)
        #             spriteGroup.add(bullet)



        screen.blit(bg_img_obj,(0,0))
        screen.blit(sunbackImg,(250,0))
        screen.blit(sun_num_surface,(270,60))

        screen.blit(flower_seed, (330, 10))
        screen.blit(wallNut_seed, (380, 10))
        screen.blit(peashooter_seed, (430, 10))


        spriteGroup.update(index)
        spriteGroup.draw(screen)

        sunList.update(index)
        sunList.draw(screen)

        (x,y) = pygame.mouse.get_pos()
        if choose == 1:
            screen.blit(sunFlowerImg,(x,y))
        elif choose == 2:
            screen.blit(wallnutImg, (x, y))
        elif choose == 3:
            screen.blit(peashooterImg, (x, y))

        index+=1
        for event in pygame.event.get():
            if event.type == GEN_SUN_EVENT:
                for sprite in spriteGroup:
                    if isinstance(sprite,SunFlower):
                        now = time.time()
                        if now - sprite.lasttime >= 5:
                            sun = Sun(sprite.rect)
                            sunList.add(sun)
                            sprite.lasttime = now

            if event.type == GEN_BULLET_EVENT:
                for sprite in spriteGroup:
                        if isinstance(sprite, Peashooter):
                            bullet = Bullet(sprite.rect, backgd_size)
                            spriteGroup.add(bullet)

            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.MOUSEBUTTONDOWN:
                pressed_key = pygame.mouse.get_pressed()
                print(pressed_key)
                if pressed_key[0] == 1:
                    pos = pygame.mouse.get_pos()
                    print(pos)
                    x,y = pos
                    if 330<=x<=380 and 10<=y<=80 and int(text) >= 50:
                        print('点中了太阳花卡片')
                        choose = 1
                    elif 380<x<=430 and 10<=y<=80 and int(text) >= 50:
                        print('点中了坚果卡片')
                        choose = 2
                    elif 430 < x <= 480 and 10 <= y <= 80 and int(text) >= 100:
                        print('点中了豌豆射手卡片')
                        choose = 3
                    elif 250 < x < 1200 and 70<y<600:
                        #种植植物
                        if choose == 1:
                            current_time = time.time()
                            sunFlower = SunFlower(current_time)
                            sunFlower.rect.top = y
                            sunFlower.rect.left = x
                            spriteGroup.add(sunFlower)
                            choose = 0

                            #扣除分数
                            text = int(text)
                            text -= 50
                            myfont = pygame.font.SysFont('arial',20)
                            sun_num_surface = myfont.render(str(text),True,(0,0,0))
                        elif choose == 2:
                            wallNut = WallNut()
                            wallNut.rect.top = y
                            wallNut.rect.left = x
                            spriteGroup.add(wallNut)
                            choose = 0

                            # 扣除分数
                            text = int(text)
                            text -= 50
                            myfont = pygame.font.SysFont('arial', 20)
                            sun_num_surface = myfont.render(str(text), True, (0, 0, 0))
                        elif choose == 3:
                            peashooter = Peashooter()
                            peashooter.rect.top = y
                            peashooter.rect.left = x
                            spriteGroup.add(peashooter)
                            choose = 0

                            # 扣除分数
                            text = int(text)
                            text -= 50
                            myfont = pygame.font.SysFont('arial', 20)
                            sun_num_surface = myfont.render(str(text), True, (0, 0, 0))

                        print('#########')
                        print(x,y)
                        pass
                    else:
                        pass
                    for sun in sunList:
                        if sun.rect.collidepoint(pos):
                            sunList.remove(sun)
                            text = str(int(text)+50)
                            sun_font = pygame.font.SysFont('arial', 20)
                            sun_num_surface = sun_font.render(text, True, (0, 0, 0))

        pygame.display.update()
コード例 #28
0
ファイル: entry2.py プロジェクト: BRENDAN-09/Py-tracer
from Vector3 import Vec3
from Camera import Camera
from Scene import Scene
from Sun import Sun
from Sky import Sky
from timeit import default_timer as timer
from Octree import Braunch

# turn on tree
useTree = False
# Create new scene
scene = Scene()
# Load Model and materials
scene.loadModel("models/pyramid.obj", "models/pyramid.mtl")
# Create Sun
sun = Sun(pos=Vec3(80, 50, 50))
sun.lookAt(Vec3(0, 0, 0))
scene.addLight(sun)
# Create sky
sky = Sky()
scene.addLight(sky)
# Create Camera
cam = Camera(Vec3(8, 4, 8), int(200), int(200), Fov=1.4, Samples=2)
cam.lookAt(Vec3(0, 3, 0))
# Render scene
ts = timer()
if useTree:
    tree = Braunch()
    tree.fromScene(scene)
    cam.render(tree, "pyramid.png")
else:
コード例 #29
0
    def _set_position(self):
        """ ~ a few arcminutes accuracy
		"""
        l0 = 318.351648  # mean longitude
        P0 = 36.340410  # mean longitude of perigee
        N0 = 318.510107  # mean longitude of node
        ii = 5.145396  # inclination
        ee = 0.054900  # eccentricity
        aa = 384401  # km, semi-major axis or moon's orbit
        theta0 = 0.5181  # degrees, semiangular size at distance a
        pi0 = 0.9507  # parallax at distance a

        sun = Sun(self.datetimeObj)

        jdJan0 = convert.datetime2jd(
            datetime.datetime(self.datetimeObj.year,
                              1,
                              1,
                              hour=0,
                              minute=0,
                              second=0))
        jd = convert.datetime2jd(self.datetimeObj)

        d = jd - jdJan0
        D = (self.datetimeObj.year - 1990) * 365.0 + (self.datetimeObj.year -
                                                      1992) / 4 + d + 2

        l = (13.1763966 * D + l0) % 360.0
        C = l - sun.longitude

        moonMeanAnomaly = (l - 0.1114041 * D - P0) % 360.0
        N = (N0 - 0.0529539 * D) % 360.0

        Ev = 1.2739 * math.sin(math.radians(2 * C - moonMeanAnomaly))
        Ae = 0.1858 * math.sin(math.radians(sun.meanAnomaly))
        A3 = 0.37 * math.sin(math.radians(sun.meanAnomaly))

        corrected_moonMeanAnomaly = moonMeanAnomaly + Ev - Ae - A3

        Ec = 6.2886 * math.sin(math.radians(corrected_moonMeanAnomaly))
        A4 = 0.214 * math.sin(math.radians(2.0 * corrected_moonMeanAnomaly))

        lprime = l + Ev + Ec - Ae + A4
        V = 0.6583 * math.sin(math.radians(2.0 * (lprime - sun.longitude)))
        lprimeprime = lprime + V

        Nprime = N - 0.16 * math.sin(math.radians(sun.meanAnomaly))
        y = math.sin(math.radians(lprimeprime - Nprime)) * math.cos(
            math.radians(ii))
        x = math.cos(math.radians(lprimeprime - Nprime))

        arcTan = math.degrees(math.atan(y / x))

        if y > 0 and x > 0:
            arcTan = arcTan % 90.0
        elif y > 0 and x < 0:
            arcTan = (arcTan % 90.0) + 90.0
        elif y < 0 and x < 0:
            arcTan = (arcTan % 90.0) + 180.0
        elif y < 0 and x > 0:
            arcTan = (arcTan % 90.0) + 270.0

        moonLongitude = arcTan + Nprime
        moonBeta = math.degrees(
            math.asin(
                math.sin(math.radians(lprimeprime - Nprime)) *
                math.sin(math.radians(ii))))

        ra, dec = convert.eclipticLatLon2RADec(moonLongitude, moonBeta)

        self.ra = ra
        self.dec = dec
コード例 #30
0
ファイル: sunflower.py プロジェクト: machangshun/PythonStudy
 def function(self):
     sun = Sun(self.screen, sets.sunImage, self.x + self.width / 2,
               self.y + self.height / 2, 0)
     Para.sunStay.append(sun)