[GRASS-SVN] r46737 - in grass-addons/grass7/raster/r.modis: . libmodis r.modis.download

svn_grass at osgeo.org svn_grass at osgeo.org
Sat Jun 18 14:34:02 EDT 2011


Author: lucadelu
Date: 2011-06-18 11:34:02 -0700 (Sat, 18 Jun 2011)
New Revision: 46737

Modified:
   grass-addons/grass7/raster/r.modis/libmodis/modis.py
   grass-addons/grass7/raster/r.modis/libmodis/rmodislib.py
   grass-addons/grass7/raster/r.modis/r.modis.download/r.modis.download.html
   grass-addons/grass7/raster/r.modis/r.modis.download/r.modis.download.py
   grass-addons/grass7/raster/r.modis/r.modis.html
Log:
add new version of r.modis.download, update library pyModis and modify the documentation

Modified: grass-addons/grass7/raster/r.modis/libmodis/modis.py
===================================================================
--- grass-addons/grass7/raster/r.modis/libmodis/modis.py	2011-06-18 09:46:30 UTC (rev 46736)
+++ grass-addons/grass7/raster/r.modis/libmodis/modis.py	2011-06-18 18:34:02 UTC (rev 46737)
@@ -22,6 +22,8 @@
 #  History
 ##################################################################
 #
+#  0.4.0 Fix a lot of bugs, add convertModis class to convert hdf to other
+#        format and projection system (To release)
 #  0.3.0 Fix the choosing of days, change name modisClass to downModis 
 #        and add parseModis (2011-05-24)
 #  0.2.1 Little change in the logging option (2011-01-21)
@@ -36,7 +38,7 @@
 # tilesUsed="h17v04,h17v05,h18v02,h18v03,h18v05,h19v04,h19v05"
 # writePath="/home/luca/test_modis"
 
-__version__ = '0.3.0'
+__version__ = '0.4.0'
 
 from datetime import *
 import string
@@ -51,9 +53,9 @@
 class downModis:
   """A class to download modis data from nasa ftp repository"""
   def __init__(self, 
-                user,
                 password,
                 destinationFolder,
+                user = "anonymous",
                 url = "e4ftl01u.ecs.nasa.gov",
                 tiles = None,
                 path = "MOLT/MOD11A1.005",
@@ -64,17 +66,17 @@
                 debug = False
               ):
     """Initialization function :
-        user=is your username
-        password=is your password
-        destinationFolder=where your file are storage
-        url=the url where download data
-        path=the directory where the data that you want download are 
-             storaged in the ftp server
-        tiles=a list of tiles that you want downloads, None == all tiles
-        today=the day to start download, to pass a date different to 
-              today use this format year-month-day
-        delta=timelag i.e. the number of days starting from today 
-              (backward)
+        password = is your password, usually your email
+        destinationFolder = where your file are storage
+        user = is your username, by default anonymous
+        url = the url where download data
+        path = the directory where the data that you want download are 
+               storaged in the ftp server
+        tiles = a list of tiles that you want downloads, None == all tiles
+        today = the day to start download, to pass a date different to 
+                today use this format year-month-day
+        delta = timelag i.e. the number of days starting from today 
+                (backward)
 
         Create ftp istance, connect user to ftp server and go to the 
         directory where data are storage
@@ -127,7 +129,7 @@
     format=LOGGING_FORMAT)
     
   def connectFTP(self):
-    """ set connection to ftp server, move to path where data are storaged
+    """ Set connection to ftp server, move to path where data are storaged
     and create a list of directory for all days"""
     try:
       # connect to ftp server
@@ -262,7 +264,7 @@
       self.getFilesList()
 
   def checkDataExist(self,listNewFile, move = 0):
-    """ Check if a data already exist in the directory of download 
+    """ Check if a data already exists in the directory of download 
     Move serve to know if function is called from download or move function"""
     fileInPath = []
     # add all files in the directory where we will save new modis data
@@ -309,7 +311,7 @@
         + '.' + fileSplit[3]
         #for debug, download only xml
         if (self.debug and fileSplit[-1] == 'xml') or not self.debug:
-          # check data exist in the return directory, if it doesn't exist
+          # check data exists in the return directory, if it doesn't exists
           oldFile = glob.glob1(self.writeFilePath, filePrefix + "*" \
           + fileSplit[-1])
           numFiles = len(oldFile)
@@ -397,21 +399,26 @@
       self.setDirectoryOver()   
 
 class parseModis:
+  """Class to parse MODIS xml files, it also can create the parameter 
+    configuration file for resample MRT software
+  """
   def __init__(self, filename):
-
+    """Initialization function :
+       filename = the name of MODIS hdf file
+    """
     from xml.etree import ElementTree
-
+    # hdf name
     self.hdfname = filename
+    # xml hdf name
     self.xmlname = self.hdfname + '.xml'
+    # tif name for the output file for resample MRT software
     self.tifname = self.hdfname.replace('.hdf','.tif')
     with open(self.xmlname) as f:
       self.tree = ElementTree.parse(f)
-    # return the name of product
-    if len(self.path.split('/')) == 2:
-      self.product = self.path.split('/')[1]
-    elif len(self.path.split('/')) == 3:
-      self.product = self.path.split('/')[2]
-
+    # return the code of tile for conf file
+    self.code = os.path.split(self.hdfname)[1].split('.')[-2]
+    self.path = os.path.split(self.hdfname)[0]
+    
   def __str__(self):
     """Print the file without xml tags"""
     retString = ""
@@ -568,6 +575,7 @@
     return value
 
   def retInputGranule(self):
+    """Return the input files used to process the considered file"""
     value = []
     self.getGranule()
     for i in self.granule.find('InputGranule').getiterator():
@@ -579,61 +587,154 @@
     self.getGranule()
     return self.granule.find('BrowseProduct').find('BrowseGranuleId').text
 
-  def confResample(self, filePath, output = None,
-                  resampl = 'NEAREST_NEIGHBOR', projtype = 'GEO',
+  def confResample(self, spectral, res = None, output = None, datum = 'WGS84',
+                  resampl = 'NEAREST_NEIGHBOR', projtype = 'GEO',  utm = None,
                   projpar = '( 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 )',
-                  datum = 'WGS84'
                   ):
+    """Create the parameter file to use with resample MRT software to create
+       tif file
+        spectral = the spectral subset to use, look the product table to 
+                   understand the layer that you want use. 
+                   For example: 
+                    - NDVI ( 1 1 1 0 0 0 0 0 0 0 0 0) copy only layer NDVI, EVI 
+                      and QA VI the other layers are not used
+                    - LST ( 1 1 0 0 1 1 0 0 0 0 0 0 ) copy only layer daily and
+                      nightly temperature and QA
+        res = the resolution for the output file, it must be set in the map 
+              unit of output projection system. The software will use the original
+              resolution of input file if res it isn't set
+        output = the output name, if it doesn't set will use the prefix name of 
+                 input hdf file
+        utm = the UTM zone if projection system is UTM
+        resampl = the type of resampling, the valid values are: NN (nearest 
+                  neighbor), BI (bilinear), CC (cubic convolution)
+        projtype = the output projection system, the valid values are: AEA 
+                   (Albers Equal Area), ER (Equirectangular), GEO (Geographic 
+                   Latitude/Longitude), HAM (Hammer), ISIN (Integerized Sinusoidal), 
+                   IGH (Interrupted Goode Homolosine), LA (Lambert Azimuthal), 
+                   LCC (LambertConformal Conic), MERCAT (Mercator), MOL (Mollweide), 
+                   PS (Polar Stereographic), SIN ()Sinusoidal), UTM (Universal 
+                   TransverseMercator)
+        datum = the datum to use, the valid values are: NAD27, NAD83, WGS66,
+                WGS76, WGS84, NONE
+        projpar = a list of projection parameters
+        """
+    ## lists of parameters accepted by resample MRT software
+    # projections
+    proj_list = ('GEO', 'HAM', 'IGH', 'ISIN', 'LA', 'LCC', 'MOL', 'PS', 'SIN', 
+                'TM', 'UTM')
+    # resampling
+    resam_list = ('NEAREST_NEIGHBOR', 'BICUBIC', 'CUBIC_CONVOLUTION', 'NONE')
+    # datum
+    datum_list = ('NONE', 'NAD27', 'NAD83', 'WGS66', 'WGS72', 'WGS84')
+    # output name
     if not output:
       fileout = self.tifname
     else:
       fileout = output
-    """Write a configuration file for resample mrt software (TO TEST)"""
-    filename = os.join.path(filePath,'%s_mrt_resample.conf' % self.product)
+    # the name of the output parameters files for resample MRT software
+    filename = os.path.join(self.path,'%s_mrt_resample.conf' % self.code)
+    # if the file already exists it remove it 
+    if os.path.exists(filename):
+      os.remove(filename)
+    # open the file
     conFile = open(filename, 'w')
-    conFile.write("INPUT_FILENAME = %s" % self.hdfname)
-    conFile.write("SPECTRAL_SUBSET = ( 1 1 )")
-    conFile.write("SPATIAL_SUBSET_TYPE = INPUT_LAT_LONG")
+    conFile.write("INPUT_FILENAME = %s\n" % self.hdfname)
+    conFile.write("SPECTRAL_SUBSET = %s\n" % spectral)
+    conFile.write("SPATIAL_SUBSET_TYPE = INPUT_LAT_LONG\n")
+    # return the boundary from the input xml file
     bound = self.retBoundary()
     # Order:  UL: N W  - LR: S E
-    conFile.write("SPATIAL_SUBSET_UL_CORNER = ( %f %f )" % (bound['max_lat'],bound['min_lon']))
-    conFile.write("SPATIAL_SUBSET_LR_CORNER = ( %f %f )" % (bound['min_lat'],bound['max_lon']))
-    conFile.write("OUTPUT_FILENAME = %s" % output)
-    conFile.write("RESAMPLING_TYPE = %s" % resampl)
-    conFile.write("OUTPUT_PROJECTION_TYPE = %s" % projtype)
-    conFile.write("OUTPUT_PROJECTION_PARAMETERS = %s" % projpar)
-    conFile.write("DATUM = %s" % datum)
+    conFile.write("SPATIAL_SUBSET_UL_CORNER = ( %f %f )\n" % (bound['max_lat'],
+                                                              bound['min_lon']))
+    conFile.write("SPATIAL_SUBSET_LR_CORNER = ( %f %f )\n" % (bound['min_lat'],
+                                                              bound['max_lon']))
+    conFile.write("OUTPUT_FILENAME = %s\n" % fileout)
+    # if resampl is in resam_list set the parameter otherwise return an error
+    if resampl in resam_list:
+      conFile.write("RESAMPLING_TYPE = %s\n" % resampl)
+    else:
+      raise IOError('The resampling type %s is not supportet.\n' \
+                   'The resampling type supported are %s' % (resampl,resam_list))
+    # if projtype is in proj_list set the parameter otherwise return an error
+    if projtype in proj_list:
+      conFile.write("OUTPUT_PROJECTION_TYPE = %s\n" % projtype)
+    else:
+      raise IOError('The projection type %s is not supportet.\n' \
+                   'The projections supported are %s' % (projtype,proj_list))
+    conFile.write("OUTPUT_PROJECTION_PARAMETERS = %s\n" % projpar)
+    # if datum is in datum_list set the parameter otherwise return an error
+    if datum in datum_list:
+      conFile.write("DATUM = %s\n" % datum)
+    else:
+      raise IOError('The datum %s is not supportet.\n' \
+                   'The datum supported are %s' % (datum,datum_list))
+    # if utm is not None write the UTM_ZONE parameter in the file
+    if utm:
+      conFile.write("UTM_ZONE = %s\n" % utm)
+    # if res is not None write the OUTPUT_PIXEL_SIZE parameter in the file
+    if res:
+      conFile.write("OUTPUT_PIXEL_SIZE = %i\n" % res)
     conFile.close()
     return filename
 
 class convertModis:
-  """A class to convert modis data from hdf to tif using resample (mrt tools)"""
-  def __init__(self,
-              hdfname, 
-              confile, 
-              mrtpath):
+  """A class to convert modis data from hdf to tif using resample (mrt tools)
+  """
+  def __init__(self, hdfname, confile, mrtpath):
+    """Initialization function :
+       hdfname = the full path to the hdf file
+       confile = the full path to the paramater file
+       mrtpath = the full path to mrt directory where inside you have bin and 
+                 data directories
+    """
+    # check if the hdf file exists
     if os.path.exists(hdfname):
-        self.name = hdfname
+      self.name = hdfname
     else:
-        raise IOError('%s not exist' % hdfname)
+      raise IOError('%s not exists' % hdfname)
+    # check if confile exists
     if os.path.exists(confile):
-        self.conf = confile
+      self.conf = confile
     else:
-        raise IOError('%s not exist' % confile)
+      raise IOError('%s not exists' % confile)
+    # check if mrtpath and subdirectories exists and set environment variables
     if os.path.exists(mrtpath):
-        self.mrtpath = mrtpath
+      if os.path.exists(os.path.join(mrtpath,'bin')):
+        self.mrtpathbin = os.path.join(mrtpath,'bin')
+        os.environ['PATH'] = "%s:%s" % (os.environ['PATH'],os.path.join(mrtpath,
+                                                                        'data'))
+      else:
+        raise IOError('The path %s not exists' % os.path.join(mrtpath,'bin'))
+      if os.path.exists(os.path.join(mrtpath,'data')):
+        self.mrtpathdata = os.path.join(mrtpath,'data')
+        os.environ['MRTDATADIR'] = os.path.join(mrtpath,'data')
+      else:
+        raise IOError('The path %s not exists' % os.path.join(mrtpath,'data'))
     else:
-        raise IOError('The path %s not exist' % mrtpath)
+      raise IOError('The path %s not exists' % mrtpath)
 
   def executable(self):
-    """return the executable
-       on windows an exe file
+    """Return the executable of resample MRT software
     """
     if sys.platform.count('linux') != -1:
-      return 'resample'
+      if os.path.exists(os.path.join(self.mrtpathbin,'resample')):
+        return os.path.join(self.mrtpathbin,'resample')
     elif sys.platform.count('win32') != -1:
-      return 'resample.exe'
+      if os.path.exists(os.path.join(self.mrtpathbin,'resample.exe')):
+        return os.path.join(self.mrtpath,'resample.exe')
 
+  def run(self):
+    """Exect the process"""
+    import subprocess
+    execut = self.executable()
+    if not os.path.exists(execut):
+      raise IOError('The path %s not exists, could be an erroneus path or '\
+                    + 'software') % execut
+    else:
+      subprocess.call([execut,'-p',self.conf])
+    return "The hdf file %s it is converted" % self.name
+      
 #class createMosaic:
   #def __init__(self
               #listfile,

Modified: grass-addons/grass7/raster/r.modis/libmodis/rmodislib.py
===================================================================
--- grass-addons/grass7/raster/r.modis/libmodis/rmodislib.py	2011-06-18 09:46:30 UTC (rev 46736)
+++ grass-addons/grass7/raster/r.modis/libmodis/rmodislib.py	2011-06-18 18:34:02 UTC (rev 46737)
@@ -15,7 +15,33 @@
 #		for details.
 #
 #############################################################################
+from grass.script import read_command,parse_command
+# interface to g.proj -p
+def get_proj():
+    """!Returns the output from running "g.proj -p" plus towgs84 parameter (g.proj -d), 
+    as a dictionary. Example:
 
+    \code
+    >>> proj = grass.get_proj()
+    >>> (proj['name'], proj['ellps'], proj['datum'])
+    (Lat/Lon, wgs84, wgs84)
+    \endcode
+
+    @return dictionary of projection values
+    """
+    gproj = read_command('g.proj',flags='p')
+    listproj = gproj.split('\n')
+    listproj.remove('-PROJ_INFO-------------------------------------------------')
+    listproj.remove('-PROJ_UNITS------------------------------------------------')
+    listproj.remove('')
+    proj = {}
+    for i in listproj:
+        ilist = i.split(':')
+        proj[ilist[0].strip()] = ilist[1].strip()
+    towgs = parse_command('g.proj',flags='d')
+    proj['towgs84']=towgs['towgs84']
+    return proj
+
 class product:
     """Definition of modis product with url and path in the ftp server
     """
@@ -80,7 +106,8 @@
     datumare supported"""
     def __init__(self,value):
         self.datum = value
-        self.datumlist = {'AGGIUNGERE':'AGGIUNGERE'}
+        self.datumlist = {'none':'NONE', 'nad27':'NAD27', 'nad83':'NAD83', 
+        'wgs66':'WGS66', 'wgs72':'WGS72', 'wgs84':'WGS84'}
 
     def returned(self):
         return self.datumlist[self.datum]

Modified: grass-addons/grass7/raster/r.modis/r.modis.download/r.modis.download.html
===================================================================
--- grass-addons/grass7/raster/r.modis/r.modis.download/r.modis.download.html	2011-06-18 09:46:30 UTC (rev 46736)
+++ grass-addons/grass7/raster/r.modis/r.modis.download/r.modis.download.html	2011-06-18 18:34:02 UTC (rev 46737)
@@ -4,55 +4,42 @@
 
 <h2>NOTE</h2>
 
-The first time that you use <em>r.modis</em> suite you have to do some easy operations to work corectly with <em>r.modis</em> modules.
-<ul>
-  <li>Create a r.modis folder inside $HOME/.grass7</li>
-  <li>Create SETTING.py file inside $HOME/.grass7/r.modis and compile like below:
-    <div class="code"><pre>
-    #!/usr/bin/python
+To set the username and password options  you have to use <em>setting</em> option; you can use a file, in this case the first line is the username, usually is 'anonymous', in the second line the password, your e-mail address
+<div class="code"><pre>
+  your_NASA_FTP_username
+  your_NASA_FTP_password
+</pre></div>
+otherwise you can pass the values from standard input.<br>
 
-    USERNAME='your_NASA_FTP_username'
-    PASSWORD='your_NASA_FTP_password'
-    MRTPATH='your_path_to_MRT_software'
-    </pre></div>
-  </li>
-</ul>
-
-The username and password should not be required but it's better set them; the username is anonymous and password is your mail. Instead NASA FTP server it is open
 <b>Warning</b>: NASA policy don't permit to open more then ten connections with the FTP servers. Please don't run more 10 the <em>r.modis.download</em> process at the same time.<br>
-By default the data downladed are store in <em>$HOME/.grass7/r.modis/download/</em>; you can change the directory with <em>folder</em> options.<br>
+By default the files downladed are store in the path where is the setting file; you can change the directory with <em>folder</em> options. You have to set <em>folder</em> option if you send user and password by standard input<br>
 The time of download change with the number of tiles, days and the type of product, for example NDVI product it is from 5 MB to 270 MB and LST is from 2 MB to 21 MB.
 
-<h4>Products</h4>
-The products already supported: 
-<ul>
-  <li>Land Surface Temperature daily (Terra): product provides per-pixel temperature and emissivity values in a sequence of swath-based to grid-based global products. The MODIS/Terra LST/E Daily L3 Global 1 km Grid product (MOD11A1), is tile-based and gridded in the Sinusoidal projection, and produced daily at 1 km spatial resolution. </li>
-  <li>Land Surface Temperature daily (Aqua): product provides per-pixel temperature and emissivity values in a sequence of swath-based to grid-based global products. The MODIS/Aqua LST/E Daily L3 Global 1 Km Grid product (MYD11A1), is tile-based and gridded in the Sinusoidal projection, and produced daily at 1 Km spatial resolution.</li>
-  <li>NDVI sixteen days (Terra): MODIS Normalized Difference Vegetation Index (NDVI) complements NOAA's Advanced Very High Resolution Radiometer (AVHRR) NDVI products and provides continuity for time series historical applications. data are provided every 16 days at 250-meter spatial resolution as a gridded level-3 product (MOD13Q1) in the Sinusoidal projection.</li>
-  <li>Snow eight days: </li>
-</ul>
-
 <h2>EXAMPLES</h2>
 
-To download LST Terra product using the default options (using $HOME/.grass7/r.modis/ as folder, SETTING.py file for username and password, starting from today until ten days ago) you can launch  
+To download LST Terra product using the default options and set the user and password by standard input you can launch  
 <div class="code"><pre>
-    r.modis.download
+    r.modis.download setting=-
 </pre></div>
 
-To download LST Terra product using the default options (using $HOME/.grass7/r.modis/ as folder, SETTING.py file for username and password) and change the starting and ending dates
+Reading the user and password options from file
 <div class="code"><pre>
-    r.modis.download startday=2011-05-31 endday=2011-05-01
+    r.modis.download setting=/home/user/.grass/r.modis/SETTING
 </pre></div>
 
+To download LST Terra product using the default options and change the starting and ending dates
+<div class="code"><pre>
+    r.modis.download setting=/home/user/.grass/r.modis/SETTING startday=2011-05-31 endday=2011-05-01
+</pre></div>
+
 To downlad another product (for example <em>Snow eight days</em>), with other default options
 <div class="code"><pre>
-    r.modis.download product=snow_terra_eight
+    r.modis.download setting=/home/user/.grass/r.modis/SETTING product=snow_terra_eight
 </pre></div>
 
-To use username and password specified (note that the command
-lines history will store the password in this way) and use the other default options
+To use <em>r.modis.download</em> in a script with one of the other module you have to set -g flag to return the name of the file containing a list of HDF names downladed
 <div class="code"><pre>
-    r.modis.download username=user password=*****
+    r.modis.download -g setting=/home/user/.grass/r.modis/SETTING startday=2011-05-31 endday=2011-05-01
 </pre></div>
 
 <h2>SEE ALSO</h2>
@@ -66,4 +53,4 @@
 
 Luca Delucchi, Google Summer of Code 2011
 
-<p><i>Last changed: $Date: 2011-06-03 14:44:59 +0200 (Mon, 09 May 2011) $</i>
\ No newline at end of file
+<p><i>Last changed: $Date: 2011-06-18 14:44:59 +0200 (Mon, 18 June 2011) $</i>
\ No newline at end of file

Modified: grass-addons/grass7/raster/r.modis/r.modis.download/r.modis.download.py
===================================================================
--- grass-addons/grass7/raster/r.modis/r.modis.download/r.modis.download.py	2011-06-18 09:46:30 UTC (rev 46736)
+++ grass-addons/grass7/raster/r.modis/r.modis.download/r.modis.download.py	2011-06-18 18:34:02 UTC (rev 46737)
@@ -20,34 +20,30 @@
 #% description: Download several tiles of MODIS products using pyModis
 #% keywords: raster
 #%end
-#%option
-#% key: product
-#% type: string
-#% description: Name of MODIS product
-#% required: yes
-#% options: lst_aqua_daily, lst_terra_daily, snow_terra_eight, ndvi_terra_sixte
-#% answer: lst_terra_daily
+#%flag
+#% key: d
+#% description: For debug mode, it will write more info in the log file
 #%end
-#%option
-#% key: username
-#% type: string
-#% key_desc: username
-#% description: Name of user to NASA ftp access, it's better use SETTING.py
-#% required: no
+#%flag
+#% key: g
+#% description: Return the name of file containing the list of HDF tiles downloaded in shell script style
 #%end
 #%option
-#% key: password
+#% key: setting
 #% type: string
-#% key_desc: password
-#% description: Password of user to NASA ftp access, it's better use SETTING.py
-#% required: no
+#% gisprompt: old,file,input
+#% label: Full path to setting file.
+#% description: "-" to pass the parameter from stdin
+#% required: yes
+#% guisection: Define
 #%end
 #%option
-#% key: folder
+#% key: product
 #% type: string
-#% description: Folder where saves the data, full path
-#% answer: $HOME/.grass7/r.modis/download
+#% description: Name of MODIS product
 #% required: no
+#% options: lst_aqua_daily, lst_terra_daily, snow_terra_eight, ndvi_terra_sixte
+#% answer: lst_terra_daily
 #%end
 #%option
 #% key: tiles
@@ -67,9 +63,11 @@
 #% description: The day to stop download. If not set the download stops 10 day before the start day
 #% required: no
 #%end
-#%flag
-#% key: d
-#% description: For debug mode, it will write more info in the log file
+#%option
+#% key: folder
+#% type: string
+#% description: The folder where store the data downloaded. If not set it take the path of setting file
+#% required: no
 #%end
 
 # import library
@@ -87,19 +85,16 @@
 except ImportError:
     pass
 
-
-def check(home,suffix):
-    """ Function to check the path necessary to work this module
+def check(home):
+    """ Check if a folder it is writable by the user that launch the process
     """
+    if os.access(home,os.W_OK):
+        return 1
+    else:
+        grass.fatal(_("Folder to write downloaded files doesn't" \
+        + " exist or is not writeable"))
+        return 0
 
-    # check if ~/.grass7/r.modis/download exist or create it
-    if not os.path.exists(home):
-        os.mkdir(home)
-        os.mkdir(os.path.join(home,suffix))
-    elif not os.path.exists(os.path.join(home,suffix)):
-        os.mkdir(os.path.join(home,suffix))
-    return 1
-
 def checkdate(options):
     """ Function to check the data and return the correct value to download the
         the tiles
@@ -125,7 +120,6 @@
     # set only end day
     elif options['startday'] == '' and options['endday'] != '':
         today = date.today().strftime("%Y-%m-%d")
-        import pdb; pdb.set_trace()
         if today <= options['endday']:
             grass.fatal(_('The last day cannot before >= of the first day'))
             return 0
@@ -139,79 +133,79 @@
     elif options['startday'] != '' and options['endday'] != '':
         valueDay, valueEnd, valueDelta = check2day(options['endday'],options['startday'])
     return valueDay, valueEnd, valueDelta 
+
 # main function
 def main():
-
     # check if you are in GRASS
     gisbase = os.getenv('GISBASE')
     if not gisbase:
         grass.fatal(_('$GISBASE not defined'))
         return 0
-
-    # set the home path
-    home = os.path.expanduser('~')
-     
+    # set username, password and folder if settings are insert by stdin
+    if options['setting'] == '-':
+        if options['folder']:
+            if check(options['folder']):
+                fold = options['folder']
+            user = raw_input(_('Insert username (usually anonymous): '))
+            passwd = raw_input(_('Insert password (your mail): '))
+        else:
+            grass.fatal(_("Please set folder option if you want pass username " \
+            + "and password by stdin"))
+            return 0
+    # set username, password and folder by file
+    else:
+        # open the file and read the the user and password:
+        # first line is username
+        # second line is password
+        filesett = open(options['setting'],'r')
+        fileread = filesett.readlines()
+        user = fileread[0].strip()
+        passwd = fileread[1].strip()
+        filesett.close()
+        # set the folder by option folder
+        if options['folder']:
+            if check(options['folder']):
+                fold = options['folder']
+        # set the folder from path where setting file is stored 
+        else:
+            path = os.path.split(options['setting'])[0]
+            if check(path):
+                fold = path
     # check the version
     version = grass.core.version()
     # this is would be set automatically
-    if version['version'].find('7.') != -1:
-        session_path = '.grass7'
-        grass_fold = os.path.join(home,session_path)
-        if not os.path.exists(grass_fold):
-          os.mkdir(grass_fold)
-    else: 
+    if version['version'].find('7.') == -1:
         grass.fatal(_('You are not in GRASS GIS version 7'))
         return 0
-    # path to ~/grass7/r.modis
-    path = os.path.join(grass_fold,'r.modis')
     # first date and delta
     firstday, finalday, delta = checkdate(options)
-    #username and password are optional because the command lines history 
-    #will store the password in this these options; so you are the possibility
-    #to use a file
-    if options['username'] == '' and options['password'] == '':
-        sett_file = os.path.join(path,'SETTING.py')
-        grass.message("For setting will use %s" % sett_file)
-        try:
-            sys.path.append(path)
-            import SETTING
-        except ImportError:
-            grass.fatal("%s not exist or is not well formatted. Create "\
-            "the file with inside:\n\n#!/usr/bin/env python\n\nusername="\
-            "your_user\npassword=xxxxx" % sett_file)
-            return 0
-        user = SETTING.username
-        passwd = SETTING.username
-    else:
-        grass.message("For setting will use username and password options")
-        user = options['username']
-        passwd = options['password']        
-    
+    # the product
     prod = product(options['product']).returned()
-    # set folder
-    if options['folder'].find('HOME/.grass7/r.modis/download') == 1:
-        fold = os.path.join(path,'download')
-        # some check
-        check(path,'download')
-    else:
-        fold = options['folder']
     # set tiles
     if options['tiles'] == '':
         tiles = None
     else:
         tiles = options['tiles']
-        
-    # start modis class
+    # set the debug
+    if flags['d']:
+      debug_opt = True
+    else:
+      debug_opt = False
+    #start modis class
     modisOgg = downModis(url = prod['url'], user = user,password = passwd, 
             destinationFolder = fold, tiles = tiles, path = prod['folder'], 
-            today = firstday, enddate = finalday, delta = delta)
+            today = firstday, enddate = finalday, delta = delta, debug = debug_opt)
     # connect to ftp
     modisOgg.connectFTP()
     # download tha tiles
     modisOgg.downloadsAllDay()
-    grass.message("All data are downloaded, now you can use r.in.modis.import "\
-    "or r.in.modis.process with option 'conf=" + modisOgg.filelist.name)
-    
+    if flags['g']:
+      grass.message(modisOgg.filelist.name)
+    else:
+      grass.message(_("Downloading MODIS product..."))
+      grass.message(_("All data are downloaded, now you can use r.in.modis.import "\
+      + "or r.in.modis.process with option 'conf=" + modisOgg.filelist.name + '\''))
+
 if __name__ == "__main__":
     options, flags = grass.parser()
     sys.exit(main())

Modified: grass-addons/grass7/raster/r.modis/r.modis.html
===================================================================
--- grass-addons/grass7/raster/r.modis/r.modis.html	2011-06-18 09:46:30 UTC (rev 46736)
+++ grass-addons/grass7/raster/r.modis/r.modis.html	2011-06-18 18:34:02 UTC (rev 46737)
@@ -1,30 +1,38 @@
 <h2>DESCRIPTION</h2>
 
-The <em>r.modis</em> suite is a toolset to import MODIS data in GRASS GIS. It use the <a href="http://gis.cri.fmach.it/development/pyModis">pyModis</a> library and the <a href="https://lpdaac.usgs.gov/lpdaac/tools/modis_reprojection_tool">MODIS Reprojection Tool</a> softwares to convert, mosaik and process MODIS data. Please check to have <a href="https://lpdaac.usgs.gov/lpdaac/tools/modis_reprojection_tool">MODIS Reprojection Tool</a> on your Operation System, <a href="http://gis.cri.fmach.it/development/pyModis">pyModis</a> it is distributed with <em>r.modis</em> program.
-The suite offers three modules for interface with MODIS data. Each modules it is useful for a specific operation, read below for more info.
-It can download several products, tiles and days of MODIS data from NASA FTP servers. After, it can import the 3 Level products as single image or daily mosaik or process the raw data.
+The <em>r.modis</em> suite is a toolset to import MODIS satellite data in GRASS GIS. 
+It uses the <a href="http://gis.cri.fmach.it/development/pyModis">pyModis</a>
+library and the <a
+href="https://lpdaac.usgs.gov/lpdaac/tools/modis_reprojection_tool"> MODIS
+Reprojection Tool</a> software to convert, mosaik and process MODIS data.
+It requires the <a
+href="https://lpdaac.usgs.gov/lpdaac/tools/modis_reprojection_tool">MODIS
+Reprojection Tool</a> to be installed while <a
+href="http://gis.cri.fmach.it/development/pyModis">pyModis</a> is
+included in the <em>r.modis</em> suite.
+The suite offers three modules as interface with MODIS data. Each modules
+is dedicated to for a specific operation.
+It can download several MODIS products, those by tiles and observation days from 
+the releated NASA FTP server. It process Level 2 data using the r.modis.process module.
+It also import Level 3 (georeferenced) products either as single image or as daily mosaik.
 
-<h2>NOTE</h2>
-The first time that you use <em>r.modis</em> suite you have to do some easy operations to work corectly with <em>r.modis</em> modules.
+<h4>Products</h4>
+The products already supported: 
 <ul>
-  <li>Create a r.modis folder inside $HOME/.grass7</li>
-  <li>Create SETTING.py file inside $HOME/.grass7/r.modis and compile like below:
-    <div class="code"><pre>
-    #!/usr/bin/python
-
-    USERNAME='your_NASA_FTP_username'
-    PASSWORD='your_NASA_FTP_password'
-    MRTPATH='your_path_to_MRT_software'
-    </pre></div>
-  </li>
+  <li>Land Surface Temperature daily (Terra): product provides per-pixel temperature and emissivity values in a sequence of swath-based to grid-based global products. The MODIS/Terra LST/E Daily L3 Global 1 km Grid product (MOD11A1), is tile-based and gridded in the Sinusoidal projection, and produced daily at 1 km spatial resolution. </li>
+  <li>Land Surface Temperature daily (Aqua): product provides per-pixel temperature and emissivity values in a sequence of swath-based to grid-based global products. The MODIS/Aqua LST/E Daily L3 Global 1 Km Grid product (MYD11A1), is tile-based and gridded in the Sinusoidal projection, and produced daily at 1 Km spatial resolution.</li>
+  <li>NDVI sixteen days (Terra): MODIS Normalized Difference Vegetation Index (NDVI) complements NOAA's Advanced Very High Resolution Radiometer (AVHRR) NDVI products and provides continuity for time series historical applications. data are provided every 16 days at 250-meter spatial resolution as a gridded level-3 product (MOD13Q1) in the Sinusoidal projection.</li>
+  <li>Snow eight days: </li>
 </ul>
-$HOME/.grass7/r.modis is also the default path where <em>r.modis</em> suite creates some subfolder to store the different MODIS files. Each module permits to change the previous folder with another directory using an module's option.
 
 <h2>SEE ALSO</h2>
 <ul>
-  <li> <a href="r.modis.download.html">r.modis.download</a>: Download MODIS products</li>
-<!--   <li> <a href="r.modis.import.html">r.modis.import</a>: Import into GRASS GIS 3 Level MODIS products as single image or daily mosaik</li> -->
-<!--  <li> <a href="r.modis.process.html">r.modis.process</a>: Calculates range of patch area size on a raster map</li>-->
+  <li> <a href="r.modis.download.html">r.modis.download</a>: Download MODIS
+products</li>
+<!--   <li> <a href="r.modis.import.html">r.modis.import</a>: Import into GRASS
+GIS 3 Level MODIS products as single image or daily mosaik</li> -->
+<!--  <li> <a href="r.modis.process.html">r.modis.process</a>: Calculates range
+of patch area size on a raster map</li>-->
 </ul>
  
 <h2>AUTHOR</h2>



More information about the grass-commit mailing list