Find (ra,dec) from an (azimuth,elevation) in skyfield - astronomy

I have a directionnal antenna on Earth and I would like to know where it points to in ra,dec coordinates. I'd like to use the new skyfield library for that, as pyephem is not developped anymore.
It is easy to compute my topos position on Earth:
planets = load('de421.bsp')
earth = planets['earth']
paris = earth + Topos('48.839059 N', '2.310147 E')
But then I can't figure out how to indicate an az,alt couple from this point. I've seen the from_altaz method but I can't manage to make it work.
If I try it from a topos:
antenna = paris.from_altaz(alt_degrees=41.1,az_degrees=180)
Traceback (most recent call last):
File "./compute.py", line 13, in <module>
antenna = paris.from_altaz(alt_degrees=41.1,az_degrees=180)
AttributeError: 'VectorSum' object has no attribute 'from_altaz'
How can I manage to do that?

The from_altaz function you try to use is from the position_lib. As this is for both fixed and moving objects (which differ through time) it's a function of time. So you need to specify the time to the observer with the .at function.
from skyfield import api
ts = api.load.timescale()
planets = api.load('de421.bsp')
earth = planets['earth']
antenna = earth + api.Topos('48.839059 N', '2.310147 E')
t = ts.now()
direction = antenna.at(t).from_altaz(alt_degrees=41.1, az_degrees=180)
ra, dec, distance = direction.radec()
print(ra)
print(dec)
This results in:
04h 43m 26.56s
-00deg 05' 39.5

Related

Mapping over asset to find mean rainfall in Google Earth Engine?

I have an asset of 25k geometries. I also have a function that maps over a list of years to find mean rainfall for a region. I was able to do this using a for loop when I had fewer regions:
def yearlyRainfall(year):
startDate = ee.Date.fromYMD(year, 1, 1)
endDate = startDate.advance(1, 'year')
filtered = chirps.filter(ee.Filter.date(startDate, endDate))
total = filtered.reduce(ee.Reducer.sum())
stats = total.reduceRegion(
reducer = ee.Reducer.mean(),
geometry = transect_region,
scale = 5566,
)
f = ee.Feature(None,{
'year': year,
'precipitation': stats.get('precipitation_sum')
})
return f
years = ee.List.sequence(1981, 2019)
for area in range(len(transect_areas)):
transect_region = transect_areas[area].geometry()
rainfallYears = ee.FeatureCollection(years.map(yearlyRainfall))
rainfalldf = geemap.ee_to_pandas(rainfallYears)
print(rainfalldf)
print(rainfalldf["precipitation"].mean())
Where transect_areas is a dictionary of regions. However, I now have to do this over 25k geometries held in a csv asset, and cannot achieve this through a for loop. I know I have to map it somehow, but I can't figure out a workaround. Any tips would be appreciated.
Tried: looping over dictionary of regions, but computation does not complete

Plotting Polygons with Folium and Pyproj

I'm trying to plot the boundaries of the localities of Brussels. The system of coordinates of my json file has to be converted to a longlat system to display the Polygons on Folium maps. The issue I get is that my coordinates are projected into the Pacific ocean. I guess it is probably due to the fact that the parameters I set are not the good ones. Please find below my code:
import json
import pyproj
import folium
# Load JSON file
with open("districts.json", "r") as f:
data = json.load(f)
# Create a transformation object
in_proj = pyproj.Proj(proj='utm',zone=31,datum='WGS84')
out_proj = pyproj.Proj(proj='longlat',datum='WGS84')
# Transform the coordinates
features = data["features"]
for feature in features:
coords = feature["geometry"]["coordinates"][0]
coords = [pyproj.transform(in_proj, out_proj, coord[0], coord[1]) for coord in coords]
feature["geometry"]["coordinates"] = [coords]
# Plot the polyggon on a map
m = folium.Map()
folium.GeoJson(data).add_to(m)
m
This corresponds to how my json file is structured:
{"type":"FeatureCollection","features":[{"geometry":{"type":"Polygon","coordinates":[[[152914.748398394,173305.19242333],[152947.4133984,173326.530423339],...,[152961.983398418,173225.325423267],[152914.748398394,173305.19242333]]]},...
(https://i.stack.imgur.com/SuU4Q.png)
(https://i.stack.imgur.com/oIKJN.png)
Does anyone has an idea how to solve this? How could I find the right parameters?
I tried different zones but I would rather know of to find the right zone number and understand how it works.

qmplot error Error in unlist(.all_aesthetics[1:42]) : object '.all_aesthetics' not found

I'm trying to plot points on a map using ggmap, ggplot2 libraries. I'm successful using get_map to prepare the map, then ggmap to plot it...although I'm only able to plot ~80 coordinate points before I get an error that I'm exceeding the google map api limit of 2048 chars. Does this limit seem correct/expected?
moving on to try using qmplot & qmap commands to (hopefully) overcome this constraint.
I'm successful with the qmplot command; I'm using:
qmap("austin", zoom = 11, source="google", maptype = "roadmap", scale = 2) to create the map.
NOT successful with qmap command. I'm using:
'qmplot(coord$lon, coord$lat, data = coord)`
coord is a df with lat/lon pairs.
I get the error: Error in unlist(.all_aesthetics[1:42]) :
object '.all_aesthetics' not found
I haven't been able to find (google) anything about this error mode.
To proof myself, I try running example code from pg 47 & 48:
https://cran.r-project.org/web/packages/ggmap/ggmap.pdf, example top of page 47
violent_crimes <- subset(crime,
offense != "auto theft" &
offense != "theft" &
offense != "burglary"
)
qmplot(lon, lat, data = violent_crimes, colour = offense,
size = I(3.5), alpha = I(.6), legend = "topleft")
preparing the violent crimes (using a built-in R dataset) command work fine. qmplot command results in the same error message that I"m getting with my code.
It's a bug that was addressed. See here
devtools::install_github("dkahle/ggmap")

Adding the results of multiple functions

Using python 3.3
Stumbled upon another problem with my program. Its the same solar program. Again i decided to add more functionality. Its basically ad-hoc. I'm adding things as i go along. I realize it can be made more efficient but once i decide its done, I'll post the whole coding up.
Anyway, i need to add the results from multiple functions. Here's a part of my coding:
def janCalc():
for a in angle(0,360,10): #angle of orientation
for d in days(1,32,1.0006630137): #day number of year
for smodule in equation(): #equation() function not shown in this coding
total_jan+=smodule #total_jan is already defined elsewhere
avg_jan=total_jan/(60*(1.0006630137*31))
ratio_jan=avg_jan/5.67
calcJan=(ratio_jan*4.79)
yield calcJan
total_jan=0 #necessary to reset total to 0 for next angle interval
def febCalc():
for a in angle(0,360,10):
for d in days ((1.0006630137*31),61,1.0006630137):
for smodule in equation():
total_feb+=smodule
avg_feb=total_feb/(60*(1.0006630137*28))
ratio_feb=avg_feb/6.56
calcFeb=(ratio_feb*4.96)
yield calcFeb
total_feb=0
#etc..............
Is there anyway to add the yield of each function?
for e.g: calcJan+calcFeb+.....
I would like to get the total results under each angle interval and then dividing by 12 to get the average value per interval. Like so:-
0 degrees---->total/12
10 deg ---->total/12
20 deg ---->total/12
30 deg ---->total/12
........
360 deg ---->total/12
If you need more info, let me know.
ADDENDUM
The solution was essentially solved by #jonrsharpe. But i encountered a bit of a problem.
Traceback (most recent call last):
File "C:\Users\User\Documents\Python\Solar program final.py", line 247, in <module>
output=[sum(vals)/12 for vals in zip(*(gen() for gen in months))]
File "C:\Users\User\Documents\Python\Solar program final.py", line 247, in <listcomp>
output=[sum(vals)/12 for vals in zip(*(gen() for gen in months))]
File "C:\Users\User\Documents\Python\Solar program final.py", line 103, in janCalc
for smodule in equation():
File "C:\Users\User\Documents\Python\Solar program final.py", line 63, in equation
d=math.asin(math.sin(math.radians(23.45))*math.sin(math.radians((360/365.242)*(d-81))))
NameError: global name 'd' is not defined
I've isolated it to:
for d in days ((1.0006630137*31),61,1.0006630137):
for smodule in equation():
It turns out i can't reference a function from inside a function? I'm not too sure. So even my original coding did not work. I assumed it was working because previously i had not defined each month as a function. I should have tested it out first.
Do you know how to get around this?
A simple example to demonstrate how to combine multiple generators:
>>> def gen1():
for x in range(5):
yield x
>>> def gen2():
for x in range(5, 10):
yield x
>>> [sum(vals) for vals in zip(*(gen() for gen in (gen1, gen2)))]
[5, 7, 9, 11, 13]
Or, written out long hand:
output = list(gen1())
for index, value in enumerate(gen2()):
output[index] += value
You can modify either version to include a division, too, so your case would look something like:
months = [janCalc, fabCalc, ...]
output = [sum(vals) / 12 for vals i zip(*(gen() for gen in months))]

R - Vectorize a JSON call

Working with Mapquest directions API to plot thousands of routes using ggplot2 in R.
Basic code theory: Have a list of end locations and a single start location. For each end location, a call to fromJSON returns routing coordinates from Mapquest. From there, have already vectorized the assignment of coordinates (read as lists in lists) to the geom_path geom of ggplot2.
Right now, running this on a location set of ~ 1200 records takes ~ 4 minutes. Would love to get that down. Any thoughts on how to vectorize the call to fromJSON (which returns a list of lists)?
Windows 7, 64-bit, R 2.14.2
libraries: plyr, ggplot2, rjson, mapproj, XML
k = 0
start_loc = "263+NORTH+CENTER+ST.,+MESA+ARIZ."
end_loc = funder_trunc[,length(funder_trunc)]
route_urls = paste(mapquest_baseurl, "&from=", start_loc, "&to=", end_loc, "&ambiguities=ignore", sep="")
for (n in route_urls) {
route_legs = fromJSON(file = url(n))$route$legs[[1]]$maneuvers
lats = unlist(lapply(route_legs, function(x) return(x$startPoint[[2]])))
lngs = unlist(lapply(route_legs, function(x) return(x$startPoint[[1]])))
frame = data.frame(cbind(lngs, lats))
path_added = geom_path(aes(lngs, lats), data = frame)
p = p + path_added
k = k + 1
print(paste("Processed ", k, " of ", nrow(funder_trunc), " records in set.", sep=""))
}
Going out on a limb here since I don't use rjson or mapproj, but it seems like calling the server thousands of times is the real culprit. If the mapquest server doesn't have an API that allows you to send multiple requests in one go, you are in trouble. If it does, then you need to find out how to use/modify rjson and/or mapproj to call it...
As #Chase said, you might be able to call it in parallel, but the server won't like getting too many parallel requests from the same client - it might ban you. Btw, it might not even like getting thousands of serial requests in rapid succession from the same client either - but apparently your current code works so I guess it doesn't mind.