def test_Astral_SolarElevationWithTimezone(): dd = Astral() location = dd['Jubail'] dt = datetime.datetime(2015, 2, 4, 9, 0, 0, tzinfo=location.tz) elevation = dd.solar_elevation(dt, location.latitude, location.longitude) assert float_almost_equal(elevation, 28.118, 0.1)
def SunState(): UTCnow = datetime.datetime.utcnow() PSTnow = datetime.datetime.now() # Moved Lat & Long to top of script a = Astral() SunAngle = a.solar_elevation(UTCnow, latitude, longitude) #SunAngleMQTT = SunAngle # SunAngle is angle (+)above/(-)below horizon if SunAngle < 0.1: SunState = 'Night' else: SunState = 'Day' if ForceNight is True: SunState = 'Night' if DebugUTC is True: print 'PSTnow =', print (PSTnow), print 'UTCnow =', print (UTCnow), print 'SunState =', print (SunState), print 'SunAngle =', print (SunAngle), print 'ForceNight =', print (ForceNight) sys.flush() return SunState
def testElevation(): city_name = "Jubail" dd = Astral() city = dd[city_name] dt = datetime.datetime.now(tz=city.tz) print("Date & time: %s" % dt) print("Date & time (UTC): %s" % dt.astimezone(pytz.utc)) print("Elevation: %.02f" % dd.solar_elevation(dt, city.latitude, city.longitude))
class StirMode(object): def __init__(self, devices): self.__devices = devices self.__stir_state = False self.__current = Timer("stir") self.__period = timedelta(seconds=3600) self.__duration = timedelta(seconds=120) # TODO Do not hard code this self.__astral = Astral()["Bern"] def stir_period(self, value): period = timedelta(seconds=value) if period > timedelta() and period < self.__duration: logger.error("Stir period must be greater than stir duration!!!") else: self.__period = period logger.info("Stir period set to: %s" % self.__period) def stir_duration(self, value): duration = timedelta(seconds=value) if self.__period > timedelta() and self.__period < duration: logger.error("Stir period must be greater than stir duration!!!") else: self.__duration = duration logger.info("Stir duration set to: %s" % self.__duration) def __pause(self): self.__stir_state = False self.__current.delay = max(timedelta(), self.__period - self.__duration) self.__devices.get_pump("boost").off() logger.info("Stir deactivated for %s" % self.__current.delay) def __stir(self): self.__stir_state = True self.__current.delay = self.__duration self.__devices.get_pump("boost").on() logger.info("Stir activated for %s" % self.__current.delay) def clear(self): self.__pause() def update(self, now): self.__current.update(now) # We only activate the stir mode if the sun elevation is greater than ~20°. # No need to stir at night, this mode is meant to lower the solar cover # temperature. if self.__astral.solar_elevation() >= 20: if self.__period > timedelta() and self.__current.elapsed(): if self.__stir_state: self.__pause() else: self.__stir()
def test_Astral_SolarElevation(): a = Astral() l = a['London'] test_data = { datetime.datetime(2015, 12, 14, 11, 0, 0): 14, datetime.datetime(2015, 12, 14, 20, 1, 0): -37, } for dt, angle1 in test_data.items(): angle2 = a.solar_elevation(dt, l.latitude, l.longitude) assert float_almost_equal(angle1, angle2)
def get_current_color(): # Get current angular elevation of the sun loc = getlatlon(location()) sol_elev = Astral.solar_elevation(Astral(), datetime.utcnow(), loc.lat, loc.lon) #print sol_elev # Use elevation of sun to set color temperature scheme = transition_scheme_t() interp = color_setting_t() #print interp.temperature #print interp.brightness interpolate_color_settings(scheme, sol_elev, interp) return (interp.temperature, interp.brightness)
def get_twilight_index(dtime, Longitude, Latitude, cf=2): a = Astral() sunpos = np.array([ a.solar_elevation(dtime[cf * i], Latitude[i], Longitude[i]) for i in range(len(Latitude)) ]) twilight_index = np.where(sunpos > 0, 0, np.NaN) twilight_index = np.where(sunpos < -12, 2, twilight_index) twilight_index[np.where( np.isnan(twilight_index) )] = twilight_index[np.where(np.isnan(twilight_index))[0] - 1] + 1 while len(np.where(np.isnan(twilight_index))[0]) > 0: twilight_index[np.where(np.isnan(twilight_index))] = twilight_index[ np.where(np.isnan(twilight_index))[0] - 1] twilight_index = twilight_index.astype(int) return twilight_index
def normalized_solar_elevation(date_time): """Return the solar elevation as a number from 0 to 1. If date_time is naive, it is assumed to be in UTC. The result is 0 for the lowest solar elevation (solar midnight), 0.5 for sunset/sunrise, and 1 for the highest solar elevation (solar noon). """ latitude, longitude = geolocation() astral = Astral() elevation = lambda t: astral.solar_elevation(t, latitude, longitude) highest = elevation(astral.solar_noon_utc(date_time.date(), longitude)) lowest = elevation(astral.solar_midnight_utc(date_time.date(), longitude)) actual = elevation(date_time) if actual > 0: return map_number(actual, (0, highest), (0.5, 1)) return map_number(actual, (lowest, 0), (0, 0.5))
def test_Astral_SolarElevation(): dd = Astral() dt = datetime.datetime(2015, 2, 3, 9, 0, 0, tzinfo=pytz.UTC) elevation = dd.solar_elevation(dt, 51.5, -0.12) assert float_almost_equal(elevation, 9.97, 0.1)
def sat2log(fn, outfn=None, xlsx=True): header, gps, engineering, profile, zoocam, zonar, misc = read_sat(fn) print(time.ctime() + ': Gathering info from sat file...') gps['GPS_info'] = gps['GPS_info'].drop_duplicates() gps['GPS_info'] = gps['GPS_info'][gps['GPS_info']['mission_status'].astype( int).between(1, 2, inclusive=True)] zoocam['Zoocam'] = zoocam['Zoocam'].drop_duplicates() engineering['Flight_Line'] = engineering['Flight_Line'].drop_duplicates() NDives = gps['GPS_info']['dive#'].to_numpy().astype(int).max() cols = gps['GPS_info'].columns.drop('Code') gps0 = gps['GPS_info'][cols].apply( pd.to_numeric, errors='coerce').groupby('dive#').mean() Latitude = gps0['Latitude'].to_numpy().astype(float) Longitude = gps0['Longitude'].to_numpy().astype(float) sel = gps0.index.values #np.arange(0,2*len(gps['GPS_info']['dive#'][gps['GPS_info']['dive#'].to_numpy().astype(int)>0].unique()),2) #Latitude = gps['GPS_info']['Latitude'][gps['GPS_info']['dive#'].to_numpy().astype(int) > 0 ].to_numpy().astype(float)[sel] #Longitude = gps['GPS_info']['Longitude'][gps['GPS_info']['dive#'].to_numpy().astype(int) > 0 ].to_numpy().astype(float)[sel] #Zcam Dive_no = gps['GPS_info']['dive#'][gps['GPS_info']['dive#'].to_numpy(). astype(int) > 0].unique().astype(int) Dir_no = np.zeros(len(Dive_no)) Dir_no[0:len(zoocam['Zoocam']['outDir'] )] = zoocam['Zoocam']['outDir'].to_numpy().astype(int)[1:] Zmax = engineering['Flight_Line']['Zmax'].to_numpy().astype(float) zc_active = np.zeros(len(Dive_no)) zc_active[0:len(zoocam['Zoocam']['UseZcam'] )] = zoocam['Zoocam']['UseZcam'].to_numpy().astype(int)[1:] Gb_rem_USB = zoocam['Zoocam']['Gb_rem_USB'].to_numpy().astype(int) Gb_rem_SD = zoocam['Zoocam']['Gb_rem_SD'].to_numpy().astype(int) ImageFile_Size = np.round( zoocam['Zoocam']['Mb_trans'].to_numpy().astype(int) / 1000, 1) zonar['Zonar_beam']['dive#'] = zonar['Zonar_beam']['dive#'].astype(int) zs_active = np.zeros(len(Dive_no)) zs_active[zonar['Zonar_beam']['pulse'].groupby( zonar['Zonar_beam']['dive#']).sum().astype(int)[1:].values > 0] = 1 #Start_YD = yd.groupby('Dive').min() #End_YD = yd.groupby('Dive').max() #Start_YD = misc['Email_mess']['Year-day'][misc['Email_mess']['dive#'].to_numpy().astype(int) > 0 ].to_numpy().astype(float)[np.arange(0,2*NDives,2)] #End_YD = misc['Email_mess']['Year-day'][misc['Email_mess']['dive#'].to_numpy().astype(int) > 0 ].to_numpy().astype(float)[np.arange(1,2*NDives,2)] #Duration = np.array((End_YD - Start_YD ) * 60).astype(float) dtime = pd.to_datetime(gps['GPS_info']['month'] + gps['GPS_info']['day'] + gps['GPS_info']['year'] + gps['GPS_info']['time'], format='%b%d%Y%H:%M') dtime = dtime.dt.tz_localize('UTC') dtime_PST = dtime.dt.tz_convert('America/Los_Angeles') hours_UTC = dtime.dt.hour + dtime.dt.minute / 60 hours_PST = dtime_PST.dt.hour + dtime_PST.dt.minute / 60 yd = gps['GPS_info']['day'].to_numpy().astype(float) + hours_UTC / 24 Start_YD = np.array(yd[gps['GPS_info']['mission_status'] == '1']) End_YD = np.array(yd[gps['GPS_info']['mission_status'] == '2']) Duration = np.array((End_YD - Start_YD) * 24 * 60).astype(float) Start_time_UTC = np.array( hours_UTC[gps['GPS_info']['mission_status'] == '1']) End_time_UTC = np.array( hours_UTC[gps['GPS_info']['mission_status'] == '2']) Start_time_PST = np.array( hours_PST[gps['GPS_info']['mission_status'] == '1']) End_time_PST = np.array( hours_PST[gps['GPS_info']['mission_status'] == '2']) Start_Date_PST = dtime_PST.dt.strftime('%d-%b-%Y')[ gps['GPS_info']['mission_status'] == '1'] interval = np.insert( np.array([ np.array(Start_time_PST)[i] - np.array(End_time_PST)[i - 1] for i in range(1, len(End_time_PST)) ]), 0, 0) * 60 elapsed_time = dtime_PST[gps['GPS_info']['mission_status'] == '2'] - dtime_PST[gps['GPS_info']['mission_status'] == '1'].to_numpy()[0] elapsed_time = np.array(elapsed_time.dt.total_seconds()) / 3600 a = Astral() sunpos = np.array([ a.solar_elevation(dtime.to_numpy()[sel[i]], Latitude[i], Longitude[i]) for i in range(len(Latitude)) ]) twilight_index = np.where(sunpos > 0, 0, np.NaN) twilight_index = np.where(sunpos < -12, 2, twilight_index) twilight_index[np.where( np.isnan(twilight_index) )] = twilight_index[np.where(np.isnan(twilight_index))[0] - 1] + 1 while len(np.where(np.isnan(twilight_index))[0]) > 0: twilight_index[np.where(np.isnan(twilight_index))] = twilight_index[ np.where(np.isnan(twilight_index))[0] - 1] twilight_index = twilight_index.astype(int) zsr = 1 / zoocam['Zoocam']['zCamMod'].to_numpy().astype( float) * 2 #every xth image sampled at 2 Hz micol = pd.MultiIndex.from_arrays( [[ 'Dive Start Location', 'Dive Start Location', 'Dive No', 'Dive No', 'Output', 'ZooCam', 'ZooCam', 'USB storage', 'SD storage', 'Image File', 'Zonar', 'UTC', 'UTC', 'Duration', 'Interval between dive', 'Start Time', 'End Time', 'Start Time', 'Start Date', 'End Time', 'Elapsed Time', 'Twilight Index', 'Zoocam' ], [ 'Latitude', 'Longitude', 'No. dives', 'Dive no.', 'Directory No.', 'Zmax', 'active', 'remaining', 'remaining', 'size (Gb)', 'active', 'Start_YD', 'End_YD', 'min', 'min', 'UTC', 'UTC', 'PST', 'PST', 'PST', 'hr', '0=day,1=sunset,2=night,3=sunrise', 'Zoocam Sample Rate' ]]) ll = pd.DataFrame(columns=micol, index=Dive_no) ll.loc[:, ('Dive Start Location', 'Latitude')] = Latitude ll.loc[:, ('Dive Start Location', 'Longitude')] = Longitude ll.loc[:, ('Dive No', 'No. dives')] = NDives ll.loc[:, ('Dive No', 'Dive no.')] = Dive_no ll.loc[:, ('Output', 'Directory No.')] = Dir_no ll.loc[:, ('ZooCam', 'Zmax')] = Zmax ll.loc[:, ('ZooCam', 'active')] = zc_active[Dive_no - 1] ll.loc[:, ('USB storage', 'remaining')] = Gb_rem_USB[Dive_no - 1] ll.loc[:, ('SD storage', 'remaining')] = Gb_rem_SD[Dive_no - 1] ll.loc[:, ('Image File', 'size (Gb)')] = ImageFile_Size[Dive_no - 1] ll.loc[:, ('Zonar', 'active')] = zs_active ll.loc[:, ('UTC', 'Start_YD')] = Start_YD ll.loc[:, ('UTC', 'End_YD')] = End_YD ll.loc[:, ('Duration', 'min')] = Duration ll.loc[:, ('Interval between dive', 'min')] = interval ll.loc[:, ('Start Time', 'UTC')] = Start_time_UTC ll.loc[:, ('End Time', 'UTC')] = End_time_UTC ll.loc[:, ('Start Date', 'PST')] = Start_Date_PST.values ll.loc[:, ('Start Time', 'PST')] = Start_time_PST ll.loc[:, ('End Time', 'PST')] = End_time_PST ll.loc[:, ('Elapsed Time', 'hr')] = elapsed_time ll.loc[:, ('Twilight Index', '0=day,1=sunset,2=night,3=sunrise')] = twilight_index ll.loc[:, ('Zoocam', 'Zoocam Sample Rate')] = zsr[Dive_no - 1] ll.loc[ll.index[1]:, ('Dive No', 'No. dives')] = '' if xlsx is True: print(time.ctime() + ': Writing log file...' + outfn + '.xlsx') ll.to_excel(outfn + '.xlsx') return ll
# Calculate solar Data solar = Astral() solar.solar_depression = 'civil' #l = Location() #l.name = 'Wohnwagen' #l.latitude = latitude #l.longitude = longitude #l.timezone = 'Europe/Berlin' #l.elevation = 0 #sun = l.sun() #data['sunrise'] = str(sun['sunrise']) #data['sunset'] = str(sun['sunset']) data['azimuth'] = solar.solar_azimuth(dateandtime, latitude, longitude) data['elevation'] = solar.solar_elevation(dateandtime, latitude, longitude) if data['elevation'] < 0: data['elevation'] = 0 data['zenith'] = solar.solar_zenith(dateandtime, latitude, longitude) # Set up a client for InfluxDB dbclient = InfluxDBClient(config[influx_server]['host'], config[influx_server]['port'], config[influx_server]['username'], config[influx_server]['password'], config[influx_server]['database']) json_body = [{ "measurement": "power", "fields": { "pv_w": float(data['/Pv/W']), "pv_v": float(data['/Pv/V']), "pv_a": float(data['/Pv/I']), "pv_state": float(data['/State']), "elev": float(data['elevation']),
azRad, elevRad = (360. - az + 90.)*np.pi/180., (90.-elev)*np.pi/180. Sx, Sy = calcFiniteSlopes(elevGrid, dx) # Calculate slope in X and Y directions AspectRad = np.arctan2(Sy, Sx) # Angle of aspect SmagRad = np.arctan(np.sqrt(Sx**2. + Sy**2.)) # magnitude of slope in radians return (((np.cos(elevRad) * np.cos(SmagRad)) + (np.sin(elevRad)* np.sin(SmagRad) * np.cos(azRad - AspectRad))))*255 a = Astral() Latitude = 47.074531 longitude = 12.846210 b = datetime.datetime(2015,10,3,7,30) c= a.solar_azimuth(b,Latitude,longitude) d= a.solar_elevation(b,Latitude,longitude) print d, a.solar_zenith(b, Latitude, longitude) print c headinfo,dtm = ascii.read_ascii("C:\Master\settings/vernagtferner14-16/dgm_vernagtferner.txt") test = calcHillshade(dtm,headinfo[-2],c,d) print np.min(test), np.max(test) plt.imshow(test, cmap="Greys") plt.show() ascii.write_ascii("test.asc",headinfo,test,format="%i")