Commit 509db604 authored by Paul Nicot's avatar Paul Nicot

maj tr_position.py + ajout de tr_snake.py (creation de cartes des suivi dans l'estuaire)

parent e82385a1
......@@ -10,14 +10,12 @@ import fiona
import shapely.geometry
from time import localtime, strftime, ctime
#
#Liste globale contenant tous les objets
#instancies a partir de la classe Spot
#
spots = []
spots = []
class Spot:
'''Classe pour les GPS SPOT'''
......@@ -28,6 +26,7 @@ class Spot:
capPlusPres = 0.0
identPlusPres = 0
parentPlusPres = 0
ecartDistance = 0
spotPlusPres = None
dejaTraite = False
......@@ -62,85 +61,6 @@ class Spot:
############################################################
#
#Calculer la distance en km entre deux points
#le long d'une ligne de vent (rhumb line)
#Le calcul se fait entre le spot courant (self) et le spot cible (ref)
#
#Ref : http://williams.best.vwh.net/avform.htm#Rhumb
#
############################################################
def calcDistance(self, ref, plusPres):
if ref == self:
return 0
if ref == None:
return 0
if plusPres == True and ref.dejaTraite == True:
return 0
lat1 = math.radians(self.latitude)
lon1 = math.radians(self.longitude)
lat2 = math.radians(ref.latitude)
lon2 = math.radians(ref.longitude)
dlat = math.radians(ref.latitude - self.latitude)
dlon = math.fabs(math.radians(ref.longitude - self.longitude))
dPhi = math.log(math.tan(lat2/2+math.pi/4)/math.tan(lat1/2+math.pi/4))
if dPhi <> 0 :
q = dlat/dPhi
else :
q = math.cos(lat1)
#if dLon > 180 degres take shorter rhumb across anti-meridian:
if math.fabs(dlon) > math.pi :
if dlon > 0 :
dlon= -(2*math.pi - dlon)
else:
dlon = (2*math.pi + dlon)
dist = math.sqrt(dlat*dlat + q*q*dlon*dlon) * Spot.rayonTerre
return dist
############################################################
#
#Calculer le cap (bearing) pour atteindre le spot cible (ref)
#a partir du spot courant (self)
#
############################################################
def calcCap(self, ref):
lat1 = math.radians(self.latitude)
lat2 = math.radians(ref.latitude)
dlon = math.radians(ref.longitude - self.longitude)
dPhi = math.log(math.tan(lat2/2+math.pi/4)/math.tan(lat1/2+math.pi/4))
if math.fabs(dlon) > math.pi :
if dlon > 0 :
dlon= -(2*math.pi - dlon)
else:
dlon = (2*math.pi + dlon)
return (math.degrees(math.atan2(dlon,dPhi)) + 360.0) % 360
def printInfoPlusPres(self) :
if self.spotPlusPres == None:
return
print 'Voisin de Spot {} est:'.format(self.esnName)
print 'Spot {} : Lat={} , Lon = {} , Dist = {} , Cap = {}{}'.format(self.identPlusPres, self.spotPlusPres.latitude,self.spotPlusPres.longitude,self.distancePlusPres, self.capPlusPres, '\n')
#############################################################
#
#Lecture du fichier XML contenant les information des spots et
......@@ -253,81 +173,7 @@ def getTags(url):
############################################################
#
#Produire un fichier html decrivant la sequence de repechage
#La page se rafraichie automatiquement au 5 minutes sur le fureteur
#(voir balise META)
#
############################################################
def ecrireHtml(fichier) :
f = open(fichier,"w")
#
#Creation du tableau pour la sequence de repechage
#
f.write("<html><head><META HTTP-EQUIV=\"refresh\" CONTENT=\"60; URL=http://demeter.uqar.ca/spots/index.html\"></head><body>\n")
f.write("Derniere mise-a-jour : " + strftime("%a, %d %b %Y %X", localtime())+ "\n")
f.write("<table border=\"1\">\n")
f.write("<tr><th>D&eacute;part</th><th>Cible</th><th>Latitude</th><th>Longitude</th><th>Dist.(km)</th><th>Cap</th><th>Date-heure</th></tr>\n")
s = spots[0]
while not s == None:
if not s.spotPlusPres == None :
f.write("<tr><td>" + str(s.esnName) + "</td><td>" + str(s.identPlusPres) + "</td><td>" + str(s.spotPlusPres.latitude) + "</td>" + \
"<td>" + str(s.spotPlusPres.longitude) + "</td><td>" + str("{0:.3f}".format(s.distancePlusPres)) + "</td>" + \
"<td>" + str("{0:.1f}".format(s.capPlusPres)) + "</td>" + \
"<td>" + s.spotPlusPres.timeStampEST + "</td></tr>" )
s = s.spotPlusPres
f.write("</table>\n")
#
#Creation du tableau des distances par rapport au Spot 0
#
f.write("<p />Distances du Spot " + str(spots[0].esnName))
f.write("<table border=\"1\">\n")
f.write("<tr><th>Cible</th><th>Latitude</th><th>Longitude</th><th>Dist. (km)</th><th>Cap</th><th>Date-heure</th></tr>\n")
s = spots[0]
for b in spots[1:] :
f.write("<tr><td>" + str(b.esnName) + "</td><td>" + str(b.latitude) + "</td>" + \
"<td>" + str(b.longitude) + "</td><td>" + str("{0:.2f}".format(s.calcDistance(b,False))) + "</td>" + \
"<td>" + str("{0:.1f}".format(s.calcCap(b))) + "</td>" + \
"<td>" + b.timeStampEST + "</td></tr>" )
f.write("</table><p /><p/>\n")
f.write("<a href=\"./spots.kml\">spots.kml</a>\n")
f.write("</body></html>")
f.close()
############################################################
#
#Produire un fichier kml pour tous les spots
#
############################################################
def ecrireKml(fichier) :
f = open(fichier,"w")
f.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
f.write("<kml xmlns=\"http://www.opengis.net/kml/2.2\">\n")
f.write("<Document>\n")
for s in spots:
f.write("<Placemark><name>Spot " + str(s.esnName) + "</name><description>(" + str(s.latitude) + \
"," +str(s.longitude) \
+ ")" + s.timeStampEST + "</description><Point><coordinates>" + str(s.longitude) + "," + \
str(s.latitude) + ",0</coordinates></Point></Placemark>")
f.write("</Document></kml>")
f.close()
############################################################
#
# Produire un fichier csv pour tous les spots
# implemente les positions des spots dans le csv
#
############################################################
......@@ -346,21 +192,30 @@ def ecrirecsv(fichier) :
point = shapely.geometry.Point(k.longitude,k.latitude)
if shape.contains(point):
k.flag = "TER"
k.flag = "LND"
else:
k.flag = "EAU"
k.flag = "OCN"
if (k.longitude < x_min) or (k.longitude > x_max) \
or (k.latitude < y_min) or (k.latitude > y_max):
k.flag = "OUT"
data = [ str(k.esnName), str(k.latitude), str(k.longitude), int(k.timeGMT), str(k.messagetype), str(k.flag)]
data = [ str(k.esnName), float(k.latitude), float(k.longitude), int(k.timeGMT), str(k.messagetype), str(k.flag)]
writer.writerow(data)
f.close
def cleancsv(fichier_clean) :
# nettoyage des doublons
with open('/home/nicopa01/data/spot/spots_pos.csv','r') as in_file,\
open(fichier_clean,'w') as out_file:
seen = set()
for line in in_file:
if line in seen: continue # skip duplicate
seen.add(line)
out_file.write(line)
#############################################################
#
......@@ -374,35 +229,9 @@ if __name__ == "__main__":
# positions = 'positions_mai_2013.xml'
getTags(url)
#
#On boucle sur tous les spots pour calculer la distance
#entre eux.
#On forme une chaine de pres en pres
#
if len(spots) == 0:
sys.exit(1)
a = spots[0]
while not a == None:
dist = 1000000.0
s = None
for b in spots:
distt = a.calcDistance(b,True)
if distt > 0 and distt < dist :
dist = distt
s = b
if not s == None:
a.distancePlusPres = dist
a.identPlusPres = s.esnName
a.capPlusPres = a.calcCap(s)
a.spotPlusPres = s
a.dejaTraite = True
a = s
#ecrireHtml("./index.html")
#ecrireKml("./spots.kml")
ecrirecsv("/home/nicopa01/data/spot/spots_pos.csv")
#ecrirecsv("./spots.csv")
cleancsv("/home/nicopa01/data/spot/spots_pos_clean.csv")
sys.exit(0)
#!/usr/bin/env python
#! python
from mpl_toolkits.basemap import Basemap
from time import gmtime, strftime
import matplotlib.pyplot as plt
import time
import numpy as np
import pandas as pd
from mpl_toolkits.axes_grid1 import make_axes_locatable
strtime = strftime("%Y-%m-%d %H:%M", gmtime())
nametime = strftime("%Y%m%d%H%M", gmtime())
# temps unix
timestamp = int(time.time())
# sec dans une journee
sday = 60 * 60 * 24
# intervalle de temps
dd = 5 # nombre de jours
dt = timestamp - 5*sday # intervalle de temps depuis dd jours
diff = timestamp - dt #
# colormap
cmap=plt.get_cmap('OrRd')
# Base de donnees ----------------------------
df = pd.read_csv('/home/nicopa01/data/spot/spots_pos.csv',delimiter=';')
df = df.drop_duplicates(take_last=True)
# Baie des Chaleurs ---------------------------
# traces des x derniers jours dans la baie
BDC = df[(df.SPOT > 699) & (df.SPOT < 800) & (df.FLAG == "OCN")
& (df.TIME > dt)]
plt.clf()
fig, ax = plt.subplots()
# caracteristiques de la carte
m = Basemap(projection='stere',lon_0=-68.5,lat_0=48,\
llcrnrlat=47.5,urcrnrlat=48.7,\
llcrnrlon=-66.9,urcrnrlon=-64.2,\
rsphere=6371.2,resolution='h')
m.drawmapboundary(fill_color='lightblue') # fill to edge
m.drawcountries()
m.fillcontinents(color='grey',lake_color='lightblue',zorder=0)
m.drawrivers()
m.drawcoastlines(linewidth=0.8)
m.drawparallels(np.arange(40,60,0.5),labels=[1,0,0,0])
m.drawmeridians(np.arange(-80,-40,1),labels=[0,0,0,1])
# trace les chemins de bouees
for spot, group in BDC.groupby(['SPOT']):
latitude = group.LAT.values
longitude = group.LON.values
t = (group.TIME.values - dt) / diff
x,y = m(longitude, latitude)
cax = plt.scatter(x,y,c=t, s=45, cmap=cmap,linewidth=0,vmin=0, vmax=1)
plt.plot(x,y,'k-',linewidth=0.5)
# colorbar
cbar = fig.colorbar(cax,fraction=0.03, pad=0.03)
cbar.set_ticks([0,0.2,0.4,0.6,0.8,1])
cbar.update_ticks()
cbar.ax.set_yticklabels(['5','4','3','2','1','0'])
cbar.set_label('jours', rotation=270)
# legende
plt.annotate(strtime + ' UTC', xy=(1, 1), xycoords='data', size=20,
xytext=(0.55, 0.1), textcoords='axes fraction',
horizontalalignment='right', verticalalignment='top')
plt.title(str(dd) + " derniers jours de derive de surface (BDC)")
# enregistrement
plt.savefig('/home/nicopa01/data/spot/suivi/BDC/BDC' + str(dd) + '_' + nametime + '.png',dpi=300)
# Estuaire du Saint-Laurent ---------------------------
# traces des x derniers jours dans l'estuaire
SLE = df[(df.SPOT > 1) & (df.SPOT < 300) & (df.FLAG == "OCN")
& (df.TIME > dt) | (df.SPOT > 899) & (df.FLAG == "OCN")
& (df.TIME > dt)]
plt.clf()
fig, ax = plt.subplots()
# caracteristiques de la carte
m = Basemap(projection='stere',lon_0=-68.5,lat_0=48,\
llcrnrlat=47.8,urcrnrlat=49.5,\
llcrnrlon=-70,urcrnrlon=-67,\
rsphere=6371.2,resolution='h')
m.drawmapboundary(fill_color='lightblue') # fill to edge
m.drawcountries()
m.fillcontinents(color='grey',lake_color='lightblue',zorder=0)
m.drawrivers()
m.drawcoastlines(linewidth=0.8)
m.drawparallels(np.arange(40,60,0.5),labels=[1,0,0,0])
m.drawmeridians(np.arange(-80,-40,1),labels=[0,0,0,1])
# trace les chemins de bouees
for spot, group in SLE.groupby(['SPOT']):
latitude = group.LAT.values
longitude = group.LON.values
t = (group.TIME.values - dt) / diff
x,y = m(longitude, latitude)
cax = plt.scatter(x,y,c=t, s=45, cmap=cmap,linewidth=0,vmin=0, vmax=1)
plt.plot(x,y,'k-',linewidth=0.5)
# colorbar
cbar = fig.colorbar(cax,fraction=0.03, pad=0.03)
cbar.set_ticks([0,0.2,0.4,0.6,0.8,1])
cbar.update_ticks()
cbar.ax.set_yticklabels(['5','4','3','2','1','0'])
cbar.set_label('jours', rotation=270)
# legende
plt.annotate(strtime + ' UTC', xy=(1, 1), xycoords='data', size=20,
xytext=(0.9, 0.1), textcoords='axes fraction',
horizontalalignment='right', verticalalignment='top')
plt.title(str(dd) + " derniers jours de derive de surface (SLE)")
#enregistrement
plt.savefig('/home/nicopa01/data/spot/suivi/SLE/SLE' + str(dd) + '_' + nametime + '.png',dpi=300)
# Old Harry ---------------------------
# traces des x derniers jours autour de Old Harry
OHA = df[(df.FLAG == "OCN") & (df.TIME > dt)]
plt.clf()
fig, ax = plt.subplots()
# caracteristiques de la carte
m = Basemap(projection='stere',lon_0=-60.5,lat_0=49,\
llcrnrlat=47.1,urcrnrlat=51.2,\
llcrnrlon=-62.9,urcrnrlon=-56.2,\
rsphere=6371.2,resolution='h')
m.drawmapboundary(fill_color='lightblue') # fill to edge
m.drawcountries()
m.fillcontinents(color='grey',lake_color='lightblue',zorder=0)
m.drawrivers()
m.drawcoastlines(linewidth=0.8)
m.drawparallels(np.arange(40,60,1),labels=[1,0,0,0])
m.drawmeridians(np.arange(-80,-40,2),labels=[0,0,0,1])
# trace les chemins de bouees
for spot, group in BDC.groupby(['SPOT']):
latitude = group.LAT.values
longitude = group.LON.values
t = (group.TIME.values - dt) / diff
x,y = m(longitude, latitude)
cax = plt.scatter(x,y,c=t, s=45, cmap=cmap,linewidth=0,vmin=0, vmax=1)
plt.plot(x,y,'k-',linewidth=0.5)
# colorbar
cbar = fig.colorbar(cax,fraction=0.03, pad=0.03)
cbar.set_ticks([0,0.2,0.4,0.6,0.8,1])
cbar.update_ticks()
cbar.ax.set_yticklabels(['5','4','3','2','1','0'])
cbar.set_label('jours', rotation=270)
# legende
plt.annotate(strtime + ' UTC', xy=(1, 1), xycoords='data', size=20,
xytext=(0.92, 0.1), textcoords='axes fraction',
horizontalalignment='right', verticalalignment='top')
plt.title(str(dd) + " derniers jours de derive de surface (BDC)")
# enregistrement
plt.savefig('/home/nicopa01/data/spot/suivi/OHA/OHA' + str(dd) + '_' + nametime + '.png',dpi=300)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment