Python - join/understand .txt in .nc - coordinates

I need to plot together the salinity in background and ocean coordinates as a polygon (identifying the basin). Find a manner the .nc recognize my .txt, and separete only the basin identificate.
For example, I have salinity (.nc) all the oceans and the coordinates of Indian Ocean (.txt). So, I need identify only the coordinates the Indian Ocean at the .nc and separate this basin/data to my future analysis
I have two files:
salinity.nc (georeferenced salinity data in Latxlon)
#salinity (.nc)
salinity = xr.open_dataset('...salinity.nc')
salinity
salinity.coords['lon'] = ((salinity.coords['lon'] + 180) % 360) - 180
salinity = salinity.sortby(salinity.lon)
lon = salinity['lon']
lat = salinity['lat']
fig=plt.figure(figsize=(10,8))
#plot
ax = fig.add_subplot(111, projection=crs.PlateCarree())
im = ax.contourf(lon, lat, salinity, cmap="Spectral_r", extend="both")
ocean.txt (a list with 666 rows x 2 columns, in each row a latxlon point)
#indianocean (.txt)
indian = pd.read_csv('.....indianocean.txt', sep=';')
indian
#plot
fig = plt.figure(figsize = (12,12))
m = Basemap()
m.plot(indian.lon, indian.lat, marker=None,color='blue')
Updating...
I'm using a shapefile to test, could plot the shape in a map, but I need to extract the salinity data only from my shapefile coordinates.
salinity = xr.open_dataset('...salinity.nc')
indshp = gpd.read_file('....indcoord.shp')
#plot
fig=plt.figure(figsize=(10,8))
ax = fig.add_subplot(111, projection=ccrs.PlateCarree())
ax.add_geometries(indshp.geometry, crs=ccrs.PlateCarree(), facecolor='none', edgecolor='red', lw =2)
im = ax.contourf(lon, lat, salinity, cmap="Spectral_r", extend="both")
Now, how I could use the salinity data only of the shapefile?
Thanks so much!

Related

Getting the centroid coordinates with moments

I have a question about how to determinate the centroid coordinates of an object. I read that for a given shape xc = m10/m00, yc = m01/m00 are the coordinates of the object centroid.
Is it possible to find the same coordinates whatever the selected ROI of an image ?
Here is my code for getting centroid cordinates for 300 images selecting the same ROI for all images:
for i in range(N_files):
images = ROI[i, :, :]
ret, thresh = cv2.threshold(images, 105, 255, cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
moments = cv2.moments(thresh)
cx_centroid.append(int(moments["m10"] / (moments["m00"]+10**-15)))
cy_centroid.append(int(moments["m01"] / (moments["m00"]+10**-15)))

Lunar Librations and Subsolar Point in Matlab

So I have been trying to write a program to generate the latitude and longitude of the lunar subsolar point in Matlab.
I have the ephemeris data from aero toolbox, but I can't seem to get values that make sense.
The method I'm currently trying (without success) is...
Generate a juliandate for a specific time
Find the position of the sun relative to the moon from the ephemeris data for the specified date
Find the (φ, θ, ψ) lunar attitude from the ephemeris data
Create a rotational matrix from the lunar attitude values
Transpose the matrix to get the inverse rotation (to convert the vector from the ICRF frame to the moon's coordinate system)
Apply that rotation to the direction of the sun vector
Convert to spherical coordinates (longitude, latitude)
mission_time = juliandate(2022, 1, 1);
sun_pos = planetEphemeris(mission_time, 'Moon', 'Sun');
moon_rot = moonLibration(mission_time);
rotm = eul2rotm(moon_rot);
rotm = transpose(rotm);
sun_vec = sun_pos / norm(sun_pos);
sun_vec = sun_vec * rotm;
[ss_long, ss_lat] = cart2sph(sun_vec(1), sun_vec(2), sun_vec(3))
fprintf("Subsolar Lat: %2.2f°\tSubsolar Long: %2.2f°\n", rad2deg(ss_long), rad2deg(ss_lat))
The subsolar latitude should be like ±1.57° but this calculation goes all over the place. What am I missing?

how can i calculate distances with pyephem?

hi i need a little help if any of you know how to calculate the distance of a coordinates and a satellite projection, i mean, when i predict the path of the satellite i need to know what is the distance between the future path and the coordinates that i put. and with that make a message alert notifiyng me when that satellite will be close to the coordinates.
this is the code that i am using any of you could help me that would be great.
from mpl_toolkits.basemap import Basemap
from geopy.distance import great_circle
from matplotlib import colors
from pyorbital import tlefile
import matplotlib.pyplot as plt
import numpy as np
import math
import ephem
from datetime import datetime
tlefile.TLE_URLS = ( 'http://celestrak.com/NORAD/elements/resource.txt',)
sat_tle = tlefile.read('NUSAT 1 (FRESCO)')
sat = ephem.readtle("NUSAT 1 (FRESCO)", sat_tle.line1, sat_tle.line2)
obs = ephem.Observer()
# location for tge coordinates
print("Latitud ")
sat_lat = input()
print("Longitud suggested point")
sat_lon = input()
obs.lat = str(sat_lat)
obs.long = str(sat_lon)
# programar proyeccion del mapa
map = Basemap(projection='ortho', lat_0=sat_lat, lon_0=sat_lon, resolution='l')
# draw coastlines, country boundaries, fill continents.
map.drawcoastlines(linewidth=0.25)
map.drawcountries(linewidth=0.25)
map.fillcontinents(color='coral',lake_color='aqua')
# draw the edge of the map projection region (the projection limb)
map.drawmapboundary(fill_color='aqua')
# grid in latitud and longitud every 30 sec.
map.drawmeridians(np.arange(0,360,30))
map.drawparallels(np.arange(-90,90,30))
# plot
passes = 4
for p in range(passes):
coords = []
dists = []
tr, azr, tt, altt, ts, azs = obs.next_pass(sat)
print """Date/Time (UTC) Alt/Azim Lat/Long Elev"""
print """====================================================="""
while tr < ts:
obs.date = tr
sat.compute(obs)
print "%s | %4.1f %5.1f | %4.1f %+6.1f | %5.1f" % \
(tr, math.degrees(sat.alt), math.degrees(sat.az), math.degrees(sat.sublat), math.degrees(sat.sublong), sat.elevation/1000.)
sat_lat = math.degrees(sat.sublat)
sat_lon = math.degrees(sat.sublong)
dist = great_circle((sat_lat, sat_lon), (sat_lat, sat_lon)).miles
coords.append([sat_lon, sat_lat])
dists.append(dist)
tr = ephem.Date(tr + 30.0 * ephem.second)
md = min(dists)
imd = 1 - (float(md) / 1400)
hue = float(240) / float(360)
clr = colors.hsv_to_rgb([hue, imd, 1])
map.drawgreatcircle(coords[0][0], coords[0][1], coords[-1][0], coords[-1][1], linewidth=2, color=clr)
obs.date = tr + ephem.minute
# map with UTC
date = datetime.utcnow()
cs=map.nightshade(date)
plt.title('next '+ str(passes)+ ' passes of the satellite')
plt.show()
You might want to look at http://rhodesmill.org/pyephem/quick.html#other-functions where it describes the function ephem.separation(). You are allowed to call it with two longitude, latitude coordinate pairs, and it will tell you how far apart they are:
ephem.separation((lon1, lat1), (lon2, lat2))
So if you pass the satellites's longitude and latitude as one of the coordinate pairs, and the longitude and latitude of the position you are interested in as the other, then you can watch for when the separation grows very small.

plot a map with labels for city names in MATLAB

I want to plot a map with labels for city names. I know how to plot polygons from a shapefile but how do I label it with place names? Would these be in the shapefile or one of the other files included in the zipfile?
my_map = shaperead('myshapefile.shp');
Zone1 = rgb('Red');
Zone2 = rgb('Purple');
Zone3 = rgb('Orange');
Zone4 = rgb('Yellow');
Zone5 = rgb('SpringGreen');
Zone6 = rgb('DeepSkyBlue');
mapColors = makesymbolspec('Polygon',{'GRID_CODE',1,'Facecolor',Zone1,'FaceAlpha',0.5},...
{'GRID_CODE',2,'Facecolor',Zone2,'FaceAlpha',0.5},{'GRID_CODE',3,'Facecolor',Zone3,'FaceAlpha',0.5},{'GRID_CODE',4,'Facecolor',Zone4},...
{'GRID_CODE',5,'Facecolor',Zone5,'FaceAlpha',0.5},{'GRID_CODE',6,'Facecolor',Zone6,'FaceAlpha',0.5});
mapshow(my_map,'SymbolSpec',mapColors,my_labels);
axis off

In MATLAB, I want to plot a map with a legend showing different regions.

In MATLAB, I want to plot a map with a legend showing different regions.
For example:
my_map = shaperead('my_shape_file.shp');
Equator = [0.1 0.5 0.8];
Tropical = [0.8 0.4 0.6];
Subtropical = [0.7 0.1 0.5];
mapColors = makesymbolspec('Polygon',{'GRID_CODE',1,'Facecolor',Equator},{'GRID_CODE',2,'Facecolor',Tropical},{'GRID_CODE',3,'Facecolor',Subtropical});
h = mapshow(my_map,'SymbolSpec',mapColors);
legend(h,{'Equatorial','Tropical','Subtropical'})
axis off
However, this legend doesn't work - it only shows 'Equatorial' region. Any suggestions?
Additional query: I also want to show city names on the map. How do I (a) find out whether my shapefile contains city names/labels and (b) show these on the map?
Thank you!