[Greater-commits] r3767 - branches/3.0.0-all-models/greater-pre-processing

scm-commit@wald.intevation.org scm-commit at wald.intevation.org
Wed Aug 17 19:35:31 CEST 2011


Author: aheinecke
Date: 2011-08-17 19:35:31 +0200 (Wed, 17 Aug 2011)
New Revision: 3767

Modified:
   branches/3.0.0-all-models/greater-pre-processing/greater-pre-processing.py
   branches/3.0.0-all-models/greater-pre-processing/upload-catchment.py
Log:
Add First GUI to greater-pre-processing


Modified: branches/3.0.0-all-models/greater-pre-processing/greater-pre-processing.py
===================================================================
--- branches/3.0.0-all-models/greater-pre-processing/greater-pre-processing.py	2011-08-17 09:46:24 UTC (rev 3766)
+++ branches/3.0.0-all-models/greater-pre-processing/greater-pre-processing.py	2011-08-17 17:35:31 UTC (rev 3767)
@@ -17,9 +17,14 @@
 
 import support
 
+import wxPython.wx as wx
+from wxPython.wizard import wxWizard, wxWizardPageSimple, \
+     wxWizardPageSimple_Chain, EVT_WIZARD_PAGE_CHANGING, \
+     EVT_WIZARD_PAGE_CHANGED
 catchment = {}
 version_str = 'greater-pre-processing 1.2.0'
 usage_str = 'greater-pre-processing [check|help|run|run-without-cleanup|clean]'
+greater_pre_proc_path = os.path.abspath(os.path.dirname(sys.argv[0]))
 
 def cygwin_call(command, suppress_output=False, extra_env={}, inputdata=None,
          logfile=None, **kw):
@@ -68,16 +73,16 @@
         return -1
     return 0
 
-def catchment_desc():
+def catchment_desc(catchment_file = "catchment.desc"):
     """Check for file "catchment.desc" and if found
     check also for correct syntax and completeness.
     Else, print appropriate error messages.
     """
     try:
-        catchment_desc = open('catchment.desc', 'r').readlines()
+        catchment_desc = open(catchment_file, 'r').readlines()
     except:
-        print "Error: Could not find or open file 'catchment.desc'"
-        print "This file is required for pre-processing the catchment."
+        raise IOError("Error: Could not find or open file 'catchment.desc'"
+                      "This file is required for pre-processing the catchment.")
         return 1
 
     print "Found 'catchment.desc':"
@@ -89,14 +94,14 @@
 
     for k in [ 'ID', 'NAME', 'DESCRIPTION', 'IN-VERSION', 'OUT-VERSION' ]:
         if not catchment.has_key(k):
-            print "Error in catchment.desc: missing", k
+            raise ValueError("Error in catchment.desc: missing", k)
             return 2
 
     for c in  catchment['ID']:
         if not((c >= 'a' and c <= 'z') or (c >= 'A' and c <= 'Z') or \
                (c >= '0' and c <= '9')):
-            print ' Error: character "' + c + \
-                  '" not allowed in CATCHEMENTID (only a-zA-Z0-9)'
+            raise ValueError(' Error: character "' + c + \
+                  '" not allowed in CATCHEMENTID (only a-zA-Z0-9)')
             return 3
 
     print ' ID                    =', catchment['ID']
@@ -108,25 +113,24 @@
     print "description complete."
 
 
-def do_check():
+def do_check(catch_dir = "."):
     # check for files .drn, .rna, .dsd, .cbp, .bgd and if found
     # check also for correct syntax and completeness.
     # provide appropriate error messages
     print "Running check ..."
-
     if catchment['IN-VERSION'] != '1.0':
-        print ' Error: Format version ' + catchment['IN-VERSION'] + \
-              ' can not be processed'
-        print ' This check is for version 1.0'
+        raise ValueError(' Error: Format version ' + catchment['IN-VERSION'] + \
+              ' can not be processed \n'
+              ' This check is for version 1.0')
         return 99
 
     # <catchmentid>.drn: digital river network
     fname = catchment['ID']+'.drn'
     try:
-        catchment_drn = open(fname, 'r').readlines()
+        catchment_drn = open(os.path.join(catch_dir, fname), 'r').readlines()
     except:
-        print " Error: Could not find or open file '" + fname + "'"
-        print " This file is required for pre-processing the catchment."
+        raise ValueError(" Error: Could not find or open file '" + fname + "'"
+              "\nThis file is required for pre-processing the catchment.")
         return 1
     else:
         print ' Found ' + fname + ' (digital river network):'
@@ -143,8 +147,8 @@
             try:
                 id = int(fields[0])
             except:
-                print '  Syntax error at line ' + str(line_count) + ':'
-                print '   StretchID ' + fields[0] + ' not an integer.'
+                raise ValueError('  Syntax error at line ' + str(line_count) + ':'
+                      '\n   StretchID ' + fields[0] + ' not an integer.')
                 return 2
             drn_count = drn_count + 1
             drn_stretch_ids.append(id)
@@ -153,12 +157,12 @@
                 float(fields[0])
                 float(fields[1])
             except:
-                print '  Syntax error at line ' + str(line_count) + ':'
-                print '   coordinates (' + fields[0] + ',' + fields[1] + ') not a float tupel.'
+                raise ValueError('  Syntax error at line ' + str(line_count) + ':'
+                      '\n   coordinates (' + fields[0] + ',' + fields[1] + ') not a float tupel.')
                 return 3
         if len(fields) > 2:
-            print '  Syntax error at line ' + str(line_count) + ':'
-            print '   incorrect number of fields (is ' + str(len(fields)) + ', should be 1 (StretchID) or 2 (coords)).'
+            raise ValueError('  Syntax error at line ' + str(line_count) + ':'
+            '\n   incorrect number of fields (is ' + str(len(fields)) + ', should be 1 (StretchID) or 2 (coords)).')
             return 4
 
     print '  Total number of stretches: ' + str(drn_count)
@@ -167,10 +171,10 @@
     # <catchmentid>.cbp: catchment boundary polygon
     fname = catchment['ID']+'.cbp'
     try:
-        catchment_cbp = open(fname, 'r').readlines()
+        catchment_cbp = open(os.path.join(catch_dir, fname), 'r').readlines()
     except:
-        print "Error: Could not find or open file '" + fname + "'"
-        print "This file is required for pre-processing the catchment."
+        raise ValueError("Error: Could not find or open file '" + fname + "'"
+                         "\nThis file is required for pre-processing the catchment.")
         return 1
     else:
         print ' Found ' + fname + ' (catchment boundary polygon):'
@@ -189,22 +193,23 @@
                 float(fields[0])
                 float(fields[1])
             except:
-                print '  Syntax error at line ' + str(line_count) + ':'
-                print '   coordinates (' + fields[0] + ',' + fields[1] + ') not a float tupel.'
+                raise ValueError('  Syntax error at line ' + str(line_count) + ':'
+                      '\n   coordinates (' + fields[0] + ',' + fields[1] + ') not a float tupel.')
                 return 3
             cbp_count = cbp_count + 1
             if cbp_count == 1:
                 cbp_first_coord = fields
             cbp_last_coord = fields
         if len(fields) != 2:
-            print '  Syntax error at line ' + str(line_count) + ':'
-            print '   incorrect number of fields (is ' + str(len(fields)) + ', should be or 2 (coordinate pair)).'
+            raise ValueError('  Syntax error at line ' + str(line_count) + ':'
+                '\n   incorrect number of fields (is ' + str(len(fields)) + \
+                ', should be or 2 (coordinate pair)).')
             return 4
 
     if cbp_first_coord != cbp_last_coord:
-        print '  Syntax error at line ' + str(line_count) + ':'
-        print '   first and last coordinate pair must be equal (polygon must be closed).'
-        print '   ' + str(cbp_first_coord) + ' != ' + str(cbp_last_coord)
+        raise ValueError('  Syntax error at line ' + str(line_count) + ':'
+                        '\n   first and last coordinate pair must be equal (polygon must be closed).'
+                        '   ' + str(cbp_first_coord) + ' != ' + str(cbp_last_coord))
         return 5
 
     print '  Total number of boundary coords: ' + str(cbp_count)
@@ -213,10 +218,10 @@
     # <catchmentid>.rna: river network attributes
     fname = catchment['ID']+'.rna'
     try:
-        catchment_rna = open(fname, 'r').readlines()
+        catchment_rna = open(os.path.join(catch_dir, fname), 'r').readlines()
     except:
-        print "Error: Could not find or open file '" + fname + "'"
-        print "This file is required for pre-processing the catchment."
+        raise ValueError("Error: Could not find or open file '" + fname + "'"
+                         "\nThis file is required for pre-processing the catchment.")
         return 1
     else:
         print ' Found ' + fname + ' (river network attributes):'
@@ -240,14 +245,14 @@
                 if fields[6] != '': float(fields[6])
                 if fields[7] != '': float(fields[7])
             except:
-                print '  Syntax error at line ' + str(line_count) + ':'
-                print '   incorrect data type (should be int,float,float,float,float,float,float,float,string.'
+                raise ValueError('  Syntax error at line ' + str(line_count) + ':'
+                    '\n incorrect data type (should be int,float,float,float,float,float,float,float,string.')
                 return 3
             rna_count = rna_count + 1
             rna_stretch_ids.append(id)
         if len(fields) != 9:
-            print '  Syntax error at line ' + str(line_count) + ':'
-            print '   incorrect number of fields (is ' + str(len(fields)) + ', should be 9).'
+            raise ValueError('  Syntax error at line ' + str(line_count) + ':'
+                             '\n   incorrect number of fields (is ' + str(len(fields)) + ', should be 9).')
             return 4
 
     print '  Total number of stretches: ' + str(rna_count)
@@ -256,10 +261,10 @@
     # <catchmentid>.dsd: discharge site data
     fname = catchment['ID']+'.dsd'
     try:
-        catchment_dsd = open(fname, 'r').readlines()
+        catchment_dsd = open(os.path.join(catch_dir, fname), 'r').readlines()
     except:
-        print "Error: Could not find or open file '" + fname + "'"
-        print "This file is required for pre-processing the catchment."
+        raise ValueError("Error: Could not find or open file '" + fname + "'"
+        "\nThis file is required for pre-processing the catchment.")
         return 1
     else:
         print ' Found ' + fname + ' (discharge site data):'
@@ -281,17 +286,17 @@
                 float(fields[5])
                 int(fields[7])
             except:
-                print '  Syntax error at line ' + str(line_count) + ':'
-                print '   incorrect data type (should be int,float,float,int,float,float,string,int,string).'
+                raise ValueError('  Syntax error at line ' + str(line_count) + ':'
+                '\n   incorrect data type (should be int,float,float,int,float,float,string,int,string).')
                 return 3
             dsd_count = dsd_count + 1
         if len(fields) != 9:
-            print '  Syntax error at line ' + str(line_count) + ':'
-            print '   incorrect number of fields (is ' + str(len(fields)) + ', should be 9).'
+            raise ValueError('  Syntax error at line ' + str(line_count) + ':'
+             '\n   incorrect number of fields (is ' + str(len(fields)) + ', should be 9).')
             return 4
         if fields[6] not in [ 'PS', 'AS', 'TF', 'AS/TF' ]:
-            print '  Syntax error at line ' + str(line_count) + ':'
-            print "   Type is '" + fields[6] + "' but must be either 'PS', 'AS', 'TF' or 'AS/TF'."
+            raise ValueError( '  Syntax error at line ' + str(line_count) + ':'
+            "\n   Type is '" + fields[6] + "' but must be either 'PS', 'AS', 'TF' or 'AS/TF'.")
             return 6
 
     print '  Total number of discharge sites: ' + str(dsd_count)
@@ -300,10 +305,10 @@
     # <catchmentid>.bgd: background data
     fname = catchment['ID']+'.bgd'
     try:
-        catchment_bgd = open(fname, 'r').readlines()
+        catchment_bgd = open(os.path.join(catch_dir, fname), 'r').readlines()
     except:
-        print "Error: Could not find or open file '" + fname + "'"
-        print "This file is required for pre-processing the catchment."
+        raise ValueError("Error: Could not find or open file '" + fname + "'"
+        "\nThis file is required for pre-processing the catchment.")
         return 1
     else:
         print ' Found ' + fname + ' (background data):'
@@ -318,16 +323,16 @@
         if len(fields) == 5:
             bgd_count = bgd_count + 1
         if len(fields) != 5:
-            print '  Syntax error at line ' + str(line_count) + ':'
-            print '   incorrect number of fields (is ' + str(len(fields)) + ', should be 5).'
+            raise ValueError('  Syntax error at line ' + str(line_count) + ':'
+                 '\n   incorrect number of fields (is ' + str(len(fields)) + ', should be 5).')
             return 4
         if fields[2] not in [ '', 'point', 'polygon', 'line', 'shape', 'image', 'grid' ]:
-            print '  Syntax error at line ' + str(line_count) + ':'
-            print "   Type is '" + fields[2] + "' but must be one of 'point', 'polygon', 'line', 'shape', 'image', 'grid' or left empty."
+            raise ValueError('  Syntax error at line ' + str(line_count) + ':'
+            "\n   Type is '" + fields[2] + "' but must be one of 'point', 'polygon', 'line', 'shape', 'image', 'grid' or left empty.")
             return 6
         if fields[4] not in [ 'yes', 'no' ]:
-            print '  Syntax error at line ' + str(line_count) + ':'
-            print "   Ctch_fl is '" + fields[4] + "' but must be either 'yes' or 'no'."
+            raise ValueError('  Syntax error at line ' + str(line_count) + ':'
+            "\n  Ctch_fl is '" + fields[4] + "' but must be either 'yes' or 'no'.")
             return 6
 
     print '  Total number of background elements : ' + str(bgd_count)
@@ -336,10 +341,10 @@
     # <catchmentid>.lks: lakes
     fname = catchment['ID']+'.lks'
     try:
-        catchment_lks = open(fname, 'r').readlines()
+        catchment_lks = open(os.path.join(catch_dir, fname), 'r').readlines()
     except:
-        print "Error: Could not find or open file '" + fname + "'"
-        print "This file is required for pre-processing the catchment."
+        raise ValueError("Error: Could not find or open file '" + fname + "'"
+             "\nThis file is required for pre-processing the catchment.")
         return 1
     else:
         print ' Found ' + fname + ' (lakes):'
@@ -353,8 +358,8 @@
         try:
             int(line)
         except:
-            print '  Syntax error at line ' + str(line_count) + ':'
-            print '   entry (' + line + ') not an integer.'
+            raise ValueError('  Syntax error at line ' + str(line_count) + ':'
+                '\n  entry (' + line + ') not an integer.')
             return 3
         lks_count = lks_count + 1
     print '  Total number of lakes: ' + str(lks_count)
@@ -363,10 +368,10 @@
     # <catchmentid>.pic: pictures
     fname = catchment['ID']+'.pic'
     try:
-        catchment_pic = open(fname, 'r').readlines()
+        catchment_pic = open(os.path.join(catch_dir, fname), 'r').readlines()
     except:
-        print "Error: Could not find or open file '" + fname + "'"
-        print "This file is required for pre-processing the catchment."
+        raise ValueError("Error: Could not find or open file '" + fname + "'"
+         "\nThis file is required for pre-processing the catchment.")
         return 1
     else:
         print ' Found ' + fname + ' (pictures):'
@@ -384,13 +389,13 @@
                 float(fields[1])
                 float(fields[2])
             except:
-                print '  Syntax error at line ' + str(line_count) + ':'
-                print '   incorrect data type (should be int,float,float,string,string).'
+                raise ValueError('  Syntax error at line ' + str(line_count) + ':'
+                     '\n   incorrect data type (should be int,float,float,string,string).')
                 return 3
             pic_count = pic_count + 1
         if len(fields) != 5:
-            print '  Syntax error at line ' + str(line_count) + ':'
-            print '   incorrect number of fields (is ' + str(len(fields)) + ', should be 5).'
+            raise ValueError( '  Syntax error at line ' + str(line_count) + ':'
+                '\n   incorrect number of fields (is ' + str(len(fields)) + ', should be 5).')
             return 4
 
     print '  Total number of pictures: ' + str(pic_count)
@@ -400,15 +405,15 @@
     for id in rna_stretch_ids:
         if id in drn_stretch_ids:
             continue
-        print 'Semantic Error: StretchID %d occurs in .rna file, but does not '\
-              'appear in .drn file' % id
+        raise ValueError('Semantic Error: StretchID %d occurs in .rna file, but does not '\
+              'appear in .drn file' % id)
         error_count += 1
 
     for id in drn_stretch_ids:
         if id in rna_stretch_ids:
             continue
-        print 'Semantic Error: StretchID %d occurs in .drn file, but does not '\
-              'appear in .rna file' % id
+        raise ValueError('Semantic Error: StretchID %d occurs in .drn file, but does not '\
+              'appear in .rna file' % id)
         error_count += 1
 
     if error_count > 0:
@@ -418,26 +423,25 @@
     return 0
 
 def do_run():
+    yield(1)
     if catchment['OUT-VERSION'] != '1.0' and catchment['OUT-VERSION'] != '2.0':
-        print ' Error: Format version ' + catchment['OUT-VERSION'] + \
+        raise ValueError(' Error: Format version ' + catchment['OUT-VERSION'] + \
               ' can not be created'
-        print ' Supported versions are 1.0 and 2.0'
-        return 99
+              '\n Supported versions are 1.0 and 2.0')
 
     # execute the pre-processing
     if do_check() != 0:
         print 'Not executing pre-processing due to error'
-        return 1
-
+    yield(5)
     print 'Running pre-processing ...'
 
     print ' Removing tmp-files and old log-file (' +catchment['ID'] + '.log ...'
     cmds = [ 'rm -f *.tmp ' + catchment['ID'] + '.log' ]
     for cmd in cmds:
         if cygwin_call(cmd) != 0:
-            print '  Error executing ' + cmd
-            return 2
+            raise OSError('  Error executing ' + cmd)
     print ' done.'
+    yield(7)
 
     print ' Creating discharges.shp ...'
     cmds = [ 'gawk -f ' + os.path.join(greater_pre_proc_path,
@@ -446,9 +450,9 @@
             'gen2shp discharges points < discharges.gen.tmp']
     for cmd in cmds:
         if cygwin_call(cmd) != 0:
-            print '  Error executing ' + cmd
-            return 2
+            raise OSError('  Error executing ' + cmd)
     print ' done.'
+    yield(10)
 
     print ' Creating rivernet.shp ...'
     cmds = [ 'gawk -v LOG=' + catchment['ID'] + '.log -f ' + \
@@ -457,9 +461,9 @@
             'gen2shp rivernet lines < rivernet.gen.tmp']
     for cmd in cmds:
         if cygwin_call(cmd) != 0:
-            print '  Error executing ' + cmd
-            return 2
+            raise OSError('  Error executing ' + cmd)
     print ' done.'
+    yield(15)
 
     print ' Creating disch_river.shp ...'
     cmds = [ 'gawk -f ' + os.path.join(greater_pre_proc_path,
@@ -468,9 +472,9 @@
             'gen2shp disch_river lines < disch_river.gen.tmp']
     for cmd in cmds:
         if cygwin_call(cmd) != 0:
-            print '  Error executing ' + cmd
-            return 2
+            raise OSError('  Error executing ' + cmd)
     print ' done.'
+    yield(20)
 
     print ' Creating catchbound.shp ...'
     cmds = [ 'sed -e "s/D/E/g" < ' + catchment['ID'] + \
@@ -483,9 +487,9 @@
             ]
     for cmd in cmds:
         if cygwin_call(cmd) != 0:
-            print '  Error executing ' + cmd
-            return 2
+            raise OSError('  Error executing ' + cmd)
     print ' done.'
+    yield(30)
 
     print ' Creating attribute files rivclass.dbf, wwtp.dbf, disch.dbf ' \
           'and river.dbf ...'
@@ -538,10 +542,13 @@
                 '-R20.10 -R20.10 ' + \
                 '-R10.5 -I10 -R10.5 -C40 disch.att ' + \
                 'disch.dbf 2>> ' + catchment['ID'] + '.log')
+    cmdno = 0
     for cmd in cmds:
         if cygwin_call(cmd) != 0:
-            print '  Error executing ' + cmd
-            return 2
+            raise OSError('  Error executing ' + cmd)
+        yield int(round(30+ 40 * float(cmdno) / len(cmds)))
+        cmdno += 1
+
     print ' done.'
 
     if catchment['OUT-VERSION'] == '2.0':
@@ -556,15 +563,13 @@
                            int(attributes[5]), int(attributes[6]) ])
         result = support.check_for_circle(table)
         if isinstance(result, list):
-            print " Error: Circle detected:"
-            print "       ", result
-            return 1
+            raise ValueError( " Error: Circle detected: %s" % result)
         elif result is None:
-            print "  Error: Circle detection routine failed"
-            return 1
+            raise ValueError( "  Error: Circle detection routine failed")
     else:
         print ' [ Check for circles only available for OUT-VERSION >= 2.0 ]'
 
+    yield(75)
     print ' Creating pics.shp ...'
     cmds = [ 'gawk -f ' + os.path.join(greater_pre_proc_path,
                 'awk', 'pic2gen.awk') + ' < ' + catchment['ID'] + '.pic > pic.gen.tmp',\
@@ -578,9 +583,9 @@
                 '2>> ' + catchment['ID'] + '.log']
     for cmd in cmds:
         if cygwin_call(cmd) != 0:
-            print '  Error executing ' + cmd
-            return 2
+            raise OSError( '  Error executing ' + cmd)
     print ' done.'
+    yield(80)
 
     if catchment['OUT-VERSION'] == '1.0':
         print ' Creating backgroundlst.dbf ...'
@@ -589,33 +594,28 @@
                      catchment['ID'] + '.log']
         for cmd in cmds:
             if cygwin_call(cmd) != 0:
-                print '  Error executing ' + cmd
-                return 2
+                raise OSError('  Error executing ' + cmd)
         print ' done.'
+    yield(90)
 
     print ' Creating Thuban session file (' + catchment['ID'] + '.session) ...'
     cmds = [ 'cp ' + os.path.join(greater_pre_proc_path, "catchment.thuban") + ' .']
     for cmd in cmds:
         if cygwin_call(cmd) != 0:
-            print '  Error executing ' + cmd
-            return 2
+            raise OSError( '  Error executing ' + cmd)
     print ' done.'
 
-    if sys.argv[1] == 'run':
-        print ' Cleaning up ...'
-        cmds = [ 'rm -f *.tmp' ]
-        for cmd in cmds:
-            if cygwin_call(cmd) != 0:
-                print '  Error executing ' + cmd
-                return 2
-        print ' done.'
-    else:
-        print ' Not removing temporary files.'
+    yield(95)
+    print ' Cleaning up ...'
+    cmds = [ 'rm -f *.tmp' ]
+    for cmd in cmds:
+        if cygwin_call(cmd) != 0:
+            raise OSError( '  Error executing ' + cmd)
+    print ' done.'
 
     print 'Pre-processing successfully finished'
-    return 0
+    yield(100)
 
-
 def do_clean():
     print 'Cleaning up ...'
 
@@ -632,6 +632,7 @@
 
 
 def usage():
+    # This is the old console version usage
     print usage_str
     print ' help  print this text'
     print ' check test for completeness and correct syntax of source files'
@@ -641,38 +642,327 @@
     print ' clean remove all temporary and all results files'
 
 
-if __name__ == '__main__':
-    import sys
 
-    print version_str
-    print
+# Texts
+intro = """\
+This wizard will guide you through the preprocessing
+of catchment data files for the GREAT-ER Software.
 
-    if catchment_desc():
-        print '\nusage:', usage_str
-        sys.exit(1)
+This converts catchments from Format 1.0 to Format 2.0
 
-    print
+For more information about preprocessing please refer to the GREAT-ER-Preprocessing Manual.
+"""
 
-    if os.environ.has_key('GREATER_PRE_PROC') == 0:
-        greater_pre_proc_path = os.path.abspath(os.path.dirname(sys.argv[0]))
-        if not os.path.exists(os.path.join(
-                                    greater_pre_proc_path,'awk','joinup.awk')):
-            print 'Error: environment variable GREATER_PRE_PROC not set'
-            sys.exit(2)
-    else:
-        greater_pre_proc_path = os.environ['GREATER_PRE_PROC']
-    
+synok = """\
+All files where found and the syntax appears to be correct.
+Press Finish to start the preprocessing."""
 
-    if len(sys.argv) == 2:
-        if sys.argv[1] == 'check':
-            do_check()
-        if sys.argv[1] == 'run':
-            do_run()
-        if sys.argv[1] == 'run-without-cleanup':
-            do_run()
-        if sys.argv[1] == 'clean':
-            do_clean()
-        if sys.argv[1] == 'help':
-            usage()
-    else:
-        print 'usage:', usage_str
+#
+#  GUI
+#
+def makePageTitle(wizPg, title):
+    """Create the page title on the wizard page wizPg.
+
+    This function was taken directly from the wxPython demo.
+    """
+    sizer = wx.wxBoxSizer(wx.wxVERTICAL)
+    wizPg.SetSizer(sizer)
+    title = wx.wxStaticText(wizPg, -1, title)
+    title.SetFont(wx.wxFont(18, wx.wxSWISS, wx.wxNORMAL, wx.wxBOLD))
+    sizer.AddWindow(title, 0, wx.wxALIGN_CENTRE|wx.wxALL, 5)
+    sizer.AddWindow(wx.wxStaticLine(wizPg, -1), 0, wx.wxEXPAND|wx.wxALL, 5)
+    return sizer
+
+class TitledPage(wxWizardPageSimple):
+
+    """Base class for wizard pages with a title.
+
+    Taken directly from the wxPython demo.
+    """
+
+    def __init__(self, parent, title):
+        wxWizardPageSimple.__init__(self, parent)
+        self.sizer = makePageTitle(self, title)
+
+class SimpleTextPage(TitledPage):
+
+    """A simple page with a title and some static text"""
+
+    def __init__(self, parent, title, text):
+        TitledPage.__init__(self, parent, title)
+        self.text = wx.wxStaticText(self, -1, text)
+        self.sizer.Add(self.text)
+
+def has_cfile(cdir):
+    """ Returns true if the directory cdir contains a catchment.desc"""
+    return os.path.isfile(os.path.join(cdir), "catchment.desc")
+
+class CatchmentPage(TitledPage):
+
+    """Wizard page for the catchment parameters"""
+
+    def __init__(self, parent):
+        TitledPage.__init__(self, parent, "Catchment Configuration")
+        if not hasattr(self, "catchment_dir"):
+            dialog = wx.wxDirDialog( None,
+                    "Please select the catchment directory.",
+                    name="Select catchment")
+            if dialog.ShowModal() == wx.wxID_OK:
+                self.catchment_dir = dialog.GetPath()
+            else:
+                wx.wxMessageBox("You have to select a directory.",
+                                "Error!", wx.wxICON_ERROR|wx.wxOK)
+                sys.exit(1)
+
+        default_id=None
+        default_name=None
+        default_description=None
+        grid = wx.wxFlexGridSizer(5, 2, 0, 0)
+
+        if not os.path.isfile(os.path.join(self.catchment_dir, "catchment.desc")):
+            grid.Add(wx.wxStaticText(self, -1, "File catchment.desc"), 0,
+                   wx.wxEXPAND|wx.wxALL, 5)
+            grid.Add(wx.wxStaticText(self, -1, "not found."), 0,
+                   wx.wxEXPAND|wx.wxALL, 5)
+        else:
+            grid.Add(wx.wxStaticText(self, -1, "File catchment.desc"), 0,
+                   wx.wxEXPAND|wx.wxALL, 5)
+            grid.Add(wx.wxStaticText(self, -1, "found."), 1,
+                   wx.wxEXPAND|wx.wxALL, 5)
+            try:
+                catchment = {}
+                with open(os.path.join(self.catchment_dir, "catchment.desc"), "r") as fptr:
+                    for line in fptr:
+                        line = line.rstrip()
+                        if len(line) == 0 or line[0] == '#': continue
+                        fields = line.split('=')
+                        catchment[fields[0]] = fields[1]
+                print catchment
+                default_id = catchment["ID"]
+                default_name = catchment["NAME"]
+                default_description = catchment["DESCRIPTION"]
+            except:
+                pass
+        self.sizer.Add(grid, 0, wx.wxEXPAND|wx.wxALL,5)
+
+        grid.Add(wx.wxStaticText(self, -1, "Selected Directory:"), 0,
+                   wx.wxEXPAND|wx.wxALL, 5)
+        grid.Add(wx.wxStaticText(self, -1, self.catchment_dir), 1,
+                   wx.wxEXPAND|wx.wxALL, 5)
+
+        for varname, title, flags in [("text_ID", "Catchment ID", 0),
+                                      ("text_NAME", "Catchment Name", 0),
+                                      ("text_DESCRIPTION", "Description", 0)]:
+            text = wx.wxStaticText(self, -1, title)
+            grid.Add(text, 0, wx.wxEXPAND|wx.wxALL, 5)
+            ctrl = wx.wxTextCtrl(self, -1, style=flags, 
+                             size=wx.wxSize(150,wx.wxDefaultSize.GetHeight()))
+            grid.Add(ctrl, 1, wx.wxEXPAND|wx.wxALL, 5)
+            setattr(self, varname, ctrl)
+        if default_id: self.text_ID.WriteText(default_id)
+        if default_name: self.text_NAME.WriteText(default_name)
+        if default_description: self.text_DESCRIPTION.WriteText(default_description)
+
+class PreProcessingApp(wx.wxApp):
+    """Greater PreProcessingApplication Class"""
+
+    def OnInit(self):
+        """Read create the wizard as the main window
+        """
+
+        wx.wxInitAllImageHandlers()
+        bitmap_filename = os.path.join(
+                            os.path.abspath(os.path.dirname(sys.argv[0])),
+                            "river_aire.png")
+        try:
+            bitmap = wx.wxImage(bitmap_filename).ConvertToBitmap()
+        except:
+            bitmap = wx.wxNullBitmap
+        wizard = self.wizard = wxWizard(wx.NULL, -1,
+                                        "GREAT-ER Pre Processing", bitmap)
+        intro_page = SimpleTextPage(wizard, "Welcome", intro)
+        self.intro_page = intro_page
+
+        wizard.FitToPage(intro_page)
+
+        self.catchment_page = CatchmentPage(wizard)
+        self.convert_page = SimpleTextPage(wizard, "Syntax check completed.", synok)
+
+        wxWizardPageSimple_Chain(intro_page, self.catchment_page)
+        wxWizardPageSimple_Chain(self.catchment_page, self.convert_page)
+
+        EVT_WIZARD_PAGE_CHANGED(self, wizard.GetId(), self.OnPageChanged)
+        EVT_WIZARD_PAGE_CHANGING(self, wizard.GetId(), self.OnPageChanging)
+
+        return True
+
+    def OnPageChanged(self, event):
+        """Handler for the wizard's PAGE_CHANGED events.
+
+        If the new page has an Activate method.  Call it.
+        """
+        meth = getattr(event.GetPage(), "Activate", None)
+        if meth is not None:
+            meth()
+
+    def OnPageChanging(self, event):
+        """Handler for the wizard's PAGE_CHANGING event.
+
+        If the old page is the catchment_page
+        and direction is forward (next), save the catchment and
+        check the values of the config by calling check_config.
+        If the upload is not successful, cancel the event so
+        that page is not changed.
+        """
+        if (event.GetPage() is self.catchment_page
+            and event.GetDirection() == True):
+            desc_file = write_desc(self.catchment_page)
+            try:
+                catchment_desc(desc_file)
+                do_check(self.catchment_page.catchment_dir)
+            except:
+                catchment_error = str(sys.exc_info()[1])
+                wx.wxMessageBox(catchment_error, "Error!", wx.wxICON_ERROR|wx.wxOK)
+                event.Veto()
+        elif (event.GetPage() is self.convert_page
+            and event.GetDirection() == True):
+            if not self.DoProcess():
+                event.Veto()
+            else:
+                wx.wxMessageBox("The catchment was successfully processed.\n"
+                                "You can upload it now by using GREAT-ER Upload.",
+                                "Finished.", wx.wxOK | wx.wxICON_INFORMATION)
+
+    def DoProcess(self):
+        """Do the preprocessing."""
+        dialog = wx.wxProgressDialog("Preprocessing Catchment",
+                                     "Preprocessing Catchment",
+                                     100,
+                                     self.wizard,
+                                     wx.wxPD_CAN_ABORT
+                                     | wx.wxPD_AUTO_HIDE
+                                     | wx.wxPD_ELAPSED_TIME
+                                     | wx.wxPD_ESTIMATED_TIME
+                                     | wx.wxPD_REMAINING_TIME)
+        try:
+            try:
+                oldcwd = os.getcwd()
+                os.chdir(self.catchment_page.catchment_dir)
+                for progress in do_run():
+                    if not dialog.Update(progress):
+                        os.chdir(oldcwd)
+                        return False
+                write_upload_desc(self.catchment_page)
+                return True
+            except:
+                wx.wxMessageBox("An error occurred:\n%s"
+                                % str(sys.exc_info()[1]),
+                                "Error prerocessing Catchment.")
+        finally:
+            os.chdir(oldcwd)
+            dialog.Destroy()
+
+
+
+    def RunWizard(self):
+        """Run the wizard.
+
+        The return value is the return value of the wizard's RunWizard
+        method.
+        """
+        return self.wizard.RunWizard(self.intro_page)
+
+def write_upload_desc(catchment_page):
+    """ Tages a CatchmentPage and writes the description for
+        uploading into the catchments.desc
+    """
+    pass
+
+def write_desc(catchment_page):
+    """ Tages a CatchmentPage and writes the description into the
+        catchment.desc
+
+        Returns the Filename of the description file as absolute path
+    """
+    cdir = catchment_page.catchment_dir
+    cfile = os.path.join(cdir, "catchment.desc")
+    with open(cfile, "w") as fptr:
+        fptr.write("ID=%s\n" % catchment_page.text_ID.GetValue())
+        fptr.write("NAME=%s\n" % catchment_page.text_NAME.GetValue())
+        fptr.write("DESCRIPTION=%s\n" % catchment_page.text_DESCRIPTION.GetValue())
+        fptr.write("IN-VERSION=%s\n" % "1.0")
+        fptr.write("OUT-VERSION=%s\n" % "2.0")
+    return cfile
+
+
+#    def DoUpload(self):
+#        """Do the upload."""
+#        dialog = wx.wxProgressDialog("Uploading Catchment",
+#                                     "Uploading Catchment",
+#                                     100,
+#                                     self.wizard,
+#                                     wx.wxPD_CAN_ABORT
+#                                     | wx.wxPD_AUTO_HIDE
+#                                     | wx.wxPD_ELAPSED_TIME
+#                                     | wx.wxPD_ESTIMATED_TIME
+#                                     | wx.wxPD_REMAINING_TIME)
+#        try:
+#            try:
+#                for progress in do_upload(self.db_page.GetDBInfo(),
+#                                          db=self.db_page.GetDBType()):
+#                    if not dialog.Update(progress):
+#                        return False
+#                return True
+#            except:
+#                raise
+#                wx.wxMessageBox("An error occurred:\n%s"
+#                                % str(sys.exc_info()[1]),
+#                                "Error Uploading Catchment")
+#        finally:
+#            dialog.Destroy()
+
+
+if __name__ == '__main__':
+    # Run the wizard.  If the wizard is cancelled, exit with status 1.
+
+    app = PreProcessingApp(0)
+    success = app.RunWizard()
+    if not success:
+        sys.exit(1)
+
+# Old console version main
+#if __name__ == '__main__':
+#    import sys
+#
+#    print version_str
+#    print
+#
+#    if catchment_desc():
+#        print '\nusage:', usage_str
+#        sys.exit(1)
+#
+#    print
+#
+#    if os.environ.has_key('GREATER_PRE_PROC') == 0:
+#        greater_pre_proc_path = os.path.abspath(os.path.dirname(sys.argv[0]))
+#        if not os.path.exists(os.path.join(
+#                                    greater_pre_proc_path,'awk','joinup.awk')):
+#            print 'Error: environment variable GREATER_PRE_PROC not set'
+#            sys.exit(2)
+#    else:
+#        greater_pre_proc_path = os.environ['GREATER_PRE_PROC']
+#    
+#
+#    if len(sys.argv) == 2:
+#        if sys.argv[1] == 'check':
+#            do_check()
+#        if sys.argv[1] == 'run':
+#            do_run()
+#        if sys.argv[1] == 'run-without-cleanup':
+#            do_run()
+#        if sys.argv[1] == 'clean':
+#            do_clean()
+#        if sys.argv[1] == 'help':
+#            usage()
+#    else:
+#        print 'usage:', usage_str

Modified: branches/3.0.0-all-models/greater-pre-processing/upload-catchment.py
===================================================================
--- branches/3.0.0-all-models/greater-pre-processing/upload-catchment.py	2011-08-17 09:46:24 UTC (rev 3766)
+++ branches/3.0.0-all-models/greater-pre-processing/upload-catchment.py	2011-08-17 17:35:31 UTC (rev 3767)
@@ -35,7 +35,6 @@
      EVT_WIZARD_PAGE_CHANGED
 
 import GreaterDB.interface
-import greater_pre_processing
 
 catchment = {}
 catch_id = -1
@@ -74,16 +73,6 @@
     else:
         return 0.0
 
-def check_preprocessing(catchment_dir):
-    return True
-
-def do_preprocessing(catchment_file):
-    """
-    Preprocesses a catchment, returns true on success otherwise the output
-    of the pre processing script.
-    """
-    greater_pre_processing.do_run()
-
 def read_catchment_desc(verbose=True):
     """Look for catchment_desc and read it
 
@@ -579,7 +568,6 @@
                         return False
                 return True
             except:
-                raise
                 wx.wxMessageBox("An error occurred:\n%s"
                                 % str(sys.exc_info()[1]),
                                 "Error Uploading Catchment")



More information about the Greater-commits mailing list