def createBinarios_single(ListMapBins):
  readtxt=selecdirectori()
  grass.run_command('g.region',rast=ListMapBins)
  grass.run_command('g.region',rast=ListMapBins)
  grass.run_command('r.reclass',input=ListMapBins,output=ListMapBins+'_bin',rules=readtxt, overwrite = True)
  Form1.speciesList=grass.mlist_grouped ('rast', pattern='(*)') ['PERMANENT']
  return readtxt
def createBinarios_single(ListMapBins):
  readtxt=selecdirectori()
  grass.run_command('g.region',rast=ListMapBins)
  grass.run_command('g.region',rast=ListMapBins)
  grass.run_command('r.reclass',input=ListMapBins,output=ListMapBins+'_bin',rules=readtxt, overwrite = True)
  Form1.speciesList=grass.mlist_grouped ('rast', pattern='(*)') ['PERMANENT']
  return readtxt
    def EvtCheckBox(self, event):
        #self.logger.AppendText('EvtCheckBox: %d\n' % event.Checked())
        if event.GetId()==95:
            if event.Checked()==1:
                Form1.Frag=True
                self.logger.AppendText('EvtCheckBox:\nSelected Metric: Frag \n')
                
                
            else:
                Form1.Frag=False
                self.logger.AppendText('EvtCheckBox: \nNot Selected Metric: Frag \n')
                

        if event.GetId()==96:
          if event.Checked()==1:
            Form1.Path=True
          else:
            Form1.Path=False
                   
            
        if event.GetId()==97:
          if event.Checked()==1:
            Form1.Cone=True
          else:
            Form1.Cone=False
                         
        
        
        if event.GetId()==98: #Form1.plotmovements
          if int(event.Checked())==1: 
            Form1.plotmovements=1
            Form1.listMapsPngAux=grass.mlist_grouped ('rast', pattern=Form1.RedularExp) ['PERMANENT']
            Form1.listMapsPng=exportPNG(Form1.listMapsPngAux)
            self.Refresh()             

          else:
            Form1.plotmovements=0
            self.logger.AppendText('   Plot momevements: %s\n' % str(Form1.plotmovements))             
            
            
        if event.GetId()==99:
          if int(event.Checked())==1:
            Form1.chebin=True
            
        if event.GetId()==150: #check EDGE
          if int(event.Checked())==1:
            Form1.checEDGE=True
          else:
            Form1.checEDGE=False
    def EvtCheckBox(self, event):
        #self.logger.AppendText('EvtCheckBox: %d\n' % event.Checked())
        if event.GetId()==95:
            if event.Checked()==1:
                Form1.Frag=True
                self.logger.AppendText('EvtCheckBox:\nSelected Metric: Frag \n')
                
                
            else:
                Form1.Frag=False
                self.logger.AppendText('EvtCheckBox: \nNot Selected Metric: Frag \n')
                

        if event.GetId()==96:
          if event.Checked()==1:
            Form1.Path=True
          else:
            Form1.Path=False
                   
            
        if event.GetId()==97:
          if event.Checked()==1:
            Form1.Cone=True
          else:
            Form1.Cone=False
                         
        
        
        if event.GetId()==98: #Form1.plotmovements
          if int(event.Checked())==1: 
            Form1.plotmovements=1
            Form1.listMapsPngAux=grass.mlist_grouped ('rast', pattern=Form1.RedularExp) ['PERMANENT']
            Form1.listMapsPng=exportPNG(Form1.listMapsPngAux)
            self.Refresh()             

          else:
            Form1.plotmovements=0
            self.logger.AppendText('   Plot momevements: %s\n' % str(Form1.plotmovements))             
            
            
        if event.GetId()==99:
          if int(event.Checked())==1:
            Form1.chebin=True
            
        if event.GetId()==150: #check EDGE
          if int(event.Checked())==1:
            Form1.checEDGE=True
          else:
            Form1.checEDGE=False
    def OnClick(self,event):
        #self.logger.AppendText(" Runing simulation %d\n" )#%event.GetId())
        
        
        if event.GetId()==240: #Run import
          grass.run_command ('r.in.gdal', flags='o' ,input=Form1.InArqCost,output=Form1.OutArqCost,overwrite=True, verbose = False)
          grass.run_command ('r.in.gdal', flags='o' ,input=Form1.InArqST,output= Form1.OutArqST,overwrite=True, verbose = False)
          grass.run_command('g.region', rast=Form1.OutArqCost,verbose=False)
          self.logger.AppendText('importing rasters... \n')
       
        if event.GetId()==260: #comnine list
          self.logger.AppendText('generating combinations... \n')
          Form1.patch_id_list_aux=combine_st(patchid_list=Form1.OutArqST)
          Form1.patch_id_list_aux_b=Form1.patch_id_list_aux.split(',')
          Form1.lenlist=len(Form1.patch_id_list_aux_b)
          Form1.lenlist_b=Form1.lenlist/2
          #print Form1.lenlist
          
        
          self.logger.AppendText('waiting ... \n')
          d= wx.MessageDialog( self, `Form1.lenlist_b`+" Combitarions simulate ? \n","", wx.YES_NO)
                            # Create a message dialog box
          retCode=d.ShowModal() # Shows 
           # finally destroy it when finished.
          d.Close(True)  # Close the frame. 

          if (retCode == wx.ID_YES):
            Form1.patch_id_list=Form1.patch_id_list_aux.split(',')
            self.logger.AppendText('\n created list \n')
            #print Form1.patch_id_list
            
              
          else:
              print ""
              self.logger.AppendText('not accepted \n')
          d.Destroy()

        
         
        
          
        #if event.GetId()==200:   #200==Select directori
        #  Form1.OutDir_files=selecdirectori()
        #  print Form1.OutDir_files
          
          
        if event.GetId()==205:   #200==Select directori
          self.logger.AppendText('Please select the directory... \n')
        
          p=grass.mlist_grouped ('rast', pattern='*MSP*') ['PERMANENT']
          j=len(p)
          #print j
          self.logger.AppendText('Foud: '+`j`)
          d= wx.MessageDialog( self, `j`+" Files \n Export files?  \n"
                               ,"", wx.YES_NO)
          # Create a message dialog box
          retCode=d.ShowModal() # Shows 
          # finally destroy it when finished.
          d.Close(True)  # Close the frame. 
          
          if (retCode == wx.ID_YES):
            Form1.OutDir_files=selecdirectori()
            os.chdir(Form1.OutDir_files)
            for i in p:
              grass.run_command('g.region', rast=i,verbose=False)
              grass.run_command('r.out.gdal',input=i, out=i+'.tif',format='GTiff',nodata=-9999)
              #print i
              self.logger.AppendText('Exporting:\n '+i +"\n" )
            else:
              #print "no"
              self.logger.AppendText('Export canceled \n' )
              d.Destroy()   
                    
                    

                                                
                    
        if event.GetId()==210:   #210==Select files st
          self.logger.AppendText("Waiting ... :\n")
          Form1.InArqST=selecdirectori()
          Form1.OutArqST=Form1.InArqST.split('\\');Form1.OutArqST=Form1.OutArqST[-1].replace('.','_')
          print   Form1.OutArqST
          self.logger.AppendText('Selected File: \n '+Form1.OutArqST)
         
          
                  
        if event.GetId()==230:   #230==Select files cost
          self.logger.AppendText("Waiting ... :\n")
          Form1.InArqCost=selecdirectori()
          print Form1.InArqCost 
          Form1.OutArqCost=Form1.InArqCost.split('\\');Form1.OutArqCost=Form1.OutArqCost[-1].replace('.','_')
          print Form1.OutArqCost
          self.logger.AppendText('Selected File: \n'+Form1.OutArqCost)
          Form1.OutArqCost
          Form1.NEXPER_FINAL=Form1.OutArqCost+'_'+Form1.NEXPER_AUX
          
        if event.GetId()==250:
          self.logger.AppendText("Waiting ... :\n")
          Form1.readtxt=selecdirectori()
          Form1.fileHandle = open (Form1.readtxt, 'r' )
          Form1.patch_id_list=Form1.fileHandle.read() 
          Form1.patch_id_list_aux_b=Form1.patch_id_list.split(',')
          print Form1.patch_id_list_aux_b
          self.logger.AppendText("TXT Combinations \n"+`Form1.patch_id_list_aux_b`)
          
      

        if event.GetId()==10:   #10==START
          
         
          
          self.logger.AppendText("Checking the list \n")
          Form1.lenlist=len(Form1.patch_id_list_aux_b)
         
          
          if  Form1.lenlist <= 1: 
            d= wx.MessageDialog( self, " Incorrect list \n"
                                             ,"", wx.OK)
            # Create a message dialog box
            d.ShowModal() # Shows it
            d.Destroy() # finally destroy it when finished.
            #frame.Close(True)  # Close the frame. 
            self.logger.AppendText(" Check list.. \n")
            
          elif Form1.lenlist > 1 and int (Form1.lenlist)%2 ==1 :
            
            d= wx.MessageDialog( self, "incorrect list \n Numbers odd patch, check the list \n  "
                                 ,"", wx.OK)
            # Create a message dialog box
            d.ShowModal() # Shows it
            d.Destroy() # finally destroy it when finished.
              #frame.Close(True)  # Close the frame. 
          else:
            Form1.patch_id_list=Form1.patch_id_list_aux.split(',')
            self.logger.AppendText(" ok list \n")
            self.logger.AppendText(" waiting... \n")
            
           
            
           
            d= wx.MessageDialog( self, " Select the output folder for'\n' text files \n"
                               ,"", wx.OK)
            # Create a message dialog box
            d.ShowModal() # Shows it
            d.Destroy() # finally destroy it when finished.
            Form1.OutDir_files_TXT=selecdirectori()
            self.logger.AppendText(" Selected output folder: \n"+Form1.OutDir_files_TXT)
            
          
            self.logger.AppendText(" running...: \n")
          self.logger.AppendText("\n creating list: \n"+`Form1.patch_id_list_aux_b`+'\n')   
          Form1.S1=""
          Form1.T1=""
          Form1.C2=Form1.C2+''
          Form1.C3=Form1.C3+''
          Form1.C4=Form1.C4+''
          
          
          
          Form1.res=grass.read_command('g.region',flags='m')
          Form1.res2=Form1.res.split('\n')
          Form1.res3=Form1.res2[5]
          Form1.res3=float(Form1.res3.replace('ewres=',''))
          Form1.escfina1=(Form1.esc*2)/Form1.res3
          
          if Form1.escfina1%2==0:
            Form1.escfina1=int(Form1.escfina1)
            Form1.escfina1=Form1.escfina1+1
          else:
            Form1.escfina1=int(round(Form1.escfina1, ndigits=0))
              
          
          grass.run_command('g.region', rast=Form1.OutArqCost, res=Form1.res3)
          grass.run_command('r.neighbors',input=Form1.OutArqCost,out=Form1.C2, method='mode',size=Form1.escfina1,overwrite = True)
          grass.run_command('r.neighbors',input=Form1.OutArqCost,out=Form1.C3, method='average',size=Form1.escfina1,overwrite = True)
          grass.run_command('r.neighbors',input=Form1.OutArqCost,out=Form1.C4, method='maximum',size=Form1.escfina1,overwrite = True)
          
          
          Form1.escfinal=0
          Form1.escapoio1=grass.read_command('g.region',flags='m')
          Form1.escapoio2=Form1.escapoio1.split("\n")
          Form1.escE=Form1.escapoio2[3]
          Form1.escW=Form1.escapoio2[2]
          Form1.escE=float(Form1.escE.replace("e=",''))
          Form1.escW=float(Form1.escW.replace("w=",''))
          Form1.escfinal=(Form1.escE-Form1.escW)/30          
          
          
          
          grass.run_command('g.region', rast=Form1.OutArqCost, res=Form1.escfinal)
          grass.run_command('r.neighbors', input=Form1.OutArqCost,out='apoio1',method='average', size=3,overwrite = True)    
          Form1.form_11='apoio2=apoio1*1.0'
#         print Form1.form_11          
          grass.mapcalc(Form1.form_11, overwrite = True, quiet = True)
          Form1.form_12='apoio2b=0.1+(((apoio2-298.3)/246.4)^2)^0.5'
          grass.mapcalc(Form1.form_12, overwrite = True, quiet = True)
          grass.run_command('g.region', rast=Form1.OutArqCost)
          
          Form1.form_13="apoio2c=apoio2b*"+`Form1.ruido_float`
          grass.mapcalc(Form1.form_13, overwrite = True, quiet = True)
          Form1.form_13="apoio2d="+Form1.OutArqCost+"-apoio2c"
          grass.mapcalc(Form1.form_13, overwrite = True, quiet = True)
          Form1.form_13="M5_AVERAGE_VIEW=((apoio2d)^2)^0.5"
          
          
                
          
          #print Form1.form_13
          grass.mapcalc(Form1.form_13, overwrite = True, quiet = True)
          
          
         
          Form1.listafinal=[]
          
          for i in range(Form1.Nsimulations1):
            Form1.listafinal.append(Form1.OutArqCost)
            Form1.listaApoioaleat3.append('')
          for i in range(Form1.Nsimulations2):
            Form1.listafinal.append(Form1.C2)
            Form1.listaApoioaleat3.append('')
          for i in range(Form1.Nsimulations3):
            Form1.listafinal.append(Form1.C3)
            Form1.listaApoioaleat3.append('')
          for i in range(Form1.Nsimulations4):
            Form1.listafinal.append(Form1.C4)  
            Form1.listaApoioaleat3.append('')
          
            
            
          
            
            
          
          grass.run_command('g.region', rast=Form1.OutArqCost, res=Form1.res3)
          Form1.Nsimulations=Form1.Nsimulations1+Form1.Nsimulations2+Form1.Nsimulations3+Form1.Nsimulations4
          #patch_id_list          
          while (len(Form1.patch_id_list)>1):
            Form1.S1=Form1.patch_id_list[0]
            Form1.T1=Form1.patch_id_list[1]
            Form1.S1FORMAT='000000'+Form1.S1
            Form1.S1FORMAT=Form1.S1FORMAT[-5:]
            Form1.T1FORMAT='000000'+Form1.T1
            Form1.T1FORMAT=Form1.T1FORMAT[-5:]
            #print Form1.S1FORMAT, Form1.T1FORMAT
            #print Form1.S1 , Form1.T1 
            del Form1.patch_id_list[0:2]
            
            Form1.PAISGEM='EXPERIMENTO'
            Form1.ARQSAIDA=Form1.PAISGEM+'_s'+Form1.S1FORMAT+'_t'+Form1.T1FORMAT
              
            self.logger.AppendText(" suing pair: \n"+Form1.S1FORMAT+'&'+Form1.T1FORMAT+ '\n')  
            Form1.S1=(int(str(Form1.S1)))
            Form1.T1=(int(str(Form1.T1)))
            Form1.form_02='source=if('+Form1.OutArqST+'!='+`Form1.S1`+',null(),'+`Form1.S1`+ ')'
            Form1.form_03='target=if('+Form1.OutArqST+'!='+`Form1.T1`+',null(),'+`Form1.T1`+ ')'
            #print Form1.form_02
            os.chdir(Form1.OutDir_files_TXT)
            grass.mapcalc(Form1.form_02, overwrite = True, quiet = True)
            grass.mapcalc(Form1.form_03, overwrite = True, quiet = True)
            
            #grass.run_command('g.mremove',vect='*', flags='f')
            grass.run_command('g.region', rast=Form1.OutArqST,verbose=False)
            
            grass.run_command('r.to.vect', input='source', out='source_shp', feature='area',verbose=False, overwrite = True ) 
            grass.run_command('r.to.vect', input='target', out='target_shp', feature='area',verbose=False, overwrite = True ) 
            grass.run_command ('v.db.addcol', map='source_shp', columns='x double precision,y double precision', overwrite = True)
            grass.run_command ('v.db.addcol', map='target_shp', columns='x double precision,y double precision', overwrite = True)
            
            grass.read_command ('v.to.db', map='source_shp', option='coor', columns="x,y", overwrite = True)
            grass.read_command ('v.to.db', map='target_shp', option='coor', columns="x,y", overwrite = True)
            
            Form1.a='' 
            Form1.a=grass.read_command('v.db.select', map='source_shp', flags='c',overwrite = True);
            Form1.var_source_x= Form1.a.split('|');
            Form1.var_source_x_b=str( Form1.var_source_x[3]); 
            Form1.var_source_x_b=Form1.var_source_x_b.replace('\n','')
            
            Form1.b=''
            Form1.b=grass.read_command('v.db.select', map='source_shp', flags='c',overwrite = True);
            Form1.var_source_y= Form1.b.split('|');
            Form1.var_source_y_b=str(Form1.var_source_y[4]);
            Form1.var_source_y_b=Form1.var_source_y_b.replace('\n','')
           
            Form1.c=''
            Form1.c=grass.read_command('v.db.select', map='target_shp', flags='c',overwrite = True)
            Form1.var_target_x= Form1.c.split('|')
            Form1.var_target_x_b=str(Form1.var_target_x[3])
            Form1.var_target_x_b=Form1.var_target_x_b.replace('\n','')
           
            Form1.d=''
            Form1.d=grass.read_command('v.db.select', map='target_shp', flags='c',overwrite = True)
            Form1.var_target_y= Form1.d.split('|')
            Form1.var_target_y_b=str( Form1.var_target_y[4])
            
            #print Form1.d
            #print Form1.var_target_y
            #print Form1.var_target_y_b
            Form1.var_target_y_b=Form1.var_target_y_b.replace('\n','')
            
            grass.run_command('g.region', rast=Form1.OutArqCost,verbose=False)
            
            
           
            Form1.mapa_corredores="corredores_s"+Form1.S1FORMAT+"_t"+Form1.T1FORMAT+'_COM0'
            Form1.mapa_corredores_sem0=Form1.NEXPER_FINAL+'_'+'S_'+Form1.S1FORMAT+"_T_"+Form1.T1FORMAT
            Form1.chekfolder=os.path.exists('Line_'+Form1.mapa_corredores_sem0)
            
            if Form1.chekfolder==False:
              os.mkdir('Line_'+Form1.mapa_corredores_sem0)
              Form1.outdir=Form1.OutDir_files_TXT+'\Line_'+Form1.mapa_corredores_sem0
            else:
              d= wx.MessageDialog( self, " Existing folder please select another location to save the lines \n"
                                   ,"", wx.OK)
              # Create a message dialog box
              d.ShowModal() # Shows it
              d.Destroy()              
              Form1.outdir=selecdirectori()            
            Form1.form_04='mapa_corredores=0'
            grass.mapcalc(Form1.form_04, overwrite = True, quiet = True)
            Form1.form_16='corredores_aux=0'
            grass.mapcalc(Form1.form_16, overwrite = True, quiet = True)
                            
            
              
              
              
            Form1.arquivo = open(Form1.mapa_corredores_sem0+'.txt','w')
            Form1.cabecalho='EXPERIMENT'','+'M'+','+'SIMULATION'+','+'LENGTHVECT'+','+'COST'+','+'Coord_source_x'+','+'Coord_source_y'+','+'Coord_target_x'+','+'Coord_target_y'+','+'Euclidean_Distance' '\n'
            Form1.arquivo.write(Form1.cabecalho)
            
            cont=0
            for i in range(Form1.Nsimulations):
              Form1.form_08='mapa_custo='+Form1.listafinal[cont]
              grass.mapcalc(Form1.form_08, overwrite = True, quiet = True)              
                       
              c=i+1
              
              
              #y=x/2
              print "------------------------------------------------------------------"
              print "=====> rodando : ",`c` 
              self.logger.AppendText('=======> runing :'+`c`+ '\n' )
              grass.run_command('r.mask',input='source')
              grass.run_command('g.region', vect='source_shp',verbose=False,overwrite = True)
              grass.run_command('v.random', output='temp_point1_s',n=30,overwrite = True)
              grass.run_command('v.select',ainput='temp_point1_s',binput='source_shp',output='temp_point2_s',operator='overlap',overwrite = True)
              grass.run_command('v.db.addtable', map='temp_point2_s',columns="temp double precision")
              grass.run_command('v.db.connect',flags='p',map='temp_point2_s')
              Form1.frag=grass.read_command('v.db.select',map='temp_point2_s',column='cat')
              Form1.frag_list=Form1.frag.split('\n')
              Form1.frag_list2=int(Form1.frag_list[1])              
              Form1.selct="cat="+`Form1.frag_list2`
              grass.run_command('v.extract',input='temp_point2_s',output='pnts_aleat_S',where=Form1.selct,overwrite = True)
              grass.run_command('r.mask',flags='r')
              
              
              grass.run_command('r.mask',input='target')
              grass.run_command('g.region', vect='target_shp',verbose=False,overwrite = True)
              
              grass.run_command('v.random', output='temp_point1_t',n=30,overwrite = True)
              grass.run_command('v.select',ainput='temp_point1_t',binput='target_shp',output='temp_point2_t',operator='overlap',overwrite = True)
              grass.run_command('v.db.addtable', map='temp_point2_t',columns="temp double precision")
              grass.run_command('v.db.connect',flags='p',map='temp_point2_t')
            
              Form1.frag=grass.read_command('v.db.select',map='temp_point2_t',column='cat')
              Form1.frag_list=Form1.frag.split('\n')
              Form1.frag_list2=int(Form1.frag_list[1])              
              Form1.selct="cat="+`Form1.frag_list2`
              grass.run_command('v.extract',input='temp_point2_t',output='pnts_aleat_T',where=Form1.selct,overwrite = True)            
            
            
              
              grass.run_command('r.mask',flags='r')
                
              grass.run_command('g.region', rast=Form1.OutArqCost,verbose=False)
              Form1.form_05='corredores_aux=mapa_corredores'
                
              grass.mapcalc(Form1.form_05, overwrite = True, quiet = True)
              if Form1.listaApoioaleat3[i]=='M6_Unikon' :
                
               
                grass.run_command('r.random.surface', out='aleat', high=100,overwrite = True)
                Form1.form_06='aleat2=1+((aleat/100.0)*'+`Form1.ruido_float`+')'
                grass.mapcalc(Form1.form_06, overwrite = True, quiet = True)
                Form1.form_07='custo_aux=mapa_custo*aleat2'  
                grass.run_command('g.region', rast='source,target',res=Form1.escfinal,verbose=False)
                grass.run_command('r.random.surface', out='aleat_Gros', high=100,overwrite = True)
                Form1.form_15='aleat2_Gros=1+((aleat_Gros/100.0)*'+`Form1.ruido_float`+')'
                grass.mapcalc(Form1.form_15, overwrite = True, quiet = True)
                grass.run_command('g.region', rast='source,target',verbose=False)
                
                Form1.form_16='custo_aux=mapa_custo*aleat2*aleat2_Gros'  
                grass.mapcalc(Form1.form_16, overwrite = True, quiet = True) 
                Form1.form_18='M6=mapa_custo*aleat2*aleat2_Gros'  
                grass.mapcalc(Form1.form_18, overwrite = True, quiet = True)                   
                
              else :  

                  grass.run_command('r.random.surface', out='aleat', high=100,overwrite = True)
                  Form1.form_06='aleat2=1+((aleat/100.0)*'+`Form1.ruido_float`+')'
                  grass.mapcalc(Form1.form_06, overwrite = True, quiet = True)
                  Form1.form_07='custo_aux=mapa_custo*aleat2'
                  grass.mapcalc(Form1.form_07, overwrite = True, quiet = True)    
              
              
              
             
                
              grass.run_command('g.region', rast=Form1.OutArqCost,verbose=False) 
              grass.run_command('r.cost', flags='k', input='custo_aux', out='custo_aux_cost', start_points='pnts_aleat_S', stop_points='pnts_aleat_T',overwrite = True)
              grass.run_command('r.drain', input='custo_aux_cost', out='custo_aux_cost_drain', vector_points='pnts_aleat_T', overwrite = True)
              grass.run_command('r.series',input='corredores_aux,custo_aux_cost_drain', output='mapa_corredores', method='sum',overwrite = True)
              Form1.form_09='custo_aux_cost_drain_sum=custo_aux_cost_drain*'+Form1.listafinal[0]
              
              grass.mapcalc(Form1.form_09, overwrite = True, quiet = True)  
             
              
              #calculando custo
              Form1.x=grass.read_command('r.univar', map='custo_aux_cost_drain_sum')
              #print Form1.x
              Form1.x_b=Form1.x.split('\n')
              #Form1.x_b=Form1.x.repleace('\n',',')
              #print Form1.x_b
              Form1.x_c=str(Form1.x_b[14])
              Form1.var_cost_sum=Form1.x_c[5:8]
              
                           
              
              
              
              #print 
              grass.run_command('g.region', rast=Form1.OutArqCost,verbose=False)
              Form1.form_10=Form1.mapa_corredores_sem0+'=if(mapa_corredores==0,null(),mapa_corredores)' 
              
              
                  
                  
                  
              grass.mapcalc(Form1.form_10, overwrite = True, quiet = True)
             #calculando a distancia
              Form1.length=grass.read_command('r.univar', map='custo_aux_cost_drain')
              #print Form1.x
              Form1.length_b=Form1.length.split('\n')
              Form1.length_c=str(Form1.length_b[14])
              Form1.length_d=Form1.length_c[5:9]
              Form1.length_e=float(Form1.length_d)
              Form1.var_dist_line=Form1.res3*Form1.length_e
              
              Form1.var_source_x_b_int=float(Form1.var_source_x_b)
              Form1.var_source_y_b_int=float(Form1.var_source_y_b)
              Form1.var_target_x_b_int=float(Form1.var_target_x_b)
              Form1.var_target_y_b_int=float(Form1.var_target_y_b)
             
              
              Form1.euclidean_a =float((Form1.var_source_x_b_int-Form1.var_target_x_b_int)**2 + (Form1.var_source_y_b_int-Form1.var_target_y_b_int)**2)
              Form1.euclidean_b= Form1.euclidean_a**0.5
              if Form1.listafinal[cont]==Form1.OutArqCost:
                Form1.M="M1"
              if Form1.listafinal[cont]=='M2_MODE':
                Form1.M="M2"
              if Form1.listafinal[cont]=='M3_MAXIMUM':
                Form1.M="M3"              
              if Form1.listafinal[cont]=='M4_AVERAGE':
                Form1.M="M4"              
              if Form1.listafinal[cont]=='M5_AVERAGE_VIEW':
                Form1.M="M5"                
              if Form1.listafinal[cont]=='M6_Unikon':
                Form1.M="M6"                
                   
                              
              
              
              
              
              
              Form1.linha=Form1.listafinal[cont].replace("@PERMANENT",'')+','+Form1.M+','+`c`+','+ `Form1.var_dist_line`+','+ `Form1.var_cost_sum`+','+ `Form1.var_source_x_b`+','+ `Form1.var_source_y_b`+','+ `Form1.var_target_x_b`+','+ `Form1.var_target_y_b`+','+ `Form1.euclidean_b`+ "\n"
              Form1.linha=Form1.linha.replace('\'','')
              #PAISGEM+var_dist_line ` `+var_cost_sum+` `+var_source_x+` `+var_source_y+` `+var_target_x+` ` var_target_y`
              Form1.var_dist_line=0.0
              Form1.var_cost_sum=0.0
              #linha=$ARQSAIDA$" simulacao="$i$" lengthvect="$var_dist_line$"  somarast="$var_cost_sum$" source_x="$var_source_x$" source_y="$var_source_y$" target_x="$var_target_x$" target_y="$var_target_y   
              
              #print Form1.linha
              Form1.arquivo.write(Form1.linha)
              Form1.linha=""
              print "MAP>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+Form1.listafinal[cont]
              #declarar isso 
              Form1.outline1='000000'+`c`
              #Form1.outline='000000'+`i`
              Form1.outline1=Form1.outline1[-3:]
              Form1.outline1=Form1.mapa_corredores_sem0+"_"+Form1.M+"_"+"_SM_"+Form1.outline1
              
              grass.run_command('r.to.vect', input='custo_aux_cost_drain', out=Form1.outline1, feature='line',verbose=False, overwrite = True )
              grass.run_command ('v.db.addcol', map=Form1.outline1, columns='dist double precision', overwrite = True)
              grass.read_command ('v.to.db', map=Form1.outline1, option='length', type='line', col='dist', units='me', overwrite = True)
              os.chdir(Form1.outdir)
              grass.run_command('v.out.ogr', input=Form1.outline1,dsn=Form1.outline1+'.shp',verbose=False,type='line')              
              grass.run_command('g.remove',vect=Form1.outline1, flags='f')              
              cont=cont+1
              
              
             
            Form1.listExport.append(Form1.mapa_corredores_sem0)  
            self.logger.AppendText(" removing auxiliary files...: \n")  
            grass.run_command('g.remove',vect='temp_point1_s,temp_point2_s,temp_point1_t,temp_point2_t,pnts_aleat_S,pnts_aleat_T,source_shp,target_shp,custo_aux_cost_drain_sem0_line', flags='f')
            grass.run_command('g.remove',rast='mapa_custo,mapa_corredores,custo_aux_cost_drain,source,target,custo_aux_cost_drain_sum,custo_aux_cost_drain_sem0,custo_aux_cost,custo_aux,corredores_aux,aleat,aleat2,aleat2_Gros,aleat3,aleat_Gros,apoio1', flags='f')
            grass.run_command('g.remove',rast='apoio2,apoio2b,apoio2c,apoio2d', flags='f')
            Form1.arquivo.close()
            grass.run_command('g.region', rast=Form1.OutArqCost,verbose=False)
            
            p=grass.mlist_grouped ('rast', pattern='*MSP*') ['PERMANENT']
          if len(Form1.listExport) > 1 :
            
            grass.run_command('r.series',input=Form1.listExport,out=Form1.OutArqCost+'RSeries',method="maximum")
            grass.run_command('g.region', rast=Form1.OutArqCost+'RSeries',verbose=False)
            grass.run_command('r.neighbors',input=Form1.OutArqCost+'RSeries',out=Form1.NEXPER_FINAL+"MW", method='average',size=Form1.escfina1,overwrite = True)
          else:
           
            grass.run_command('g.region', rast=Form1.OutArqCost,verbose=False)
            grass.run_command('r.neighbors',input=Form1.listExport[0],out=Form1.NEXPER_FINAL+"MW", method='average',size=Form1.escfina1,overwrite = True)
          
          
          j=len(Form1.listExport)
          #print j
          self.logger.AppendText(" waiting ...: \n")  
          d= wx.MessageDialog( self, `j`+" Files \n successful! \n want to export the files??  \n"
                               ,"", wx.YES_NO)
          # Create a message dialog box
          retCode=d.ShowModal() # Shows 
          # finally destroy it when finished.
          d.Close(True)  # Close the frame. 
            
          if (retCode == wx.ID_YES):
            Form1.OutDir_files=selecdirectori()
            os.chdir(Form1.OutDir_files)
            self.logger.AppendText(" exporting all files ... \n") 
            for i in Form1.listExport:
              grass.run_command('r.out.gdal',input=i, out=i+'.tif',format='GTiff',nodata=-9999)
              #print i
              
                
          else:
            #print "no"
            self.logger.AppendText(" finalized \n") 
            d.Destroy()
import grass.script as grass
from grass.script import raster as grassR
import os
import string
import glob
import re
import fnmatch


lista_classificada=grass.mlist_grouped ('rast', pattern='*classificada*') ['PERMANENT']

for i in lista_classificada:
    print i
    #grass.run_command('g.region' ,rast=i)
    #expressao2=i+"_binMata=if("+i+"==11 || "+i+"==12 || "+i+"==13,1,0)"
    #grass.mapcalc(expressao2, overwrite = True, quiet = True)    
import grass.script as grass
from grass.script import raster as grassR
import os
import string
import glob
import re
import fnmatch

lista_classificada_FRAG120m_mata_clump_AreaHA=grass.mlist_grouped ('rast', pattern='**') ['PERMANENT']
for i in lista_classificada_FRAG120m_mata_clump_AreaHA:
    
        #print i
        grass.run_command('g.remove',flags='f',rast=i)
    
        else:
                path = shell.SHGetPathFromIDList (pidl)
                #print "Opening", #path
                a=(path)
      
                return a
   



dir1=selecdirectori()
dirsRaiz1=os.listdir(dir1)#primeira raizprint dirs
os.chdir(dir1)

#sempre iniciar o indice
list_rast_resist=grass.mlist_grouped ('rast', pattern='*resist*') ['PERMANENT']
for i in range(len(dirsRaiz1)):
        os.chdir(dir1+'\\'+dirsRaiz1[i])
        dirsRaiz2=os.listdir(dir1+'\\'+dirsRaiz1[i])
        o=0
        for o in range(len(dirsRaiz2)):
                os.chdir(dir1+"\\"+dirsRaiz1[i]+'\\'+dirsRaiz2[o])
                dirsRaiz3=os.listdir(dir1+"\\"+dirsRaiz1[i]+'\\'+dirsRaiz2[o])
                cont=0
                for p in dirsRaiz3:
                        #print p
            
            
                        if p.endswith('.txt'):
                                continue
                        else:
"""
alguns mapas estavam com valos FCELL precisei forca-los para inteiro, e remove os FCELL
"""

import grass.script as grass
from grass.script import raster as grassR
import os
import string
import glob
import re
import fnmatch

list_tot=grass.mlist_grouped ('rast', pattern='*Bin*') ['PERMANENT']

for i in list_tot:
    grass.run_command("g.region",rast=i)
    if not "int" in i :
        print i
        grass.run_command("g.remove",flags="f",rast=i)
    #expressao2=i+"_int=int("+i+")"
    #grass.mapcalc(expressao2, overwrite = True, quiet = True)        
    def __init__(self, parent, id):
        wx.Panel.__init__(self, parent, id)
        
        #variavels_______________________________________
        Form1.mapa_entrada=''
        Form1.Path=False
        Form1.Frag=False
        Form1.Cone=False
        Form1.background_filename=[]
        
        Form1.size = 450
        Form1.hsize = 450
        
        Form1.formcalculate='Multiple'
        Form1.species_profile_group=''
        Form1.speciesList=[]
        Form1.species_profile=''
        Form1.petternmaps=''
        Form1.start_raio=0
        
        Form1.label_prefix=''
        Form1.RedularExp=''
        Form1.listMapsPng=[]
        Form1.listMapsPngAux=[]
        Form1.contBG=0
        Form1.plotmovements=0
        Form1.lenlistpng=0  
        
        Form1.ListmapsPath=[]
        Form1.ListMapsGroupCalc=[]
        Form1.escala_frag=''
        Form1.escala_ED=''
        Form1.dirout=''
        Form1.chebin=''
        Form1.checEDGE=''
        
        
        
        
        #________________________________________________

        #self.speciesList = ['Random walk','Core dependent','Frag. dependent', 'Habitat dependent', 'Moderately generalist', 'Highly generalist']
        Form1.speciesList=grass.mlist_grouped ('rast', pattern='(*)') ['PERMANENT']
        
        #____________________________________________________________________________
        
        
        Form1.start_popsize=5
        Form1.numberruns=100
        Form1.timesteps=200


        Form1.dirout=selecdirectori()

        
        Form1.output_prefix2='Nome do arquivo + ext '


        
        
        self.quote = wx.StaticText(self, id=-1, label="Connectivity Index",pos=wx.Point(20, 20))
        
        font = wx.Font(12, wx.SWISS, wx.NORMAL, wx.BOLD)
        self.quote.SetForegroundColour("blue")
        self.quote.SetFont(font)

        #____________________________________________________________________________
        
        # A multiline TextCtrl - This is here to show how the events work in this program, don't pay too much attention to it
        #caixa de mensagem
        self.logger = wx.TextCtrl(self,5, '',wx.Point(20,330), wx.Size(340,120),wx.TE_MULTILINE | wx.TE_READONLY)
        
        self.editname = wx.TextCtrl(self, 190, '', wx.Point(180, 82), wx.Size(100,-1)) #Regular expression
        self.editname = wx.TextCtrl(self, 191, '', wx.Point(270,200), wx.Size(80,-1)) #escala
        self.editname = wx.TextCtrl(self, 192, '', wx.Point(260,225), wx.Size(90,-1)) #borda
        
        wx.EVT_TEXT(self, 190, self.EvtText)
        wx.EVT_TEXT(self, 191, self.EvtText)
        wx.EVT_TEXT(self, 192, self.EvtText)
        #____________________________________________________________________________
        # A button
        self.button =wx.Button(self, 10, "START SIMULATION", wx.Point(20, 480))
        wx.EVT_BUTTON(self, 10, self.OnClick)
        self.button =wx.Button(self, 8, "EXIT", wx.Point(270, 480))
        wx.EVT_BUTTON(self, 8, self.OnExit)        
        self.button =wx.Button(self, 9, "change Map", wx.Point(280, 295))
        wx.EVT_BUTTON(self, 9, self.OnClick) 
        
        self.button =wx.Button(self, 11, "TXT RULES", wx.Point(283,260))
        wx.EVT_BUTTON(self,11, self.OnClick)        

        #____________________________________________________________________________
        ##------------ LElab_logo
        imageFile = 'logo_lab.png'
        im1 = Image.open(imageFile)
        jpg1 = wx.Image(imageFile, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
        wx.StaticBitmap(self, -1, jpg1, (20,190), (jpg1.GetWidth(), jpg1.GetHeight()), style=wx.SUNKEN_BORDER)
        
       
        
        
        
        
        

       #______________________________________________________________________________________________________________
       #static text
        
        self.SelecMetrcis = wx.StaticText(self,-1,"Chose Metric:",wx.Point(20,150))
        
        
        self.SelecMetrcis = wx.StaticText(self,-1,"Show Maps List:",wx.Point(180,300))
        self.SelecMetrcis = wx.StaticText(self,-1,"Regular Expression:",wx.Point(182, 62))
        self.SelecMetrcis = wx.StaticText(self,-1,"List Scale Unit(m):",wx.Point(180,200))
        self.SelecMetrcis = wx.StaticText(self,-1,"List Ed. Unit(m):",wx.Point(180,228))
        wx.EVT_TEXT(self, 185, self.EvtText)
        
        
        #______________________________________________________________________________________________________________
        # the combobox Control
        #Form1.editspeciesList=wx.ComboBox(self, 93, Form1.species_profile, wx.Point(80, 115), wx.Size(280, -1),
        #Form1.speciesList, wx.CB_DROPDOWN)
        #wx.EVT_COMBOBOX(self, 93, self.EvtComboBox)
        #wx.EVT_TEXT(self, 93, self.EvtText)
        
        #______________________________________________________________________________________________________________
        # Checkbox

        self.insure = wx.CheckBox(self, 96, "AH Path.",wx.Point(90,150))
        wx.EVT_CHECKBOX(self, 96,   self.EvtCheckBox)     
        
        self.insure = wx.CheckBox(self, 95, "AH Frag.",wx.Point(160,150))
        wx.EVT_CHECKBOX(self, 95,   self.EvtCheckBox)   
        
       
        
        self.insure = wx.CheckBox(self, 97, "AH Con.",wx.Point(230,150))
        wx.EVT_CHECKBOX(self, 97,   self.EvtCheckBox)  
        
        self.insure = wx.CheckBox(self, 150, "EDGE.",wx.Point(295,150))
        wx.EVT_CHECKBOX(self, 150,   self.EvtCheckBox)        
        
        
        self.insure = wx.CheckBox(self, 98, "",wx.Point(260,300))
        wx.EVT_CHECKBOX(self, 98,   self.EvtCheckBox)  
        
        self.insure = wx.CheckBox(self, 99, "Create Bin.",wx.Point(180,265))
        wx.EVT_CHECKBOX(self, 99,   self.EvtCheckBox)        
        
        #______________________________________________________________________________________________________________
        #Radio Boxes
        self.dispersiveList = ['Multiple', 'Single',          ]
        rb = wx.RadioBox(self, 92, "Chose form calculate", wx.Point(20, 62), wx.DefaultSize,
                        self.dispersiveList, 2, wx.RA_SPECIFY_COLS)
        wx.EVT_RADIOBOX(self, 92, self.EvtRadioBox)
        
        
        #______________________________________________________________________________________________________________ 
        #backgroun inicial
        Form1.background_filename=['Pai10.png']
        Form1.background_filename_start=Form1.background_filename[0]
                                
                                
                                
        img =Image.open(Form1.background_filename[0])
      
        # redimensionamos sem perder a qualidade
        img = img.resize((Form1.size,Form1.hsize),Image.ANTIALIAS)
        img.save(Form1.background_filename[0])        
      
      
        imageFile=Form1.background_filename[0]
        im1 = Image.open(imageFile)
        jpg1 = wx.Image(imageFile, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
        wx.StaticBitmap(self, -1, jpg1, (380,40), (jpg1.GetWidth(),  jpg1.GetHeight()), style=wx.SIMPLE_BORDER)        
Exemple #11
0
#Felipe alterei aqui, consegue ver ai?

#Eitaporra

import grass.script as grass
import os
os.chdir(r'C:\_data\vivi_brito\shps_500m\Mapa_het_saidas_grass')
lista_rast = grass.mlist_grouped('rast', pattern='*land*')['PERMANENT']

for i in lista_rast:
    grass.run_command('g.region', rast=i)
    stats = grass.read_command('r.stats', input=i)
    ListStats = stats.split('\n')
    #print ListStats
    del ListStats[-1]
    del ListStats[-1]
    lista_multplos2 = []
    y = 0
    #print len(ListStats)
    while len(ListStats) >= y:
        if y == 0:
            resulti = 1
        else:
            resulti = resulti * 2
        lista_multplos2.append(resulti)
        y = y + 1
    cont_reclasse = 0
    lista_jucao_final = []
    for sts in ListStats:
        formatname = '000000' + ` lista_multplos2[cont_reclasse] `
        #print formatname
import grass.script as grass
from PIL import Image
import wx
import random
import re
import time
import math

lista_vects = grass.mlist_grouped('rast', pattern='*0250*')['PERMANENT']
x = 0
for i in lista_vects:
    #if "QQ" in i :
    #out=i.replace('QQ_pts_2_buf2km_merge_v0_Join_rast2000m_img','QQ_pts_2_buffer_2000_extracByMask_rast_img')
    print i
    #grass.run_command('g.rename',rast=i+','+out,overwrite=True)
import grass.script as grass
from grass.script import raster as grassR
import os
import string
import glob
import re
import fnmatch



lista_rasters_maps_old=grass.mlist_grouped ('rast', pattern='*Bin*') ['PERMANENT']

lista_vect_maps_old=grass.mlist_grouped ('vect', pattern='*id_2*') ['PERMANENT']

for i in lista_vect_maps_old: 
        check="id2_"+i[40:41]

        for a in lista_rasters_maps_old:
                if "FRAG60m_mata_clump_AreaHA" in a:
                        if check in a:
                                grass.run_command('g.region',rast=a)
                                grass.run_command('v.what.rast', vector=i,raster=a, column="FG060")
                
                
                if "FRAG120m_mata_clump_AreaHA" in a:
                        if check in a:
                                grass.run_command('g.region',rast=a)
                                grass.run_command('v.what.rast', vector=i,raster=a, column="FG120")                
   
                if "patch_clump_mata_limpa_AreaHA" in a:
                        if check in a:
import grass.script as grass
import os
os.chdir(r'C:\_data\vivi_brito\shps_500m\Mapa_het_saidas_grass')

lista_rast=grass.mlist_grouped ('rast', pattern='*land*') ['PERMANENT']

for i in lista_rast:
    grass.run_command('g.region',rast=i)
    stats=grass.read_command('r.stats',input=i)
    ListStats=stats.split('\n')
    #print ListStats
    del ListStats[-1]
    del ListStats[-1]
    lista_multplos2=[]
    y=0
    #print len(ListStats)
    while len(ListStats)>=y:
        if y==0:
            resulti=1
        else:
            resulti=resulti*2
        lista_multplos2.append(resulti)
        y=y+1
    cont_reclasse=0
    lista_jucao_final=[]
    for sts in ListStats:
        formatname='000000'+`lista_multplos2[cont_reclasse]`
        #print formatname
        formatname=formatname[-5:]
        #print formatname
        expressao1=i+'_'+formatname+'_bin=if('+i+"=="+sts+","+`lista_multplos2[cont_reclasse]`+',0)'
Exemple #15
0
    def __init__(self, parent, id):
        wx.Panel.__init__(self, parent, id)
        self.listmaps=grass.mlist_grouped ('rast', pattern='(*)') ['PERMANENT']
        Form1.maps_profile=self.listmaps[0]

        
        
        #Form1.start_popsize=5
        Form1.numberruns=100
        Form1.timesteps=200




        Form1.OutDir_files='Caminho dos arquivos'
        Form1.OutDir_files_TXT=''
        Form1.InArqCost='Nome do arquivo + ext '
        Form1.InArqST=''
        Form1.OutArqCost=''
        Form1.C2='M2_MODE'
        Form1.C3='M3_MAXIMUM'
        Form1.C4='M4_AVERAGE'
        Form1.C5='M5_AVERAGE_VIEW'
        Form1.C6='M6_Unikon'
        Form1.listaApoioaleat3=[]
        Form1.contInp=['1','1','1','1','1','1']
        
        Form1.lista=''
        Form1.edtstart_list='Ex:1,2,3,4,...'
        Form1.patch_id_list=''
        #Form1.patch_id_list.Append=[]
        Form1.edtCost='Name cost map'
        Form1.edtST='Map Name of Source and Target'
        Form1.escname=''
        
        
        Form1pares=''
        Form1.patch_id_list_aux=''
        Form1.patch_id_list_aux_b=''
        
        #Formulas
        
        Form1.S1=''
        Form1.T1=''
        Form1.S1FORMAT=''
        Form1.T1FORMAT=''
        Form1.PAISGEM=''
        Form1.ARQSAIDA=''
        Form1.NEXPER_AUX='MSP'
        Form1.NEXPER_APOIO=''
        Form1.NEXPER_FINAL=''
        
    
        Form1.Form_01=''        
        Form1.form_02=''
        Form1.form_03=''
        Form1.form_04=''
        Form1.form_05=''
        Form1.form_06=''
        Form1.form_07=''
        Form1.form_08=''
        Form1.form_09=''
        Form1.form_10=''
        Form1.form_11=''
        Form1.form_12=""
        Form1.form_13=''
        Form1.form_14=""
        Form1.form_15=''
        Form1.form_16=''
        Form1.form_17=""
        Form1.form_18=""
        Form1.chekfolder=''
    
    
        Form1.a=''
        Form1.b=''
        Form1.c=''
        Form1.d=''
        Form1.listExport=[]
        Form1.ap=0
        Form1.ap2=0
        Form1.ap3=0
        Form1.ap4=0
        Form1.ap5=0
        Form1.ap6=0
        
    
        Form1.var_source_x=''
        Form1.var_source_x_b=''
        Form1.var_source_y=''
        Form1.var_source_y_b=''
        Form1.var_target_x=''
        Form1.var_target_x_b=''
        Form1.var_target_y=''
        Form1.var_target_y_b=''
        Form1.outline=''
        Form1.outline1=''
        Form1.outdir=''        
    

        Form1.arquivo=''
        Form1.x=''
        Form1.x_b=''
        Form1.x_c=''
        
        
        Form1.M=''
        
        Form1.var_cost_sum=''
        Form1.var_dist_line=0.0
        Form1.linha=''
        Form1.readtxt=''
        Form1.ileHandle=''
        Form1.form_16=''
        Form1.lenlist=0.0
        Form1.lenlist_b=0.0
        Form1.Nsimulations=0
        Form1.Nsimulations1=15
        Form1.Nsimulations2=15
        Form1.Nsimulations3=15
        Form1.Nsimulations4=15
        Form1.NsimulationsStart='15'
        Form1.startscale='300'
        
        Form1.escalafina=0
        Form1.esc=300
        Form1.res=''
        Form1.res2=[]
        Form1.res3=''
        
        Form1.euclidean_a=0.0  
        Form1.euclidean_b=0.0  
        Form1.cabecalho=''
        
        Form1.length=''
        Form1.length_b=''
        Form1.length_c=''
        Form1.length_d=''
        Form1.length_e=0.0
        
                     
      
        
        
        
        
        
        
        
        
     
        Form1.var_source_x_b_int=0.0
        Form1.var_source_y_b_int=0.0
        Form1.var_target_x_b_int=0.0
        Form1.var_target_y_b_int=0.0
        Form1.ruido='2.0'
        Form1.ruido_float=2.0
        Form1.listafinal=[]
        Form1.escfinal=0
        Form1.escapoio1=''
        Form1.escapoio2=[]
        Form1.escE=''
        Form1.escW=''
        Form1.escfinal=0.0
        Form1.frag=''
        Form1.frag_list=''
        Form1.frag_list2=''
        Form1.selct=''   
        
       
        
    
        
        

        
        self.quote = wx.StaticText(self, id=-1, label="Land Scape Corridor",pos=wx.Point(20, 20))
        
        font = wx.Font(12, wx.SWISS, wx.NORMAL, wx.BOLD)
        self.quote.SetForegroundColour("blue")
        self.quote.SetFont(font)
        #__________________________________________________________________________________________
        self.quote = wx.StaticText(self, id=-1, label="Simulation Number:",pos=wx.Point(20,200))
                
        font = wx.Font(10, wx.SWISS, wx.NORMAL, wx.BOLD)
        self.quote.SetForegroundColour("green")
        self.quote.SetFont(font)        
                        
                        
                        
        #__________________________________________________________________________________________                
        self.quote = wx.StaticText(self, id=-1, label="Using Map Already Imported:",pos=wx.Point(20,90))
                      
        font = wx.Font(10, wx.SWISS, wx.NORMAL, wx.BOLD)
        self.quote.SetForegroundColour("green")
        self.quote.SetFont(font)         
                        
      
        # A multiline TextCtrl - This is here to show how the events work in this program, don't pay too much attention to it
        self.logger = wx.TextCtrl(self,5, "",wx.Point(20,269), wx.Size(320,100),wx.TE_MULTILINE | wx.TE_READONLY)
        # A button
        self.button =wx.Button(self, 10, "START SIMULATION", wx.Point(20,379))
        wx.EVT_BUTTON(self, 10, self.OnClick)
        
        #self.button =wx.Button(self, 9, "change Background", wx.Point(140, 500))
        #wx.EVT_BUTTON(self, 9, self.OnClick)

        #self.button =wx.Button(self, 11, "change Landscape", wx.Point(140, 530))
        #wx.EVT_BUTTON(self, 11, self.OnClick)

        #self.button =wx.Button(self, 200, "OUTPUT DIRECTORY", wx.Point(137,263))
        #wx.EVT_BUTTON(self, 200, self.OnClick)
      
        self.button =wx.Button(self, 205, " RUN  EXPORT FILES ", wx.Point(137,379))
        wx.EVT_BUTTON(self, 205, self.OnClick)        
        
        self.button =wx.Button(self, 210, "select files", wx.Point(230,55))#st
        wx.EVT_BUTTON(self, 210, self.OnClick) 
        
        self.button =wx.Button(self, 230, "select files", wx.Point(72,55)) #cost
        wx.EVT_BUTTON(self, 230, self.OnClick) 
        
        self.button =wx.Button(self, 240, "IMPORT FILES", wx.Point(308,55))#import files
        wx.EVT_BUTTON(self, 240, self.OnClick)         
        
        
        self.button =wx.Button(self, 250, "READ LIST TXT", wx.Point(322,145))#import files
        
        wx.EVT_BUTTON(self, 250, self.OnClick)           

        self.button =wx.Button(self, 260, "COMBINE ALL", wx.Point(418,145))#import files
        wx.EVT_BUTTON(self, 260, self.OnClick) 
        
        
        self.button =wx.Button(self, 8, "EXIT", wx.Point(260, 379))
        wx.EVT_BUTTON(self, 8, self.OnExit)

        ##------------ LElab_logo
        imageFile = 'logo_lab.png'
        im1 = Image.open(imageFile)
        jpg1 = wx.Image(imageFile, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
        wx.StaticBitmap(self, -1, jpg1, (348,270), (jpg1.GetWidth(), jpg1.GetHeight()), style=wx.SUNKEN_BORDER)
        
        
        # the edit control - one line version.
        self.lblname = wx.StaticText(self, -1, "Cost Map:",wx.Point(20,58))
        self.lblname2 = wx.StaticText(self, -1, "Target Source:",wx.Point(155,60))
        self.lblname2 = wx.StaticText(self, -1, "Variability:",wx.Point(400,60))
        self.lblname = wx.StaticText(self, -1, "Cost:",wx.Point(20,115))
        self.lblname = wx.StaticText(self, -1, "ST:",wx.Point(270,115))
        self.lblname = wx.StaticText(self, -1, "M1:",wx.Point(70,230))
        self.lblname = wx.StaticText(self, -1, "M2:",wx.Point(130,230))
        self.lblname = wx.StaticText(self, -1, "M3:",wx.Point(190,230))
        self.lblname = wx.StaticText(self, -1, "M4:",wx.Point(250,230))
        #self.lblname = wx.StaticText(self, -1, "M5:",wx.Point(260,220))
        #self.lblname = wx.StaticText(self, -1, "M6:",wx.Point(320,220))
        self.lblname = wx.StaticText(self, -1, "Name Output corridor:",wx.Point(20,180))
        self.lblname = wx.StaticText(self, -1, "Scale unit (M) :",wx.Point(330,180))
        self.editname = wx.TextCtrl(self, 180, Form1.edtstart_list, wx.Point(126,146), wx.Size(195,-1))
        
        self.editname = wx.TextCtrl(self, 185, 'Proposed name of the cost map', wx.Point(130,175), wx.Size(195,-1))
        self.editname = wx.TextCtrl(self, 186, '2.0', wx.Point(455,55), wx.Size(30,-1))
        #self.editname = wx.TextCtrl(self, 265, Form1.edtCost, wx.Point(110,97), wx.Size(195,-1))
        #self.editname = wx.TextCtrl(self, 266, Form1.edtST, wx.Point(308,97), wx.Size(195,-1))
        self.editname = wx.TextCtrl(self, 190, Form1.NsimulationsStart, wx.Point(90,228), wx.Size(35,-1))
        self.editname = wx.TextCtrl(self, 191, Form1.NsimulationsStart, wx.Point(150,228), wx.Size(35,-1))
        self.editname = wx.TextCtrl(self, 192, Form1.NsimulationsStart, wx.Point(210,228), wx.Size(35,-1))
        self.editname = wx.TextCtrl(self, 193, Form1.NsimulationsStart, wx.Point(270,228), wx.Size(35,-1))
        #self.editname = wx.TextCtrl(self, 194, Form1.NsimulationsStart, wx.Point(280,187), wx.Size(35,-1))
        #self.editname = wx.TextCtrl(self, 195, Form1.NsimulationsStart, wx.Point(340,187), wx.Size(35,-1))
        self.editname = wx.TextCtrl(self, 196, Form1.startscale, wx.Point(405,175), wx.Size(50,-1))
                
       
        
        wx.EVT_TEXT(self, 180, self.EvtText)
       
        wx.EVT_TEXT(self, 185, self.EvtText)
        wx.EVT_TEXT(self, 186, self.EvtText)
        wx.EVT_TEXT(self, 190, self.EvtText)
        wx.EVT_TEXT(self, 191, self.EvtText)
        wx.EVT_TEXT(self, 192, self.EvtText)
        wx.EVT_TEXT(self, 193, self.EvtText)
        wx.EVT_TEXT(self, 194, self.EvtText)
        wx.EVT_TEXT(self, 195, self.EvtText)
        wx.EVT_TEXT(self, 196, self.EvtText)
        wx.EVT_TEXT(self, 265, self.EvtText)
        wx.EVT_TEXT(self, 266, self.EvtText)
        #wx.EVT_CHAR(self.editname, self.EvtChar)
        

        Form1.lista = wx.StaticText(self, -1, "Enter a list manually :",wx.Point(20,150)) #lista
        #Form1.edtstart_list = wx.TextCtrl(self, 30, str(Form1.lista ), wx.Point(90, 120), wx.Size(35,-1))
        #wx.EVT_TEXT(self, 30, self.EvtText)
        #wx.EVT_CHAR(Form1.edtstart_popsize, self.EvtChar)
        
        
        # the combobox Control

        #self.lblspeciesList = wx.StaticText(self,-1,"Species Profile:",wx.Point(20, 150))
        self.editspeciesList=wx.ComboBox(self, 93, 'Click to select', wx.Point(50, 112), wx.Size(215, -1),
        self.listmaps, wx.CB_DROPDOWN)
        wx.EVT_COMBOBOX(self, 93, self.EvtComboBox)
        wx.EVT_TEXT(self, 93, self.EvtText)
        
        
        self.editspeciesList=wx.ComboBox(self, 95, 'Click to select', wx.Point(290, 112), wx.Size(215, -1),
                                         self.listmaps, wx.CB_DROPDOWN)
        wx.EVT_COMBOBOX(self, 95, self.EvtComboBox)
        wx.EVT_TEXT(self, 95, self.EvtText)        
        
        # Checkbox

        

       # self.insure = wx.CheckBox(self, 95, "Prob.Death",wx.Point(260,180))
       # wx.EVT_CHECKBOX(self, 95,   self.EvtCheckBox)        
        
        # Radio Boxes
        self.dispersiveList = ['1', '2', '3',         ]
Exemple #16
0
    def OnClick(self,event):
        #self.logger.AppendText(" Runing simulation %d\n" )#%event.GetId())
        
        
        if event.GetId()==240: #Run import
          grass.run_command ('r.in.gdal', flags='o' ,input=Form1.InArqCost,output=Form1.OutArqCost,overwrite=True, verbose = False)
          grass.run_command ('r.in.gdal', flags='o' ,input=Form1.InArqST,output= Form1.OutArqST,overwrite=True, verbose = False)
          grass.run_command('g.region', rast=Form1.OutArqCost,verbose=False)
          self.logger.AppendText('importing rasters... \n')
       
        if event.GetId()==260: #comnine list
          self.logger.AppendText('generating combinations... \n')
          Form1.patch_id_list_aux=combine_st(patchid_list=Form1.OutArqST)
          Form1.patch_id_list_aux_b=Form1.patch_id_list_aux.split(',')
          Form1.lenlist=len(Form1.patch_id_list_aux_b)
          Form1.lenlist_b=Form1.lenlist/2
          #print Form1.lenlist
          
        
          self.logger.AppendText('waiting ... \n')
          d= wx.MessageDialog( self, `Form1.lenlist_b`+" Combitarions simulate ? \n","", wx.YES_NO)
                            # Create a message dialog box
          retCode=d.ShowModal() # Shows 
           # finally destroy it when finished.
          d.Close(True)  # Close the frame. 

          if (retCode == wx.ID_YES):
            Form1.patch_id_list=Form1.patch_id_list_aux.split(',')
            self.logger.AppendText('\n created list \n')
            #print Form1.patch_id_list
            
              
          else:
              print ""
              self.logger.AppendText('not accepted \n')
          d.Destroy()

        
         
        
          
        #if event.GetId()==200:   #200==Select directori
        #  Form1.OutDir_files=selecdirectori()
        #  print Form1.OutDir_files
          
          
        if event.GetId()==205:   #200==Select directori
          self.logger.AppendText('Please select the directory... \n')
        
          p=grass.mlist_grouped ('rast', pattern='*MSP*') ['PERMANENT']
          j=len(p)
          #print j
          self.logger.AppendText('Foud: ')
          d= wx.MessageDialog( self, " Files \n Export files?  \n"
                               ,"", wx.YES_NO)
          # Create a message dialog box
          retCode=d.ShowModal() # Shows 
          # finally destroy it when finished.
          d.Close(True)  # Close the frame. 
          
          if (retCode == wx.ID_YES):
            Form1.OutDir_files=selecdirectori()
            os.chdir(Form1.OutDir_files)
            for i in p:
              grass.run_command('g.region', rast=i,verbose=False)
              grass.run_command('r.out.gdal',input=i, out=i+'.tif',format='GTiff',nodata=-9999)
              #print i
              self.logger.AppendText('Exporting:\n '+i +"\n" )
            else:
              #print "no"
              self.logger.AppendText('Export canceled \n' )
              d.Destroy()   
                    
                    

                                                
                    
        if event.GetId()==210:   #210==Select files st
          self.logger.AppendText("Waiting ... :\n")
          Form1.InArqST=selecdirectori()
          Form1.OutArqST=Form1.InArqST.split('\\');Form1.OutArqST=Form1.OutArqST[-1].replace('.','_')
          print   Form1.OutArqST
          self.logger.AppendText("Automatically Map ST Selected:\n")
          self.logger.AppendText("\n",Form1.NEXPER_FINAL)
         
          
                  
        if event.GetId()==230:   #230==Select files cost
          self.logger.AppendText("Waiting ... :\n")
          Form1.InArqCost=selecdirectori()
          print Form1.InArqCost 
          Form1.OutArqCost=Form1.InArqCost.split('\\');Form1.OutArqCost=Form1.OutArqCost[-1].replace('.','_')
          print Form1.OutArqCost
          self.logger.AppendText('Selected File: \n'+Form1.OutArqCost)
          Form1.OutArqCost
          Form1.NEXPER_FINAL=Form1.OutArqCost+'_'+Form1.NEXPER_AUX
          self.logger.AppendText("Automatically Map Cost Selected:\n")
          self.logger.AppendText("\n",Form1.NEXPER_FINAL)
          
        if event.GetId()==250:
          self.logger.AppendText("Waiting ... :\n")
          Form1.readtxt=selecdirectori()
          Form1.fileHandle = open (Form1.readtxt, 'r' )
          Form1.patch_id_list=Form1.fileHandle.read() 
          Form1.patch_id_list_aux_b=Form1.patch_id_list.split(',')
          print Form1.patch_id_list_aux_b
          self.logger.AppendText("TXT Combinations \n"+`Form1.patch_id_list_aux_b`)
          
      

        if event.GetId()==10:   #10==START
                        
          
         
          
          self.logger.AppendText("Checking the list \n")
          Form1.lenlist=len(Form1.patch_id_list_aux_b)
         
          
          if  Form1.lenlist <= 1: 
            d= wx.MessageDialog( self, " Incorrect list \n"
                                             ,"", wx.OK)
            # Create a message dialog box
            d.ShowModal() # Shows it
            d.Destroy() # finally destroy it when finished.
            #frame.Close(True)  # Close the frame. 
            self.logger.AppendText(" Check list.. \n")
            
          elif Form1.lenlist > 1 and int (Form1.lenlist)%2 ==1 :
            
            d= wx.MessageDialog( self, "incorrect list \n Numbers odd patch, check the list \n  "
                                 ,"", wx.OK)
            # Create a message dialog box
            d.ShowModal() # Shows it
            d.Destroy() # finally destroy it when finished.
              #frame.Close(True)  # Close the frame. 
          else:
            Form1.patch_id_list=Form1.patch_id_list_aux.split(',')
            self.logger.AppendText(" ok list \n")
            self.logger.AppendText(" waiting... \n")
            
           
            
           
            d= wx.MessageDialog( self, " Select the output folder for'\n' text files \n"
                               ,"", wx.OK)
            # Create a message dialog box
            d.ShowModal() # Shows it
            d.Destroy() # finally destroy it when finished.
            Form1.OutDir_files_TXT=selecdirectori()
            self.logger.AppendText(" Selected output folder: \n"+Form1.OutDir_files_TXT)
            
          
            self.logger.AppendText(" running...: \n")
          self.logger.AppendText("\n creating list: \n"+`Form1.patch_id_list_aux_b`+'\n') 
          d= wx.MessageDialog( self," CLICK on ok and wait for the order di processing,\n the end will let you know , thank you"
                               ,"", wx.OK)
          
          retCode=d.ShowModal() # Shows 
          # finally destroy it when finished.
          d.Close(True)             
          
          Form1.S1=""
          Form1.T1=""
          Form1.C2=Form1.C2+''
          Form1.C3=Form1.C3+''
          Form1.C4=Form1.C4+''
          
          
          
          Form1.res=grass.read_command('g.region',flags='m')
          Form1.res2=Form1.res.split('\n')
          Form1.res3=Form1.res2[5]
          Form1.res3=float(Form1.res3.replace('ewres=',''))
          Form1.escfina1=(Form1.esc*2)/Form1.res3
          
          if Form1.escfina1%2==0:
            Form1.escfina1=int(Form1.escfina1)
            Form1.escfina1=Form1.escfina1+1
          else:
            Form1.escfina1=int(round(Form1.escfina1, ndigits=0))
             
          
          grass.run_command('g.region', rast=Form1.OutArqCost, res=Form1.res3)
          if Form1.Nsimulations2>0:
            grass.run_command('r.neighbors',input=Form1.OutArqCost,out=Form1.C2, method='mode',size=Form1.escfina1,overwrite = True)
            
          if Form1.Nsimulations3>0:
            grass.run_command('r.neighbors',input=Form1.OutArqCost,out=Form1.C3, method='average',size=Form1.escfina1,overwrite = True)
          
          if Form1.Nsimulations4>0:
            grass.run_command('r.neighbors',input=Form1.OutArqCost,out=Form1.C4, method='maximum',size=Form1.escfina1,overwrite = True)
          
          Form1.escfinal=0
          Form1.escapoio1=grass.read_command('g.region',flags='m')
          Form1.escapoio2=Form1.escapoio1.split("\n")
          Form1.escE=Form1.escapoio2[3]
          Form1.escW=Form1.escapoio2[2]
          Form1.escE=float(Form1.escE.replace("e=",''))
          Form1.escW=float(Form1.escW.replace("w=",''))
          Form1.escfinal=(Form1.escE-Form1.escW)/30          
          
          
          
         
          Form1.listafinal=[]
          
          for i in range(Form1.Nsimulations1):
            Form1.listafinal.append(Form1.OutArqCost)
            Form1.listaApoioaleat3.append('')
          for i in range(Form1.Nsimulations2):
            Form1.listafinal.append(Form1.C2)
            Form1.listaApoioaleat3.append('')
          for i in range(Form1.Nsimulations3):
            Form1.listafinal.append(Form1.C3)
            Form1.listaApoioaleat3.append('')
          for i in range(Form1.Nsimulations4):
            Form1.listafinal.append(Form1.C4)  
            Form1.listaApoioaleat3.append('')
          
          
            
            
          
            
            
          
          grass.run_command('g.region', rast=Form1.OutArqCost, res=Form1.res3)
          Form1.Nsimulations=Form1.Nsimulations1+Form1.Nsimulations2+Form1.Nsimulations3+Form1.Nsimulations4
          
                    
          #patch_id_list          
          while (len(Form1.patch_id_list)>1):
            Form1.S1=Form1.patch_id_list[0]
            Form1.T1=Form1.patch_id_list[1]
            Form1.S1FORMAT='000000'+Form1.S1
            Form1.S1FORMAT=Form1.S1FORMAT[-5:]
            Form1.T1FORMAT='000000'+Form1.T1
            Form1.T1FORMAT=Form1.T1FORMAT[-5:]
            #print Form1.S1FORMAT, Form1.T1FORMAT
            #print Form1.S1 , Form1.T1 
            del Form1.patch_id_list[0:2]
            
            Form1.PAISGEM='EXPERIMENTO'
            Form1.ARQSAIDA=Form1.PAISGEM+'_s'+Form1.S1FORMAT+'_t'+Form1.T1FORMAT
              
            self.logger.AppendText(" suing pair: \n"+Form1.S1FORMAT+'&'+Form1.T1FORMAT+ '\n')  
            Form1.S1=(int(str(Form1.S1)))
            Form1.T1=(int(str(Form1.T1)))
            Form1.form_02='source=if('+Form1.OutArqST+'!='+`Form1.S1`+',null(),'+`Form1.S1`+ ')'
            Form1.form_03='target=if('+Form1.OutArqST+'!='+`Form1.T1`+',null(),'+`Form1.T1`+ ')'
            #print Form1.form_02
            os.chdir(Form1.OutDir_files_TXT)
            grass.mapcalc(Form1.form_02, overwrite = True, quiet = True)
            grass.mapcalc(Form1.form_03, overwrite = True, quiet = True)
            
            #grass.run_command('g.mremove',vect='*', flags='f')
            grass.run_command('g.region', rast=Form1.OutArqST,verbose=False)
            
            grass.run_command('r.to.vect', input='source', out='source_shp', feature='area',verbose=False, overwrite = True ) 
            grass.run_command('r.to.vect', input='target', out='target_shp', feature='area',verbose=False, overwrite = True ) 
            grass.run_command ('v.db.addcol', map='source_shp', columns='x double precision,y double precision', overwrite = True)
            grass.run_command ('v.db.addcol', map='target_shp', columns='x double precision,y double precision', overwrite = True)
            
            grass.read_command ('v.to.db', map='source_shp', option='coor', columns="x,y", overwrite = True)
            grass.read_command ('v.to.db', map='target_shp', option='coor', columns="x,y", overwrite = True)
            
            Form1.a='' 
            Form1.a=grass.read_command('v.db.select', map='source_shp', flags='c',overwrite = True);
            Form1.var_source_x= Form1.a.split('|');
            Form1.var_source_x_b=str( Form1.var_source_x[3]); 
            Form1.var_source_x_b=Form1.var_source_x_b.replace('\n','')
            
            Form1.b=''
            Form1.b=grass.read_command('v.db.select', map='source_shp', flags='c',overwrite = True);
            Form1.var_source_y= Form1.b.split('|');
            Form1.var_source_y_b=str(Form1.var_source_y[4]);
            Form1.var_source_y_b=Form1.var_source_y_b.replace('\n','')
           
            Form1.c=''
            Form1.c=grass.read_command('v.db.select', map='target_shp', flags='c',overwrite = True)
            Form1.var_target_x= Form1.c.split('|')
            Form1.var_target_x_b=str(Form1.var_target_x[3])
            Form1.var_target_x_b=Form1.var_target_x_b.replace('\n','')
           
            Form1.d=''
            Form1.d=grass.read_command('v.db.select', map='target_shp', flags='c',overwrite = True)
            Form1.var_target_y= Form1.d.split('|')
            Form1.var_target_y_b=str( Form1.var_target_y[4])
            
            #print Form1.d
            #print Form1.var_target_y
            #print Form1.var_target_y_b
            Form1.var_target_y_b=Form1.var_target_y_b.replace('\n','')
            
            grass.run_command('g.region', rast=Form1.OutArqCost,verbose=False)
            
            
           
            Form1.mapa_corredores="corredores_s"+Form1.S1FORMAT+"_t"+Form1.T1FORMAT+'_COM0'
            Form1.mapa_corredores_sem0=Form1.NEXPER_FINAL+'_'+'S_'+Form1.S1FORMAT+"_T_"+Form1.T1FORMAT
            Form1.chekfolder=os.path.exists('Line_'+Form1.mapa_corredores_sem0)
            
            if Form1.chekfolder==False:
              os.mkdir('Line_'+Form1.mapa_corredores_sem0)
              Form1.outdir=Form1.OutDir_files_TXT+'\Line_'+Form1.mapa_corredores_sem0
            else:
              d= wx.MessageDialog( self, " Existing folder please select another location to save the lines \n"
                                   ,"", wx.OK)
              # Create a message dialog box
              d.ShowModal() # Shows it
              d.Destroy()              
              Form1.outdir=selecdirectori()            
            Form1.form_04='mapa_corredores=0'
            grass.mapcalc(Form1.form_04, overwrite = True, quiet = True)
            Form1.form_16='corredores_aux=0'
            grass.mapcalc(Form1.form_16, overwrite = True, quiet = True)
                            
            
              
              
              
            Form1.arquivo = open(Form1.mapa_corredores_sem0+'.txt','w')
            Form1.cabecalho='EXPERIMENT'','+'M'+','+'SIMULATION'+','+'LENGTHVECT'+','+'COST'+','+'Coord_source_x'+','+'Coord_source_y'+','+'Coord_target_x'+','+'Coord_target_y'+','+'Euclidean_Distance' '\n'
            Form1.arquivo.write(Form1.cabecalho)
            
            cont=0
            for i in range(Form1.Nsimulations):
              print "custo>>>>>>>>>>>>",Form1.listafinal[cont]
              Form1.form_08='mapa_custo='+Form1.listafinal[cont]
              grass.mapcalc(Form1.form_08, overwrite = True, quiet = True)  
              grass.run_command('g.region',rast='mapa_custo')              
              c=i+1
              
              #y=x/2
              print "------------------------------------------------------------------"
              print "=====> rodando : ",`c` 
              self.logger.AppendText('=======> runing :'+`c`+ '\n' )
              grass.run_command('r.mask',input='source')
              grass.run_command('g.region', vect='source_shp',verbose=False,overwrite = True)
              grass.run_command('v.random', output='temp_point1_s',n=30,overwrite = True)
              grass.run_command('v.select',ainput='temp_point1_s',binput='source_shp',output='temp_point2_s',operator='overlap',overwrite = True)
              grass.run_command('v.db.addtable', map='temp_point2_s',columns="temp double precision")
              grass.run_command('v.db.connect',flags='p',map='temp_point2_s')
              Form1.frag=grass.read_command('v.db.select',map='temp_point2_s',column='cat')
              Form1.frag_list=Form1.frag.split('\n')
              Form1.frag_list2=int(Form1.frag_list[1])              
              Form1.selct="cat="+`Form1.frag_list2`
              grass.run_command('v.extract',input='temp_point2_s',output='pnts_aleat_S',where=Form1.selct,overwrite = True)
              grass.run_command('r.mask',flags='r')
              
              
              grass.run_command('r.mask',input='target')
              grass.run_command('g.region', vect='target_shp',verbose=False,overwrite = True)
              
              grass.run_command('v.random', output='temp_point1_t',n=30,overwrite = True)
              grass.run_command('v.select',ainput='temp_point1_t',binput='target_shp',output='temp_point2_t',operator='overlap',overwrite = True)
              grass.run_command('v.db.addtable', map='temp_point2_t',columns="temp double precision")
              grass.run_command('v.db.connect',flags='p',map='temp_point2_t')
            
              Form1.frag=grass.read_command('v.db.select',map='temp_point2_t',column='cat')
              Form1.frag_list=Form1.frag.split('\n')
              Form1.frag_list2=int(Form1.frag_list[1])              
              Form1.selct="cat="+`Form1.frag_list2`
              grass.run_command('v.extract',input='temp_point2_t',output='pnts_aleat_T',where=Form1.selct,overwrite = True)            
            
            
              
              grass.run_command('r.mask',flags='r')
                
              grass.run_command('g.region', rast=Form1.OutArqCost,verbose=False)
              Form1.form_05='corredores_aux=mapa_corredores'
                
              grass.mapcalc(Form1.form_05, overwrite = True, quiet = True)
              if Form1.listaApoioaleat3[i]=='M6_Unikon' :
                
               
                grass.run_command('r.random.surface', out='aleat', high=100,overwrite = True)
                Form1.form_06='aleat2=1+((aleat/100.0)*'+`Form1.ruido_float`+')'
                grass.mapcalc(Form1.form_06, overwrite = True, quiet = True)
                Form1.form_07='custo_aux=mapa_custo*aleat2'  
                grass.run_command('g.region', rast='source,target',res=Form1.escfinal,verbose=False)
                grass.run_command('r.random.surface', out='aleat_Gros', high=100,overwrite = True)
                Form1.form_15='aleat2_Gros=1+((aleat_Gros/100.0)*'+`Form1.ruido_float`+')'
                grass.mapcalc(Form1.form_15, overwrite = True, quiet = True)
                grass.run_command('g.region', rast='source,target',verbose=False)
                
                Form1.form_16='custo_aux=mapa_custo*aleat2*aleat2_Gros'  
                grass.mapcalc(Form1.form_16, overwrite = True, quiet = True) 
                Form1.form_18='M6=mapa_custo*aleat2*aleat2_Gros'  
                grass.mapcalc(Form1.form_18, overwrite = True, quiet = True)                   
                
              else :  

                  grass.run_command('r.random.surface', out='aleat', high=100,overwrite = True)
                  Form1.form_06='aleat2=1+((aleat/100.0)*'+`Form1.ruido_float`+')'
                  grass.mapcalc(Form1.form_06, overwrite = True, quiet = True)
                  Form1.form_07='custo_aux=mapa_custo*aleat2'
                  grass.mapcalc(Form1.form_07, overwrite = True, quiet = True)    
              
              
              
             
                
              grass.run_command('g.region', rast=Form1.OutArqCost,verbose=False) 
              grass.run_command('r.cost', flags='k', input='custo_aux', out='custo_aux_cost', start_points='pnts_aleat_S', stop_points='pnts_aleat_T',overwrite = True)
              grass.run_command('r.drain', input='custo_aux_cost', out='custo_aux_cost_drain', vector_points='pnts_aleat_T', overwrite = True)
              grass.run_command('r.series',input='corredores_aux,custo_aux_cost_drain', output='mapa_corredores', method='sum',overwrite = True)
              Form1.form_09='custo_aux_cost_drain_sum=custo_aux_cost_drain*'+Form1.listafinal[0]
              
              
              
              grass.mapcalc(Form1.form_09, overwrite = True, quiet = True)  
             
              
              #calculando custo
              Form1.x=grass.read_command('r.univar', map='custo_aux_cost_drain_sum')
              #print Form1.x
              Form1.x_b=Form1.x.split('\n')
              #Form1.x_b=Form1.x.repleace('\n',',')
              #print Form1.x_b
              Form1.x_c=str(Form1.x_b[14])
              Form1.var_cost_sum=Form1.x_c[5:8]
              
                           
              
              
              
              #print 
              grass.run_command('g.region', rast=Form1.OutArqCost,verbose=False)
              Form1.form_10=Form1.mapa_corredores_sem0+'=if(mapa_corredores==0,null(),mapa_corredores)'
              
              
              

              grass.mapcalc(Form1.form_10, overwrite = True, quiet = True)
             #calculando a distancia
              Form1.length=grass.read_command('r.univar', map='custo_aux_cost_drain')
              #print Form1.x
              Form1.length_b=Form1.length.split('\n')
              Form1.length_c=str(Form1.length_b[14])
              Form1.length_d=Form1.length_c[5:9]
              Form1.length_e=float(Form1.length_d)
              Form1.var_dist_line=Form1.res3*Form1.length_e
              
              Form1.var_source_x_b_int=float(Form1.var_source_x_b)
              Form1.var_source_y_b_int=float(Form1.var_source_y_b)
              Form1.var_target_x_b_int=float(Form1.var_target_x_b)
              Form1.var_target_y_b_int=float(Form1.var_target_y_b)
             
              
              Form1.euclidean_a =float((Form1.var_source_x_b_int-Form1.var_target_x_b_int)**2 + (Form1.var_source_y_b_int-Form1.var_target_y_b_int)**2)
              Form1.euclidean_b= Form1.euclidean_a**0.5
              if Form1.listafinal[cont]==Form1.OutArqCost:
                Form1.M="M1"
              if Form1.listafinal[cont]=='M2_MODE':
                Form1.M="M2"
              if Form1.listafinal[cont]=='M3_MAXIMUM':
                Form1.M="M3"              
              if Form1.listafinal[cont]=='M4_AVERAGE':
                Form1.M="M4"              
              if Form1.listafinal[cont]=='M5_AVERAGE_VIEW':
                Form1.M="M5"                
              if Form1.listafinal[cont]=='M6_Unikon':
                Form1.M="M6"                
                   
                              
              
              
              
              
              
              Form1.linha=Form1.listafinal[cont].replace("@PERMANENT",'')+','+Form1.M+','+`c`+','+ `Form1.var_dist_line`+','+ `Form1.var_cost_sum`+','+ `Form1.var_source_x_b`+','+ `Form1.var_source_y_b`+','+ `Form1.var_target_x_b`+','+ `Form1.var_target_y_b`+','+ `Form1.euclidean_b`+ "\n"
              Form1.linha=Form1.linha.replace('\'','')
              #PAISGEM+var_dist_line ` `+var_cost_sum+` `+var_source_x+` `+var_source_y+` `+var_target_x+` ` var_target_y`
              Form1.var_dist_line=0.0
              Form1.var_cost_sum=0.0
              #linha=$ARQSAIDA$" simulacao="$i$" lengthvect="$var_dist_line$"  somarast="$var_cost_sum$" source_x="$var_source_x$" source_y="$var_source_y$" target_x="$var_target_x$" target_y="$var_target_y   
              
              #print Form1.linha
              Form1.arquivo.write(Form1.linha)
              Form1.linha=""
              print "MAP>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+Form1.listafinal[cont]
              #declarar isso 
              Form1.outline1='000000'+`c`
              #Form1.outline='000000'+`i`
              Form1.outline1=Form1.outline1[-3:]
              Form1.outline1=Form1.mapa_corredores_sem0+'_'+Form1.M+"_SM_"+Form1.outline1
              grass.run_command('g.region',rast='custo_aux_cost_drain')
              grass.run_command('r.to.vect', input='custo_aux_cost_drain', out=Form1.outline1, feature='line',verbose=False, overwrite = True )
              grass.run_command ('v.db.addcol', map=Form1.outline1, columns='dist double precision', overwrite = True)
              grass.read_command ('v.to.db', map=Form1.outline1, option='length', type='line', col='dist', units='me', overwrite = True)
              os.chdir(Form1.outdir)
              grass.run_command('v.out.ogr', input=Form1.outline1,dsn=Form1.outline1+'.shp',verbose=False,type='line')              
              grass.run_command('g.remove',vect=Form1.outline1, flags='f')              
              cont=cont+1
              
              
             
            Form1.listExport.append(Form1.mapa_corredores_sem0)  
            self.logger.AppendText(" removing auxiliary files...: \n")  
            grass.run_command('g.remove',vect='temp_point1_s,temp_point2_s,temp_point1_t,temp_point2_t,pnts_aleat_S,pnts_aleat_T,source_shp,target_shp,custo_aux_cost_drain_sem0_line', flags='f')
            grass.run_command('g.remove',rast='mapa_custo,mapa_corredores,custo_aux_cost_drain,source,target,custo_aux_cost_drain_sum,custo_aux_cost_drain_sem0,custo_aux_cost,custo_aux,corredores_aux,aleat,aleat2,aleat2_Gros,aleat3,aleat_Gros,apoio1', flags='f')
            grass.run_command('g.remove',rast='apoio2,apoio2b,apoio2c,apoio2d', flags='f')
            
            Form1.arquivo.close()
            
            grass.run_command('g.region', rast=Form1.OutArqCost,verbose=False)

            
            grass.run_command('r.series',input=Form1.listExport,out=Form1.OutArqCost+'RSeries',method="maximum")
            grass.run_command('g.region', rast=Form1.OutArqCost+'RSeries',verbose=False)
            grass.run_command('r.neighbors',input=Form1.OutArqCost+'RSeries',out=Form1.NEXPER_FINAL+"_MW_ALL_Corridors", method='average',size=Form1.escfina1,overwrite = True)

            Form1.listExport.append(Form1.NEXPER_FINAL+"_MW_ALL_Corridors")
            
            os.chdir(Form1.OutDir_files_TXT)
            for expt in Form1.listExport:
              grass.run_command('g.region', rast=expt)
              grass.run_command('r.out.gdal',input=expt, out=expt+'.tif')           
              
                
            d= wx.MessageDialog( self," Finish"
                                 ,"", wx.OK)
            
            retCode=d.ShowModal() # Shows 
            
            d.Close(True)         
import grass.script as grass
import os

lista_clumps=grass.mlist_grouped ('rast', pattern='*orig_clump_mata_limpa_AreaHA') ['PERMANENT']

#lista_clumps=lista_clumps[0:2]
#listaold=['1000','120','180','240','30','350','440','500','60','720','840','90']
#cont_listold=0
#for i in lista_clumps:
    ##print i 
    #formato='00000'+listaold[cont_listold]
    #formato=formato[-4:]
    #if listaold[cont_listold] in i:
        #out_rename=i.replace(listaold[cont_listold],formato)
        #print out_rename
        #cont_listold=cont_listold+1
        #grass.run_command('g.rename',rast=i+','+out_rename)
    #if cont_listold == 12:
        #cont_listold=0
for i in lista_clumps:
    escClump=i[38:42]
    print escClump
def heterogeneidade(i):
    grass.run_command('g.region', rast=i)
    stats = grass.read_command('r.stats', input=i)
    ListStats = stats.split('\n')
    #print ListStats
    del ListStats[-1]
    del ListStats[-1]
    lista_multplos2 = []
    y = 0
    #print len(ListStats)
    while len(ListStats) >= y:
        if y == 0:
            resulti = 1
        else:
            resulti = resulti * 2
        lista_multplos2.append(resulti)
        y = y + 1
    cont_reclasse = 0
    lista_jucao_final = []
    for sts in ListStats:
        formatname = '000000' + ` lista_multplos2[cont_reclasse] `
        #print formatname
        formatname = formatname[-5:]
        #print formatname
        expressao1 = i + '_' + formatname + '_bin=if(' + i + "==" + sts + "," + ` lista_multplos2[
            cont_reclasse] ` + ',0)'
        #print expressao1
        grass.mapcalc(expressao1, overwrite=True, quiet=True)
        expressao2 = i + '_' + formatname + '_bin_int=int(' + i + '_' + formatname + '_bin)'
        grass.mapcalc(expressao2, overwrite=True, quiet=True)
        grass.run_command('g.region', rast=i + '_' + formatname + '_bin_int')
        grass.run_command('r.neighbors',
                          input=i + '_' + formatname + '_bin_int',
                          out=i + '_' + formatname + '_bin_int_dila_50m',
                          method='maximum',
                          size=5,
                          overwrite=True)
        cont_reclasse = cont_reclasse + 1
        grass.run_command('g.remove',
                          flags='f',
                          rast=i + '_' + formatname + '_bin')
        lista_jucao_final.append(i + '_' + formatname + '_bin_int_dila_50m')

    grass.run_command('r.series',
                      input=lista_jucao_final,
                      out='temp',
                      overwrite=True,
                      method='sum')
    expressao3 = i + '_MapaHet_FINAL=int(if(' + i + '>0,temp,null()))'
    grass.mapcalc(expressao3, overwrite=True, quiet=True)
    grass.run_command('g.remove', flags='f', rast='temp')
    grass.run_command('r.colors', map=i + '_MapaHet_FINAL', color='random')
    grass.run_command('r.out.gdal',
                      input=i + '_MapaHet_FINAL',
                      out=i + '_MapaHet_FINAL.tif')
    for rm in lista_jucao_final:
        grass.run_command('g.remove', flags='f', rast=rm)

    lista_remove = grass.mlist_grouped('rast',
                                       pattern='*bin_int*')['PERMANENT']
    for a in lista_remove:
        grass.run_command('g.remove', flags='f', rast=a)
import grass.script as grass
from PIL import Image
import wx
import random
import re
import time
import math

lista_vects=grass.mlist_grouped ('vect', pattern='*semdissolv*') ['PERMANENT']

for i in lista_vects:
    out=i.replace('FINAL','2000m')
    grass.run_command('g.rename',vect=i+','+out)
    
import grass.script as grass
import os
lista_jucao_final=grass.mlist_grouped ('rast', pattern='*dila_50m_clip*') ['PERMANENT'] 
print lista_jucao_final
grass.run_command('r.series',input=lista_jucao_final,out='teste_MapaHet_FINAL',overwrite = True,method='sum')
    def __init__(self, parent, id):
        wx.Panel.__init__(self, parent, id)
        
        #variavels_______________________________________
        Form1.mapa_entrada=''
        Form1.Path=False
        Form1.Frag=False
        Form1.Cone=False
        Form1.background_filename=[]
        
        Form1.size = 450
        Form1.hsize = 450
        
        Form1.formcalculate='Multiple'
        Form1.species_profile_group=''
        Form1.speciesList=[]
        Form1.species_profile=''
        Form1.petternmaps=''
        Form1.start_raio=0
        
        Form1.label_prefix=''
        Form1.RedularExp=''
        Form1.listMapsPng=[]
        Form1.listMapsPngAux=[]
        Form1.contBG=0
        Form1.plotmovements=0
        Form1.lenlistpng=0  
        
        Form1.ListmapsPath=[]
        Form1.ListMapsGroupCalc=[]
        Form1.escala_frag=''
        Form1.escala_ED=''
        Form1.dirout=''
        Form1.chebin=''
        Form1.checEDGE=''
        
        
        
        
        #________________________________________________

        #self.speciesList = ['Random walk','Core dependent','Frag. dependent', 'Habitat dependent', 'Moderately generalist', 'Highly generalist']
        Form1.speciesList=grass.mlist_grouped ('rast', pattern='(*)') ['PERMANENT']
        
        #____________________________________________________________________________
        
        
        Form1.start_popsize=5
        Form1.numberruns=100
        Form1.timesteps=200


        Form1.dirout=selecdirectori()

        
        Form1.output_prefix2='Nome do arquivo + ext '


        
        
        self.quote = wx.StaticText(self, id=-1, label="Connectivity Index",pos=wx.Point(20, 20))
        
        font = wx.Font(12, wx.SWISS, wx.NORMAL, wx.BOLD)
        self.quote.SetForegroundColour("blue")
        self.quote.SetFont(font)

        #____________________________________________________________________________
        
        # A multiline TextCtrl - This is here to show how the events work in this program, don't pay too much attention to it
        #caixa de mensagem
        self.logger = wx.TextCtrl(self,5, '',wx.Point(20,330), wx.Size(340,120),wx.TE_MULTILINE | wx.TE_READONLY)
        
        self.editname = wx.TextCtrl(self, 190, '', wx.Point(180, 82), wx.Size(100,-1)) #Regular expression
        self.editname = wx.TextCtrl(self, 191, '', wx.Point(270,200), wx.Size(80,-1)) #escala
        self.editname = wx.TextCtrl(self, 192, '', wx.Point(260,225), wx.Size(90,-1)) #borda
        
        wx.EVT_TEXT(self, 190, self.EvtText)
        wx.EVT_TEXT(self, 191, self.EvtText)
        wx.EVT_TEXT(self, 192, self.EvtText)
        #____________________________________________________________________________
        # A button
        self.button =wx.Button(self, 10, "START SIMULATION", wx.Point(20, 480))
        wx.EVT_BUTTON(self, 10, self.OnClick)
        self.button =wx.Button(self, 8, "EXIT", wx.Point(270, 480))
        wx.EVT_BUTTON(self, 8, self.OnExit)        
        self.button =wx.Button(self, 9, "change Map", wx.Point(280, 295))
        wx.EVT_BUTTON(self, 9, self.OnClick) 
        
        self.button =wx.Button(self, 11, "TXT RULES", wx.Point(283,260))
        wx.EVT_BUTTON(self,11, self.OnClick)        

        #____________________________________________________________________________
        ##------------ LElab_logo
        imageFile = 'logo_lab.png'
        im1 = Image.open(imageFile)
        jpg1 = wx.Image(imageFile, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
        wx.StaticBitmap(self, -1, jpg1, (20,190), (jpg1.GetWidth(), jpg1.GetHeight()), style=wx.SUNKEN_BORDER)
        
       
        
        
        
        
        

       #______________________________________________________________________________________________________________
       #static text
        
        self.SelecMetrcis = wx.StaticText(self,-1,"Chose Metric:",wx.Point(20,150))
        
        
        self.SelecMetrcis = wx.StaticText(self,-1,"Show Maps List:",wx.Point(180,300))
        self.SelecMetrcis = wx.StaticText(self,-1,"Regular Expression:",wx.Point(182, 62))
        self.SelecMetrcis = wx.StaticText(self,-1,"List Scale Unit(m):",wx.Point(180,200))
        self.SelecMetrcis = wx.StaticText(self,-1,"List Ed. Unit(m):",wx.Point(180,228))
        wx.EVT_TEXT(self, 185, self.EvtText)
        
        
        #______________________________________________________________________________________________________________
        # the combobox Control
        #Form1.editspeciesList=wx.ComboBox(self, 93, Form1.species_profile, wx.Point(80, 115), wx.Size(280, -1),
        #Form1.speciesList, wx.CB_DROPDOWN)
        #wx.EVT_COMBOBOX(self, 93, self.EvtComboBox)
        #wx.EVT_TEXT(self, 93, self.EvtText)
        
        #______________________________________________________________________________________________________________
        # Checkbox

        self.insure = wx.CheckBox(self, 96, "AH Path.",wx.Point(90,150))
        wx.EVT_CHECKBOX(self, 96,   self.EvtCheckBox)     
        
        self.insure = wx.CheckBox(self, 95, "AH Frag.",wx.Point(160,150))
        wx.EVT_CHECKBOX(self, 95,   self.EvtCheckBox)   
        
       
        
        self.insure = wx.CheckBox(self, 97, "AH Con.",wx.Point(230,150))
        wx.EVT_CHECKBOX(self, 97,   self.EvtCheckBox)  
        
        self.insure = wx.CheckBox(self, 150, "EDGE.",wx.Point(295,150))
        wx.EVT_CHECKBOX(self, 150,   self.EvtCheckBox)        
        
        
        self.insure = wx.CheckBox(self, 98, "",wx.Point(260,300))
        wx.EVT_CHECKBOX(self, 98,   self.EvtCheckBox)  
        
        self.insure = wx.CheckBox(self, 99, "Create Bin.",wx.Point(180,265))
        wx.EVT_CHECKBOX(self, 99,   self.EvtCheckBox)        
        
        #______________________________________________________________________________________________________________
        #Radio Boxes
        self.dispersiveList = ['Multiple', 'Single',          ]
        rb = wx.RadioBox(self, 92, "Chose form calculate", wx.Point(20, 62), wx.DefaultSize,
                        self.dispersiveList, 2, wx.RA_SPECIFY_COLS)
        wx.EVT_RADIOBOX(self, 92, self.EvtRadioBox)
        
        
        #______________________________________________________________________________________________________________ 
        #backgroun inicial
        Form1.background_filename=['Pai10.png']
        Form1.background_filename_start=Form1.background_filename[0]
                                
                                
                                
        img =Image.open(Form1.background_filename[0])
      
        # redimensionamos sem perder a qualidade
        img = img.resize((Form1.size,Form1.hsize),Image.ANTIALIAS)
        img.save(Form1.background_filename[0])        
      
      
        imageFile=Form1.background_filename[0]
        im1 = Image.open(imageFile)
        jpg1 = wx.Image(imageFile, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
        wx.StaticBitmap(self, -1, jpg1, (380,40), (jpg1.GetWidth(),  jpg1.GetHeight()), style=wx.SIMPLE_BORDER)        
    expression12=Listmapspath+"_patch_clump_mata="+Listmapspath+"_patch_clump*"+Listmapspath
    grass.mapcalc(expression12, overwrite = True, quiet = True)
    expression13=Listmapspath+"_patch_clump_mata_limpa=if("+Listmapspath+"_patch_clump_mata>0,"+Listmapspath+"_patch_clump_mata,null())"
    grass.mapcalc(expression13, overwrite = True, quiet = True)
    txt_reclass=rulesreclass(Listmapspath+"_patch_clump_mata_limpa")
    grass.run_command('r.reclass',input=Listmapspath+"_patch_clump_mata_limpa",output=Listmapspath+"_patch_clump_mata_limpa_AreaHA",rules=txt_reclass,overwrite = True)
    mean(Listmapspath+"_patch_clump_mata_limpa_AreaHA")
    pct_flt(Listmapspath,Listmapspath+"_patch_clump_mata_limpa")
    grass.run_command('g.remove',flags='f',rast='A,MapaBinario,MapaBinario_A,MapaBinario_AB,MapaBinario_ABC,MapaBinario_ABCD')  
    #os.remove(txt_reclass)
#---------------------------------------------------------------------------------------------------------------------------------





#---------------------------------------------------------------------------------------------------------------------------------
lista_rasts=grass.mlist_grouped ('rast', pattern='*QQ_pts_2_buffer_1000_extratcByMask_rast_img*') ['PERMANENT']

for i in lista_rasts:
    out_bin=i+'bin'
    expressao_mata=out_bin+'=if('+i+'==14 |'+i+'==13,'+i+',0)'
    grass.run_command('g.region',rast=i)
    grass.mapcalc(expressao_mata, overwrite = True, quiet = True)
    #print expressao_mata
    create_EDGE_single(out_bin)
    pacthSingle(out_bin)
    heterogeneidade(i)
    indice_antropi(i)
    
  #print frags
 def OnClick(self,event):
     #self.logger.AppendText(" Click on object with Id %d\n" %event.GetId())
     
     #______________________________________________________________________________________________________________ 
     if event.GetId()==10:   #10==START
       if Form1.formcalculate=="Single":
         if Form1.Path==True:   
           pacthSingle(Form1.mapa_entrada)
         if Form1.Frag==True:
           areaFragSingle(Form1.mapa_entrada)
         if Form1.Cone==True:
           areaconSingle(Form1.mapa_entrada)
         if Form1.checEDGE==True:
           create_EDGE_single(Form1.mapa_entrada,Form1.escala_ED,Form1.dirout)
       else:
         Form1.ListMapsGroupCalc=grass.mlist_grouped ('rast', pattern=Form1.RedularExp) ['PERMANENT']
         if Form1.Path==True:
           Form1.ListmapsPath=Path(Form1.ListMapsGroupCalc)
         
         if Form1.Frag==True:
           areaFrag(Form1.ListMapsGroupCalc)
         if Form1.Cone==True:
           areacon(Form1.ListMapsGroupCalc) 
         if Form1.checEDGE==True:
           create_EDGE(Form1.ListMapsGroupCalc,Form1.escala_ED,Form1.dirout)
         
     
     
     
     #______________________________________________________________________________________________________________ 
     if event.GetId()==9:   #9==CHANGE BACKGROUND
       if Form1.plotmovements==1:
         if Form1.formcalculate=="Single":
           x=1
         else:
           self.Refresh()
           Form1.background_filename=Form1.listMapsPng
           Form1.background_filename_start=Form1.background_filename[Form1.contBG]   
           img =Image.open(Form1.background_filename[Form1.contBG])
         
           # redimensionamos sem perder a qualidade
           img = img.resize((Form1.size,Form1.hsize),Image.ANTIALIAS)
           img.save(Form1.background_filename[Form1.contBG])        
         
         
           imageFile=Form1.background_filename[Form1.contBG]
           im1 = Image.open(imageFile)
           jpg1 = wx.Image(imageFile, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
           wx.StaticBitmap(self, -1, jpg1, (380,40), (jpg1.GetWidth(),  jpg1.GetHeight()), style=wx.SIMPLE_BORDER)
                             
           Form1.background_filename=Form1.background_filename_start
           Form1.contBG=Form1.contBG+1
           self.Refresh() 
           if len(Form1.listMapsPng)==Form1.contBG:
             Form1.contBG=0      
             self.Refresh() 
           #______________________________________________________________________________________________________________ 
     if event.GetId()==11:
       if Form1.chebin==True:
         if  Form1.formcalculate=="Single":
           createBinarios_single(Form1.mapa_entrada)
         else:
           Form1.ListMapsGroupCalc=grass.mlist_grouped ('rast', pattern=Form1.RedularExp) ['PERMANENT']
           createBinarios(Form1.ListMapsGroupCalc)
       
       
     
     
     # 
     d= wx.MessageDialog( self, " Finish calculate \n"
                         " ","Thanks", wx.OK)
                         # Create a message dialog box
     d.ShowModal() # Shows it
     d.Destroy()
 def OnClick(self,event):
     #self.logger.AppendText(" Click on object with Id %d\n" %event.GetId())
     
     #______________________________________________________________________________________________________________ 
     if event.GetId()==10:   #10==START
       if Form1.formcalculate=="Single":
         if Form1.Path==True:   
           pacthSingle(Form1.mapa_entrada)
         if Form1.Frag==True:
           areaFragSingle(Form1.mapa_entrada)
         if Form1.Cone==True:
           areaconSingle(Form1.mapa_entrada)
         if Form1.checEDGE==True:
           create_EDGE_single(Form1.mapa_entrada,Form1.escala_ED,Form1.dirout)
       else:
         Form1.ListMapsGroupCalc=grass.mlist_grouped ('rast', pattern=Form1.RedularExp) ['PERMANENT']
         if Form1.Path==True:
           Form1.ListmapsPath=Path(Form1.ListMapsGroupCalc)
         
         if Form1.Frag==True:
           areaFrag(Form1.ListMapsGroupCalc)
         if Form1.Cone==True:
           areacon(Form1.ListMapsGroupCalc) 
         if Form1.checEDGE==True:
           create_EDGE(Form1.ListMapsGroupCalc,Form1.escala_ED,Form1.dirout)
         
     
     
     
     #______________________________________________________________________________________________________________ 
     if event.GetId()==9:   #9==CHANGE BACKGROUND
       if Form1.plotmovements==1:
         if Form1.formcalculate=="Single":
           x=1
         else:
           self.Refresh()
           Form1.background_filename=Form1.listMapsPng
           Form1.background_filename_start=Form1.background_filename[Form1.contBG]   
           img =Image.open(Form1.background_filename[Form1.contBG])
         
           # redimensionamos sem perder a qualidade
           img = img.resize((Form1.size,Form1.hsize),Image.ANTIALIAS)
           img.save(Form1.background_filename[Form1.contBG])        
         
         
           imageFile=Form1.background_filename[Form1.contBG]
           im1 = Image.open(imageFile)
           jpg1 = wx.Image(imageFile, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
           wx.StaticBitmap(self, -1, jpg1, (380,40), (jpg1.GetWidth(),  jpg1.GetHeight()), style=wx.SIMPLE_BORDER)
                             
           Form1.background_filename=Form1.background_filename_start
           Form1.contBG=Form1.contBG+1
           self.Refresh() 
           if len(Form1.listMapsPng)==Form1.contBG:
             Form1.contBG=0      
             self.Refresh() 
           #______________________________________________________________________________________________________________ 
     if event.GetId()==11:
       if Form1.chebin==True:
         if  Form1.formcalculate=="Single":
           createBinarios_single(Form1.mapa_entrada)
         else:
           Form1.ListMapsGroupCalc=grass.mlist_grouped ('rast', pattern=Form1.RedularExp) ['PERMANENT']
           createBinarios(Form1.ListMapsGroupCalc)
       
       
     
     
     # 
     d= wx.MessageDialog( self, " Finish calculate \n"
                         " ","Thanks", wx.OK)
                         # Create a message dialog box
     d.ShowModal() # Shows it
     d.Destroy()
import re
import fnmatch

#list_tot=grass.mlist_grouped ('rast', pattern='**') ['PERMANENT']
#ls_bu_vzio=[]
#ls_clip_map=[]
#for i in list_tot:
    #if "_clip2K" in i:
        #ls_clip_map.append(i)
    #else:
        #ls_bu_vzio.append(i)





#for i in ls_clip_map:
    #cont_id=0
    #for a in ls_bu_vzio:
        #if "id2__"+`cont_id` in i:
            #grass.run_command("g.region",rast=a)
            ##expressao2="Bin_id2_"+`cont_id`+"="+a+"+"+i
            #grass.run_command("r.series",input=a+","+i,out="Bin_id2_"+`cont_id`,method="sum",overwrite=True)
                      
        #cont_id=cont_id+1    
#
os.chdir(r"E:\data_2015\___john\Gabi_mapeamento_2015_05_d28\paisagens_antigas_DATA1\rasters_serapados_bufer_vazio_e_clip\Mapas_bin")
list_tot=grass.mlist_grouped ('rast', pattern='Bin_id2_*') ['PERMANENT']
for i in list_tot:
    grass.run_command("g.region",rast=i)
    grass.run_command("r.out.gdal",input=i,out=i+".tif",nodata=-9999)
    grass.mapcalc(expression10, overwrite = True, quiet = True)
    expression11=Listmapspath+"_patch=A"
    grass.mapcalc(expression11, overwrite = True, quiet = True)
    #r.colors map=$i"_patch" color=random
    grass.run_command('r.clump',input=Listmapspath+"_patch",output=Listmapspath+"_patch_clump",overwrite = True)
    expression12=Listmapspath+"_patch_clump_mata="+Listmapspath+"_patch_clump*"+Listmapspath
    grass.mapcalc(expression12, overwrite = True, quiet = True)
    expression13=Listmapspath+"_patch_clump_mata_limpa=if("+Listmapspath+"_patch_clump_mata>0,"+Listmapspath+"_patch_clump_mata,null())"
    grass.mapcalc(expression13, overwrite = True, quiet = True)
    txt_reclass=rulesreclass(Listmapspath+"_patch_clump_mata_limpa")
    grass.run_command('r.reclass',input=Listmapspath+"_patch_clump_mata_limpa",output=Listmapspath+"_patch_clump_mata_limpa_AreaHA",rules=txt_reclass,overwrite = True)
    mean(Listmapspath+"_patch_clump_mata_limpa_AreaHA")
    pct_flt(Listmapspath,Listmapspath+"_patch_clump_mata_limpa")
    grass.run_command('g.remove',flags='f',rast='A,MapaBinario,MapaBinario_A,MapaBinario_AB,MapaBinario_ABC,MapaBinario_ABCD')  
    os.remove(txt_reclass)


lista_rasts=grass.mlist_grouped ('rast', pattern='*0250*') ['PERMANENT']
temp=lista_rasts[0:2]
for i in temp:
    out_bin=i+'bin'
    expressao_mata=out_bin+'=if('+i+'==14 |'+i+'==13,'+i+',0)'
    grass.run_command('g.region',rast=i)
    grass.mapcalc(expressao_mata, overwrite = True, quiet = True)
    #print expressao_mata
    create_EDGE_single(out_bin)
    pacthSingle(out_bin)
    heterogeneidade(i)
    indice_antropi(i)
    
  ##print frags
import grass.script as grass
from grass.script import raster as grassR
import os
import string
import glob
import re
import fnmatch

p = grass.mlist_grouped("rast", pattern="(*)")["PERMANENT"]
for i in p:
    if "streams" in i:
        out = i + "_shp"
        out = out.replace("-", "_")
        grass.run_command("g.region", rast=i)
        grass.run_command("r.to.vect", input=i, out=out, feature="line", overwrite=True)
import grass.script as grass
import os
from grass.script import raster as grassR


p = grass.mlist_grouped("rast", pattern="*sem0*")["PERMANENT"]


for i in p:
    grass.run_command("r.to.vect", input=i, out=i + "_vect", feature="area", verbose=False, overwrite=True)
    grass.run_command(
        "v.buffer", input=i + "_vect", output=i + "_vect_buffer", type="point", distance=100, overwrite=True
    )
    grass.run_command("v.build.all")
    grass.run_command(
        "v.to.rast", input=i + "_vect_buffer", out=i + "_vect_buff_rast", use="attr", column="cat", overwrite=True
    )
import grass.script as grass
from grass.script import raster as grassR
import os
import string
import glob
import re
import fnmatch

lista_arquivos = []
LISTA = []
LISTA = []

grupo = grass.mlist_grouped("rast", pattern="**")["PERMANENT"]

for i in grupo:
    exp = i + "New=if(" + i + "==128,null()," + i + ")"
    # print exp
    grass.run_command("g.region", rast=i)
    grass.mapcalc(exp, overwrite=True, quiet=True)
    grass.run_command("g.remove", rast=i, flags="f")
import grass.script as grass
import os
p=grass.mlist_grouped ('rast', pattern='mapa*') ['PERMANENT']
for i in p:
    #print i
    grass.run_command("r.neighbors",input=i,out=i+"_dila_25m",method='maximum',size=11)
    

    
os.chdir("J:\Users\juliana\Documents\RESULTADOS_DOUTORADO\Paisagens_Modelos_Smmal_Mammals\Florestais\Florestais_heterogenea")


lista=[]
lista=os.listdir(r"J:\Users\juliana\Documents\RESULTADOS_DOUTORADO\Paisagens_Modelos_Smmal_Mammals\Florestais\Florestais_heterogenea")

os.getcwd()

c=0

for i in lista:
    temp=i
    grass.run_command( 'g.mapset',  mapset='PERMANENT', location='newLocation', gisdbase='J:\Users\juliana\Documents\RESULTADOS_DOUTORADO\Paisagens_Modelos_Smmal_Mammals\Florestais\Florestais_heterogenea\\'+temp+'\\grass')
   
    #grass.run_command( 'g.region',flags='p')
    p=grass.mlist_grouped ('rast', pattern='Custo_Pai*') ['PERMANENT']
    os.chdir('J:\Users\juliana\Documents\RESULTADOS_DOUTORADO\Paisagens_Modelos_Smmal_Mammals\Florestais\Florestais_heterogenea\saidas_grass')
    inp=p
    outfile=''.join(p)
    grass.run_command('g.region',rast=inp)
    grass.run_command('r.out.gdal',input=inp, out=outfile+'_small_HE.tif', format='GTiff')
    c=c+1
    
    print p
                       #linha2="list=`g.mlist pattern=\"*sem0\" sep=\"comma\"`" "\n" "r.series in=$list out=soma_abertas_"+temp+" method=sum""\n" 
                       #linha3="list=`g.mlist pattern=\"*soma_abertas_"+temp+"\" sep=\"comma\"`" "\n" "g.region rast=$list" "\n" "r.grow.distance in=$list out=distance_abertas_"+temp+" -m" "\n"
                       
                       # linha4="\n" "cd \"F:\data\Juliana_inpe\RESULTADOS_Smmal_Mammals\juliana_teste\saidas\""
                       # linha5="\n""listaex=`g.mlist pattern=\"*distance\"`" "\n" "for i in $" "\n" "do" "\n" "out=`echo $i|awk '{gsub(\"_Bin"",""_Bin.tif\");print}'`" "\n" "r.out.gdal in=$a out=$out format=GTiff nodata=-9999 --v" "\n" "done" "\n"        
    
def heterogeneidade(i):
    grass.run_command('g.region',rast=i)
    # extraindo apensa as classes do mapa
    stats=grass.read_command('r.stats',input=i)
    ListStats=stats.split('\n')
    #-----------------------------------------
    
    
    del ListStats[-1]
    del ListStats[-1]
    lista_multplos2=[]
    #controlado de laco
    y=0
    #---------------------
    
    # criando multplos de 2
    while len(ListStats)>=y:
        if y==0:
            resulti=1
        else:
            resulti=resulti*2
        lista_multplos2.append(resulti)
        y=y+1
    #-----------------------------------------
    
    # controla as classes
    cont_reclasse=0
    lista_jucao_final=[]
    #-----------------------------------------
    
    # esse laco separa cada classe em um mapa
    #dissolv de acordo com aescala
    # e junta tudo no final
    for sts in ListStats:
        #formatando nome de saida
        formatname='000000'+`lista_multplos2[cont_reclasse]`
        
        formatname=formatname[-5:]
        #---------------------------------------------------------------
        
        # criando um mapa para cada classe
        expressao1=i+'_'+formatname+'_bin=if('+i+"=="+sts+","+`lista_multplos2[cont_reclasse]`+',0)'
        
        grass.mapcalc(expressao1, overwrite = True, quiet = True)
        #--------------------------------------------------------
        
        # criando mapa inteiro 
        expressao2=i+'_'+formatname+'_bin_int=int('+i+'_'+formatname+'_bin)'
        grass.mapcalc(expressao2, overwrite = True, quiet = True)
        #--------------------------------------------------
        
        # fazendo a dilatacao
        grass.run_command('g.region',rast=i+'_'+formatname+'_bin_int')
        grass.run_command('r.neighbors',input=i+'_'+formatname+'_bin_int',out=i+'_'+formatname+'_bin_int_dila_50m',method='maximum',size=5,overwrite = True)
        #------------------------
        cont_reclasse=cont_reclasse+1
        
        #removendo mapa de apoio
        grass.run_command('g.remove',flags='f',rast=i+'_'+formatname+'_bin')
        
        #--------------------------------------------------
        
        #incrementando alista de mapas
        lista_jucao_final.append(i+'_'+formatname+'_bin_int_dila_50m') 
        #---------------------------------------------
    
    #somando mapas    
    grass.run_command('r.series',input=lista_jucao_final,out='temp',overwrite = True,method='sum')
    #-------------------------
    
    # criando map inteiro e clipando
    expressao3=i+'_MapaHet_FINAL=int(if('+i+'>0,temp,null()))'
    grass.mapcalc(expressao3, overwrite = True, quiet = True)  
    #--------------------------------------------
    
    #removendo mapa de apoio 
    grass.run_command('g.remove',flags='f',rast='temp')
    
    #atribuindo cor    
    grass.run_command('r.colors',map=i+'_MapaHet_FINAL',color='random')
    #------------------------------------------
    
    
   # exportando mapa
    grass.run_command('r.out.gdal',input=i+'_MapaHet_FINAL',out=i+'_MapaHet_FINAL.tif')
    #------------------------------------------
    
    #removendo mapas
    for rm in lista_jucao_final:
        grass.run_command('g.remove',flags='f',rast=rm)  
    
    # removendo mapas
    lista_remove=grass.mlist_grouped ('rast', pattern='*bin_int*') ['PERMANENT']
    for a in lista_remove:
        grass.run_command('g.remove',flags='f',rast=a) 
                      output=Listmapspath + "_patch_clump_mata_limpa_AreaHA",
                      rules=txt_reclass,
                      overwrite=True)
    mean(Listmapspath + "_patch_clump_mata_limpa_AreaHA")
    pct_flt(Listmapspath, Listmapspath + "_patch_clump_mata_limpa")
    grass.run_command(
        'g.remove',
        flags='f',
        rast=
        'A,MapaBinario,MapaBinario_A,MapaBinario_AB,MapaBinario_ABC,MapaBinario_ABCD'
    )
    #os.remove(txt_reclass)


#---------------------------------------------------------------------------------------------------------------------------------

#---------------------------------------------------------------------------------------------------------------------------------
lista_rasts = grass.mlist_grouped('rast', pattern='*1000*')['PERMANENT']

for i in lista_rasts:
    out_bin = i + 'bin'
    expressao_mata = out_bin + '=if(' + i + '==14 |' + i + '==13,' + i + ',0)'
    grass.run_command('g.region', rast=i)
    grass.mapcalc(expressao_mata, overwrite=True, quiet=True)
    #print expressao_mata
    create_EDGE_single(out_bin)
    pacthSingle(out_bin)
    heterogeneidade(i)
    indice_antropi(i)

#print frags
import grass.script as grass
import os

lista_clumps=grass.mlist_grouped ('rast', pattern='*AreaHA*') ['PERMANENT']
cont_list=0
#for i in lista_clumps:
    #print i
for i in range(300):
    if i>298:
        formato='00000'+`i`
        formato=formato[-4:]        
        query='Unique_id='+`i`
        #grass.run_command('v.build',map='hex_5000_shp')
        #extrai um hegaono
        grass.run_command('v.extract',input='hex_5000_shp',out='temp',where=query,overwrite=True)
        #seta a regiao do hexagono
        grass.run_command('g.region',vect='temp')
        
        #nome de saida do buffer de 8k
        output_buffer='hexag_buffer_50kha_'+formato
        
        #criando buffer de 8k
        grass.run_command('v.buffer',input='temp',out=output_buffer,distance=8000,overwrite=True)
        #criando uma tabela
        grass.run_command('v.db.addtable', map=output_buffer,columns="id integer")
        #conectando a tabela
        grass.run_command('v.db.connect', flags='p',map=output_buffer)    
        
        #extraindo os valors do mapa clump e colocando os valores na tabela de atributo do temp para o hexago de 5ha
        #grass.run_command('v.rast.stats',vector='temp',raster=lista_clumps[cont_list],colprefix='cone',flags='c')
        
def heterogeneidade(i):
    grass.run_command('g.region', rast=i)
    # extraindo apensa as classes do mapa
    stats = grass.read_command('r.stats', input=i)
    ListStats = stats.split('\n')
    #-----------------------------------------

    del ListStats[-1]
    del ListStats[-1]
    lista_multplos2 = []
    #controlado de laco
    y = 0
    #---------------------

    # criando multplos de 2
    while len(ListStats) >= y:
        if y == 0:
            resulti = 1
        else:
            resulti = resulti * 2
        lista_multplos2.append(resulti)
        y = y + 1
    #-----------------------------------------

    # controla as classes
    cont_reclasse = 0
    lista_jucao_final = []
    #-----------------------------------------

    # esse laco separa cada classe em um mapa
    #dissolv de acordo com aescala
    # e junta tudo no final
    for sts in ListStats:
        #formatando nome de saida
        formatname = '000000' + ` lista_multplos2[cont_reclasse] `

        formatname = formatname[-5:]
        #---------------------------------------------------------------

        # criando um mapa para cada classe
        expressao1 = i + '_' + formatname + '_bin=if(' + i + "==" + sts + "," + ` lista_multplos2[
            cont_reclasse] ` + ',0)'

        grass.mapcalc(expressao1, overwrite=True, quiet=True)
        #--------------------------------------------------------

        # criando mapa inteiro
        expressao2 = i + '_' + formatname + '_bin_int=int(' + i + '_' + formatname + '_bin)'
        grass.mapcalc(expressao2, overwrite=True, quiet=True)
        #--------------------------------------------------

        # fazendo a dilatacao
        grass.run_command('g.region', rast=i + '_' + formatname + '_bin_int')
        grass.run_command('r.neighbors',
                          input=i + '_' + formatname + '_bin_int',
                          out=i + '_' + formatname + '_bin_int_dila_50m',
                          method='maximum',
                          size=5,
                          overwrite=True)
        #------------------------
        cont_reclasse = cont_reclasse + 1

        #removendo mapa de apoio
        grass.run_command('g.remove',
                          flags='f',
                          rast=i + '_' + formatname + '_bin')

        #--------------------------------------------------

        #incrementando alista de mapas
        lista_jucao_final.append(i + '_' + formatname + '_bin_int_dila_50m')
        #---------------------------------------------

    #somando mapas
    grass.run_command('r.series',
                      input=lista_jucao_final,
                      out='temp',
                      overwrite=True,
                      method='sum')
    #-------------------------

    # criando map inteiro e clipando
    expressao3 = i + '_MapaHet_FINAL=int(if(' + i + '>0,temp,null()))'
    grass.mapcalc(expressao3, overwrite=True, quiet=True)
    #--------------------------------------------

    #removendo mapa de apoio
    grass.run_command('g.remove', flags='f', rast='temp')

    #atribuindo cor
    grass.run_command('r.colors', map=i + '_MapaHet_FINAL', color='random')
    #------------------------------------------

    # exportando mapa
    grass.run_command('r.out.gdal',
                      input=i + '_MapaHet_FINAL',
                      out=i + '_MapaHet_FINAL.tif')
    #------------------------------------------

    #removendo mapas
    for rm in lista_jucao_final:
        grass.run_command('g.remove', flags='f', rast=rm)

    # removendo mapas
    lista_remove = grass.mlist_grouped('rast',
                                       pattern='*bin_int*')['PERMANENT']
    for a in lista_remove:
        grass.run_command('g.remove', flags='f', rast=a)
import grass.script as grass
from grass.script import raster as grassR
import os
import string
import glob
import re
import fnmatch


ListMapsGroupCalc=grass.mlist_grouped ('rast', pattern='*FLT_bin*') ['PERMANENT']
for i in ListMapsGroupCalc:
    #print i
    expressao=i+'_float='+i+'*1.0'
    grass.mapcalc(expressao, overwrite = True, quiet = True)
    for i in listapoio:
        temp1=i.split(' ')
        cod=int(temp1[0])
        aream2=float(temp1[1])
        area_HA=round(aream2/10000,2)
        fd.write(`cod`+','+`aream2`+','+`area_HA`+'\n')
    fd.close()







grass.run_command('r.mask',flags='r')
lista_classificada=grass.mlist_grouped ('rast', pattern='*classificada_1996*') ['PERMANENT']
lista_buffers=grass.mlist_grouped ('rast', pattern='*buffer_1996_semdissolv*') ['PERMANENT']


escala_edge=[7,19]

for i in lista_classificada:
    os.chdir(r'E:\data_2015\___john\001.Thalita_p2\__Resultados_metricas_parte1')
    folderveg=i[13:19]+'_veg_all'
    folderEd=i[13:19]+'_Edge_all' 
    #print   folderveg
    os.mkdir(folderveg)
    os.mkdir(folderEd)
    x=1
    for a in lista_buffers[0:4]:
        #print i,"*",a
Exemple #38
0
def main():
    if not flags['a'] and not options['input']:
        grass.fatal('Parameter <input> required')

    map_input = []
    map_output = []
    if flags['a']:
        mapset = grass.gisenv()['MAPSET']
        map_input = map_output = grass.mlist_grouped(type = 'vect',
                                                    mapset = mapset)[mapset]
    else:
        map_input = [options['input']]
    
    if not flags['a']:
        if not options['output']:
            map_output = map_input
        else:
            map_output = [options['output']]

    i = 0
    for imap in map_input:
        # determine feature type
        ret = grass.read_command('v.info',
                                 flags = 't',
                                 map = imap)
        if not ret:
            grass.fatal('Unable to get information about vector map <%s>' % imap)
        
        info = {}
        for line in ret.splitlines():
            key, value = line.split('=')
            info[key.strip()] = int(value.strip())
        
        # extension needed?
        fnum = 0
        if info['points'] > 0:
            fnum += 1
        if info['lines'] > 0:
            fnum += 1
        if info['areas'] > 0:
            fnum += 1
        
        for ftype in ('points', 'lines', 'areas'):
            if info[ftype] < 1:
                continue
            
            omap = map_output[i]
            if fnum != 1:
                omap += '_' + ftype
                
            grass.message('Converting <%s> to <%s> (%s)...' % \
                          (imap, omap, ftype))
        
            if grass.overwrite():
                grass.run_command('v.out.ogr',
                                  input = imap,
                                  type = ftype.rstrip('s'),
                                  dsn = "PG:dbname=%s" % options['dbname'],
                                  olayer = omap,
                                  format = 'PostgreSQL',
                                  lco = "OVERWRITE=YES")
            else:
                grass.run_command('v.out.ogr',
                                  input = imap,
                                  type = ftype.rstrip('s'),
                                  dsn = "PG:dbname=%s" % options['dbname'],
                                  olayer = omap,
                                  format = 'PostgreSQL')
        i += 1
    
    return 0
Exemple #39
0
def main():

    os.environ['GRASS_MESSAGE_FORMAT'] = 'silent'
    grass.run_command('g.gisenv', set='OVERWRITE=1')
    mapset = grass.gisenv()['MAPSET']

    parse = OptionParser(usage=usage, description=description)
    parse.add_option('-f',
                     '--force',
                     action="store_true",
                     default=False,
                     help='force the rasterization of the cities vector layer')
    parse.add_option('-c',
                     '--cat',
                     metavar='ID',
                     help='run script on a single city cat ID number')
    parse.add_option('-t',
                     '--maxtime',
                     metavar='MINUTES',
                     default='180',
                     help='sets the max travel time per city')
    parse.add_option('-p',
                     '--pop',
                     metavar='FIELDNAME',
                     default='POP2010',
                     help='name of the population field within cities')
    parse.add_option(
        '-P',
        '--preserve',
        default=False,
        action="store_true",
        help='preserves the individual city travel time maps (city##_tt)')
    parse.add_option('-r',
                     '--rebuild',
                     default=False,
                     action="store_true",
                     help='rebuild city travel time maps even if one exists')
    parse.add_option(
        '-m',
        '--mode',
        default="max",
        help='operate in either max or gravity mode (default=max)')

    opts, args = parse.parse_args()
    if len(args) != 1:
        parse.error("'cities' layer name rquired")
    else:
        cities = args[0]

    if opts.mode == 'grav':
        dest = 'cities_grav'
        method = '$dest=$dest+if(isnull($tt), 0.0, $pop/($tt+0.1)^2)'
    elif opts.mode == 'max':
        dest = 'cities_max'
        method = '$dest=max($dest,if(isnull($tt), 0.0, $pop/($tt+0.1)^2))'
    else:
        parse.error("option mode must be max or gravity")

    # if the cat ID of the city has been given just create the city map
    # NOTE: short-circuits the rest of the script!
    if opts.cat:
        tt = make_city_tt(cities, opts.cat, maxcost=opts.maxtime)
        grass.run_command('g.rename', rast='%s,city%s_tt' % (tt, opts.cat))
        grass.message('city%s_tt: city travel time created.' % opts.cat)
        sys.exit(0)

    grass.mapcalc("$dest=0.0", dest=dest)

    # get all the existing travel time maps
    ttmaps = grass.mlist_grouped('rast', pattern='city*_tt').get(mapset, [])

    # ywkim added to figure out the number of class
    # create the list for the unique class category
    numClass = grass.parse_command('v.db.select',
                                   flags='c',
                                   map=cities,
                                   column='cat,CLASS',
                                   fs='=')
    classList = []
    classUniList = []
    classAveList = []

    for cat, CLASS in numClass.items():
        classList.append(int(CLASS))

    classList.sort()

    classStartValue = 0

    for i in range(len(classList)):
        if classList[i] != classStartValue:
            classUniList.append(classList[i])
            classStartValue = classList[i]

    # create the average number for the class
    for i in range(len(classUniList)):
        totalNum = 0
        indexCounter = 0
        aveVal = 0
        classAve = grass.parse_command('v.db.select',
                                       flags='c',
                                       map=cities,
                                       column='cat,' + opts.pop,
                                       where='CLASS = ' + str(classUniList[i]),
                                       fs='=')

        for cat, pop in classAve.items():
            totalNum = totalNum + int(pop)
            indexCounter = indexCounter + 1

        aveVal = totalNum / indexCounter
        classAveList.append(aveVal)
    """
    ywkim disabled this routine to make it class based routine
    # for each city calculate the accumulated cost surface and
    # convert gavity map by dividing population by cost squared and
    # create a composite map gravity may be summing all maps together
    catpop = grass.parse_command('v.db.select', flags='c', 
        map=cities, column='cat,'+opts.pop, fs='=')

    for cat,pop in catpop.items():
        print cat, pop
        citytt = 'city%s_tt' % cat
        if opts.rebuild or citytt not in ttmaps:
            make_city_tt(cities, cat, maxcost=opts.maxtime)
            if opts.preserve:
                grass.run_command('g.rename', rast='tt,%s' % citytt)
            else:
                citytt = 'tt'
        grass.mapcalc(method, dest=dest, pop=pop, tt=citytt)

    normalize(dest)
    print dest, "created."
    """

    for i in range(len(classUniList)):
        classVal = classUniList[i]
        aveVal = classAveList[i]
        print "Class =  ", classVal, ", Average = ", aveVal
        citytt = 'city%s_tt' % classUniList[i]
        if opts.rebuild or citytt not in ttmaps:
            make_city_tt(cities, classVal, maxcost=opts.maxtime)
            if opts.preserve:
                grass.run_command('g.rename', rast='tt,%s' % citytt)
            else:
                citytt = 'tt'
        grass.mapcalc(method, dest=dest, pop=aveVal, tt=citytt)

    normalize(dest)
    print dest, "created."
from grass.script import raster as grassR
import os
import string
import glob
import re
import fnmatch


'''
para cada paisagem(buffer) separadamente, foram extraidas algumas metricas de conectividade
sendo elas: conectividade funcional, fragmentacao e area de fragmento.

'''

#---------------------------------------------------------------------------------------------------------------------------------------------------------------
lista_classificada_FRAG120m_mata_clump_AreaHA=grass.mlist_grouped ('rast', pattern='*FRAG120m_mata_clump_AreaHA*') ['PERMANENT']
lista_classificada_FRAG60m_mata_clump_AreaHA=grass.mlist_grouped ('rast', pattern='*FRAG60m_mata_clump_AreaHA*') ['PERMANENT']
lista_classificada_patch_clump_mata_limpa_AreaHA=grass.mlist_grouped ('rast', pattern='*patch_clump_mata_limpa_AreaHA*') ['PERMANENT']
lista_classificada_dila_120m_orig_clump_mata_limpa_AreaHA=grass.mlist_grouped ('rast', pattern='*dila_120m_orig_clump_mata_limpa_AreaHA*') ['PERMANENT']
lista_classificada_dila_60m_orig_clump_mata_limpa_AreaHA=grass.mlist_grouped ('rast', pattern='*dila_60m_orig_clump_mata_limpa_AreaHA*') ['PERMANENT']
#---------------------------------------------------------------------------------------------------------------------------------------------------------------

"""
Criando grupo de vetor de 2014
"""
#---------------------------------------------------------------------------------------------------------------------------------------------------------------
lista_vectors_outrostemp=grass.mlist_grouped ('vect', pattern='**') ['PERMANENT']
lista_vectors_outros=[]
#---------------------------------------------------------------------------------------------------------------------------------------------------------------

def main():

    os.environ['GRASS_MESSAGE_FORMAT'] = 'silent'
    grass.run_command('g.gisenv', set='OVERWRITE=1')
    mapset = grass.gisenv()['MAPSET']

    parse = OptionParser(usage=usage, description=description)
    parse.add_option('-f', '--force', action="store_true", default=False,
        help='force the rasterization of the cities vector layer')
    parse.add_option('-c', '--cat', metavar='ID',
        help='run script on a single city cat ID number')
    parse.add_option('-t', '--maxtime', metavar='MINUTES', default='60',
        help='sets the max travel time per city')
    parse.add_option('-p', '--pop', metavar='FIELDNAME', default='POP2010',
        help='name of the population field within cities')
    parse.add_option('-P', '--preserve', default=False, action="store_true",
        help='preserves the individual city travel time maps (city##_tt)')
    parse.add_option('-r', '--rebuild', default=False, action="store_true",
        help='rebuild city travel time maps even if one exists')
    parse.add_option('-m', '--mode', default="max",
        help='operate in either max or gravity mode (default=max)')

    opts, args = parse.parse_args()
    if len(args) != 1:
        parse.error("'cities' layer name rquired")
    else:
        cities = args[0]

    if opts.mode == 'grav':
        dest = 'cities_grav'
        method = '$dest=$dest+if(isnull($tt), 0.0, $pop/($tt+0.1)^2)'
    elif opts.mode == 'max':
        dest = 'cities_max'
        method = '$dest=max($dest,if(isnull($tt), 0.0, $pop/($tt+0.1)^2))'
    else:
        parse.error("option mode must be max or gravity")

    # if the cat ID of the city has been given just create the city map
    # NOTE: short-circuits the rest of the script!
    if opts.cat:
        tt = make_city_tt(cities, opts.cat, maxcost=opts.maxtime)
        grass.run_command('g.rename', rast='%s,city%s_tt' % (tt,opts.cat))
        grass.message('city%s_tt: city travel time created.' % opts.cat)
        sys.exit(0)


    grass.mapcalc("$dest=0.0", dest=dest)

    # get all the existing travel time maps
    ttmaps = grass.mlist_grouped('rast', pattern='city*_tt').get(mapset,[])

    # for each city calculate the accumulated cost surface and
    # convert gavity map by dividing population by cost squared and
    # create a composite map gravity may be summing all maps together
    catpop = grass.parse_command('v.db.select', flags='c', 
        map=cities, column='cat,'+opts.pop, fs='=')

    for cat,pop in catpop.items():
        print cat, pop
        citytt = 'city%s_tt' % cat
        if opts.rebuild or citytt not in ttmaps:
            make_city_tt(cities, cat, maxcost=opts.maxtime)
            if opts.preserve:
                grass.run_command('g.rename', rast='tt,%s' % citytt)
            else:
                citytt = 'tt'
        grass.mapcalc(method, dest=dest, pop=pop, tt=citytt)

    normalize(dest)
    print dest, "created."