xdenisx

targets2shp

Aug 8th, 2014
323
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.30 KB | None | 0 0
  1. import xlrd
  2. import datetime
  3. import sys
  4. import shapefile as sf
  5. import numpy as np
  6. from math import pi, cos, sin, radians, degrees, atan2
  7. import math
  8.  
  9. def nautical(kilometers=0, meters=0, miles=0, feet=0):
  10.     nm = 0.
  11.     if feet:
  12.         miles += feet / ft(1.)
  13.     if miles:
  14.         kilometers += km(miles=miles)
  15.     if meters:
  16.         kilometers += meters / 1000.
  17.     nm += kilometers / 1.852
  18.     return nm
  19.  
  20. ''' Distance and azimuth '''
  21. def dist(llat1,llong1,llat2,llong2):
  22.     rad = 6372795
  23.    
  24.     lat1 = llat1*math.pi/180.
  25.     lat2 = llat2*math.pi/180.
  26.     long1 = llong1*math.pi/180.
  27.     long2 = llong2*math.pi/180.
  28.  
  29.     cl1 = math.cos(lat1)
  30.     cl2 = math.cos(lat2)
  31.     sl1 = math.sin(lat1)
  32.     sl2 = math.sin(lat2)
  33.     delta = long2 - long1
  34.     cdelta = math.cos(delta)
  35.     sdelta = math.sin(delta)
  36.  
  37.     y = math.sqrt(math.pow(cl2*sdelta,2)+math.pow(cl1*sl2-sl1*cl2*cdelta,2))
  38.     x = sl1*sl2+cl1*cl2*cdelta
  39.     ad = math.atan2(y,x)
  40.     dist = ad*rad
  41.  
  42.     x = (cl1*sl2) - (sl1*cl2*cdelta)
  43.     y = sdelta*cl2
  44.     z = math.degrees(math.atan(-y/x))
  45.  
  46.     if (x < 0):
  47.         z = z+180.
  48.  
  49.     z2 = (z+180.) % 360. - 180.
  50.     z2 = - math.radians(z2)
  51.     anglerad2 = z2 - ((2*math.pi)*math.floor((z2/(2*math.pi))) )
  52.     angledeg = (anglerad2*180.)/math.pi
  53.  
  54.     #print 'Distance >> %.0f %s' % (dist/1000., ' [km]')
  55.     #print 'Initial bearing >> ', angledeg, '[degrees]'
  56.     return dist, angledeg
  57.  
  58. ff = "updated_targets.xls" #sys.argv[1]
  59. width = []
  60. length = []
  61. height = []
  62. speed = []
  63. direction = []
  64. type = []
  65.  
  66. ###########################
  67. #### Shapefile creation
  68. ###########################
  69. shp_filename = 'shp\\%s' % ff.split('.')[0] #'updated_targets.shp'
  70. # create the shapefile
  71. w = sf.Writer(sf.POINT)
  72. w.field('name','C','90')
  73. w.field('type','C','90')
  74. w.field('date','C','90')
  75. w.field('direction','C','90')
  76. w.field('speed','C','90')
  77. w.field('height','C','90')
  78. w.field('width','C','90')
  79. w.field('length','C','90')
  80. w.field('mass','C','90')
  81. w.field('sources','C','90')
  82. w.field('note','C','200')
  83. ############################
  84.  
  85. # Model file
  86. f_model_flag =0
  87. try:
  88.     f_model = open('T:\\KARA\\ICEBERG_FORECAST\\target.txt','w')
  89.     date_model = open('T:\\KARA\\ICEBERG_FORECAST\\data.txt','w')
  90.     f_model_flag == 1
  91. except:
  92.     print "Cannot mount disk T !"
  93.    
  94. iid = 0
  95.  
  96. rb = xlrd.open_workbook(ff,formatting_info=True)
  97. sheet = rb.sheet_by_index(0)
  98.  
  99. names = []
  100.  
  101. for rownum in range(sheet.nrows):
  102.     row = sheet.row_values(rownum)
  103.     try:
  104.         names.append(row[0])
  105.     except:
  106.         pass
  107.     #for c_el in row:
  108.     #    print c_el
  109.  
  110. unique_names = set(names)
  111.  
  112. ilist = []
  113. # lat/lons lists
  114. llat = []
  115. llon = []
  116. names = []
  117.  
  118. ff_last_copd_positions = open('last_copd_positions.txt','w')
  119.  
  120. for iname in unique_names:
  121.     print iname
  122.     for rownum in range(sheet.nrows):
  123.         row = sheet.row_values(rownum)
  124.         if row[0]==iname:
  125.             ilist.append({'name':row[0], 'type':row[2], 'date':row[4], \
  126.                       'lat':row[5], 'lon':row[6], 'direction':row[7], \
  127.                       'speed':row[8], 'height':row[9], 'width':row[10], \
  128.                       'length':row[11], 'mass':row[12], 'sources':row[13], \
  129.                       'note':row[14]})
  130.     try:
  131.         sorted_list = sorted(ilist, key=lambda x: datetime.datetime.strptime(x['date'],\
  132.                                                                      '%m/%d/%Y %I:%M:%S %p'))
  133.     except:
  134.         print 'Error! iname: %s' % iname
  135.     ilast = sorted_list[-1]
  136.  
  137.     # add lats/lons to lists
  138.     llat.append(float(ilast['lat']))
  139.     llon.append(float(ilast['lon']))
  140.     names.append(int(ilast['name'].split('-')[-1]))
  141.  
  142.     # for statistics
  143.     if ilast['height']<>'':
  144.         height.append(float(ilast['height']))
  145.     if ilast['length']<>'':
  146.         length.append(float(ilast['length']))
  147.     if ilast['width']<>'':
  148.         width.append(float(ilast['width']))
  149.     if ilast['direction']<>'':
  150.         direction.append(float(ilast['direction']))
  151.     if ilast['speed']<>'':
  152.         speed.append(float(ilast['speed']))
  153.     if ilast['type']<>'':
  154.         type.append(ilast['type'])
  155.        
  156.     # to TXT file
  157.     ff_last_copd_positions.write(('%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;\n') % (ilast['name'],ilast['type'],\
  158.                                                  ilast['date'],ilast['lat'], \
  159.                                                  ilast['lon'], ilast['direction'], \
  160.                                                  ilast['speed'], ilast['height'], \
  161.                                                  ilast['width'], ilast['length'], \
  162.                                                  ilast['mass'], ilast['sources'], \
  163.                                                  ilast['note']))
  164.     # to SHAPE file
  165.     w.point(float(ilast['lon']), float(ilast['lat']))
  166.     w.record(ilast['name'],ilast['type'],ilast['date'],ilast['direction'],ilast['speed'],ilast['height'], \
  167.              ilast['width'],ilast['length'],ilast['mass'],ilast['sources'],ilast['note'])
  168.  
  169.     # to model file
  170.     if ilast['width']<>'' and ilast['length']<>'' and f_model_flag==1:
  171.         if float(ilast['width'])>=10 and float(ilast['length'])>=10:
  172.             f_model.write('%d %s %s %s %s 3 15\n' % (iid,ilast['lat'],ilast['lon'],ilast['width'],ilast['length']))
  173.         else:
  174.             # if less size than 10m
  175.             f_model.write('%d %s %s 20 20 3 15\n' % (iid,ilast['lat'],ilast['lon']))
  176.     else:
  177.         if f_model_flag==1:
  178.             f_model.write('%d %s %s 30 30 3 15\n' % (iid, ilast['lat'],ilast['lon']))
  179.     # model date
  180.     if f_model_flag==1:
  181.         mod_date = datetime.datetime.strptime(ilast['date'],'%m/%d/%Y %I:%M:%S %p')
  182.         date_model.write('%s %s %s %s\n' % (mod_date.year,mod_date.month,mod_date.day,mod_date.hour))    
  183.    
  184.     iid = iid + 1
  185.     # make an empty list
  186.     ilist = []
  187.  
  188. try:
  189.     f_model.close()
  190.     date_model.close()
  191. except:
  192.     print 'Error!'
  193.  
  194. # create the PRJ file
  195. prjfn = shp_filename
  196. prj = open("%s.prj" % prjfn, "w")
  197. epsg = 'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433]]'
  198. prj.write(epsg)
  199. prj.close()  
  200. w.save(shp_filename)
  201.  
  202. ff_last_copd_positions.close()
  203.  
  204. ######################
  205. # Statistics
  206. ######################
  207.  
  208. print '\nTotal: %s' % iid
  209.  
  210. w = np.array(width)
  211. l = np.array(length)
  212. h = np.array(height)
  213. s = np.array(speed)
  214. d = np.array(direction)
  215.  
  216. # width/length/heigth mean values
  217. w_mean = w.mean()
  218. l_mean = l.mean()
  219. h_mean = h.mean()
  220. s_mean = s.mean()
  221.  
  222. # Averaging azimuth
  223. try:
  224.     rads = [radians(i) for i in d]
  225.     ave = lambda x: sum(x)/len(x)
  226.     rotate = lambda x: x+2*(pi) if x<0 else x
  227.     # Calculate the averages
  228.     sa = ave([sin(i) for i in rads]) # Average of the sines
  229.     ca = ave([cos(i) for i in rads]) # Average of the cosines
  230.     # Take the arctan of the averages, rotate to positive values, and then
  231.     # convert back to degrees.
  232.     d_mean = degrees(rotate(atan2(sa,ca)))
  233. except:
  234.     print 'cannot calculate azimuth'
  235.  
  236. try:
  237.     print '\nMean values\n Width: %5.2f m \n Length: %5.2f m \n Heigth: %5.2f m\
  238. \n Speed: %5.2f kt\n Direction: %5.0f degrees\n' % \
  239.       (w_mean, l_mean, h_mean, s_mean, d_mean)
  240. except:
  241.     pass
  242.  
  243. u_type = set(type)
  244. # all targets number
  245. all_targets_ch = 0
  246.  
  247. for itype in u_type:
  248.     i = 0
  249.     for iitype in type:
  250.         if iitype == itype:
  251.             i = i + 1
  252.     print '%s = %d' % (itype, i)
  253.     all_targets_ch = all_targets_ch + i
  254.  
  255. # checking total targets
  256. print '\nTotal\All types: %s\%d\n' % (iid, all_targets_ch)
  257.            
  258. # closest targets
  259. ilat = np.array(llat)
  260. ilon = np.array(llon)
  261. inames = np.array(names)
  262.  
  263. # West Alpha point
  264. lat0 = 74.4561
  265. lon0 = 63.8400
  266.  
  267. mdist = 10000.
  268.  
  269. fdist = open('txt//distances.txt','w')
  270.  
  271. for i in range(len(inames)):
  272.     d, a = dist(lat0, lon0, ilat[i], ilon[i])
  273.     dist_nm = nautical(meters = d)
  274.     #print 'Nomer: %d %5.2f' % (i,dist_nm)
  275.     if dist_nm < mdist:
  276.         mdist = dist_nm
  277.         aa = a
  278.         print 'Min distance: %5.1f   %5.1f' % (mdist,a)
  279.         idx = i
  280.     # distance to a file
  281.     fdist.write('%5d %5.1f %5.0f\n' % (names[i],dist_nm,a))
  282.    
  283. fdist.close()
  284.  
  285. print '\nClosest to (%s %s) is (%s %s) (#%s)' % (lat0, lon0, ilat[idx], ilon[idx], int(inames[idx]))
  286. print 'Distance: %7.1f [nm]/%.0f' % (mdist,aa)
Advertisement
Add Comment
Please, Sign In to add comment