distance_matrix.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. # Author: Omar Vega Ramos
  4. # E-mail: ovruni@riseup.net
  5. # License: GNU GPL - GNU General Public License v3.0 or later
  6. # http://www.gnu.org/licenses/gpl.html
  7. from argparse import ArgumentParser
  8. from csv import reader, writer
  9. from math import sin, cos, sqrt, atan2, radians
  10. from os.path import isfile
  11. def calculate_distance(lat1, lon1, lat2, lon2):
  12. R = 6373.0 # Radius of the earth in km
  13. lat1 = radians(lat1)
  14. lon1 = radians(lon1)
  15. lat2 = radians(lat2)
  16. lon2 = radians(lon2)
  17. dlon = lon2 - lon1
  18. dlat = lat2 - lat1
  19. a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
  20. c = 2 * atan2(sqrt(a), sqrt(1 - a))
  21. distance = R * c # Distance in km
  22. return distance
  23. parser = ArgumentParser(description='Calculate the distances between the coordinates of two CSV files.')
  24. parser.add_argument('input1', help='name of the first input file')
  25. parser.add_argument('input2', help='name of the second input file')
  26. parser.add_argument('--lat', default='lat', help='column name for latitude')
  27. parser.add_argument('--lon', default='lon', help='column name for longitude')
  28. parser.add_argument('-o', '--output', default='output.csv', help='name of the output file')
  29. args = parser.parse_args()
  30. if isfile(args.input1) == False:
  31. exit("{}: error: the file '{}' does not exist".format(parser.prog, args.input1))
  32. if isfile(args.input2) == False:
  33. exit("{}: error: the file '{}' does not exist".format(parser.prog, args.input2))
  34. table1 = []
  35. table2 = []
  36. header1 = None
  37. header2 = None
  38. lat_pos1 = None
  39. lon_pos1 = None
  40. lat_pos2 = None
  41. lon_pos2 = None
  42. with open(args.input1) as csv_file:
  43. csv_reader = reader(csv_file, delimiter=',')
  44. is_header = True
  45. for row in csv_reader:
  46. if is_header == True:
  47. header1 = row
  48. for i, col in enumerate(header1):
  49. if col == args.lat:
  50. lat_pos1 = i
  51. elif col == args.lon:
  52. lon_pos1 = i
  53. if lat_pos1 == None:
  54. print("ERROR: Column ´{}´ does not exist in file ´{}´".format(args.lat, args.input1))
  55. quit()
  56. if lon_pos1 == None:
  57. print("ERROR: Column ´{}´ does not exist in file ´{}´".format(args.lon, args.input1))
  58. quit()
  59. is_header = False
  60. continue
  61. table1.append(row)
  62. with open(args.input2) as csv_file:
  63. csv_reader = reader(csv_file, delimiter=',')
  64. is_header = True
  65. for row in csv_reader:
  66. if is_header == True:
  67. header2 = row
  68. for i, col in enumerate(header2):
  69. if col == args.lat:
  70. lat_pos2 = i
  71. elif col == args.lon:
  72. lon_pos2 = i
  73. if lat_pos2 == None:
  74. print("ERROR: Column ´{}´ does not exist in file ´{}´".format(args.lat, args.input2))
  75. quit()
  76. if lon_pos2 == None:
  77. print("ERROR: Column ´{}´ does not exist in file ´{}´".format(args.lon, args.input2))
  78. quit()
  79. is_header = False
  80. continue
  81. table2.append(row)
  82. rows = []
  83. row = header1 + header2 + ['distance (km)']
  84. rows.append(row)
  85. for row1 in table1:
  86. lat1 = row1[lat_pos1]
  87. lon1 = row1[lon_pos1]
  88. if lat1 == '' or lon1 == '':
  89. print("ERROR: Wrong coordinates in {} file.".format(args.input1))
  90. quit()
  91. lat1 = float(lat1)
  92. lon1 = float(lon1)
  93. for row2 in table2:
  94. lat2 = row2[lat_pos2]
  95. lon2 = row2[lon_pos2]
  96. if lat2 == '' or lon2 == '':
  97. print("ERROR: Wrong coordinates in {} file.".format(args.input2))
  98. quit()
  99. lat2 = float(lat2)
  100. lon2 = float(lon2)
  101. distance = calculate_distance(lat1, lon1, lat2, lon2)
  102. row = row1 + row2 + [distance]
  103. rows.append(row)
  104. with open(args.output, 'w', encoding='UTF8', newline='') as f:
  105. writer = writer(f)
  106. writer.writerows(rows)
  107. print("The ´{}´ file was generated.".format(args.output))