modis_download_from_list.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. #!/usr/bin/env python
  2. # Script to download massive MODIS data from a text file containing a list of
  3. # MODIS file name
  4. #
  5. # (c) Copyright Luca Delucchi 2013
  6. # Authors: Luca Delucchi
  7. # Email: luca dot delucchi at fmach dot it
  8. #
  9. ##################################################################
  10. #
  11. # This MODIS Python script is licensed under the terms of GNU GPL 2.
  12. # This program is free software; you can redistribute it and/or
  13. # modify it under the terms of the GNU General Public License as
  14. # published by the Free Software Foundation; either version 2 of
  15. # the License, or (at your option) any later version.
  16. # This program is distributed in the hope that it will be useful,
  17. # but WITHOUT ANY WARRANTY; without even implied warranty of
  18. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  19. # See the GNU General Public License for more details.
  20. #
  21. ##################################################################
  22. """Script to download massive MODIS data from a text file containing a list of
  23. MODIS file name"""
  24. from datetime import date
  25. try:
  26. from pymodis import optparse_gui
  27. WXPYTHON = True
  28. except:
  29. WXPYTHON = False
  30. from pymodis import downmodis
  31. from pymodis import optparse_required
  32. import sys
  33. import os
  34. import getpass
  35. def write_out(out, ts, options, day):
  36. """Write the missing files"""
  37. opts = options.prod.split('.')
  38. for ti in ts:
  39. out.write("{co}\n".format(co=".".join((opts[0], "A{da}".format(da=day),
  40. ti, opts[1], '*', 'hdf*'))))
  41. def main():
  42. """Main function"""
  43. # usage
  44. usage = "usage: %prog [options] destination_folder"
  45. if 1 == len(sys.argv) and WXPYTHON:
  46. option_parser_class = optparse_gui.OptionParser
  47. else:
  48. option_parser_class = optparse_required.OptionParser
  49. parser = option_parser_class(usage=usage,
  50. description='modis_download_from_list')
  51. # file
  52. parser.add_option("-f", "--file", dest="file", type='file',
  53. help="Input file containing data to download")
  54. # url
  55. parser.add_option("-u", "--url", default="https://e4ftl01.cr.usgs.gov",
  56. help="http/ftp server url [default=%default]",
  57. dest="url")
  58. # username and password from stdin
  59. parser.add_option("-I", "--input", dest="input", action="store_true",
  60. help="insert user and password from standard input")
  61. # password
  62. parser.add_option("-P", "--password", dest="password",
  63. help="password to connect to the server")
  64. # username
  65. parser.add_option("-U", "--username", dest="user",
  66. help="username to connect to the server ")
  67. # path to add the path in the server
  68. parser.add_option("-s", "--source", dest="path", default="MOLT",
  69. help="directory on the http/ftp server "
  70. "[default=%default]")
  71. # path to add the url
  72. parser.add_option("-p", "--product", dest="prod", default="MOD11A1.006",
  73. help="product name as on the http/ftp server "
  74. "[default=%default]")
  75. # path to file with server missing tiles
  76. parser.add_option("-o", "--outputs", dest="outs", default=None,
  77. help="the output where write the missing files in the"
  78. " server [default=%default]. Use 'stdout' to write to "
  79. " STDOUT")
  80. # use netrc file
  81. parser.add_option("-n", action="store_true", dest="netrc", default=False,
  82. help="use netrc file to read user and password")
  83. # debug
  84. parser.add_option("-x", action="store_true", dest="debug", default=False,
  85. help="this is useful for debugging the "
  86. "download [default=%default]")
  87. # jpg
  88. parser.add_option("-j", action="store_true", dest="jpg", default=False,
  89. help="download also the jpeg overview files "
  90. "[default=%default]")
  91. # return options and argument
  92. (options, args) = parser.parse_args()
  93. if len(args) == 0 and not WXPYTHON:
  94. parser.print_help()
  95. sys.exit(1)
  96. if len(args) > 1:
  97. parser.error("You have to define the destination folder for HDF file")
  98. if not os.path.isdir(args[0]):
  99. parser.error("The destination folder is not a dir or not exists")
  100. if options.netrc:
  101. user = None
  102. password = None
  103. elif options.input:
  104. if sys.version_info.major == 3:
  105. user = input("Username: ")
  106. else:
  107. user = raw_input("Username: ")
  108. password = getpass.getpass()
  109. else:
  110. user = options.user
  111. password = options.password
  112. f = open(options.file)
  113. lines = [elem for elem in f.readlines()]
  114. vals = {}
  115. for elem in lines:
  116. if elem != '\n':
  117. dat = elem.split('.')[1].replace('A', '')
  118. fisplit = elem.strip().split('.')
  119. if dat not in vals.keys():
  120. vals[dat] = [fisplit[2]]
  121. else:
  122. vals[dat].append(fisplit[2])
  123. if not options.outs:
  124. write = None
  125. elif options.outs == "stdout":
  126. write = sys.stdout
  127. else:
  128. write = open(options.outs, 'w')
  129. for d, tiles in sorted(vals.items(), reverse=True):
  130. year = int(d[0:4])
  131. doy = int(d[4:7])
  132. fdate = date.fromordinal(date(year, 1, 1).toordinal() + doy - 1).isoformat()
  133. modisOgg = downmodis.downModis(url=options.url, user=user,
  134. password=password,
  135. destinationFolder=args[0],
  136. tiles=','.join(sorted(set(tiles))),
  137. path=options.path, product=options.prod,
  138. delta=1, today=fdate,
  139. debug=options.debug, jpg=options.jpg)
  140. modisOgg.connect()
  141. day = modisOgg.getListDays()[0]
  142. if modisOgg.urltype == 'http':
  143. listAllFiles = modisOgg.getFilesList(day)
  144. else:
  145. listAllFiles = modisOgg.getFilesList()
  146. if not listAllFiles:
  147. if write:
  148. write_out(write, tiles, options, d)
  149. continue
  150. listFilesDown = modisOgg.checkDataExist(listAllFiles)
  151. if listFilesDown:
  152. if options.debug:
  153. print(listFilesDown)
  154. modisOgg.dayDownload(day, listFilesDown)
  155. for fi in listFilesDown:
  156. if 'xml' not in fi:
  157. try:
  158. tiles.remove(fi.split('.')[2])
  159. except ValueError:
  160. pass
  161. if write:
  162. write_out(write, tiles, options, d)
  163. if modisOgg.urltype == 'http':
  164. modisOgg.closeFilelist()
  165. else:
  166. modisOgg.closeFTP()
  167. if __name__ == "__main__":
  168. main()