Exemplo n.º 1
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
Exemplo n.º 2
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
Exemplo n.º 3
0
    def __init__(self):
        self.sky = SurroundingSky()

        sun = Sun((0, 0, 0), (0, 0, 0))

        earth = Earth(sun.offset(79262956, -128906582, -13927363), (24.85, 15.34, 2.499))

        # Some interesting values:
        #  Distant orbit
        #self.userSpaceship = UserSpaceship(earth.offset(0, 0, 19999), earth.relativeVelocity(-4.4667, 0, 0))
        #  Roughly as high as the ISS
        self.userSpaceship = UserSpaceship(earth.offset(0, 0, earth.radius + 340), earth.relativeVelocity(-7.73, 0, 0))
        #  GEO
        # self.userSpaceship = UserSpaceship(earth.offset(0, 0, 42164), earth.relativeVelocity(-3.07, 0, 0))
        #  Here's a good resource for finding velocity for a circular orbit at a given altitude,
        #  though you need to remember that it's altitude and not distance from the centre of the
        #  Earth: <http://home.att.net/~ntdoug/UCM2.html>

        spaceStation = SpaceStation(earth.offset(1, 1, earth.radius + 335), earth.relativeVelocity(-7.73, 0, 0))

        self.objects = []
        self.objects.append(sun)
        self.objects.append(earth)
        self.objects.append(self.userSpaceship)
        self.objects.append(spaceStation)

        self.initialDashboardRelativeTo = earth
Exemplo n.º 4
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)
Exemplo n.º 5
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)
Exemplo n.º 6
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
Exemplo n.º 7
0
    def get(self):
        obj = {'notes':'Returns info about the sunrise/sunset for a location. All values are in UTC hours', 'credits':'Uses the Python port of sunsetrise.c: https://github.com/mabroor/suncal Host set up by Jeff Easter (http://feesta.com)'}

        arguments = self.request.arguments
        if 'lat' in arguments and 'lon' in arguments:

            lat = float(self.get_argument('lat'))
            lon = float(self.get_argument('lon'))
            obj["lat"] = lat
            obj["lon"] = lon

            extended = True if 'extended' in arguments else False
            obj["extended"] = extended

            now = datetime.datetime.now()
            year = int(self.get_argument('year')) if 'year' in arguments else now.year
            month = int(self.get_argument('month')) if 'month' in arguments else now.month
            day = int(self.get_argument('day')) if 'day' in arguments else now.day
            obj["year"] = year
            obj["month"] = month
            obj["day"] = day

            dt = datetime.datetime(year, month, day)
            day_seconds = time.mktime(dt.timetuple())

            obj["day_seconds"] = day_seconds
            obj["sunrise"], obj["sunset"] = Sun.sunRiseSet(year, month, day, lon, lat)
            obj["sunrise_seconds"] = int(obj["sunrise"] * HOUR + day_seconds)
            obj["sunRiseSet"] = Sun.sunRiseSet(year, month, day, lon, lat)
            obj["sunset_seconds"] = int(obj["sunset"] * HOUR + day_seconds)
            obj["dayLength"] = Sun.dayLength(year, month, day, lon, lat)
            obj["dayLength_seconds"] = int(obj["dayLength"] * HOUR)

            if extended is True:
                obj["aviationTime"] = Sun.aviationTime(year, month, day, lon, lat)
                obj["civilTwilight"] = Sun.civilTwilight(year, month, day, lon, lat)
                obj["dayCivilTwilightLength"] = Sun.dayCivilTwilightLength(year, month, day, lon, lat)
                obj["nauticalTwilight"] = Sun.nauticalTwilight(year, month, day, lon, lat)
                obj["dayNauticalTwilightLength"] = Sun.dayNauticalTwilightLength(year, month, day, lon, lat)
                obj["astronomicalTwilight"] = Sun.astronomicalTwilight(year, month, day, lon, lat)
                obj["dayAstronomicalTwilightLength"] = Sun.dayAstronomicalTwilightLength(year, month, day, lon, lat)

            self.write(json.dumps(obj))
        else:
            obj['status'] = 'error'
            obj['message'] = 'missing lat or lon'
            obj['arguments required'] = 'lat, lon'
            obj['arguments optional'] = 'extended, year, month, day'
            self.write(json.dumps(obj))
Exemplo n.º 8
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()
Exemplo n.º 9
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()
Exemplo n.º 10
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
Exemplo n.º 11
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()
Exemplo n.º 12
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
Exemplo n.º 13
0
def main():

    serverAddress = 'localhost'
    serverPort = 10000
    try:
        opts, args = getopt.getopt(sys.argv[1:], "i:p:vh", ["ip=","port=","verbose","help"])

        for o,a in opts:
            if o in ["-h","--help"]:
                usage()
                sys.exit(0);
            elif o in ["-i","--ip"]:
                serverAddress = a
            elif o in ["-p","--port"]:
                serverPort = int(a)
    except getopt.GetoptError as err:
        print(err)
        usage()
        sys.exit(2)

    sun = Sun()
    coords = {'longitude' : -2.6, 'latitude' : 53.6 }


    # Create a TCP/IP socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
    # Bind the socket to the port
    server = (serverAddress, serverPort)

    print ("Start on " + serverAddress + " port %d" % serverPort )
#    print('starting up on {} port {}'.format(*serverAddress))
    sock.bind(server)
    
    # Listen for incoming connections
    sock.listen(1)
    
    while True:
        # Wait for a connection
        print('waiting for a connection')
        connection, clientAddress = sock.accept()
        try:
            print('connection from', clientAddress)
    
            hoursSr=int(sun.getSunriseTime( coords )['hr'])
            minsSr=int(sun.getSunriseTime( coords )['min'])

            hoursSs=int(sun.getSunsetTime( coords )['hr'])
            minsSs=int(sun.getSunsetTime( coords )['min'])

            sr = sun.getSunriseTime( coords )['decimal']
            ss = sun.getSunsetTime( coords )['decimal']

            out = '{ "sunrise": "%d:%d","sunset": "%d:%d" }\n' % ( hoursSr,minsSr, hoursSs, minsSs)
#            out = '{ "sunrise": "%s","sunset": "%s" }\n' % ( sun.toHMS(sr), sun.toHMS(ss))
            connection.sendall(bytes(out,'utf-8'))
        finally:
            # Clean up the connection
            connection.close()
Exemplo n.º 14
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)
Exemplo n.º 15
0
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]))
Exemplo n.º 16
0
	def __init__(self, logLevel, overwriteTelldus):
		self.schemas = []
		self.devices = []
		self.executedDates = {}
		self.executedDates['start'] = []
		self.executedDates['end'] = []
		self.sunDates = []
		self.logLevel = logLevel
		self.overwriteTelldus = overwriteTelldus

		self.telldus = Telldus(logLevel)
		self.deviceParser = Devices(logLevel)
		self.schemaParser = Schemas(logLevel)
		self.dataSourceParser = DataSources(logLevel)
		self.sun = Sun()
		self.webServer = None
		self.webThread = None

		# logging
		logging.basicConfig(level=logLevel)
		fileLog = logging.FileHandler(Settings.loggingPath)
		self.logger = logging.getLogger('engine')
		self.logger.addHandler(fileLog)
Exemplo n.º 17
0
class Engine:
	VERSION = '0.0.5'
	running = True

	def __init__(self, logLevel, overwriteTelldus):
		self.schemas = []
		self.devices = []
		self.executedDates = {}
		self.executedDates['start'] = []
		self.executedDates['end'] = []
		self.sunDates = []
		self.logLevel = logLevel
		self.overwriteTelldus = overwriteTelldus

		self.telldus = Telldus(logLevel)
		self.deviceParser = Devices(logLevel)
		self.schemaParser = Schemas(logLevel)
		self.dataSourceParser = DataSources(logLevel)
		self.sun = Sun()
		self.webServer = None
		self.webThread = None

		# logging
		logging.basicConfig(level=logLevel)
		fileLog = logging.FileHandler(Settings.loggingPath)
		self.logger = logging.getLogger('engine')
		self.logger.addHandler(fileLog)

	def load(self):
		# load schemas
		self.logger.info('loading schemas')
		self.schemas = self.schemaParser.load()

		# load devices
		self.logger.info('loading devices')
		self.devices = self.deviceParser.load(self.telldus)

		# load datasources
		self.logger.info('loading datasources')
		self.datasources = self.dataSourceParser.load()

		# starting web service
		self.logger.info('starting web service on port 8080')
		self.webThread = threading.Thread(target = self.startWebService)
		self.webThread.start()

		if len(self.devices) != self.telldus.getNumberOfDevices():
			if not overwriteTelldus:
				self.logger.info('number of devices in lightswitch differs from telldus. run with -o to overwrite telldus.')
				#self.telldus.close()
				#exit(1)
			else:
				self.logger.info('replacing devices in telldus with devices from lightswitch.')
				self.updateTelldusWithDevices()

		if Settings.enableExperimenal:
			self.logger.info(' ')
			self.logger.info(' ')
			self.logger.info('         RUNNING EXPERIMENTAL FEATURES')
			self.logger.info(' ')
			self.logger.info(' ')

		self.startUp()

	def run(self):
		self.logger.info('running on %s platform', platform.system())

		self.logger.info('running application version ' + self.VERSION)

		# lightswitch main loop
		try:
			while self.running:
				now = datetime.today().replace(second=0, microsecond=0)
				weekday = datetime.today().weekday()

				if Settings.enableExperimenal:
					for device in self.devices:
						if device.getSunrise() == 'on' and now not in self.sunDates and now == self.sun.sunrise():
							self.logger.info('turning off device %s because of sunrise', device.getName())
							self.telldus.turnOff(device.getTelldusId())
							device.setStatus('Off')

							self.sunDates.append(now)
						elif device.getSunset() == 'on' and now not in self.sunDates and now == self.sun.sunset():
							self.logger.info('turning on device %s because of sunset', device.getName())
							self.telldus.turnOn(device.getTelldusId())
							device.setStatus('On')

							self.sunDates.append(now)

				for schema in self.schemas:
					startDate = self.schemaParser.getStartDate(schema)

					# check if its a start of a schedule
					if (startDate is not None and\
							now == startDate and\
							weekday in schema.getDays() and\
							now not in self.executedDates['start'] and\
							self.schemaParser.tryCondition(self.dataSourceParser, schema)\
						) or (\
							startDate is None and self.schemaParser.tryCondition(self.dataSourceParser, schema) and\
							now not in self.executedDates['start']):

						self.logger.info('executing schema %s', schema.getName())
						self.execute(schema)

				if 'start' in self.executedDates.keys():
					self.executedDates['start'].append(now)
				else:
					self.executedDates['start'] = [now]

				if len(self.executedDates) > 100:
					self.executedDates = {}

				if len(self.sunDates) > 100:
					self.sunDates = []

				time.sleep(1)
		except KeyboardInterrupt:
			pass
		
		#self.webThread.join()
		self.webThread._Thread__stop()
		self.telldus.close()
		sys.exit(3)

	def startWebService(self):
		self.webServer = Web(self, self.deviceParser, self.schemaParser)

	def startUp(self):
		power = {}
		self.logger.debug('synchronizing devices')

		for schema in self.schemas:
			startDate = self.schemaParser.getStartDate(schema)
			now = datetime.today().replace(second=0, microsecond=0)
			weekday = datetime.today().weekday()

			if startDate is not None and\
					startDate < now and\
					weekday in schema.getDays() and\
					self.schemaParser.tryCondition(self.dataSourceParser, schema):

				self.logger.info('adding schema %s to execution', schema.getName())
				
				for device in schema.getDevices().split(','):
					if schema.getPower() == 'dim':
						power[int(device)] = schema.getPower() + ":" + str(schema.getLevel())
					else:
						power[int(device)] = schema.getPower()

		for device in power.keys():
			dev = self.deviceParser.findDevice(device)

			if dev is None:
				self.logger.info('no device with id %d was found', device)
				continue

			if power[device] == 'on':
				self.logger.info('turning on device')
				self.telldus.turnOn(dev.getTelldusId())
				self.telldus.turnOn(dev.getTelldusId())
				dev.setStatus('On')
			elif power[device] == 'off':
				self.logger.info('turning off device')
				self.telldus.turnOff(dev.getTelldusId())
				dev.setStatus('Off')
			elif power[device][0:3] == 'dim':
				self.logger.info('dimming device to level %d', int(power[device][4:]))
				self.telldus.dim(dev.getTelldusId(), int(power[device][4:]))
				dev.setStatus('Dimmed')
				#dev.setStatus('On')
				#self.telldus.dim(dev.getTelldusId(), int((float(power[device][4:]) / float(100)) * float(254)))

	def execute(self, schema):
		for id in schema.getDevices().split(','):
			self.logger.debug('looking for device with id %d', int(id))
			device = self.deviceParser.findDevice(int(id))

			if device is None:
				return

			self.logger.debug('device found')
			if schema.getPower() == 'on':
				self.logger.info('turning on device')
				self.telldus.turnOn(device.getTelldusId())
				time.sleep(1)
				self.telldus.turnOn(device.getTelldusId())
				device.setStatus('On')
			elif schema.getPower() == 'dim':
				self.logger.info('dimming device to level %d', schema.getProcentualLevel())
				self.telldus.dim(device.getTelldusId(), schema.getLevel())
				device.setStatus('Dimmed ' + schema.getProcentualLevel() + '%')
			else:
				self.logger.info('turning off device')
				self.telldus.turnOff(device.getTelldusId())
				self.telldus.turnOff(device.getTelldusId())
				device.setStatus('Off')

			#time.sleep(1)

	def updateTelldusWithDevices(self):
		self.logger.debug('removing devices from telldus')
		for i in range(self.telldus.getNumberOfDevices()):
			self.telldus.removeDevice(self.telldus.getDeviceId(i))

		for device in self.devices:
			self.logger.debug('adding device %s to telldus', device.getName())

			tdevice = self.telldus.addDevice(len(self.devices))
			tdevice.setName(device.getName())
			tdevice.setProtocol(device.getProtocol())
			tdevice.setModel(device.getModel())
			tdevice.setParameter('house', device.getHouse())
			tdevice.setParameter('unit', device.getUnit())
Exemplo n.º 18
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
Exemplo n.º 19
0
class Shading_System_Controller():
    def __init__(self, name, season, latitude, longitude):
        self.name = name
        self.sun = Sun(latitude, longitude)
        self.season = season
        self.rooms = []
        self.dweet = 'ICTBUILDINGPUTINASHADE'

    def set_season(self, season):
        self.season = season

    def add_room(self, room_name, area, length, width, height):
        new_room = Room(room_name, area, length, width, height)
        self.rooms.append(new_room)

    def compute_statistics(self, window):
        if (self.sun.elevation > 0 and window.window_azimuth - 90 <
                self.sun.azimuth < window.window_azimuth + 90):
            w = compute_w_projection(window.device_width,\
                   window.window_azimuth,\
                   self.sun.azimuth,\
                   window.angle)

            print('Each device covers: ' + str(w))
            print('Number of devices: ' + str(window.device_number))
            print ('Covering in total:' \
              + str((window.device_number * w * window.height)\
              /(window.length*window.height)*100) + '%' )
        else:
            print('No need to Shade window with ' +
                  str(window.window_azimuth) + ' degree in azimuth')

    def check_status(self, timestamp):

        # self.set_season(get_season(date.today()))
        self.set_season(get_season(timestamp.date()))
        self.sun.compute_elevation_azimuth(timestamp)
        self.sun.print_elevation_azimuth()

        for i in range(len(self.rooms)):
            for window in self.rooms[i].windows:

                if (window.window_azimuth - 90 < self.sun.azimuth <
                        window.window_azimuth + 90):
                    self.compute_device_orientation(window)
                else:
                    window.set_angle(0)

                # self.compute_statistics(window)
                #print (window.window_azimuth)

    def compute_device_orientation(self, window):

        if self.season == 'Summer':

            if self.sun.elevation < 0:
                window.set_angle(0)
            else:
                angle = self.compute_summer_device_orientation(window)
                print('set angle in summer to: ' + str(angle))
                window.set_angle(angle)

        elif self.season == 'Winter':

            if self.sun.elevation < 0:
                window.set_angle(0)
            else:
                angle = int(self.compute_winter_device_orientation(window))
                print('set angle in winter to: ' + str(angle))
                window.set_angle(angle)

        else:
            print('No Season recognized!')

    def compute_winter_device_orientation(self, window):

        # if (-90 < self.sun.azimuth - window.window_azimuth < 90):
        # 	angle = self.sun.azimuth - window.window_azimuth
        # else:
        # 	angle = 0

        # return angle
        return self.sun.azimuth - window.window_azimuth

    def compute_summer_device_orientation(self, window):

        w = compute_w_projection(window.device_width,	\
               window.window_azimuth,	\
               self.sun.azimuth,		\
               window.angle)
        angle = window.angle

        if (window.window_azimuth > self.sun.azimuth):
            # while ((w < window.device_width) and angle < 79):

            # 	# angle += 5

            # 	# w = compute_w_projection(window.device_width,	\
            # 	# 						 window.window_azimuth,	\
            # 	# 						 self.sun.azimuth,		\
            # 	# 						 angle)

            # 	# print ('increasing angle to: '\
            # 	# 		+ str(angle) + 'and obtaining w: ' + str(w))
            angles = []
            for angle in range(0, 80, 5):
                angles.append(compute_w_projection(window.device_width,	\
                      window.window_azimuth,				\
                      self.sun.azimuth,					\
                      angle))

            return angles.index(max(angles)) * 5

        else:
            # angle = 0
            # while ( w < window.device_width and angle > -79):
            # angle -= 5
            # w = compute_w_projection(window.device_width,	\
            # 						 window.window_azimuth,	\
            # 						 self.sun.azimuth, 		\
            # 						 abs(angle))
            # print ('decreasing angle to: ' \
            # 		+ str(angle) + 'and obtaining w: ' + str(w))

            angles = []
            for angle in range(-80, 0, 5):
                angles.append(compute_w_projection(window.device_width,	\
                      window.window_azimuth,				\
                      self.sun.azimuth,					\
                      abs(angle)))

            return angles.index(min(angles)) * (-5)

    def parse_shade_message(self, msg):

        if (msg['type'] == 'ACK'):
            print(dweepy.dweet_for(self.dweet, msg))
        else:
            pass
Exemplo n.º 20
0
class SolarHeating:
    """
    Computes whether the differential solar heating can occur as used in
    section 3.1.2 "Telescope Surface Observing Efficiency" of
    DS Project Note 5.2.
    """

    def __init__(self):
        self.sun = Sun()
        self.day_offset = timedelta(hours=2)
        self.night_offset = timedelta(hours=3)
        self.cache = dict()

    def isDayTime(self, dt):
        value = self.cache.get(dt)
        if value is None:
            value = self.computeDayTime(dt)
            self.cache[dt] = value
        return value

    def computeDayTime(self, dt):
        long = TimeAgent.GBTLONG
        lat = TimeAgent.rad2deg(TimeAgent.GBTLAT)

        rise, set = self.sun.sunRiseSet(dt.year, dt.month, dt.day, long, lat)
        if rise >= 24.0:
            rise -= 24.0
            rise_delta = timedelta(days=1)
        else:
            rise_delta = timedelta()
        rise_hour = int(rise)
        rise_minute = int(60*(rise - rise_hour))
        today = datetime(dt.year, dt.month, dt.day, rise_hour, rise_minute) + \
              self.day_offset + rise_delta
        if set >= 24.0:
            set -= 24.0
            set_delta = timedelta(days=1)
        else:
            set_delta = timedelta()
        set_hour = int(set)
        set_minute = int(60*(set - set_hour))
        tonight = datetime(dt.year, dt.month, dt.day, set_hour, set_minute) + \
                  self.night_offset + set_delta

        yesterday = dt - timedelta(days = 1)
        _, set = self.sun.sunRiseSet(yesterday.year, yesterday.month,
                                     yesterday.day, long, lat)
        if set >= 24.0:
            set -= 24.0
            set_delta = timedelta(days=1)
        else:
            set_delta = timedelta()
        set_hour = int(set)
        set_minute = int(60*(set - set_hour))
        lastnight = datetime(yesterday.year, yesterday.month, yesterday.day,
                             set_hour, set_minute) + \
                             self.night_offset + set_delta
        if dt < lastnight:
            return True
        elif dt < today:
            return False
        elif dt < tonight:
            return True
        else:
            return False

    def getSunRiseSet(self, dt):
        "Returns the physical sun rise & set times"
        long = TimeAgent.GBTLONG
        lat = TimeAgent.rad2deg(TimeAgent.GBTLAT)
        rise, set = self.sun.sunRiseSet(dt.year, dt.month, dt.day, long, lat)
        return (rise, set)
Exemplo n.º 21
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)
Exemplo n.º 22
0
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
Exemplo n.º 23
0
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:
Exemplo n.º 24
0
	def test_Sun(self):
		sun = Sun()
		now = datetime.datetime.now()

		sun.sunIsDown()
		sun.sunIsUp()
		sun.UpdateDb()
		assert sun.adjustAngle(-180) == 180
		assert sun.adjustAngle(540) == 180
		assert sun.adjustTime(-12) == 12
		assert sun.adjustTime(36) == 12
		sun.sunrise(now, 57.7007, 11.9682)
		sun.sunset(now, 57.7007, 11.9682)
		sun.SQLQuery("INSERT INTO ha_data (DataId, DataName, DataText, DataStatus, DataLastUpdated) VALUES (9999, 'Test', 'Test', 200, NOW()) ON DUPLICATE KEY UPDATE DataText = VALUES(DataText), DataStatus = VALUES(DataStatus), DataLastUpdated = VALUES(DataLastUpdated)")
Exemplo n.º 25
0
 def __init__(self):
     self.sun = Sun()
     self.day_offset = timedelta(hours=2)
     self.night_offset = timedelta(hours=3)
     self.cache = dict()
Exemplo n.º 26
0
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))
Exemplo n.º 27
0
def getopsimouts(inputobs_file , override_config_file=None, outfile=None, 
	         verbose=False):
    """
    Obtains the output of opsimObs for interesting quantities based on the input
    file. This function is used in creating the ouputs converted into the simlib
    file.

    TODO: Actually this function should go into makelsstsims rather than here.
    """
    config = setDefaultConfigs(override_config_file)

    # 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)
    if verbose:
        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)
    if verbose:
        print '# Reading downtime required %.2f seconds' %(dt)

    # Read observations.
    obs = ObsFields()
    obs.readInputObs(inputobs_file, config)
    nobs = len(obs.ra)
    dt, t = dtime(t)
    if verbose:
        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)
        if verbose:
            print '# Checking %d input observations required %.2f seconds' %(nobs, dt)
            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)
    if verbose:
        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)
    if verbose:
        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)
    if verbose:
        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)
    if verbose:
        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()
    """
    for i in range(len(obs.mjd)):
        # Calculate sky brightness for each observation. 
        skybright.setSkyBright(obs.alt[i], obs.az[i], moon.alt[i], moon.az[i], moon.phase[i], 
                               bandpass=obs.filter[i])
        sky[i] = 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)
    if verbose:
        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)
    if verbose:
        print '# Calculating the m5 limit for %d observations required %.2f seconds' %(nobs, dt)
        
    # Print out interesting values. 
    obs.printObs(sun, moon, sky, maglimit,  config, outfile)
Exemplo n.º 28
0
 def __init__(self):
     self.logger = logging.getLogger('cr-smart-home')
     self.log = Log()
     self.sun = Sun()
Exemplo n.º 29
0
 def __init__(self, name, season, latitude, longitude):
     self.name = name
     self.sun = Sun(latitude, longitude)
     self.season = season
     self.rooms = []
     self.dweet = 'ICTBUILDINGPUTINASHADE'
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()
Exemplo n.º 31
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):
Exemplo n.º 32
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
    # 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)
Exemplo n.º 34
0
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)
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()
Exemplo n.º 36
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()
Exemplo n.º 37
0
#!/usr/bin/env python3

from Sun import Sun
import time

coords = {'longitude' : -2.6, 'latitude' : 53.6 }
# coords = {'longitude' : 53, 'latitude' : -2.6 }

sun = Sun()

# Sunrise time UTC (decimal, 24 hour format)

now =  time.gmtime()
print("    ", time.strftime("%H:%m:%S",now))

sr = sun.getSunriseTime( coords )['decimal']
print("Sunrise " , sr)
print("    " + sun.toHMS( sr ))

# Sunset time UTC (decimal, 24 hour format)
ss = sun.getSunsetTime( coords )['decimal']
print("Sunset " , ss )
print("    " + sun.toHMS( ss ))
Exemplo n.º 38
0
clock = pygame.time.Clock()
while True:
    if index > 100:
        index = 0

    clock.tick(15)
    # 启动消息队列,获取消息并处理
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    screen.blit(backgroundImg, (0, 0))
    screen.blit(sunbackImg, (250, 30))
    screen.blit(txtImg, (300, 33))

    screen.blit(peashooter.images[index % 13], peashooter.rect)
    screen.blit(sunFlower.images[index % 13], sunFlower.rect)
    screen.blit(wallNut.images[index % 13], wallNut.rect)

    if index % 30 == 0:
        sun = Sun(sunFlower.rect)
        sunList.append(sun)

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

    index += 1

    pygame.display.update()
Exemplo n.º 39
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
Exemplo n.º 40
0
from Sun import Sun

coords = {'longitude': 145, 'latitude': -38}

sun = Sun()

# Sunrise time UTC (decimal, 24 hour format)
print sun.getSunriseTime(coords)['decimal']

# Sunset time UTC (decimal, 24 hour format)
print sun.getSunsetTime(coords)['decimal']