Changeset 23670


Ignore:
Timestamp:
01/31/19 07:34:11 (6 years ago)
Author:
bdef
Message:

CHG: python scripts after 2to3 and indentation fix

Location:
issm/trunk-jpl/src/py3
Files:
154 edited

Legend:

Unmodified
Added
Removed
  • issm/trunk-jpl/src/py3/boundaryconditions/PattynSMB.py

    r21255 r23670  
    11import os
    2 import numpy as np
     2import numpy as  np
    33def PattynSMB(md,Tf):
    44        """
  • issm/trunk-jpl/src/py3/boundaryconditions/SetIceSheetBC.py

    r19895 r23670  
    11import os
    2 import numpy
     2import numpy as np
    33from ContourToMesh import ContourToMesh
    44
     
    1414
    1515        #node on Dirichlet
    16         pos=numpy.nonzero(md.mesh.vertexonboundary)
    17         md.stressbalance.spcvx=float('nan')*numpy.ones(md.mesh.numberofvertices)
    18         md.stressbalance.spcvy=float('nan')*numpy.ones(md.mesh.numberofvertices)
    19         md.stressbalance.spcvz=float('nan')*numpy.ones(md.mesh.numberofvertices)
     16        pos=np.nonzero(md.mesh.vertexonboundary)
     17        md.stressbalance.spcvx=float('nan')*np.ones((md.mesh.numberofvertices))
     18        md.stressbalance.spcvy=float('nan')*np.ones((md.mesh.numberofvertices))
     19        md.stressbalance.spcvz=float('nan')*np.ones((md.mesh.numberofvertices))
    2020        md.stressbalance.spcvx[pos]=0
    2121        md.stressbalance.spcvy[pos]=0
    2222        md.stressbalance.spcvz[pos]=0
    23         md.stressbalance.referential=float('nan')*numpy.ones((md.mesh.numberofvertices,6))
    24         md.stressbalance.loadingforce=0*numpy.ones((md.mesh.numberofvertices,3))
     23        md.stressbalance.referential=float('nan')*np.ones((md.mesh.numberofvertices,6))
     24        md.stressbalance.loadingforce=0*np.ones((md.mesh.numberofvertices,3))
    2525
    2626        #Dirichlet Values
    27         if isinstance(md.inversion.vx_obs,numpy.ndarray) and numpy.size(md.inversion.vx_obs,axis=0)==md.mesh.numberofvertices and isinstance(md.inversion.vy_obs,numpy.ndarray) and numpy.size(md.inversion.vy_obs,axis=0)==md.mesh.numberofvertices:
     27        if isinstance(md.inversion.vx_obs,np.ndarray) and np.size(md.inversion.vx_obs,axis=0)==md.mesh.numberofvertices and isinstance(md.inversion.vy_obs,np.ndarray) and np.size(md.inversion.vy_obs,axis=0)==md.mesh.numberofvertices:
    2828                print("      boundary conditions for stressbalance model: spc set as observed velocities")
    2929                md.stressbalance.spcvx[pos]=md.inversion.vx_obs[pos]
     
    3939
    4040        #Deal with other boundary conditions
    41         if numpy.all(numpy.isnan(md.balancethickness.thickening_rate)):
    42                 md.balancethickness.thickening_rate=numpy.zeros((md.mesh.numberofvertices,1))
     41        if np.all(np.isnan(md.balancethickness.thickening_rate)):
     42                md.balancethickness.thickening_rate=np.zeros((md.mesh.numberofvertices))
    4343                print("      no balancethickness.thickening_rate specified: values set as zero")
    44         md.masstransport.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
    45         md.balancethickness.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
    46         md.damage.spcdamage=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
     44        md.masstransport.spcthickness=float('nan')*np.ones((md.mesh.numberofvertices))
     45        md.balancethickness.spcthickness=float('nan')*np.ones((md.mesh.numberofvertices))
     46        md.damage.spcdamage=float('nan')*np.ones((md.mesh.numberofvertices))
    4747
    48         if isinstance(md.initialization.temperature,numpy.ndarray) and numpy.size(md.initialization.temperature,axis=0)==md.mesh.numberofvertices:
    49                 md.thermal.spctemperature=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
     48        if isinstance(md.initialization.temperature,np.ndarray) and np.size(md.initialization.temperature,axis=0)==md.mesh.numberofvertices:
     49                md.thermal.spctemperature=float('nan')*np.ones((md.mesh.numberofvertices))
    5050                if hasattr(md.mesh,'vertexonsurface'):
    51                         pos=numpy.nonzero(md.mesh.vertexonsurface)[0]
     51                        pos=np.nonzero(md.mesh.vertexonsurface)[0]
    5252                        md.thermal.spctemperature[pos]=md.initialization.temperature[pos]    #impose observed temperature on surface
    53                 if not isinstance(md.basalforcings.geothermalflux,numpy.ndarray) or not numpy.size(md.basalforcings.geothermalflux)==md.mesh.numberofvertices:
    54                         md.basalforcings.geothermalflux=50.*10**-3*numpy.ones((md.mesh.numberofvertices,1))    #50 mW/m^2
     53                if not isinstance(md.basalforcings.geothermalflux,np.ndarray) or not np.size(md.basalforcings.geothermalflux)==md.mesh.numberofvertices:
     54                        md.basalforcings.geothermalflux=50.*10**-3*np.ones((md.mesh.numberofvertices))    #50 mW/m^2
    5555        else:
    5656                print("      no thermal boundary conditions created: no observed temperature found")
  • issm/trunk-jpl/src/py3/boundaryconditions/SetIceShelfBC.py

    r19895 r23670  
    11import os
    2 import numpy
     2import numpy as np
    33from ContourToMesh import ContourToMesh
    44import MatlabFuncs as m
     
    2626                if not os.path.exists(icefrontfile):
    2727                        raise IOError("SetIceShelfBC error message: ice front file '%s' not found." % icefrontfile)
    28                 [nodeinsideicefront,dum]=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,icefrontfile,'node',2)
    29                 nodeonicefront=numpy.logical_and(md.mesh.vertexonboundary,nodeinsideicefront.reshape(-1))
     28                nodeinsideicefront=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,icefrontfile,'node',2)
     29                nodeonicefront=np.logical_and(md.mesh.vertexonboundary,nodeinsideicefront.reshape(-1))
    3030        else:
    31                 nodeonicefront=numpy.zeros((md.mesh.numberofvertices),bool)
     31                nodeonicefront=np.zeros((md.mesh.numberofvertices),bool)
    3232
    3333#       pos=find(md.mesh.vertexonboundary & ~nodeonicefront);
    34         pos=numpy.nonzero(numpy.logical_and(md.mesh.vertexonboundary,numpy.logical_not(nodeonicefront)))[0]
    35         md.stressbalance.spcvx=float('nan')*numpy.ones(md.mesh.numberofvertices)
    36         md.stressbalance.spcvy=float('nan')*numpy.ones(md.mesh.numberofvertices)
    37         md.stressbalance.spcvz=float('nan')*numpy.ones(md.mesh.numberofvertices)
    38         md.stressbalance.referential=float('nan')*numpy.ones((md.mesh.numberofvertices,6))
    39         md.stressbalance.loadingforce=0*numpy.ones((md.mesh.numberofvertices,3))
     34        pos=np.nonzero(np.logical_and(md.mesh.vertexonboundary,np.logical_not(nodeonicefront)))[0]
     35        md.stressbalance.spcvx=float('nan')*np.ones(md.mesh.numberofvertices)
     36        md.stressbalance.spcvy=float('nan')*np.ones(md.mesh.numberofvertices)
     37        md.stressbalance.spcvz=float('nan')*np.ones(md.mesh.numberofvertices)
     38        md.stressbalance.referential=float('nan')*np.ones((md.mesh.numberofvertices,6))
     39        md.stressbalance.loadingforce=0*np.ones((md.mesh.numberofvertices,3))
    4040
    4141        #Icefront position
    42         pos=numpy.nonzero(nodeonicefront)[0]
     42        pos=np.nonzero(nodeonicefront)[0]
    4343        md.mask.ice_levelset[pos]=0
    4444
     
    5353                values=md.mask.ice_levelset[md.mesh.segments[:,0:-1]-1]
    5454                segmentsfront=1-values
    55                 numpy.sum(segmentsfront,axis=1)!=numbernodesfront
    56                 segments=numpy.nonzero(numpy.sum(segmentsfront,axis=1)!=numbernodesfront)[0]
     55                np.sum(segmentsfront,axis=1)!=numbernodesfront
     56                segments=np.nonzero(np.sum(segmentsfront,axis=1)!=numbernodesfront)[0]
    5757                #Find all nodes for these segments and spc them
    5858                pos=md.mesh.segments[segments,0:-1]-1
    5959        else:
    60                 pos=numpy.nonzero(md.mesh.vertexonboundary)[0]
     60                pos=np.nonzero(md.mesh.vertexonboundary)[0]
    6161        md.stressbalance.spcvx[pos]=0
    6262        md.stressbalance.spcvy[pos]=0
     
    6464                                                                                                                                                                                                                                           
    6565        #Dirichlet Values
    66         if isinstance(md.inversion.vx_obs,numpy.ndarray) and numpy.size(md.inversion.vx_obs,axis=0)==md.mesh.numberofvertices and isinstance(md.inversion.vy_obs,numpy.ndarray) and numpy.size(md.inversion.vy_obs,axis=0)==md.mesh.numberofvertices:
     66        if isinstance(md.inversion.vx_obs,np.ndarray) and np.size(md.inversion.vx_obs,axis=0)==md.mesh.numberofvertices and isinstance(md.inversion.vy_obs,np.ndarray) and np.size(md.inversion.vy_obs,axis=0)==md.mesh.numberofvertices:
    6767                #reshape to rank-2 if necessary to match spc arrays
    68                 if numpy.ndim(md.inversion.vx_obs)==1:
    69                         md.inversion.vx_obs=md.inversion.vx_obs.reshape(-1,1)
    70                 if numpy.ndim(md.inversion.vy_obs)==1:
    71                         md.inversion.vy_obs=md.inversion.vy_obs.reshape(-1,1)
     68                if np.ndim(md.inversion.vx_obs)==1:
     69                        md.inversion.vx_obs=md.inversion.vx_obs.reshape(-1,)
     70                if np.ndim(md.inversion.vy_obs)==1:
     71                        md.inversion.vy_obs=md.inversion.vy_obs.reshape(-1,)
    7272                print("      boundary conditions for stressbalance model: spc set as observed velocities")
    7373                md.stressbalance.spcvx[pos]=md.inversion.vx_obs[pos]
     
    8181
    8282        #Deal with other boundary conditions
    83         if numpy.all(numpy.isnan(md.balancethickness.thickening_rate)):
    84                 md.balancethickness.thickening_rate=numpy.zeros((md.mesh.numberofvertices,1))
     83        if np.all(np.isnan(md.balancethickness.thickening_rate)):
     84                md.balancethickness.thickening_rate=np.zeros((md.mesh.numberofvertices))
    8585                print("      no balancethickness.thickening_rate specified: values set as zero")
    86         md.masstransport.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
    87         md.balancethickness.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
    88         md.damage.spcdamage=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
     86        md.masstransport.spcthickness=float('nan')*np.ones((md.mesh.numberofvertices))
     87        md.balancethickness.spcthickness=float('nan')*np.ones((md.mesh.numberofvertices))
     88        md.damage.spcdamage=float('nan')*np.ones((md.mesh.numberofvertices))
    8989
    90         if isinstance(md.initialization.temperature,numpy.ndarray) and numpy.size(md.initialization.temperature,axis=0)==md.mesh.numberofvertices:
    91                 md.thermal.spctemperature=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
     90        if isinstance(md.initialization.temperature,np.ndarray) and np.size(md.initialization.temperature,axis=0)==md.mesh.numberofvertices:
     91                md.thermal.spctemperature=float('nan')*np.ones((md.mesh.numberofvertices))
    9292                if hasattr(md.mesh,'vertexonsurface'):
    93                         pos=numpy.nonzero(md.mesh.vertexonsurface)[0]
     93                        pos=np.nonzero(md.mesh.vertexonsurface)[0]
    9494                        md.thermal.spctemperature[pos]=md.initialization.temperature[pos]    #impose observed temperature on surface
    95                 if not isinstance(md.basalforcings.geothermalflux,numpy.ndarray) or not numpy.size(md.basalforcings.geothermalflux,axis=0)==md.mesh.numberofvertices:
    96                         md.basalforcings.geothermalflux=numpy.zeros((md.mesh.numberofvertices,1))
     95                if not isinstance(md.basalforcings.geothermalflux,np.ndarray) or not np.size(md.basalforcings.geothermalflux,axis=0)==md.mesh.numberofvertices:
     96                        md.basalforcings.geothermalflux=np.zeros((md.mesh.numberofvertices))
    9797        else:
    9898                print("      no thermal boundary conditions created: no observed temperature found")
  • issm/trunk-jpl/src/py3/boundaryconditions/SetMarineIceSheetBC.py

    r19895 r23670  
    11import os
    2 import numpy
     2import numpy as np
    33from ContourToMesh import ContourToMesh
    44import MatlabFuncs as m
     
    2828                if not os.path.exists(icefrontfile):
    2929                        raise IOError("SetMarineIceSheetBC error message: ice front file '%s' not found." % icefrontfile)
    30                 [incontour,dum]=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,icefrontfile,'node',2)
    31                 vertexonicefront=numpy.logical_and(md.mesh.vertexonboundary,incontour.reshape(-1))
     30                incontour=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,icefrontfile,'node',2)
     31                vertexonicefront=np.logical_and(md.mesh.vertexonboundary,incontour.reshape(-1))
    3232        else:
    3333                #Guess where the ice front is
    34                 vertexonfloatingice=numpy.zeros((md.mesh.numberofvertices,1))
    35                 pos=numpy.nonzero(numpy.sum(md.mask.groundedice_levelset[md.mesh.elements-1]<0.,axis=1) >0.)[0]
     34                vertexonfloatingice=np.zeros((md.mesh.numberofvertices))
     35                pos=np.nonzero(np.sum(md.mask.groundedice_levelset[md.mesh.elements-1]<0.,axis=1) >0.)[0]
    3636                vertexonfloatingice[md.mesh.elements[pos].astype(int)-1]=1.
    37                 vertexonicefront=numpy.logical_and(numpy.reshape(md.mesh.vertexonboundary,(-1,1)),vertexonfloatingice>0.)
     37                vertexonicefront=np.logical_and(np.reshape(md.mesh.vertexonboundary,(-1,)),vertexonfloatingice>0.)
    3838
    3939#       pos=find(md.mesh.vertexonboundary & ~vertexonicefront);
    40         pos=numpy.nonzero(numpy.logical_and(md.mesh.vertexonboundary,numpy.logical_not(vertexonicefront)))[0]
    41         if not numpy.size(pos):
     40        pos=np.nonzero(np.logical_and(md.mesh.vertexonboundary,np.logical_not(vertexonicefront)))[0]
     41        if not np.size(pos):
    4242                print("SetMarineIceSheetBC warning: ice front all around the glacier, no dirichlet found. Dirichlet must be added manually.")
    4343
    44         md.stressbalance.spcvx=float('nan')*numpy.ones(md.mesh.numberofvertices)
    45         md.stressbalance.spcvy=float('nan')*numpy.ones(md.mesh.numberofvertices)
    46         md.stressbalance.spcvz=float('nan')*numpy.ones(md.mesh.numberofvertices)
    47         md.stressbalance.referential=float('nan')*numpy.ones((md.mesh.numberofvertices,6))
    48         md.stressbalance.loadingforce=0*numpy.ones((md.mesh.numberofvertices,3))
     44        md.stressbalance.spcvx=float('nan')*np.ones(md.mesh.numberofvertices)
     45        md.stressbalance.spcvy=float('nan')*np.ones(md.mesh.numberofvertices)
     46        md.stressbalance.spcvz=float('nan')*np.ones(md.mesh.numberofvertices)
     47        md.stressbalance.referential=float('nan')*np.ones((md.mesh.numberofvertices,6))
     48        md.stressbalance.loadingforce=0*np.ones((md.mesh.numberofvertices,3))
    4949
    5050        #Position of ice front
    51         pos=numpy.nonzero(vertexonicefront)[0]
     51        pos=np.nonzero(vertexonicefront)[0]
    5252        md.mask.ice_levelset[pos]=0
    5353
     
    6262                values=md.mask.ice_levelset[md.mesh.segments[:,0:-1]-1]
    6363                segmentsfront=1-values
    64                 numpy.sum(segmentsfront,axis=1)!=numbernodesfront
    65                 segments=numpy.nonzero(numpy.sum(segmentsfront,axis=1)!=numbernodesfront)[0]
     64                np.sum(segmentsfront,axis=1)!=numbernodesfront
     65                segments=np.nonzero(np.sum(segmentsfront,axis=1)!=numbernodesfront)[0]
    6666                #Find all nodes for these segments and spc them
    6767                pos=md.mesh.segments[segments,0:-1]-1
    6868        else:
    69                 pos=numpy.nonzero(md.mesh.vertexonboundary)[0]
     69                pos=np.nonzero(md.mesh.vertexonboundary)[0]
    7070        md.stressbalance.spcvx[pos]=0
    7171        md.stressbalance.spcvy[pos]=0
     
    7373
    7474        #Dirichlet Values
    75         if isinstance(md.inversion.vx_obs,numpy.ndarray) and numpy.size(md.inversion.vx_obs,axis=0)==md.mesh.numberofvertices and isinstance(md.inversion.vy_obs,numpy.ndarray) and numpy.size(md.inversion.vy_obs,axis=0)==md.mesh.numberofvertices:
     75        if isinstance(md.inversion.vx_obs,np.ndarray) and np.size(md.inversion.vx_obs,axis=0)==md.mesh.numberofvertices and isinstance(md.inversion.vy_obs,np.ndarray) and np.size(md.inversion.vy_obs,axis=0)==md.mesh.numberofvertices:
    7676                print("      boundary conditions for stressbalance model: spc set as observed velocities")
    7777                md.stressbalance.spcvx[pos]=md.inversion.vx_obs[pos]
     
    8080                print("      boundary conditions for stressbalance model: spc set as zero")
    8181
    82         md.hydrology.spcwatercolumn=numpy.zeros((md.mesh.numberofvertices,2))
    83         pos=numpy.nonzero(md.mesh.vertexonboundary)[0]
     82        md.hydrology.spcwatercolumn=np.zeros((md.mesh.numberofvertices,2))
     83        pos=np.nonzero(md.mesh.vertexonboundary)[0]
    8484        md.hydrology.spcwatercolumn[pos,0]=1
    8585
     
    8989
    9090        #Deal with other boundary conditions
    91         if numpy.all(numpy.isnan(md.balancethickness.thickening_rate)):
    92                 md.balancethickness.thickening_rate=numpy.zeros((md.mesh.numberofvertices,1))
     91        if np.all(np.isnan(md.balancethickness.thickening_rate)):
     92                md.balancethickness.thickening_rate=np.zeros((md.mesh.numberofvertices))
    9393                print("      no balancethickness.thickening_rate specified: values set as zero")
    9494
    95         md.masstransport.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
    96         md.balancethickness.spcthickness=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
    97         md.damage.spcdamage=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
     95        md.masstransport.spcthickness=float('nan')*np.ones((md.mesh.numberofvertices))
     96        md.balancethickness.spcthickness=float('nan')*np.ones((md.mesh.numberofvertices))
     97        md.damage.spcdamage=float('nan')*np.ones((md.mesh.numberofvertices))
    9898
    99         if isinstance(md.initialization.temperature,numpy.ndarray) and numpy.size(md.initialization.temperature,axis=0)==md.mesh.numberofvertices:
    100                 md.thermal.spctemperature=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
     99        if isinstance(md.initialization.temperature,np.ndarray) and np.size(md.initialization.temperature,axis=0)==md.mesh.numberofvertices:
     100                md.thermal.spctemperature=float('nan')*np.ones((md.mesh.numberofvertices))
    101101                if hasattr(md.mesh,'vertexonsurface'):
    102                         pos=numpy.nonzero(md.mesh.vertexonsurface)[0]
     102                        pos=np.nonzero(md.mesh.vertexonsurface)[0]
    103103                        md.thermal.spctemperature[pos]=md.initialization.temperature[pos]    #impose observed temperature on surface
    104                 if not isinstance(md.basalforcings.geothermalflux,numpy.ndarray) or not numpy.size(md.basalforcings.geothermalflux,axis=0)==md.mesh.numberofvertices:
    105                         md.basalforcings.geothermalflux=numpy.zeros((md.mesh.numberofvertices,1))
    106                         md.basalforcings.geothermalflux[numpy.nonzero(md.mask.groundedice_levelset>0.)]=50.*10.**-3    #50mW/m2
     104                if not isinstance(md.basalforcings.geothermalflux,np.ndarray) or not np.size(md.basalforcings.geothermalflux,axis=0)==md.mesh.numberofvertices:
     105                        md.basalforcings.geothermalflux=np.zeros((md.mesh.numberofvertices))
     106                        md.basalforcings.geothermalflux[np.nonzero(md.mask.groundedice_levelset>0.)]=50.*10.**-3    #50mW/m2
    107107        else:
    108108                print("      no thermal boundary conditions created: no observed temperature found")
  • issm/trunk-jpl/src/py3/classes/SMBcomponents.py

    r19898 r23670  
    11from fielddisplay import fielddisplay
    2 from EnumDefinitions import *
    32from checkfield import *
    43from project3d import *
     
    3938        def initialize(self,md): # {{{
    4039
    41                 if numpy.all(numpy.isnan(self.accumulation)):
    42                         self.accumulation=numpy.zeros((md.mesh.numberofvertices,1))
     40                if np.all(np.isnan(self.accumulation)):
     41                        self.accumulation=np.zeros((md.mesh.numberofvertices))
    4342                        print("      no SMB.accumulation specified: values set as zero")
    4443
    45                 if numpy.all(numpy.isnan(self.runoff)):
    46                         self.runoff=numpy.zeros((md.mesh.numberofvertices,1))
     44                if np.all(np.isnan(self.runoff)):
     45                        self.runoff=np.zeros((md.mesh.numberofvertices))
    4746                        print("      no SMB.runoff specified: values set as zero")
    4847
    49                 if numpy.all(numpy.isnan(self.evaporation)):
    50                         self.evaporation=numpy.zeros((md.mesh.numberofvertices,1))
     48                if np.all(np.isnan(self.evaporation)):
     49                        self.evaporation=np.zeros((md.mesh.numberofvertices))
    5150                        print("      no SMB.evaporation specified: values set as zero")
    5251
     
    5554        def checkconsistency(self,md,solution,analyses):    # {{{
    5655
    57                 if MasstransportAnalysisEnum() in analyses:
     56                if 'MasstransportAnalysis' in analyses:
    5857                        md = checkfield(md,'fieldname','smb.accumulation','timeseries',1,'NaN',1,'Inf',1)
    5958
    60                 if BalancethicknessAnalysisEnum() in analyses:
     59                if 'BalancethicknessAnalysis' in analyses:
    6160                        md = checkfield(md,'fieldname','smb.accumulation','size',[md.mesh.numberofvertices],'NaN',1,'Inf',1)
    6261
    63                 if MasstransportAnalysisEnum() in analyses:
     62                if 'MasstransportAnalysis' in analyses:
    6463                        md = checkfield(md,'fieldname','smb.runoff','timeseries',1,'NaN',1,'Inf',1)
    6564
    66                 if BalancethicknessAnalysisEnum() in analyses:
     65                if 'BalancethicknessAnalysis' in analyses:
    6766                        md = checkfield(md,'fieldname','smb.runoff','size',[md.mesh.numberofvertices],'NaN',1,'Inf',1)
    6867
    69                 if MasstransportAnalysisEnum() in analyses:
     68                if 'MasstransportAnalysis' in analyses:
    7069                        md = checkfield(md,'fieldname','smb.evaporation','timeseries',1,'NaN',1,'Inf',1)
    7170
    72                 if BalancethicknessAnalysisEnum() in analyses:
     71                if 'BalancethicknessAnalysis' in analyses:
    7372                        md = checkfield(md,'fieldname','smb.evaporation','size',[md.mesh.numberofvertices],'NaN',1,'Inf',1)
    7473               
     
    7776                return md
    7877        # }}}
    79         def marshall(self,md,fid):    # {{{
     78        def marshall(self,prefix,md,fid):    # {{{
    8079
    81                 yts=365.0*24.0*3600.0
     80                yts=md.constants.yts
    8281
    83                 WriteData(fid,'enum',SmbEnum(),'data',SMBcomponentsEnum(),'format','Integer');
    84                 WriteData(fid,'object',self,'class','smb','fieldname','accumulation','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
    85                 WriteData(fid,'object',self,'class','smb','fieldname','runoff','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
    86                 WriteData(fid,'object',self,'class','smb','fieldname','evaporation','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
     82                WriteData(fid,prefix,'name','md.smb.model','data',2,'format','Integer');
     83                WriteData(fid,prefix,'object',self,'class','smb','fieldname','accumulation','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     84                WriteData(fid,prefix,'object',self,'class','smb','fieldname','runoff','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     85                WriteData(fid,prefix,'object',self,'class','smb','fieldname','evaporation','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
    8786               
    8887                #process requested outputs
     
    9291                        outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:]
    9392                        outputs    =outputscopy
    94                 WriteData(fid,'data',outputs,'enum',SmbRequestedOutputsEnum(),'format','StringArray')
     93                WriteData(fid,prefix,'data',outputs,'name','md.smb.requested_outputs','format','StringArray')
    9594
    9695        # }}}
  • issm/trunk-jpl/src/py3/classes/SMBd18opdd.py

    r19898 r23670  
    1 import numpy
     1import numpy as np
    22from fielddisplay import fielddisplay
    3 from EnumDefinitions import *
    43from checkfield import checkfield
    54from WriteData import WriteData
     
    2120                self.rlapslgm                  = 0.
    2221                self.dpermil                   = 0.
     22                self.f                         = 0.
    2323                self.Tdiff                     = float('NaN')
    2424                self.sealev                    = float('NaN')
    2525                self.ismungsm                  = 0
    2626                self.isd18opd                  = 0
     27                self.issetpddfac               = 0
     28                self.istemperaturescaled       = 0
     29                self.isprecipscaled            = 0
    2730                self.delta18o                  = float('NaN')
    2831                self.delta18o_surface          = float('NaN')
    2932                self.temperatures_presentday   = float('NaN')
    3033                self.precipitations_presentday = float('NaN')
     34                self.temperatures_reconstructed   = float('NaN')
     35                self.precipitations_reconstructed = float('NaN')
     36                self.pddfac_snow               = float('NaN')
     37                self.pddfac_ice                = float('NaN')
    3138
    3239                #set defaults
     
    3845
    3946                string="%s\n%s"%(string,fielddisplay(self,'isd18opd','is delta18o parametrisation from present day temperature and precipitation activated (0 or 1, default is 0)'))
     47                string="%s\n%s"%(string,fielddisplay(self,'issetpddfac','is user passing in defined pdd factors at each vertex (0 or 1, default is 0)'))
    4048                string="%s\n%s"%(string,fielddisplay(self,'desfac','desertification elevation factor (between 0 and 1, default is 0.5) [m]'))
    4149                string="%s\n%s"%(string,fielddisplay(self,'s0p','should be set to elevation from precip source (between 0 and a few 1000s m, default is 0) [m]'))
     
    4553                        string="%s\n%s"%(string,fielddisplay(self,'temperatures_presentday','monthly present day surface temperatures [K], required if delta18o/mungsm is activated'))
    4654                        string="%s\n%s"%(string,fielddisplay(self,'precipitations_presentday','monthly surface precipitation [m/yr water eq], required if delta18o or mungsm is activated'))
     55                        string="%s\n%s"%(string,fielddisplay(self,'istemperaturescaled','if delta18o parametrisation from present day temperature and precipitation is activated, is temperature scaled to delta18o value? (0 or 1, default is 1)'))
     56                        string="%s\n%s"%(string,fielddisplay(self,'isprecipscaled','if delta18o parametrisation from present day temperature and precipitation is activated, is precipitation scaled to delta18o value? (0 or 1, default is 1)'))
     57                       
     58                        if self.istemperaturescaled==0:
     59                                string="%s\n%s"%(string,fielddisplay(self,'temperatures_reconstructed','monthly historical surface temperatures [K], required if delta18o/mungsm/d18opd is activated and istemperaturescaled is not activated'))
     60                               
     61                        if self.isprecipscaled==0:
     62                                string="%s\n%s"%(string,fielddisplay(self,'precipitations_reconstructed','monthly historical precipitation [m/yr water eq], required if delta18o/mungsm/d18opd is activated and isprecipscaled is not activated'))
     63
    4764                        string="%s\n%s"%(string,fielddisplay(self,'delta18o','delta18o [per mil], required if pdd is activated and delta18o activated'))
    4865                        string="%s\n%s"%(string,fielddisplay(self,'dpermil','degree per mil, required if d18opd is activated'))
     66                        string="%s\n%s"%(string,fielddisplay(self,'f','precip/temperature scaling factor, required if d18opd is activated'))
     67
     68                if self.issetpddfac==1:
     69                        string="%s\n%s"%(string,fielddisplay(self,'pddfac_snow','Pdd factor for snow, at each vertex [mm ice equiv/day/degree C]'))
     70                        string="%s\n%s"%(string,fielddisplay(self,'pddfac_ice','Pdd factor for ice, at each vertex [mm ice equiv/day/degree C]'))
    4971                string="%s\n%s"%(string,fielddisplay(self,'requested_outputs','additional outputs requested'))
    5072
     
    5577                if self.isd18opd: self.temperatures_presentday=project3d(md,'vector',self.temperatures_presentday,'type','node')
    5678                if self.isd18opd: self.precipitations_presentday=project3d(md,'vector',self.precipitations_presentday,'type','node')
     79                if self.istemperaturescaled==0: self.temperatures_reconstructed=project3d(md,'vector',self.temperatures_reconstructed,'type','node')
     80                if self.isprecipscaled==0: self.temperatures_reconstructed=project3d(md,'vector',self.precipitations_reconstructed,'type','node')
     81                if self.isd18opd: self.precipitations_presentday=project3d(md,'vector',self.precipitations_presentday,'type','node')
     82                if self.issetpddfac: self.pddfac_snow=project3d(md,'vector',self.pddfac_snow,'type','node')
     83                if self.issetpddfac: self.pddfac_ice=project3d(md,'vector',self.pddfac_ice,'type','node')
    5784                self.s0p=project3d(md,'vector',self.s0p,'type','node')
    5885                self.s0t=project3d(md,'vector',self.s0t,'type','node')
     
    6592        def initialize(self,md): # {{{
    6693
    67                 if numpy.all(numpy.isnan(self.s0p)):
    68                         self.s0p=numpy.zeros((md.mesh.numberofvertices,1))
     94                if np.all(np.isnan(self.s0p)):
     95                        self.s0p=np.zeros((md.mesh.numberofvertices))
    6996                        print("      no SMBd18opdd.s0p specified: values set as zero")
    7097
    71                 if numpy.all(numpy.isnan(self.s0t)):
    72                         self.s0t=numpy.zeros((md.mesh.numberofvertices,1))
     98                if np.all(np.isnan(self.s0t)):
     99                        self.s0t=np.zeros((md.mesh.numberofvertices))
    73100                        print("      no SMBd18opdd.s0t specified: values set as zero")
    74101                       
     
    80107                self.ismungsm   = 0
    81108                self.isd18opd   = 1
     109                self.istemperaturescaled = 1
     110                self.isprecipscaled = 1
    82111                self.desfac     = 0.5
    83112                self.rlaps      = 6.5
    84113                self.rlapslgm   = 6.5
    85114                self.dpermil    = 2.4
    86 
     115                self.f          = 0.169
     116                self.issetpddfac = 0
    87117                return self
    88118        #}}}
    89119        def checkconsistency(self,md,solution,analyses):    # {{{
    90120
    91                 if MasstransportAnalysisEnum() in analyses:
     121                if 'MasstransportAnalysis' in analyses:
    92122                        md = checkfield(md,'fieldname','smb.desfac','<=',1,'numel',[1])
    93                         md = checkfield(md,'fieldname','smb.s0p','>=',0,'NaN',1,'Inf',1,'size',[md.mesh.numberofvertices,1])
    94                         md = checkfield(md,'fieldname','smb.s0t','>=',0,'NaN',1,'Inf',1,'size',[md.mesh.numberofvertices,1])
     123                        md = checkfield(md,'fieldname','smb.s0p','>=',0,'NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
     124                        md = checkfield(md,'fieldname','smb.s0t','>=',0,'NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
    95125                        md = checkfield(md,'fieldname','smb.rlaps','>=',0,'numel',[1])
    96126                        md = checkfield(md,'fieldname','smb.rlapslgm','>=',0,'numel',[1])
    97127
    98128                        if self.isd18opd:
     129                                lent=float(np.size(self.temperatures_presentday,1))
     130                                lenp=float(np.size(self.precipitations_presentday,1))
     131                                multt=np.ceil(lent/12.)*12.
     132                                multp=np.ceil(lenp/12.)*12.
    99133                                md = checkfield(md,'fieldname','smb.temperatures_presentday','size',[md.mesh.numberofvertices+1,12],'NaN',1,'Inf',1,'timeseries',1)
    100134                                md = checkfield(md,'fieldname','smb.precipitations_presentday','size',[md.mesh.numberofvertices+1,12],'NaN',1,'Inf',1,'timeseries',1)
    101                                 md = checkfield(md,'fieldname','smb.delta18o','NaN',1,'Inf',1,'size',[2,numpy.nan],'singletimeseries',1)
     135
     136                                if self.istemperaturescaled==0:
     137                                        lent=float(np.size(self.temperatures_reconstructed,1))
     138                                        multt=np.ceil(lent/12.)*12.
     139                                        md = checkfield(md,'fieldname','smb.temperatures_reconstructed','size',[md.mesh.numberofvertices+1,multt],'NaN',1,'Inf',1,'timeseries',1)
     140
     141                                if self.isprecipscaled==0:
     142                                        lenp=float(np.size(self.precipitations_reconstructed,1))
     143                                        multp=np.ceil(lent/12.)*12.
     144                                        md = checkfield(md,'fieldname','smb.precipitations_reconstructed','size',[md.mesh.numberofvertices+1,multt],'NaN',1,'Inf',1,'timeseries',1)
     145
     146                                md = checkfield(md,'fieldname','smb.delta18o','NaN',1,'Inf',1,'size',[2,np.nan],'singletimeseries',1)
    102147                                md = checkfield(md,'fieldname','smb.dpermil','>=',0,'numel',[1])
    103                
     148                                md = checkfield(md,'fieldname','smb.f','>=',0,'numel',[1])
     149
     150                        if self.issetpddfac:
     151                                md = checkfield(md,'fieldname','smb.pddfac_snow','>=',0,'NaN',1,'Inf',1)
     152                                md = checkfield(md,'fieldname','smb.pddfac_ice','>=',0,'NaN',1,'Inf',1)
     153
    104154                md = checkfield(md,'fieldname','masstransport.requested_outputs','stringrow',1)
    105155
    106156                return md
    107157        # }}}
    108         def marshall(self,md,fid):    # {{{
    109 
    110                 yts=365.0*24.0*3600.0
    111 
    112                 WriteData(fid,'enum',SmbEnum(),'data',SMBd18opddEnum(),'format','Integer')
    113 
    114                 WriteData(fid,'object',self,'class','smb','fieldname','ismungsm','format','Boolean')
    115                 WriteData(fid,'object',self,'class','smb','fieldname','isd18opd','format','Boolean')
    116                 WriteData(fid,'object',self,'class','smb','fieldname','desfac','format','Double')
    117                 WriteData(fid,'object',self,'class','smb','fieldname','s0p','format','DoubleMat','mattype',1);
    118                 WriteData(fid,'object',self,'class','smb','fieldname','s0t','format','DoubleMat','mattype',1);
    119                 WriteData(fid,'object',self,'class','smb','fieldname','rlaps','format','Double')
    120                 WriteData(fid,'object',self,'class','smb','fieldname','rlapslgm','format','Double')
    121                 WriteData(fid,'object',self,'class','smb','fieldname','Tdiff','format','DoubleMat','mattype',1,'timeserieslength',2)
    122                 WriteData(fid,'object',self,'class','smb','fieldname','sealev','format','DoubleMat','mattype',1,'timeserieslength',2)
     158        def marshall(self,prefix,md,fid):    # {{{
     159
     160                yts=md.constants.yts
     161
     162                WriteData(fid,prefix,'name','md.smb.model','data',5,'format','Integer')
     163
     164                WriteData(fid,prefix,'object',self,'class','smb','fieldname','ismungsm','format','Boolean')
     165                WriteData(fid,prefix,'object',self,'class','smb','fieldname','isd18opd','format','Boolean')
     166                WriteData(fid,prefix,'object',self,'class','smb','fieldname','issetpddfac','format','Boolean');
     167                WriteData(fid,prefix,'object',self,'class','smb','fieldname','desfac','format','Double')
     168                WriteData(fid,prefix,'object',self,'class','smb','fieldname','s0p','format','DoubleMat','mattype',1);
     169                WriteData(fid,prefix,'object',self,'class','smb','fieldname','s0t','format','DoubleMat','mattype',1);
     170                WriteData(fid,prefix,'object',self,'class','smb','fieldname','rlaps','format','Double')
     171                WriteData(fid,prefix,'object',self,'class','smb','fieldname','rlapslgm','format','Double')
     172                WriteData(fid,prefix,'object',self,'class','smb','fieldname','Tdiff','format','DoubleMat','mattype',1,'timeserieslength',2,'yts',md.constants.yts)
     173                WriteData(fid,prefix,'object',self,'class','smb','fieldname','sealev','format','DoubleMat','mattype',1,'timeserieslength',2,'yts',md.constants.yts)
    123174
    124175                if self.isd18opd:
    125                         WriteData(fid,'object',self,'class','smb','fieldname','temperatures_presentday','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1)
    126                         WriteData(fid,'object',self,'class','smb','fieldname','precipitations_presentday','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
    127                         WriteData(fid,'object',self,'class','smb','fieldname','delta18o','format','DoubleMat','mattype',1,'timeserieslength',2)
    128                         WriteData(fid,'object',self,'class','smb','fieldname','dpermil','format','Double')
    129                        
     176                        WriteData(fid,prefix,'object',self,'class','smb','fieldname','temperatures_presentday','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     177                        WriteData(fid,prefix,'object',self,'class','smb','fieldname','precipitations_presentday','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     178                        WriteData(fid,prefix,'object',self,'class','smb','fieldname','istemperaturescaled','format','Boolean')
     179                        WriteData(fid,prefix,'object',self,'class','smb','fieldname','isprecipscaled','format','Boolean')
     180
     181                        if self.istemperaturescaled==0:
     182                                WriteData(fid,prefix,'object',self,'class','smb','fieldname','temperatures_reconstructed','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     183
     184                        if self.isprecipscaled==0:
     185                                WriteData(fid,prefix,'object',self,'class','smb','fieldname','precipitations_reconstructed','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     186
     187                        WriteData(fid,prefix,'object',self,'class','smb','fieldname','delta18o','format','DoubleMat','mattype',1,'timeserieslength',2,'yts',md.constants.yts)
     188                        WriteData(fid,prefix,'object',self,'class','smb','fieldname','dpermil','format','Double')
     189                        WriteData(fid,prefix,'object',self,'class','smb','fieldname','f','format','Double')
     190
     191                if self.issetpddfac:
     192                        WriteData(fid,prefix,'object',self,'class','smb','fieldname','pddfac_snow','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     193                        WriteData(fid,prefix,'object',self,'class','smb','fieldname','pddfac_ice','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     194
    130195                #process requested outputs
    131196                outputs = self.requested_outputs
     
    134199                        outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:]
    135200                        outputs    =outputscopy
    136                 WriteData(fid,'data',outputs,'enum',SmbRequestedOutputsEnum(),'format','StringArray')
     201                WriteData(fid,prefix,'data',outputs,'name','md.smb.requested_outputs','format','StringArray')
    137202
    138203        # }}}
  • issm/trunk-jpl/src/py3/classes/SMBforcing.py

    r19898 r23670  
    1 import numpy
     1import numpy as np
    22from fielddisplay import fielddisplay
    3 from EnumDefinitions import *
    43from checkfield import checkfield
    54from WriteData import WriteData
     
    3433        def initialize(self,md): # {{{
    3534
    36                 if numpy.all(numpy.isnan(self.mass_balance)):
    37                         self.mass_balance=numpy.zeros((md.mesh.numberofvertices,1))
     35                if np.all(np.isnan(self.mass_balance)):
     36                        self.mass_balance=np.zeros((md.mesh.numberofvertices))
    3837                        print("      no SMBforcing.mass_balance specified: values set as zero")
    3938
     
    4241        def checkconsistency(self,md,solution,analyses):    # {{{
    4342
    44                 if MasstransportAnalysisEnum() in analyses:
     43                if 'MasstransportAnalysis' in analyses:
    4544                        md = checkfield(md,'fieldname','smb.mass_balance','timeseries',1,'NaN',1,'Inf',1)
    4645
    47                 if BalancethicknessAnalysisEnum() in analyses:
     46                if 'BalancethicknessAnalysis' in analyses:
    4847                        md = checkfield(md,'fieldname','smb.mass_balance','size',[md.mesh.numberofvertices],'NaN',1,'Inf',1)
    4948
     
    5150                return md
    5251        # }}}
    53         def marshall(self,md,fid):    # {{{
     52        def marshall(self,prefix,md,fid):    # {{{
    5453
    55                 yts=365.0*24.0*3600.0
     54                yts=md.constants.yts
    5655
    57                 WriteData(fid,'enum',SmbEnum(),'data',SMBforcingEnum(),'format','Integer');
    58                 WriteData(fid,'object',self,'class','smb','fieldname','mass_balance','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
     56                WriteData(fid,prefix,'name','md.smb.model','data',1,'format','Integer');
     57                WriteData(fid,prefix,'object',self,'class','smb','fieldname','mass_balance','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     58                #WriteData(fid,prefix,'object',self,'class','smb','fieldname','mass_balance','format','CompressedMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts);
    5959               
    6060                #process requested outputs
     
    6464                        outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:]
    6565                        outputs    =outputscopy
    66                 WriteData(fid,'data',outputs,'enum',SmbRequestedOutputsEnum(),'format','StringArray')
     66                WriteData(fid,prefix,'data',outputs,'name','md.smb.requested_outputs','format','StringArray')
    6767
    6868        # }}}
  • issm/trunk-jpl/src/py3/classes/SMBgradients.py

    r19898 r23670  
    11from fielddisplay import fielddisplay
    2 from EnumDefinitions import *
    32from checkfield import checkfield
    43from WriteData import WriteData
     
    4847        def checkconsistency(self,md,solution,analyses):    # {{{
    4948
    50                 if MasstransportAnalysisEnum() in analyses:
     49                if 'MasstransportAnalysis' in analyses:
    5150                        md = checkfield(md,'fieldname','smb.href','timeseries',1,'NaN',1,'Inf',1)
    5251                        md = checkfield(md,'fieldname','smb.smbref','timeseries',1,'NaN',1,'Inf',1)
     
    5756                return md
    5857        # }}}
    59         def marshall(self,md,fid):    # {{{
     58        def marshall(self,prefix,md,fid):    # {{{
    6059
    61                 yts=365.0*24.0*3600.0
     60                yts=md.constants.yts
    6261
    63                 WriteData(fid,'enum',SmbEnum(),'data',SMBgradientsEnum(),'format','Integer');
    64                 WriteData(fid,'object',self,'class','smb','fieldname','href','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1)
    65                 WriteData(fid,'object',self,'class','smb','fieldname','smbref','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
    66                 WriteData(fid,'object',self,'class','smb','fieldname','b_pos','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
    67                 WriteData(fid,'object',self,'class','smb','fieldname','b_neg','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
     62                WriteData(fid,prefix,'name','md.smb.model','data',6,'format','Integer');
     63                WriteData(fid,prefix,'object',self,'class','smb','fieldname','href','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     64                WriteData(fid,prefix,'object',self,'class','smb','fieldname','smbref','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     65                WriteData(fid,prefix,'object',self,'class','smb','fieldname','b_pos','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     66                WriteData(fid,prefix,'object',self,'class','smb','fieldname','b_neg','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
    6867               
    6968                #process requested outputs
     
    7372                        outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:]
    7473                        outputs    =outputscopy
    75                 WriteData(fid,'data',outputs,'enum',SmbRequestedOutputsEnum(),'format','StringArray')
     74                WriteData(fid,prefix,'data',outputs,'name','md.smb.requested_outputs','format','StringArray')
    7675
    7776        # }}}
  • issm/trunk-jpl/src/py3/classes/SMBmeltcomponents.py

    r19898 r23670  
    11from fielddisplay import fielddisplay
    2 from EnumDefinitions import *
    32from checkfield import *
    43from project3d import *
     
    3029        def extrude(self,md): # {{{
    3130
    32                 self.mass_balance=project3d(md,'vector',self.accumulation,'type','node');
    33                 self.mass_balance=project3d(md,'vector',self.evaporation,'type','node');
    34                 self.mass_balance=project3d(md,'vector',self.melt,'type','node');
    35                 self.mass_balance=project3d(md,'vector',self.refreeze,'type','node');
     31                self.accumulation=project3d(md,'vector',self.accumulation,'type','node');
     32                self.evaporation=project3d(md,'vector',self.evaporation,'type','node');
     33                self.melt=project3d(md,'vector',self.melt,'type','node');
     34                self.refreeze=project3d(md,'vector',self.refreeze,'type','node');
    3635                return self
    3736        #}}}
     
    4140        def initialize(self,md): # {{{
    4241
    43                 if numpy.all(numpy.isnan(self.accumulation)):
    44                         self.accumulation=numpy.zeros((md.mesh.numberofvertices,1))
     42                if np.all(np.isnan(self.accumulation)):
     43                        self.accumulation=np.zeros((md.mesh.numberofvertices))
    4544                        print("      no SMB.accumulation specified: values set as zero")
    4645
    47                 if numpy.all(numpy.isnan(self.evaporation)):
    48                         self.evaporation=numpy.zeros((md.mesh.numberofvertices,1))
     46                if np.all(np.isnan(self.evaporation)):
     47                        self.evaporation=np.zeros((md.mesh.numberofvertices))
    4948                        print("      no SMB.evaporation specified: values set as zero")
    5049
    51                 if numpy.all(numpy.isnan(self.melt)):
    52                         self.melt=numpy.zeros((md.mesh.numberofvertices,1))
     50                if np.all(np.isnan(self.melt)):
     51                        self.melt=np.zeros((md.mesh.numberofvertices))
    5352                        print("      no SMB.melt specified: values set as zero")
    5453
    55                 if numpy.all(numpy.isnan(self.refreeze)):
    56                         self.refreeze=numpy.zeros((md.mesh.numberofvertices,1))
     54                if np.all(np.isnan(self.refreeze)):
     55                        self.refreeze=np.zeros((md.mesh.numberofvertices))
    5756                        print("      no SMB.refreeze specified: values set as zero")
    5857
     
    6160        def checkconsistency(self,md,solution,analyses):    # {{{
    6261
    63                 if MasstransportAnalysisEnum() in analyses:
     62                if 'MasstransportAnalysis' in analyses:
    6463                        md = checkfield(md,'fieldname','smb.accumulation','timeseries',1,'NaN',1,'Inf',1)
    6564
    66                 if BalancethicknessAnalysisEnum() in analyses:
     65                if 'BalancethicknessAnalysis' in analyses:
    6766                        md = checkfield(md,'fieldname','smb.accumulation','size',[md.mesh.numberofvertices],'NaN',1,'Inf',1)
    6867
    69                 if MasstransportAnalysisEnum() in analyses:
     68                if 'MasstransportAnalysis' in analyses:
    7069                        md = checkfield(md,'fieldname','smb.melt','timeseries',1,'NaN',1,'Inf',1)
    7170
    72                 if BalancethicknessAnalysisEnum() in analyses:
     71                if 'BalancethicknessAnalysis' in analyses:
    7372                        md = checkfield(md,'fieldname','smb.melt','size',[md.mesh.numberofvertices],'NaN',1,'Inf',1)
    7473
    75                 if MasstransportAnalysisEnum() in analyses:
     74                if 'MasstransportAnalysis' in analyses:
    7675                        md = checkfield(md,'fieldname','smb.refreeze','timeseries',1,'NaN',1,'Inf',1)
    7776
    78                 if BalancethicknessAnalysisEnum() in analyses:
     77                if 'BalancethicknessAnalysis' in analyses:
    7978                        md = checkfield(md,'fieldname','smb.refreeze','size',[md.mesh.numberofvertices],'NaN',1,'Inf',1)
    8079
    81                 if MasstransportAnalysisEnum() in analyses:
     80                if 'MasstransportAnalysis' in analyses:
    8281                        md = checkfield(md,'fieldname','smb.evaporation','timeseries',1,'NaN',1,'Inf',1)
    8382
    84                 if BalancethicknessAnalysisEnum() in analyses:
     83                if 'BalancethicknessAnalysis' in analyses:
    8584                        md = checkfield(md,'fieldname','smb.evaporation','size',[md.mesh.numberofvertices],'NaN',1,'Inf',1)
    8685
     
    8887                return md
    8988        # }}}
    90         def marshall(self,md,fid):    # {{{
     89        def marshall(self,prefix,md,fid):    # {{{
    9190
    92                 yts=365.0*24.0*3600.0
     91                yts=md.constants.yts
    9392
    94                 WriteData(fid,'enum',SmbEnum(),'data',SMBmeltcomponentsEnum(),'format','Integer');
    95                 WriteData(fid,'object',self,'class','smb','fieldname','accumulation','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
    96                 WriteData(fid,'object',self,'class','smb','fieldname','evaporation','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
    97                 WriteData(fid,'object',self,'class','smb','fieldname','melt','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
    98                 WriteData(fid,'object',self,'class','smb','fieldname','refreeze','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
    99                
     93                WriteData(fid,prefix,'name','md.smb.model','data',3,'format','Integer');
     94                WriteData(fid,prefix,'object',self,'class','smb','fieldname','accumulation','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     95                WriteData(fid,prefix,'object',self,'class','smb','fieldname','evaporation','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     96                WriteData(fid,prefix,'object',self,'class','smb','fieldname','melt','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     97                WriteData(fid,prefix,'object',self,'class','smb','fieldname','refreeze','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     98
    10099                #process requested outputs
    101100                outputs = self.requested_outputs
     
    104103                        outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:]
    105104                        outputs    =outputscopy
    106                 WriteData(fid,'data',outputs,'enum',SmbRequestedOutputsEnum(),'format','StringArray')
     105                WriteData(fid,prefix,'data',outputs,'name','md.smb.requested_outputs','format','StringArray')
    107106
    108107        # }}}
  • issm/trunk-jpl/src/py3/classes/SMBpdd.py

    r19898 r23670  
    1 import numpy
     1import numpy as np
    22from fielddisplay import fielddisplay
    3 from EnumDefinitions import *
    43from checkfield import checkfield
    54from WriteData import WriteData
     
    2726                self.isdelta18o                = 0
    2827                self.ismungsm                  = 0
     28                self.issetpddfac               = 0
    2929                self.delta18o                  = float('NaN')
    3030                self.delta18o_surface          = float('NaN')
     
    9595        def initialize(self,md): # {{{
    9696
    97                 if numpy.all(numpy.isnan(self.s0p)):
    98                         self.s0p=numpy.zeros((md.mesh.numberofvertices,1))
     97                if np.all(np.isnan(self.s0p)):
     98                        self.s0p=np.zeros((md.mesh.numberofvertices))
    9999                        print("      no SMBpdd.s0p specified: values set as zero")
    100100
    101                 if numpy.all(numpy.isnan(self.s0t)):
    102                         self.s0t=numpy.zeros((md.mesh.numberofvertices,1))
     101                if np.all(np.isnan(self.s0t)):
     102                        self.s0t=np.zeros((md.mesh.numberofvertices))
    103103                        print("      no SMBpdd.s0t specified: values set as zero")
    104104
     
    118118        def checkconsistency(self,md,solution,analyses):    # {{{
    119119
    120                 if MasstransportAnalysisEnum() in analyses:
     120                if 'MasstransportAnalysis' in analyses:
    121121                        md = checkfield(md,'fieldname','smb.desfac','<=',1,'numel',[1])
    122                         md = checkfield(md,'fieldname','smb.s0p','>=',0,'NaN',1,'Inf',1,'size',[md.mesh.numberofvertices,1])
    123                         md = checkfield(md,'fieldname','smb.s0t','>=',0,'NaN',1,'Inf',1,'size',[md.mesh.numberofvertices,1])
     122                        md = checkfield(md,'fieldname','smb.s0p','>=',0,'NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
     123                        md = checkfield(md,'fieldname','smb.s0t','>=',0,'NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
    124124                        md = checkfield(md,'fieldname','smb.rlaps','>=',0,'numel',[1])
    125125                        md = checkfield(md,'fieldname','smb.rlapslgm','>=',0,'numel',[1])
     
    129129                                md = checkfield(md,'fieldname','smb.precipitation','NaN',1,'Inf',1,'timeseries',1)
    130130                        elif self.isdelta18o:
    131                                 md = checkfield(md,'fieldname','smb.delta18o','NaN',1,'Inf',1,'size',[2,numpy.nan],'singletimeseries',1)
    132                                 md = checkfield(md,'fieldname','smb.delta18o_surface','NaN',1,'Inf',1,'size',[2,numpy.nan],'singletimeseries',1)
     131                                md = checkfield(md,'fieldname','smb.delta18o','NaN',1,'Inf',1,'size',[2,np.nan],'singletimeseries',1)
     132                                md = checkfield(md,'fieldname','smb.delta18o_surface','NaN',1,'Inf',1,'size',[2,np.nan],'singletimeseries',1)
    133133                                md = checkfield(md,'fieldname','smb.temperatures_presentday','size',[md.mesh.numberofvertices+1,12],'NaN',1,'Inf',1,'timeseries',1)
    134134                                md = checkfield(md,'fieldname','smb.temperatures_lgm','size',[md.mesh.numberofvertices+1,12],'NaN',1,'Inf',1,'timeseries',1)
    135135                                md = checkfield(md,'fieldname','smb.precipitations_presentday','size',[md.mesh.numberofvertices+1,12],'NaN',1,'Inf',1,'timeseries',1)
    136136                                md = checkfield(md,'fieldname','smb.precipitations_lgm','size',[md.mesh.numberofvertices+1,12],'NaN',1,'Inf',1,'timeseries',1)                                       
    137                                 md = checkfield(md,'fieldname','smb.Tdiff','NaN',1,'Inf',1,'size',[2,numpy.nan],'singletimeseries',1)
    138                                 md = checkfield(md,'fieldname','smb.sealev','NaN',1,'Inf',1,'size',[2,numpy.nan],'singletimeseries',1)
     137                                md = checkfield(md,'fieldname','smb.Tdiff','NaN',1,'Inf',1,'size',[2,np.nan],'singletimeseries',1)
     138                                md = checkfield(md,'fieldname','smb.sealev','NaN',1,'Inf',1,'size',[2,np.nan],'singletimeseries',1)
    139139                        elif self.ismungsm:
    140140                                md = checkfield(md,'fieldname','smb.temperatures_presentday','size',[md.mesh.numberofvertices+1,12],'NaN',1,'Inf',1,'timeseries',1)
     
    142142                                md = checkfield(md,'fieldname','smb.precipitations_presentday','size',[md.mesh.numberofvertices+1,12],'NaN',1,'Inf',1,'timeseries',1)
    143143                                md = checkfield(md,'fieldname','smb.precipitations_lgm','size',[md.mesh.numberofvertices+1,12],'NaN',1,'Inf',1,'timeseries',1)                                       
    144                                 md = checkfield(md,'fieldname','smb.Pfac','NaN',1,'Inf',1,'size',[2,numpy.nan],'singletimeseries',1)
    145                                 md = checkfield(md,'fieldname','smb.Tdiff','NaN',1,'Inf',1,'size',[2,numpy.nan],'singletimeseries',1)
    146                                 md = checkfield(md,'fieldname','smb.sealev','NaN',1,'Inf',1,'size',[2,numpy.nan],'singletimeseries',1)
     144                                md = checkfield(md,'fieldname','smb.Pfac','NaN',1,'Inf',1,'size',[2,np.nan],'singletimeseries',1)
     145                                md = checkfield(md,'fieldname','smb.Tdiff','NaN',1,'Inf',1,'size',[2,np.nan],'singletimeseries',1)
     146                                md = checkfield(md,'fieldname','smb.sealev','NaN',1,'Inf',1,'size',[2,np.nan],'singletimeseries',1)
    147147
    148148                md = checkfield(md,'fieldname','masstransport.requested_outputs','stringrow',1)
    149149                return md
    150150        #}}}
    151         def marshall(self,md,fid):    # {{{
     151        def marshall(self,prefix,md,fid):    # {{{
    152152
    153                 yts=365.0*24.0*3600.0
     153                yts=md.constants.yts
    154154
    155                 WriteData(fid,'enum',SmbEnum(),'data',SMBpddEnum(),'format','Integer')
     155                WriteData(fid,prefix,'name','md.smb.model','data',4,'format','Integer')
    156156
    157                 WriteData(fid,'object',self,'class','smb','fieldname','isdelta18o','format','Boolean')
    158                 WriteData(fid,'object',self,'class','smb','fieldname','ismungsm','format','Boolean')
    159                 WriteData(fid,'object',self,'class','smb','fieldname','desfac','format','Double')
    160                 WriteData(fid,'object',self,'class','smb','fieldname','s0p','format','DoubleMat','mattype',1);
    161                 WriteData(fid,'object',self,'class','smb','fieldname','s0t','format','DoubleMat','mattype',1);
    162                 WriteData(fid,'object',self,'class','smb','fieldname','rlaps','format','Double')
    163                 WriteData(fid,'object',self,'class','smb','fieldname','rlapslgm','format','Double')
     157                WriteData(fid,prefix,'object',self,'class','smb','fieldname','isdelta18o','format','Boolean')
     158                WriteData(fid,prefix,'object',self,'class','smb','fieldname','ismungsm','format','Boolean')
     159                WriteData(fid,prefix,'object',self,'class','smb','fieldname','issetpddfac','format','Boolean');
     160                WriteData(fid,prefix,'object',self,'class','smb','fieldname','desfac','format','Double')
     161                WriteData(fid,prefix,'object',self,'class','smb','fieldname','s0p','format','DoubleMat','mattype',1);
     162                WriteData(fid,prefix,'object',self,'class','smb','fieldname','s0t','format','DoubleMat','mattype',1);
     163                WriteData(fid,prefix,'object',self,'class','smb','fieldname','rlaps','format','Double')
     164                WriteData(fid,prefix,'object',self,'class','smb','fieldname','rlapslgm','format','Double')
    164165
    165166                if (self.isdelta18o==0 and self.ismungsm==0):
    166                         WriteData(fid,'object',self,'class','smb','fieldname','monthlytemperatures','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1)
    167                         WriteData(fid,'object',self,'class','smb','fieldname','precipitation','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
     167                        WriteData(fid,prefix,'object',self,'class','smb','fieldname','monthlytemperatures','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     168                        WriteData(fid,prefix,'object',self,'class','smb','fieldname','precipitation','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
    168169                elif self.isdelta18o:
    169                         WriteData(fid,'object',self,'class','smb','fieldname','temperatures_presentday','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1)
    170                         WriteData(fid,'object',self,'class','smb','fieldname','temperatures_lgm','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1)
    171                         WriteData(fid,'object',self,'class','smb','fieldname','precipitations_presentday','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
    172                         WriteData(fid,'object',self,'class','smb','fieldname','precipitations_lgm','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
    173                         WriteData(fid,'object',self,'class','smb','fieldname','delta18o_surface','format','DoubleMat','mattype',1,'timeserieslength',2)
    174                         WriteData(fid,'object',self,'class','smb','fieldname','delta18o','format','DoubleMat','mattype',1,'timeserieslength',2)
    175                         WriteData(fid,'object',self,'class','smb','fieldname','Tdiff','format','DoubleMat','mattype',1,'timeserieslength',2)
    176                         WriteData(fid,'object',self,'class','smb','fieldname','sealev','format','DoubleMat','mattype',1,'timeserieslength',2)                   
     170                        WriteData(fid,prefix,'object',self,'class','smb','fieldname','temperatures_presentday','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     171                        WriteData(fid,prefix,'object',self,'class','smb','fieldname','temperatures_lgm','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     172                        WriteData(fid,prefix,'object',self,'class','smb','fieldname','precipitations_presentday','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     173                        WriteData(fid,prefix,'object',self,'class','smb','fieldname','precipitations_lgm','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     174                        WriteData(fid,prefix,'object',self,'class','smb','fieldname','delta18o_surface','format','DoubleMat','mattype',1,'timeserieslength',2,'yts',md.constants.yts)
     175                        WriteData(fid,prefix,'object',self,'class','smb','fieldname','delta18o','format','DoubleMat','mattype',1,'timeserieslength',2,'yts',md.constants.yts)
     176                        WriteData(fid,prefix,'object',self,'class','smb','fieldname','Tdiff','format','DoubleMat','mattype',1,'timeserieslength',2,'yts',md.constants.yts)
     177                        WriteData(fid,prefix,'object',self,'class','smb','fieldname','sealev','format','DoubleMat','mattype',1,'timeserieslength',2,'yts',md.constants.yts)                     
    177178                elif self.ismungsm:
    178                         WriteData(fid,'object',self,'class','smb','fieldname','temperatures_presentday','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1)
    179                         WriteData(fid,'object',self,'class','smb','fieldname','temperatures_lgm','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1)
    180                         WriteData(fid,'object',self,'class','smb','fieldname','precipitations_presentday','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
    181                         WriteData(fid,'object',self,'class','smb','fieldname','precipitations_lgm','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
    182                         WriteData(fid,'object',self,'class','smb','fieldname','Pfac','format','DoubleMat','mattype',1,'timeserieslength',2)
    183                         WriteData(fid,'object',self,'class','smb','fieldname','Tdiff','format','DoubleMat','mattype',1,'timeserieslength',2)
    184                         WriteData(fid,'object',self,'class','smb','fieldname','sealev','format','DoubleMat','mattype',1,'timeserieslength',2)
     179                        WriteData(fid,prefix,'object',self,'class','smb','fieldname','temperatures_presentday','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     180                        WriteData(fid,prefix,'object',self,'class','smb','fieldname','temperatures_lgm','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     181                        WriteData(fid,prefix,'object',self,'class','smb','fieldname','precipitations_presentday','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     182                        WriteData(fid,prefix,'object',self,'class','smb','fieldname','precipitations_lgm','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     183                        WriteData(fid,prefix,'object',self,'class','smb','fieldname','Pfac','format','DoubleMat','mattype',1,'timeserieslength',2,'yts',md.constants.yts)
     184                        WriteData(fid,prefix,'object',self,'class','smb','fieldname','Tdiff','format','DoubleMat','mattype',1,'timeserieslength',2,'yts',md.constants.yts)
     185                        WriteData(fid,prefix,'object',self,'class','smb','fieldname','sealev','format','DoubleMat','mattype',1,'timeserieslength',2,'yts',md.constants.yts)
    185186                       
    186187                #process requested outputs
     
    190191                        outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:]
    191192                        outputs    =outputscopy
    192                 WriteData(fid,'data',outputs,'enum',SmbRequestedOutputsEnum(),'format','StringArray')
     193                WriteData(fid,prefix,'data',outputs,'name','md.smb.requested_outputs','format','StringArray')
    193194
    194195        # }}}
  • issm/trunk-jpl/src/py3/classes/autodiff.py

    r19895 r23670  
    1 import numpy
     1import numpy as np
    22from dependent import dependent
    33from independent import independent
    44from fielddisplay import fielddisplay
    5 from EnumDefinitions import *
    65from checkfield import checkfield
    76from WriteData import WriteData
     
    1514        """
    1615        def __init__(self,*args):    # {{{
    17                 self.isautodiff   = False
    18                 self.dependents   = []
    19                 self.independents = []
    20                 self.driver       = 'fos_forward'
    21                 self.obufsize     = float('NaN')
    22                 self.lbufsize     = float('NaN')
    23                 self.cbufsize     = float('NaN')
    24                 self.tbufsize     = float('NaN')
    25                 self.gcTriggerMaxSize     = float('NaN')
    26                 self.gcTriggerRatio     = float('NaN')
     16                self.isautodiff                         = False
     17                self.dependents                         = []
     18                self.independents                       = []
     19                self.driver                                             = 'fos_forward'
     20                self.obufsize                                   = float('NaN')
     21                self.lbufsize                                   = float('NaN')
     22                self.cbufsize                                   = float('NaN')
     23                self.tbufsize                                   = float('NaN')
     24                self.gcTriggerMaxSize = float('NaN')
     25                self.gcTriggerRatio   = float('NaN')
     26                self.tapeAlloc                          = float('NaN')
    2727                if not len(args):
    2828                        self.setdefaultparameters()
     
    3030                        raise RuntimeError("constructor not supported")
    3131        # }}}
     32
    3233        def __repr__(self):    # {{{
    3334                s ="      automatic differentiation parameters:\n"
    34 
    3535                s+="%s\n" % fielddisplay(self,'isautodiff',"indicates if the automatic differentiation is activated")
    3636                s+="%s\n" % fielddisplay(self,'dependents',"list of dependent variables")
     
    4343                s+="%s\n" % fielddisplay(self,'gcTriggerRatio',"free location block sorting/consolidation triggered if the ratio between allocated and used locations exceeds gcTriggerRatio")
    4444                s+="%s\n" % fielddisplay(self,'gcTriggerMaxSize',"free location block sorting/consolidation triggered if the allocated locations exceed gcTriggerMaxSize)")
     45                s+="%s\n" % fielddisplay(self,'tapeAlloc','Iteration count of a priori memory allocation of the AD tape');
    4546
    4647                return s
    4748        # }}}
     49
    4850        def setdefaultparameters(self):    # {{{
    49                
    50                 self.obufsize     = 524288
    51                 self.lbufsize     = 524288
    52                 self.cbufsize     = 524288
    53                 self.tbufsize     = 524288
    54                 self.gcTriggerRatio=2.0
    55                 self.gcTriggerMaxSize=65536
     51                self.obufsize                                   = 524288
     52                self.lbufsize                                   = 524288
     53                self.cbufsize                                   = 524288
     54                self.tbufsize                                   = 524288
     55                self.gcTriggerRatio             =       2.0
     56                self.gcTriggerMaxSize   =       65536
     57                self.tapeAlloc                          = 15000000;
    5658                return self
    5759        # }}}
     60
    5861        def checkconsistency(self,md,solution,analyses):    # {{{
    59 
    60                 #Early return
     62                #Early return
    6163                if not self.isautodiff:
    62                         return md 
    63                
     64                        return md
     65
    6466                md = checkfield(md,'fieldname','autodiff.obufsize','>=',524288)
    6567                md = checkfield(md,'fieldname','autodiff.lbufsize','>=',524288)
     
    6769                md = checkfield(md,'fieldname','autodiff.tbufsize','>=',524288)
    6870                md = checkfield(md,'fieldname','autodiff.gcTriggerRatio','>=',2.0)
    69                 md = checkfield(md,'fieldname','autodiff.gcTriggerMaxSize','>=',2000000)
     71                md = checkfield(md,'fieldname','autodiff.gcTriggerMaxSize','>=',65536)
     72                md = checkfield(md,'fieldname','autodiff.tapeAlloc','>=',0);
    7073
    7174                #Driver value:
    7275                md = checkfield(md,'fieldname','autodiff.driver','values',['fos_forward','fov_forward','fov_forward_all','fos_reverse','fov_reverse','fov_reverse_all'])
    7376
    74                 #go through our dependents and independents and check consistency: 
     77                #go through our dependents and independents and check consistency:
    7578                for dep in self.dependents:
    7679                        dep.checkconsistency(md,solution,analyses)
     
    8083                return md
    8184        # }}}
    82         def marshall(self,md,fid):    # {{{
    83                 WriteData(fid,'object',self,'fieldname','isautodiff','format','Boolean')
    84                 WriteData(fid,'object',self,'fieldname','driver','format','String')
     85
     86        def marshall(self,prefix,md,fid):    # {{{
     87                WriteData(fid,prefix,'object',self,'fieldname','isautodiff','format','Boolean')
     88                WriteData(fid,prefix,'object',self,'fieldname','driver','format','String')
    8589
    8690                #early return
    8791                if not self.isautodiff:
    88                         WriteData(fid,'data',False,'enum',AutodiffMassFluxSegmentsPresentEnum(),'format','Boolean')
    89                         WriteData(fid,'data',False,'enum',AutodiffKeepEnum(),'format','Boolean')
     92                        WriteData(fid,prefix,'data',False,'name','md.autodiff.mass_flux_segments_present','format','Boolean')
     93                        WriteData(fid,prefix,'data',False,'name','md.autodiff.keep','format','Boolean')
    9094                        return
    91                        
     95
    9296                #buffer sizes {{{
    93                 WriteData(fid,'object',self,'fieldname','obufsize','format','Double');
    94                 WriteData(fid,'object',self,'fieldname','lbufsize','format','Double');
    95                 WriteData(fid,'object',self,'fieldname','cbufsize','format','Double');
    96                 WriteData(fid,'object',self,'fieldname','tbufsize','format','Double');
    97                 WriteData(fid,'object',self,'fieldname','gcTriggerRatio','format','Double');
    98                 WriteData(fid,'object',self,'fieldname','gcTriggerMaxSize','format','Double');
     97                WriteData(fid,prefix,'object',self,'fieldname','obufsize','format','Double');
     98                WriteData(fid,prefix,'object',self,'fieldname','lbufsize','format','Double');
     99                WriteData(fid,prefix,'object',self,'fieldname','cbufsize','format','Double');
     100                WriteData(fid,prefix,'object',self,'fieldname','tbufsize','format','Double');
     101                WriteData(fid,prefix,'object',self,'fieldname','gcTriggerRatio','format','Double');
     102                WriteData(fid,prefix,'object',self,'fieldname','gcTriggerMaxSize','format','Double');
     103                WriteData(fid,prefix,'object',self,'fieldname','tapeAlloc','format','Integer');
    99104                #}}}
    100105                #process dependent variables {{{
    101106                num_dependent_objects=len(self.dependents)
    102                 WriteData(fid,'data',num_dependent_objects,'enum',AutodiffNumDependentObjectsEnum(),'format','Integer')
     107                WriteData(fid,prefix,'data',num_dependent_objects,'name','md.autodiff.num_dependent_objects','format','Integer')
    103108
    104109                if num_dependent_objects:
    105110                        names=[]
    106                         types=numpy.zeros(num_dependent_objects)
    107                         indices=numpy.zeros(num_dependent_objects)
     111                        types=np.zeros(num_dependent_objects)
     112                        indices=np.zeros(num_dependent_objects)
    108113
    109114                        for i,dep in enumerate(self.dependents):
    110                                 names[i]=dep.name
     115                                names.append(dep.name)
    111116                                types[i]=dep.typetoscalar()
    112117                                indices[i]=dep.index
    113118
    114                         WriteData(fid,'data',names,'enum',AutodiffDependentObjectNamesEnum(),'format','StringArray')
    115                         WriteData(fid,'data',types,'enum',AutodiffDependentObjectTypesEnum(),'format','IntMat','mattype',3)
    116                         WriteData(fid,'data',indices,'enum',AutodiffDependentObjectIndicesEnum(),'format','IntMat','mattype',3)
     119                        WriteData(fid,prefix,'data',names,'name','md.autodiff.dependent_object_names','format','StringArray')
     120                        WriteData(fid,prefix,'data',types,'name','md.autodiff.dependent_object_types','format','IntMat','mattype',3)
     121                        WriteData(fid,prefix,'data',indices,'name','md.autodiff.dependent_object_indices','format','IntMat','mattype',3)
    117122                #}}}
    118123                #process independent variables {{{
    119124                num_independent_objects=len(self.independents)
    120                 WriteData(fid,'data',num_independent_objects,'enum',AutodiffNumIndependentObjectsEnum(),'format','Integer')
     125                WriteData(fid,prefix,'data',num_independent_objects,'name','md.autodiff.num_independent_objects','format','Integer')
    121126
    122127                if num_independent_objects:
    123                         names=numpy.zeros(num_independent_objects)
    124                         types=numpy.zeros(num_independent_objects)
     128                        names=[None] * num_independent_objects
     129                        types=np.zeros(num_independent_objects)
    125130
    126131                        for i,indep in enumerate(self.independents):
    127                                 names[i]=StringToEnum(indep.name)[0]
     132                                names[i]=indep.name
    128133                                types[i]=indep.typetoscalar()
    129134
    130                         WriteData(fid,'data',names,'enum',AutodiffIndependentObjectNamesEnum(),'format','IntMat','mattype',3)
    131                         WriteData(fid,'data',types,'enum',AutodiffIndependentObjectTypesEnum(),'format','IntMat','mattype',3)
     135                        WriteData(fid,prefix,'data',names,'name','md.autodiff.independent_object_names','format','StringArray')
     136                        WriteData(fid,prefix,'data',types,'name','md.autodiff.independent_object_types','format','IntMat','mattype',3)
    132137                #}}}
    133138                #if driver is fos_forward, build index:  {{{
     
    136141
    137142                        for indep in self.independents:
    138                                 if not numpy.isnan(indep.fos_forward_index):
     143                                if not np.isnan(indep.fos_forward_index):
    139144                                        index+=indep.fos_forward_index
    140145                                        break
     
    146151
    147152                        index-=1    #get c-index numbering going
    148                         WriteData(fid,'data',index,'enum',AutodiffFosForwardIndexEnum(),'format','Integer')
     153                        WriteData(fid,prefix,'data',index,'name','md.autodiff.fos_forward_index','format','Integer')
    149154                #}}}
    150155                #if driver is fos_reverse, build index:  {{{
     
    153158
    154159                        for dep in self.dependents:
    155                                 if not numpy.isnan(dep.fos_reverse_index):
     160                                if not np.isnan(dep.fos_reverse_index):
    156161                                        index+=dep.fos_reverse_index
    157162                                        break
     
    163168
    164169                        index-=1    #get c-index numbering going
    165                         WriteData(fid,'data',index,'enum',AutodiffFosReverseIndexEnum(),'format','Integer')
     170                        WriteData(fid,prefix,'data',index,'name','md.autodiff.fos_reverse_index','format','Integer')
    166171                #}}}
    167172                #if driver is fov_forward, build indices:  {{{
     
    180185
    181186                        indices-=1    #get c-indices numbering going
    182                         WriteData(fid,'data',indices,'enum',AutodiffFovForwardIndicesEnum(),'format','IntMat','mattype',3)
     187                        WriteData(fid,prefix,'data',indices,'name','md.autodiff.fov_forward_indices','format','IntMat','mattype',3)
    183188                #}}}
    184189                #deal with mass fluxes:  {{{
     
    186191
    187192                if mass_flux_segments:
    188                         WriteData(fid,'data',mass_flux_segments,'enum',MassFluxSegmentsEnum(),'format','MatArray')
     193                        WriteData(fid,prefix,'data',mass_flux_segments,'name','md.autodiff.mass_flux_segments','format','MatArray')
    189194                        flag=True
    190195                else:
    191196                        flag=False
    192                 WriteData(fid,'data',flag,'enum',AutodiffMassFluxSegmentsPresentEnum(),'format','Boolean')
     197                WriteData(fid,prefix,'data',flag,'name','md.autodiff.mass_flux_segments_present','format','Boolean')
    193198                #}}}
    194199                #deal with trace keep on: {{{
    195200                keep=False
    196201
    197                 #From ADOLC userdoc: 
    198                 # The optional integer argument keep of trace on determines whether the numerical values of all active variables are 
    199                 # recorded in a buffered temporary array or file called the taylor stack. This option takes effect if keep = 1 and 
    200                 # prepares the scene for an immediately following gradient evaluation by a call to a routine implementing the reverse 
    201                 # mode as described in the Section 4 and Section 5. 
     202                #From ADOLC userdoc:
     203                # The optional integer argument keep of trace on determines whether the numerical values of all active variables are
     204                # recorded in a buffered temporary array or file called the taylor stack. This option takes effect if keep = 1 and
     205                # prepares the scene for an immediately following gradient evaluation by a call to a routine implementing the reverse
     206                # mode as described in the Section 4 and Section 5.
    202207                #
    203208
    204209                if len(self.driver)<=3:
    205                         keep=False    #there is no "_reverse" string within the driver string: 
     210                        keep=False    #there is no "_reverse" string within the driver string:
    206211                else:
    207212                        if strncmpi(self.driver[3:],'_reverse',8):
     
    209214                        else:
    210215                                keep=False
    211                 WriteData(fid,'data',keep,'enum',AutodiffKeepEnum(),'format','Boolean')
     216                WriteData(fid,prefix,'data',keep,'name','md.autodiff.keep','format','Boolean')
    212217                #}}}
    213218
  • issm/trunk-jpl/src/py3/classes/balancethickness.py

    r19898 r23670  
    11from fielddisplay import fielddisplay
    2 from EnumDefinitions import *
    32from checkfield import checkfield
    43from WriteData import WriteData
     
    1615                self.thickening_rate   = float('NaN')
    1716                self.stabilization     = 0
     17               
     18                self.omega             = float('NaN')
     19                self.slopex            = float('NaN')
     20                self.slopey            = float('NaN')
    1821
    1922                #set defaults
     
    3942        def checkconsistency(self,md,solution,analyses):    # {{{
    4043                #Early return
    41                 if not solution==BalancethicknessSolutionEnum():
     44                if not solution=='BalancethicknessSolution':
    4245                        return md
    4346
     
    4548                md = checkfield(md,'fieldname','balancethickness.thickening_rate','size',[md.mesh.numberofvertices],'NaN',1,'Inf',1)
    4649                md = checkfield(md,'fieldname','balancethickness.stabilization','size',[1],'values',[0,1,2,3])
    47 
     50                #md = checkfield(md,'fieldname','balancethickness.omega','size', [md.mesh.numberofvertices],'NaN',1,'Inf',1,'>=',0);
    4851                return md
    4952        # }}}
    50         def marshall(self,md,fid):    # {{{
     53        def marshall(self,prefix,md,fid):    # {{{
    5154
    52                 yts=365.0*24.0*3600.0
     55                yts=md.constants.yts
    5356
    54                 WriteData(fid,'object',self,'fieldname','spcthickness','format','DoubleMat','mattype',1)
    55                 WriteData(fid,'object',self,'fieldname','thickening_rate','format','DoubleMat','mattype',1,'scale',1./yts)
    56                 WriteData(fid,'object',self,'fieldname','stabilization','format','Integer')
     57                WriteData(fid,prefix,'object',self,'fieldname','spcthickness','format','DoubleMat','mattype',1)
     58                WriteData(fid,prefix,'object',self,'fieldname','thickening_rate','format','DoubleMat','mattype',1,'scale',1./yts)
     59                WriteData(fid,prefix,'object',self,'fieldname','stabilization','format','Integer')
     60                WriteData(fid,prefix,'object',self,'fieldname','slopex','format','DoubleMat','mattype',1)
     61                WriteData(fid,prefix,'object',self,'fieldname','slopey','format','DoubleMat','mattype',1)
     62                WriteData(fid,prefix,'object',self,'fieldname','omega','format','DoubleMat','mattype',1)
    5763        # }}}
  • issm/trunk-jpl/src/py3/classes/bamggeom.py

    r19895 r23670  
    1 import numpy
     1import numpy as np
    22
    33class bamggeom(object):
     
    1010
    1111        def __init__(self,*args):    # {{{
    12                 self.Vertices=numpy.empty((0,3))
    13                 self.Edges=numpy.empty((0,3))
    14                 self.TangentAtEdges=numpy.empty((0,4))
    15                 self.Corners=numpy.empty((0,1))
    16                 self.RequiredVertices=numpy.empty((0,1))
    17                 self.RequiredEdges=numpy.empty((0,1))
    18                 self.CrackedEdges=numpy.empty((0,0))
    19                 self.SubDomains=numpy.empty((0,4))
     12                self.Vertices=np.empty((0,3))
     13                self.Edges=np.empty((0,3))
     14                self.TangentAtEdges=np.empty((0,4))
     15                self.Corners=np.empty((0,1))
     16                self.RequiredVertices=np.empty((0,1))
     17                self.RequiredEdges=np.empty((0,1))
     18                self.CrackedEdges=np.empty((0,0))
     19                self.SubDomains=np.empty((0,4))
    2020
    2121                if not len(args):
     
    2525                elif len(args) == 1:
    2626                        object=args[0]
    27                         for field in list(object.keys()):
     27                        for field in object.keys():
    2828                                if field in vars(self):
    2929                                        setattr(self,field,object[field])
  • issm/trunk-jpl/src/py3/classes/bamgmesh.py

    r19895 r23670  
    1 import numpy
     1import numpy as np
    22
    33class bamgmesh(object):
     
    1010
    1111        def __init__(self,*args):    # {{{
    12                 self.Vertices=numpy.empty((0,3))
    13                 self.Edges=numpy.empty((0,3))
    14                 self.Triangles=numpy.empty((0,0))
    15                 self.Quadrilaterals=numpy.empty((0,0))
    16                 self.IssmEdges=numpy.empty((0,0))
    17                 self.IssmSegments=numpy.empty((0,0))
    18                 self.VerticesOnGeomVertex=numpy.empty((0,0))
    19                 self.VerticesOnGeomEdge=numpy.empty((0,0))
    20                 self.EdgesOnGeomEdge=numpy.empty((0,0))
    21                 self.SubDomains=numpy.empty((0,4))
    22                 self.SubDomainsFromGeom=numpy.empty((0,0))
    23                 self.ElementConnectivity=numpy.empty((0,0))
    24                 self.NodalConnectivity=numpy.empty((0,0))
    25                 self.NodalElementConnectivity=numpy.empty((0,0))
    26                 self.CrackedVertices=numpy.empty((0,0))
    27                 self.CrackedEdges=numpy.empty((0,0))
     12                self.Vertices=np.empty((0,3))
     13                self.Edges=np.empty((0,3))
     14                self.Triangles=np.empty((0,0))
     15                self.IssmEdges=np.empty((0,0))
     16                self.IssmSegments=np.empty((0,0))
     17                self.VerticesOnGeomVertex=np.empty((0,0))
     18                self.VerticesOnGeomEdge=np.empty((0,0))
     19                self.EdgesOnGeomEdge=np.empty((0,0))
     20                self.SubDomains=np.empty((0,4))
     21                self.SubDomainsFromGeom=np.empty((0,0))
     22                self.ElementConnectivity=np.empty((0,0))
     23                self.NodalConnectivity=np.empty((0,0))
     24                self.NodalElementConnectivity=np.empty((0,0))
     25                self.CrackedVertices=np.empty((0,0))
     26                self.CrackedEdges=np.empty((0,0))
    2827
    2928                if not len(args):
     
    3332                elif len(args) == 1:
    3433                        object=args[0]
    35                         for field in list(object.keys()):
     34                        for field in object.keys():
    3635                                if field in vars(self):
    3736                                        setattr(self,field,object[field])
     
    4544                s+="    Edges: %s\n" % str(self.Edges)
    4645                s+="    Triangles: %s\n" % str(self.Triangles)
    47                 s+="    Quadrilaterals: %s\n" % str(self.Quadrilaterals)
    4846                s+="    IssmEdges: %s\n" % str(self.IssmEdges)
    4947                s+="    IssmSegments: %s\n" % str(self.IssmSegments)
  • issm/trunk-jpl/src/py3/classes/basalforcings.py

    r19898 r23670  
    11from fielddisplay import fielddisplay
    22from project3d import project3d
    3 from EnumDefinitions import *
    43from checkfield import checkfield
    54from WriteData import WriteData
    6 import numpy
     5import numpy as np
    76
    87class basalforcings(object):
     
    3938        def initialize(self,md): # {{{
    4039
    41                 if numpy.all(numpy.isnan(self.groundedice_melting_rate)):
    42                         self.groundedice_melting_rate=numpy.zeros((md.mesh.numberofvertices,1))
     40                if np.all(np.isnan(self.groundedice_melting_rate)):
     41                        self.groundedice_melting_rate=np.zeros((md.mesh.numberofvertices))
    4342                        print("      no basalforcings.groundedice_melting_rate specified: values set as zero")
    4443
    45                 if numpy.all(numpy.isnan(self.floatingice_melting_rate)):
    46                         self.floatingice_melting_rate=numpy.zeros((md.mesh.numberofvertices,1))
     44                if np.all(np.isnan(self.floatingice_melting_rate)):
     45                        self.floatingice_melting_rate=np.zeros((md.mesh.numberofvertices))
    4746                        print("      no basalforcings.floatingice_melting_rate specified: values set as zero")
     47                #if np.all(np.isnan(self.geothermalflux)):
     48                        #self.geothermalflux=np.zeros((md.mesh.numberofvertices))
     49                        #print "      no basalforcings.geothermalflux specified: values set as zero"
    4850
    4951                return self
     
    5456        def checkconsistency(self,md,solution,analyses):    # {{{
    5557
    56                 if MasstransportAnalysisEnum() in analyses and not (solution==TransientSolutionEnum() and not md.transient.ismasstransport):
     58                if 'MasstransportAnalysis' in analyses and not (solution=='TransientSolution' and not md.transient.ismasstransport):
    5759                        md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'Inf',1,'timeseries',1)
    5860                        md = checkfield(md,'fieldname','basalforcings.floatingice_melting_rate','NaN',1,'Inf',1,'timeseries',1)
    5961
    60                 if BalancethicknessAnalysisEnum() in analyses:
     62                if 'BalancethicknessAnalysis' in analyses:
    6163                        md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
    6264                        md = checkfield(md,'fieldname','basalforcings.floatingice_melting_rate','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
    6365
    64                 if ThermalAnalysisEnum() in analyses and not (solution==TransientSolutionEnum() and not md.transient.isthermal):
     66                if 'ThermalAnalysis' in analyses and not (solution=='TransientSolution' and not md.transient.isthermal):
    6567                        md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'Inf',1,'timeseries',1)
    6668                        md = checkfield(md,'fieldname','basalforcings.floatingice_melting_rate','NaN',1,'Inf',1,'timeseries',1)
     
    6971                return md
    7072        # }}}
    71         def marshall(self,md,fid):    # {{{
     73        def marshall(self,prefix,md,fid):    # {{{
    7274
    73                 yts=365.0*24.0*3600.0
     75                yts=md.constants.yts
    7476
    75                 WriteData(fid,'enum',BasalforcingsEnum(),'data',FloatingMeltRateEnum(),'format','Integer');
    76                 WriteData(fid,'object',self,'fieldname','groundedice_melting_rate','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
    77                 WriteData(fid,'object',self,'fieldname','floatingice_melting_rate','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
    78                 WriteData(fid,'object',self,'fieldname','geothermalflux','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1)
     77                WriteData(fid,prefix,'name','md.basalforcings.model','data',1,'format','Integer');
     78                WriteData(fid,prefix,'object',self,'fieldname','groundedice_melting_rate','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     79                WriteData(fid,prefix,'object',self,'fieldname','floatingice_melting_rate','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     80                WriteData(fid,prefix,'object',self,'fieldname','geothermalflux','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
    7981        # }}}
  • issm/trunk-jpl/src/py3/classes/calving.py

    r20465 r23670  
    11from fielddisplay import fielddisplay
    22from project3d import project3d
    3 from EnumDefinitions import *
    4 from StringToEnum import StringToEnum
    53from checkfield import checkfield
    64from WriteData import WriteData
     
    1614        def __init__(self): # {{{
    1715
    18                 self.stabilization = 0
    19                 self.spclevelset   = float('NaN')
    2016                self.calvingrate   = float('NaN')
    2117                self.meltingrate   = float('NaN')
     
    2723        def __repr__(self): # {{{
    2824                string='   Calving parameters:'
    29                 string="%s\n%s"%(string,fielddisplay(self,'stabilization','0: no, 1: artificial_diffusivity, 2: streamline upwinding'))
    30                 string="%s\n%s"%(string,fielddisplay(self,'spclevelset','levelset constraints (NaN means no constraint)'))
    3125                string="%s\n%s"%(string,fielddisplay(self,'calvingrate','calving rate at given location [m/a]'))
    32                 string="%s\n%s"%(string,fielddisplay(self,'meltingrate','melting rate at given location [m/a]'))
    3326
    3427                return string
    3528                #}}}
    3629        def extrude(self,md): # {{{
    37                 self.spclevelset=project3d(md,'vector',self.spclevelset,'type','node')
    3830                self.calvingrate=project3d(md,'vector',self.calvingrate,'type','node')
    39                 self.meltingrate=project3d(md,'vector',self.meltingrate,'type','node')
    4031                return self
    4132        #}}}
    4233        def setdefaultparameters(self): # {{{
    43 
    44                 #stabilization = 2 by default
    45                 self.stabilization = 2
    4634
    4735                return self
     
    5038
    5139                #Early return
    52                 if (solution!=TransientSolutionEnum()) or (not md.transient.iscalving):
     40                if (solution!='TransientSolution') or (not md.transient.ismovingfront):
    5341                        return md
    5442
    55                 md = checkfield(md,'fieldname','calving.spclevelset','Inf',1,'timeseries',1)
    56                 md = checkfield(md,'fieldname','calving.stabilization','values',[0,1,2]);
    5743                md = checkfield(md,'fieldname','calving.calvingrate','>=',0,'timeseries',1,'NaN',1,'Inf',1);
    58                 md = checkfield(md,'fieldname','calving.meltingrate','>=',0,'timeseries',1,'NaN',1,'Inf',1);
    5944
    6045                return md
    6146        # }}}
    62         def marshall(self,md,fid):    # {{{
     47        def marshall(self,prefix,md,fid):    # {{{
    6348
    64                 yts=365.*24.*3600.
     49                yts=md.constants.yts
    6550
    66                 WriteData(fid,'enum',CalvingLawEnum(),'data',DefaultCalvingEnum(),'format','Integer');
    67                 WriteData(fid,'enum',LevelsetStabilizationEnum(),'data',self.stabilization,'format','Integer');
    68                 WriteData(fid,'enum',SpclevelsetEnum(),'data',self.spclevelset,'format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1);
    69                 WriteData(fid,'object',self,'fieldname','calvingrate','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'scale',1./yts)
    70                 WriteData(fid,'object',self,'fieldname','meltingrate','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'scale',1./yts)
     51                WriteData(fid,prefix,'name','md.calving.law','data',1,'format','Integer');
     52                WriteData(fid,prefix,'object',self,'fieldname','calvingrate','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts,'scale',1./yts)
    7153        # }}}
  • issm/trunk-jpl/src/py3/classes/calvinglevermann.py

    r20465 r23670  
    11from fielddisplay import fielddisplay
    2 from EnumDefinitions import *
    3 from StringToEnum import StringToEnum
    42from checkfield import checkfield
    53from WriteData import WriteData
     
    1513        def __init__(self): # {{{
    1614
    17                 self.stabilization = 0
    18                 self.spclevelset   = float('NaN')
    1915                self.coeff         = float('NaN')
    2016                self.meltingrate   = float('NaN')
     
    2622        def __repr__(self): # {{{
    2723                string='   Calving Levermann parameters:'
    28                 string="%s\n%s"%(string,fielddisplay(self,'spclevelset','levelset constraints (NaN means no constraint)'))
    29                 string="%s\n%s"%(string,fielddisplay(self,'stabilization','0: no, 1: artificial_diffusivity, 2: streamline upwinding'))
    3024                string="%s\n%s"%(string,fielddisplay(self,'coeff','proportionality coefficient in Levermann model'))
    31                 string="%s\n%s"%(string,fielddisplay(self,'meltingrate','melting rate at given location [m/a]'))
    3225
    3326                return string
    3427                #}}}
    3528        def extrude(self,md): # {{{
    36                 self.spclevelset=project3d(md,'vector',self.spclevelset,'type','node')
    3729                self.coeff=project3d(md,'vector',self.coeff,'type','node')
    38                 self.meltingrate=project3d(md,'vector',self.meltingrate,'type','node')
    3930                return self
    4031        #}}}
    4132        def setdefaultparameters(self): # {{{
    42 
    43                 #stabilization = 2 by default
    44                 self.stabilization = 2
    4533
    4634                #Proportionality coefficient in Levermann model
     
    5038
    5139                #Early return
    52                 if (solution!=TransientSolutionEnum()) or (not md.transient.iscalving):
     40                if (solution!='TransientSolution') or (not md.transient.ismovingfront):
    5341                        return md
    5442
    55                 md = checkfield(md,'fieldname','calving.spclevelset','Inf',1,'timeseries',1)
    56                 md = checkfield(md,'fieldname','calving.stabilization','values',[0,1,2]);
    5743                md = checkfield(md,'fieldname','calving.coeff','size',[md.mesh.numberofvertices],'>',0)
    58                 md = checkfield(md,'fieldname','calving.meltingrate','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices],'>=',0)
    5944                return md
    6045        # }}}
    61         def marshall(self,md,fid):    # {{{
    62                 yts=365.*24.*3600.
    63                 WriteData(fid,'enum',CalvingLawEnum(),'data',CalvingLevermannEnum(),'format','Integer');
    64                 WriteData(fid,'enum',LevelsetStabilizationEnum(),'data',self.stabilization,'format','Integer');
    65                 WriteData(fid,'enum',SpclevelsetEnum(),'data',self.spclevelset,'format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1);
    66                 WriteData(fid,'enum',CalvinglevermannCoeffEnum(),'data',self.coeff,'format','DoubleMat','mattype',1)
    67                 WriteData(fid,'object',self,'fieldname','meltingrate','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'scale',1./yts)
     46        def marshall(self,prefix,md,fid):    # {{{
     47                yts=md.constants.yts
     48                WriteData(fid,prefix,'name','md.calving.law','data',3,'format','Integer');
     49                WriteData(fid,prefix,'object',self,'fieldname','coeff','format','DoubleMat','mattype',1)
    6850        # }}}
  • issm/trunk-jpl/src/py3/classes/clusters/generic.py

    r19895 r23670  
    44import subprocess
    55from IssmConfig import IssmConfig
    6 from EnumToString import EnumToString
    76from issmdir import issmdir
    87from pairoptions import pairoptions
     
    1817           Usage:
    1918              cluster=generic('name','astrid','np',3);
    20               cluster=generic('name',oshostname(),'np',3,'login','username');
     19              cluster=generic('name',gethostname(),'np',3,'login','username');
    2120        """
    2221
    23         def __init__(self,**kwargs):    # {{{
     22        def __init__(self,*args):    # {{{
    2423
    2524                self.name=''
     
    2827                self.port=0
    2928                self.interactive=1
    30                 self.codepath=issmdir()+'/bin'
     29                self.codepath=IssmConfig('ISSM_PREFIX')[0]+'/bin'
    3130                self.executionpath=issmdir()+'/execution'
    3231                self.valgrind=issmdir()+'/externalpackages/valgrind/install/bin/valgrind'
     
    3534
    3635                #use provided options to change fields
    37                 options=pairoptions(**kwargs)
     36                options=pairoptions(*args)
    3837
    3938                #get name
     
    6968                return md
    7069        # }}}
    71         def BuildQueueScript(self,dirname,modelname,solution,io_gather,isvalgrind,isgprof,isdakota):    # {{{
     70        def BuildQueueScript(self,dirname,modelname,solution,io_gather,isvalgrind,isgprof,isdakota,isoceancoupling):    # {{{
    7271
    7372                executable='issm.exe';
    7473                if isdakota:
    75                         version=IssmConfig('_DAKOTA_VERSION_')[0:2]
    76                         version=float(version)
     74                        version=IssmConfig('_DAKOTA_VERSION_')
     75                        version=float(version[0])
    7776                        if version>=6:
    7877                                executable='issm_dakota.exe'
     78                if isoceancoupling:
     79                        executable='issm_ocean.exe'
    7980
    8081                #write queuing script
     
    8687                                if self.interactive:
    8788                                        if IssmConfig('_HAVE_MPI_')[0]:
    88                                                 fid.write('mpiexec -np %i %s/%s %s %s/%s %s ' % (self.np,self.codepath,executable,EnumToString(solution)[0],self.executionpath,dirname,modelname))
     89                                                fid.write('mpiexec -np %i %s/%s %s %s/%s %s ' % (self.np,self.codepath,executable,solution,self.executionpath,dirname,modelname))
    8990                                        else:
    90                                                 fid.write('%s/%s %s %s/%s %s ' % (self.codepath,executable,EnumToString(solution)[0],self.executionpath,dirname,modelname))
     91                                                fid.write('%s/%s %s %s/%s %s ' % (self.codepath,executable,solution,self.executionpath,dirname,modelname))
    9192                                else:
    9293                                        if IssmConfig('_HAVE_MPI_')[0]:
    93                                                 fid.write('mpiexec -np %i %s/%s %s %s/%s %s 2> %s.errlog >%s.outlog ' % (self.np,self.codepath,executable,EnumToString(solution)[0],self.executionpath,dirname,modelname,modelname,modelname))
     94                                                fid.write('mpiexec -np %i %s/%s %s %s/%s %s 2> %s.errlog >%s.outlog ' % (self.np,self.codepath,executable,solution,self.executionpath,dirname,modelname,modelname,modelname))
    9495                                        else:
    95                                                 fid.write('%s/%s %s %s/%s %s 2> %s.errlog >%s.outlog ' % (self.codepath,executable,EnumToString(solution)[0],self.executionpath,dirname,modelname,modelname,modelname))
     96                                                fid.write('%s/%s %s %s/%s %s 2> %s.errlog >%s.outlog ' % (self.codepath,executable,solution,self.executionpath,dirname,modelname,modelname,modelname))
    9697                        elif isgprof:
    9798                                fid.write('\n gprof %s/%s gmon.out > %s.performance' % (self.codepath,executable,modelname))
     
    101102                                if IssmConfig('_HAVE_MPI_')[0]:
    102103                                        fid.write('mpiexec -np %i %s --leak-check=full --suppressions=%s %s/%s %s %s/%s %s 2> %s.errlog >%s.outlog ' % \
    103                                                         (self.np,self.valgrind,self.valgrindsup,self.codepath,executable,EnumToString(solution)[0],self.executionpath,dirname,modelname,modelname,modelname))
     104                                                        (self.np,self.valgrind,self.valgrindsup,self.codepath,executable,solution,self.executionpath,dirname,modelname,modelname,modelname))
    104105                                else:   
    105106                                        fid.write('%s --leak-check=full --suppressions=%s %s/%s %s %s/%s %s 2> %s.errlog >%s.outlog ' % \
    106                                                         (self.valgrind,self.valgrindsup,self.codepath,executable,EnumToString(solution)[0],self.executionpath,dirname,modelname,modelname,modelname))
     107                                                        (self.valgrind,self.valgrindsup,self.codepath,executable,solution,self.executionpath,dirname,modelname,modelname,modelname))
    107108
    108109                        if not io_gather:    #concatenate the output files:
     
    115116                        fid.write('@echo off\n')
    116117                        if self.interactive:
    117                                 fid.write('"%s/%s" %s "%s/%s" %s ' % (self.codepath,executable,EnumToString(solution)[0],self.executionpath,dirname,modelname))
     118                                fid.write('"%s/%s" %s "%s/%s" %s ' % (self.codepath,executable,solution,self.executionpath,dirname,modelname))
    118119                        else:
    119120                                fid.write('"%s/%s" %s "%s/%s" %s 2> %s.errlog >%s.outlog' % \
    120                                         (self.codepath,executable,EnumToString(solution)[0],self.executionpath,dirname,modelname,modelname,modelname))
     121                                        (self.codepath,executable,solution,self.executionpath,dirname,modelname,modelname,modelname))
    121122                        fid.close()
    122123
     
    156157                        fid.write('@echo off\n')
    157158                        if self.interactive:
    158                                 fid.write('"%s/issm.exe" %s "%s/%s" %s ' % (self.codepath,EnumToString(solution)[0],self.executionpath,modelname,modelname))
     159                                fid.write('"%s/issm.exe" %s "%s/%s" %s ' % (self.codepath,solution,self.executionpath,modelname,modelname))
    159160                        else:
    160161                                fid.write('"%s/issm.exe" %s "%s/%s" %s 2> %s.errlog >%s.outlog' % \
    161                                         (self.codepath,EnumToString(solution)[0],self.executionpath,modelname,modelname,modelname,modelname))
     162                                        (self.codepath,solution,self.executionpath,modelname,modelname,modelname,modelname))
    162163                        fid.close()
    163164
     
    183184
    184185        # }}}
    185         def LaunchQueueJob(self,modelname,dirname,filelist,restart):    # {{{
     186        def LaunchQueueJob(self,modelname,dirname,filelist,restart,batch):    # {{{
    186187
    187188                print('launching solution sequence on remote cluster')
     
    189190                        launchcommand='cd %s && cd %s chmod 777 %s.queue && ./%s.queue' % (self.executionpath,dirname,modelname,modelname)
    190191                else:
    191                         launchcommand='cd %s && rm -rf ./%s && mkdir %s && cd %s && mv ../%s.tar.gz ./ && tar -zxf %s.tar.gz  && chmod 777 %s.queue && ./%s.queue' % \
    192                                 (self.executionpath,dirname,dirname,dirname,dirname,dirname,modelname,modelname)
     192                        if batch:
     193                                launchcommand='cd %s && rm -rf ./%s && mkdir %s && cd %s && mv ../%s.tar.gz ./ && tar -zxf %s.tar.gz' % \
     194                                                (self.executionpath,dirname,dirname,dirname,dirname,dirname)
     195                        else:
     196                                launchcommand='cd %s && rm -rf ./%s && mkdir %s && cd %s && mv ../%s.tar.gz ./ && tar -zxf %s.tar.gz  && chmod 777 %s.queue && ./%s.queue' % \
     197                                        (self.executionpath,dirname,dirname,dirname,dirname,dirname,modelname,modelname)
    193198                issmssh(self.name,self.login,self.port,launchcommand)
    194199        # }}}
  • issm/trunk-jpl/src/py3/classes/clusters/pfe.py

    r19895 r23670  
    44import subprocess
    55from fielddisplay import fielddisplay
    6 from EnumToString import EnumToString
    76from pairoptions import pairoptions
    87from issmssh import issmssh
     
    2524        """
    2625
    27         def __init__(self,**kwargs):
     26        def __init__(self,*args):
    2827                # {{{
    2928
     
    4544
    4645                #use provided options to change fields
    47                 options=pairoptions(**kwargs)
     46                options=pairoptions(*args)
    4847
    4948                #initialize cluster using user settings if provided
     
    134133                return self
    135134        # }}}
    136         def BuildQueueScript(self,dirname,modelname,solution,io_gather,isvalgrind,isgprof,isdakota):
     135        def BuildQueueScript(self,dirname,modelname,solution,io_gather,isvalgrind,isgprof,isdakota,isoceancoupling):
    137136                # {{{
    138137
     
    143142                        if version>=6:
    144143                                executable='issm_dakota.exe'
     144                if isoceancoupling:
     145                        executable='issm_ocean.exe'
    145146
    146147                #write queuing script
     
    162163                fid.write('source $ISSM_DIR/etc/environment.sh\n')
    163164                fid.write('cd %s/%s/\n\n' % (self.executionpath,dirname))
    164                 fid.write('mpiexec -np %i %s/%s %s %s/%s %s\n' % (self.nprocs(),self.codepath,executable,str(EnumToString(solution)[0]),self.executionpath,dirname,modelname))
     165                fid.write('mpiexec -np %i %s/%s %s %s/%s %s\n' % (self.nprocs(),self.codepath,executable,str(solution),self.executionpath,dirname,modelname))
    165166               
    166167                fid.close()
     
    180181
    181182                # }}}
    182         def LaunchQueueJob(self,modelname,dirname,filelist,restart):
     183        def LaunchQueueJob(self,modelname,dirname,filelist,restart,batch):
    183184                        # {{{
    184185
  • issm/trunk-jpl/src/py3/classes/constants.py

    r19895 r23670  
    11from fielddisplay import fielddisplay
    2 from EnumDefinitions import *
    32from checkfield import checkfield
    43from WriteData import WriteData
     
    1312
    1413        def __init__(self): # {{{
    15                 self.g                    = 0
    16                 self.yts                  = 0
    17                 self.referencetemperature = 0
     14                self.g                    = 0.
     15                self.omega                = 0.
     16                self.yts                  = 0.
     17                self.referencetemperature = 0.
    1818               
    1919                #set defaults
     
    2525
    2626                string="%s\n%s"%(string,fielddisplay(self,"g","gravitational acceleration [m/s^2]"))
     27                string="%s\n%s"%(string,fielddisplay(self,"omega","angular velocity of Earth [rad/s]"))
    2728                string="%s\n%s"%(string,fielddisplay(self,"yts","number of seconds in a year [s/yr]"))
    2829                string="%s\n%s"%(string,fielddisplay(self,"referencetemperature","reference temperature used in the enthalpy model [K]"))
     
    3536                self.g=9.81
    3637
     38                #Earth's rotation speed
     39                self.omega = 7.292*1e-5;
     40
    3741                #converstion from year to seconds
    38                 self.yts=365*24*3600
     42                self.yts=365.*24.*3600.
    3943
    4044                #the reference temperature for enthalpy model (cf Aschwanden)
     
    4549        def checkconsistency(self,md,solution,analyses):    # {{{
    4650
    47                 md = checkfield(md,'fieldname','constants.g','>',0,'size',[1])
    48                 md = checkfield(md,'fieldname','constants.yts','>',0,'size',[1])
    49                 md = checkfield(md,'fieldname','constants.referencetemperature','size',[1])
     51                md = checkfield(md,'fieldname','constants.g','>=',0,'size',[1,1])
     52                md = checkfield(md,'fieldname','constants.omega','>=',0,'size',[1,1])
     53                md = checkfield(md,'fieldname','constants.yts','>',0,'size',[1,1])
     54                md = checkfield(md,'fieldname','constants.referencetemperature','size',[1,1])
    5055
    5156                return md
    5257        # }}}
    53         def marshall(self,md,fid):    # {{{
    54                 WriteData(fid,'object',self,'fieldname','g','format','Double')
    55                 WriteData(fid,'object',self,'fieldname','yts','format','Double')
    56                 WriteData(fid,'object',self,'fieldname','referencetemperature','format','Double')
     58        def marshall(self,prefix,md,fid):    # {{{
     59                WriteData(fid,prefix,'object',self,'fieldname','g','format','Double')
     60                WriteData(fid,prefix,'object',self,'fieldname','yts','format','Double')
     61                WriteData(fid,prefix,'object',self,'fieldname','referencetemperature','format','Double')
    5762        # }}}
  • issm/trunk-jpl/src/py3/classes/damage.py

    r19903 r23670  
    11from fielddisplay import fielddisplay
    22from project3d import project3d
    3 from EnumDefinitions import *
    4 from StringToEnum import StringToEnum
    53from checkfield import checkfield
    64from WriteData import WriteData
    7 import MatlabFuncs as m
    85
    96class damage(object):
     
    1613
    1714        def __init__(self,*args):    # {{{
    18                        
    19                 #damage:
    20                 self.isdamage           = 0.
    21                 self.D                  = float('NaN')
    22                 self.law                = float('NaN')
    23                 self.spcdamage          = float('NaN')
    24                 self.max_damage         = float('NaN')
    25                
     15                #damage:
     16                self.isdamage   = 0.
     17                self.D                                  = float('NaN')
     18                self.law                                = float('NaN')
     19                self.spcdamage  = float('NaN')
     20                self.max_damage = float('NaN')
     21
    2622                #numerical
    27                 self.stabilization      = float('NaN')
    28                 self.maxiter            = float('NaN')
    29                 self.elementinterp      = ''
     23                self.stabilization = float('NaN')
     24                self.maxiter                     = float('NaN')
     25                self.elementinterp = ''
    3026
    31                 #general parameters for evolution law: 
    32                 self.stress_threshold   = float('NaN')
    33                 self.kappa              = float('NaN')
    34                 self.c1                 = float('NaN')
    35                 self.c2                 = float('NaN')
    36                 self.c3                 = float('NaN')
    37                 self.c4                 = float('NaN')
    38                 self.healing            = float('NaN')
    39                 self.equiv_stress       = float('NaN')
    40                 self.requested_outputs  = []
     27                #general parameters for evolution law:
     28                self.stress_threshold  = float('NaN')
     29                self.kappa             = float('NaN')
     30                self.c1                = float('NaN')
     31                self.c2                = float('NaN')
     32                self.c3                = float('NaN')
     33                self.c4                = float('NaN')
     34                self.healing                                     = float('NaN')
     35                self.equiv_stress      = float('NaN')
     36                self.requested_outputs = []
    4137
    4238                if not len(args):
     
    4440                else:
    4541                        raise RuntimeError("constructor not supported")
     42        # }}}
    4643
    47         # }}}
    4844        def __repr__(self):    # {{{
    4945                s ='   Damage:\n'
    50                
    5146                s+="%s\n" % fielddisplay(self,"isdamage","is damage mechanics being used? [0 (default) or 1]")
    5247                if self.isdamage:
     
    7065                return s
    7166        # }}}
     67
    7268        def extrude(self,md): # {{{
    7369                self.D=project3d(md,'vector',self.D,'type','node')
     
    7571                return self
    7672        #}}}
     73
    7774        def setdefaultparameters(self):    # {{{
     75                #damage parameters:
     76                self.isdamage           =       0
     77                self.D                                  =       0
     78                self.law                                =       0
     79                self.max_damage =       1-1e-5 #if damage reaches 1, solve becomes singular, as viscosity becomes nil
    7880
    79                 #damage parameters:
    80                 self.isdamage=0
    81                 self.D=0
    82                 self.law=0
    83 
    84                 self.max_damage=1-1e-5 #if damage reaches 1, solve becomes singular, as viscosity becomes nil
    85                
    8681                #Type of stabilization used
    8782                self.stabilization=4
    88                        
     83
    8984                #Maximum number of iterations
    9085                self.maxiter=100
     
    9388                self.elementinterp='P1'
    9489
    95                 #damage evolution parameters 
     90                #damage evolution parameters
    9691                self.stress_threshold=1.3e5
    9792                self.kappa=2.8
     
    108103                return self
    109104        # }}}
     105
    110106        def defaultoutputs(self,md): # {{{
    111                
    112107                if md.mesh.domaintype().lower()=='2dhorizontal':
    113108                        list = ['DamageDbar']
     
    115110                        list = ['DamageD']
    116111                return list
     112        #}}}
    117113
    118         #}}}
    119114        def checkconsistency(self,md,solution,analyses):    # {{{
    120 
    121115                md = checkfield(md,'fieldname','damage.isdamage','numel',[1],'values',[0,1])
    122116                if self.isdamage:
     
    139133                        md = checkfield(md,'fieldname','damage.requested_outputs','stringrow',1)
    140134                elif self.law != 0:
    141                         if (solution==DamageEvolutionSolutionEnum):
     135                        if (solution=='DamageEvolutionSolution'):
    142136                                raise RuntimeError('Invalid evolution law (md.damage.law) for a damage solution')
    143137
    144138                return md
    145139        # }}}
    146         def marshall(self,md,fid):    # {{{
    147140
    148                 WriteData(fid,'object',self,'fieldname','isdamage','format','Boolean')
     141        def marshall(self,prefix,md,fid):    # {{{
     142                WriteData(fid,prefix,'object',self,'fieldname','isdamage','format','Boolean')
    149143                if self.isdamage:
    150                         WriteData(fid,'object',self,'fieldname','D','format','DoubleMat','mattype',1)
    151                         WriteData(fid,'object',self,'fieldname','law','format','Integer')
    152                         WriteData(fid,'object',self,'fieldname','spcdamage','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1)
    153                         WriteData(fid,'object',self,'fieldname','max_damage','format','Double')
    154                         WriteData(fid,'object',self,'fieldname','stabilization','format','Integer')
    155                         WriteData(fid,'object',self,'fieldname','maxiter','format','Integer')
    156                         WriteData(fid,'enum',DamageElementinterpEnum(),'data',StringToEnum(self.elementinterp)[0],'format','Integer')
    157                         WriteData(fid,'object',self,'fieldname','stress_threshold','format','Double')
    158                         WriteData(fid,'object',self,'fieldname','kappa','format','Double')
    159                         WriteData(fid,'object',self,'fieldname','c1','format','Double')
    160                         WriteData(fid,'object',self,'fieldname','c2','format','Double')
    161                         WriteData(fid,'object',self,'fieldname','c3','format','Double')
    162                         WriteData(fid,'object',self,'fieldname','c4','format','Double')
    163                         WriteData(fid,'object',self,'fieldname','healing','format','Double')
    164                         WriteData(fid,'object',self,'fieldname','equiv_stress','format','Integer')
    165                        
     144                        WriteData(fid,prefix,'object',self,'fieldname','D','format','DoubleMat','mattype',1)
     145                        WriteData(fid,prefix,'object',self,'fieldname','law','format','Integer')
     146                        WriteData(fid,prefix,'object',self,'fieldname','spcdamage','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     147                        WriteData(fid,prefix,'object',self,'fieldname','max_damage','format','Double')
     148                        WriteData(fid,prefix,'object',self,'fieldname','stabilization','format','Integer')
     149                        WriteData(fid,prefix,'object',self,'fieldname','maxiter','format','Integer')
     150                        WriteData(fid,prefix,'name','md.damage.elementinterp','data',self.elementinterp,'format','String')
     151                        WriteData(fid,prefix,'object',self,'fieldname','stress_threshold','format','Double')
     152                        WriteData(fid,prefix,'object',self,'fieldname','kappa','format','Double')
     153                        WriteData(fid,prefix,'object',self,'fieldname','c1','format','Double')
     154                        WriteData(fid,prefix,'object',self,'fieldname','c2','format','Double')
     155                        WriteData(fid,prefix,'object',self,'fieldname','c3','format','Double')
     156                        WriteData(fid,prefix,'object',self,'fieldname','c4','format','Double')
     157                        WriteData(fid,prefix,'object',self,'fieldname','healing','format','Double')
     158                        WriteData(fid,prefix,'object',self,'fieldname','equiv_stress','format','Integer')
     159
    166160                #process requested outputs
    167161                outputs = self.requested_outputs
     
    170164                        outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:]
    171165                        outputs    =outputscopy
    172                 WriteData(fid,'data',outputs,'enum',DamageEvolutionRequestedOutputsEnum(),'format','StringArray')
     166                if self.isdamage:
     167                        WriteData(fid,prefix,'data',outputs,'name','md.damage.requested_outputs','format','StringArray')
    173168        # }}}
  • issm/trunk-jpl/src/py3/classes/debug.py

    r19895 r23670  
    3030                return self
    3131        #}}}
    32         def marshall(self,md,fid):    # {{{
    33                 WriteData(fid,'object',self,'fieldname','profiling','format','Boolean')
     32        def marshall(self,prefix,md,fid):    # {{{
     33                WriteData(fid,prefix,'object',self,'fieldname','profiling','format','Boolean')
    3434        # }}}
  • issm/trunk-jpl/src/py3/classes/dependent.py

    r19895 r23670  
    11import os.path
    2 import numpy
     2import numpy as np
    33from pairoptions import pairoptions
    44from fielddisplay import fielddisplay
    5 import MatlabFuncs as m
    6 from EnumDefinitions import *
     5from MatlabFuncs import *
    76from MeshProfileIntersection import MeshProfileIntersection
    87
     
    2827
    2928                #use provided options to change fields
    30                 options=pairoptions(**kwargs)
     29                options=pairoptions(*args)
    3130
    3231                self.name=options.getfieldvalue('name','')
     
    4443                        #process the file and retrieve segments
    4544                        mesh=options.getfieldvalue('mesh')
    46                         self.segments=MeshProfileIntersection(mesh.elements,mesh.x,mesh.y,self.exp)
     45                        self.segments=MeshProfileIntersection(mesh.elements,mesh.x,mesh.y,self.exp)[0]
    4746        # }}}
    4847        def __repr__(self):    # {{{
    4948                s ="   dependent variable:\n"
    5049
    51                 s+="%s\n" % fielddisplay(self,'name',"variable name (must match corresponding Enum)")
     50                s+="%s\n" % fielddisplay(self,'name',"variable name (must match corresponding String)")
    5251                s+="%s\n" % fielddisplay(self,'type',"type of variable ('vertex' or 'scalar')")
    5352
    54                 if not numpy.isnan(self.fos_reverse_index):
     53                if not np.isnan(self.fos_reverse_index):
    5554                        s+="%s\n" % fielddisplay(self,'fos_reverse_index',"index for fos_reverse driver of ADOLC")
    5655                if self.exp:
     
    7170                                raise RuntimeError("dependent checkconsistency error: index for segments should be >=0")
    7271
    73                 if not numpy.isnan(self.fos_reverse_index):
     72                if not np.isnan(self.fos_reverse_index):
    7473                        if not strcmpi(driver,'fos_reverse'):
    7574                                raise TypeError("cannot declare a dependent with a fos_reverse_index when the driver is not fos_reverse!")
  • issm/trunk-jpl/src/py3/classes/flowequation.py

    r19895 r23670  
    1 import numpy
     1import numpy as np
    22import copy
    33from project3d import project3d
    44from fielddisplay import fielddisplay
    5 from EnumDefinitions import *
    65from checkfield import checkfield
    76from WriteData import WriteData
     
    1716
    1817        def __init__(self): # {{{
    19                
     18
    2019                self.isSIA                          = 0
    2120                self.isSSA                          = 0
     
    5049                string="%s\n%s"%(string,fielddisplay(self,'isFS',"are the Full-FS (FS) equations used ?"))
    5150                string="%s\n%s"%(string,fielddisplay(self,'fe_SSA',"Finite Element for SSA: 'P1', 'P1bubble' 'P1bubblecondensed' 'P2'"))
    52                 string="%s\n%s"%(string,fielddisplay(self,'fe_HO' ,"Finite Element for HO:  'P1' 'P1bubble' 'P1bubblecondensed' 'P1xP2' 'P2xP1' 'P2'"))
     51                string="%s\n%s"%(string,fielddisplay(self,'fe_HO' ,"Finite Element for HO:  'P1','P1bubble','P1bubblecondensed','P1xP2','P2xP1','P2','P2bubble','P1xP3','P2xP4'"))
    5352                string="%s\n%s"%(string,fielddisplay(self,'fe_FS' ,"Finite Element for FS:  'P1P1' (debugging only) 'P1P1GLS' 'MINIcondensed' 'MINI' 'TaylorHood' 'LATaylorHood' 'XTaylorHood'"))
    5453                string="%s\n%s"%(string,fielddisplay(self,'vertex_equation',"flow equation for each vertex"))
     
    8382
    8483                #Early return
    85                 if (StressbalanceAnalysisEnum() not in analyses and StressbalanceSIAAnalysisEnum() not in analyses) or (solution==TransientSolutionEnum() and not md.transient.isstressbalance):
     84                if ('StressbalanceAnalysis' not in analyses and 'StressbalanceSIAAnalysis' not in analyses) or (solution=='TransientSolution' and not md.transient.isstressbalance):
    8685                        return md
    8786
     
    9392                md = checkfield(md,'fieldname','flowequation.fe_SSA','values',['P1','P1bubble','P1bubblecondensed','P2','P2bubble'])
    9493                md = checkfield(md,'fieldname','flowequation.fe_HO' ,'values',['P1','P1bubble','P1bubblecondensed','P1xP2','P2xP1','P2','P2bubble','P1xP3','P2xP4'])
    95                 md = checkfield(md,'fieldname','flowequation.fe_FS' ,'values',['P1P1','P1P1GLS','MINIcondensed','MINI','TaylorHood','XTaylorHood','OneLayerP4z','CrouzeixRaviart'])
     94                md = checkfield(md,'fieldname','flowequation.fe_FS' ,'values',['P1P1','P1P1GLS','MINIcondensed','MINI','TaylorHood','LATaylorHood','XTaylorHood','OneLayerP4z','CrouzeixRaviart','LACrouzeixRaviart'])
    9695                md = checkfield(md,'fieldname','flowequation.borderSSA','size',[md.mesh.numberofvertices],'values',[0,1])
    9796                md = checkfield(md,'fieldname','flowequation.borderHO','size',[md.mesh.numberofvertices],'values',[0,1])
     
    105104                        md = checkfield(md,'fieldname','flowequation.vertex_equation','size',[md.mesh.numberofvertices],'values',[1,2])
    106105                        md = checkfield(md,'fieldname','flowequation.element_equation','size',[md.mesh.numberofelements],'values',[1,2])
     106                elif m.strcmp(md.mesh.domaintype(),'2Dvertical'):
     107                        md = checkfield(md,'fieldname','flowequation.vertex_equation','size',[md.mesh.numberofvertices],'values',[2,4,5])
     108                        md = checkfield(md,'fieldname','flowequation.element_equation','size',[md.mesh.numberofelements],'values',[2,4,5])
    107109                elif m.strcmp(md.mesh.domaintype(),'3D'):
    108                         md = checkfield(md,'fieldname','flowequation.vertex_equation','size',[md.mesh.numberofvertices],'values',numpy.arange(0,8+1))
    109                         md = checkfield(md,'fieldname','flowequation.element_equation','size',[md.mesh.numberofelements],'values',numpy.arange(0,8+1))
     110                        md = checkfield(md,'fieldname','flowequation.vertex_equation','size',[md.mesh.numberofvertices],'values',np.arange(0,8+1))
     111                        md = checkfield(md,'fieldname','flowequation.element_equation','size',[md.mesh.numberofelements],'values',np.arange(0,8+1))
    110112                else:
    111113                        raise RuntimeError('mesh type not supported yet')
     
    113115                        md.checkmessage("no element types set for this model")
    114116
    115                 if StressbalanceSIAAnalysisEnum() in analyses:
     117                if 'StressbalanceSIAAnalysis' in analyses:
    116118                        if any(self.element_equation==1):
    117                                 if numpy.any(numpy.logical_and(self.vertex_equation,md.mask.groundedice_levelset)):
     119                                if np.any(np.logical_and(self.vertex_equation,md.mask.groundedice_levelset)):
    118120                                        print("\n !!! Warning: SIA's model is not consistent on ice shelves !!!\n")
    119121
    120122                return md
    121123        # }}}
    122         def marshall(self,md,fid):    # {{{
    123                 WriteData(fid,'object',self,'fieldname','isSIA','format','Boolean')
    124                 WriteData(fid,'object',self,'fieldname','isSSA','format','Boolean')
    125                 WriteData(fid,'object',self,'fieldname','isL1L2','format','Boolean')
    126                 WriteData(fid,'object',self,'fieldname','isHO','format','Boolean')
    127                 WriteData(fid,'object',self,'fieldname','isFS','format','Boolean')
    128                 WriteData(fid,'enum',FlowequationFeSSAEnum(),'data',StringToEnum(self.fe_SSA)[0],'format','Integer')
    129                 WriteData(fid,'enum',FlowequationFeHOEnum() ,'data',StringToEnum(self.fe_HO)[0] ,'format','Integer')
    130                 WriteData(fid,'enum',FlowequationFeFSEnum() ,'data',StringToEnum(self.fe_FS)[0] ,'format','Integer')
    131                 WriteData(fid,'enum',AugmentedLagrangianREnum(),'data',self.augmented_lagrangian_r ,'format','Double')
    132                 WriteData(fid,'enum',AugmentedLagrangianRhopEnum(),'data',self.augmented_lagrangian_rhop ,'format','Double')
    133                 WriteData(fid,'enum',AugmentedLagrangianRlambdaEnum(),'data',self.augmented_lagrangian_rlambda ,'format','Double')
    134                 WriteData(fid,'enum',AugmentedLagrangianRholambdaEnum(),'data',self.augmented_lagrangian_rholambda ,'format','Double')
    135                 WriteData(fid,'enum',AugmentedLagrangianThetaEnum() ,'data',self.XTH_theta ,'format','Double')
    136                 WriteData(fid,'object',self,'fieldname','borderSSA','format','DoubleMat','mattype',1)
    137                 WriteData(fid,'object',self,'fieldname','borderHO','format','DoubleMat','mattype',1)
    138                 WriteData(fid,'object',self,'fieldname','borderFS','format','DoubleMat','mattype',1)
     124        def marshall(self,prefix,md,fid):    # {{{
     125                WriteData(fid,prefix,'object',self,'fieldname','isSIA','format','Boolean')
     126                WriteData(fid,prefix,'object',self,'fieldname','isSSA','format','Boolean')
     127                WriteData(fid,prefix,'object',self,'fieldname','isL1L2','format','Boolean')
     128                WriteData(fid,prefix,'object',self,'fieldname','isHO','format','Boolean')
     129                WriteData(fid,prefix,'object',self,'fieldname','isFS','format','Boolean')
     130                WriteData(fid,prefix,'object',self,'fieldname','fe_SSA','data',self.fe_SSA,'format','String')
     131                WriteData(fid,prefix,'object',self,'fieldname','fe_HO','data',self.fe_HO,'format','String')
     132                WriteData(fid,prefix,'object',self,'fieldname','fe_FS','data',self.fe_FS ,'format','String')
     133                WriteData(fid,prefix,'object',self,'fieldname','augmented_lagrangian_r','format','Double');
     134                WriteData(fid,prefix,'object',self,'fieldname','augmented_lagrangian_rhop','format','Double');
     135                WriteData(fid,prefix,'object',self,'fieldname','augmented_lagrangian_rlambda','format','Double');
     136                WriteData(fid,prefix,'object',self,'fieldname','augmented_lagrangian_rholambda','format','Double');
     137                WriteData(fid,prefix,'object',self,'fieldname','XTH_theta','data',self.XTH_theta ,'format','Double')
     138                WriteData(fid,prefix,'object',self,'fieldname','borderSSA','format','DoubleMat','mattype',1)
     139                WriteData(fid,prefix,'object',self,'fieldname','borderHO','format','DoubleMat','mattype',1)
     140                WriteData(fid,prefix,'object',self,'fieldname','borderFS','format','DoubleMat','mattype',1)
    139141                #convert approximations to enums
    140                 data=copy.deepcopy(self.vertex_equation)
    141                 data[numpy.nonzero(data==0)]=NoneApproximationEnum()
    142                 data[numpy.nonzero(data==1)]=SIAApproximationEnum()
    143                 data[numpy.nonzero(data==2)]=SSAApproximationEnum()
    144                 data[numpy.nonzero(data==3)]=L1L2ApproximationEnum()
    145                 data[numpy.nonzero(data==4)]=HOApproximationEnum()
    146                 data[numpy.nonzero(data==5)]=FSApproximationEnum()
    147                 data[numpy.nonzero(data==6)]=SSAHOApproximationEnum()
    148                 data[numpy.nonzero(data==7)]=HOFSApproximationEnum()
    149                 data[numpy.nonzero(data==8)]=SSAFSApproximationEnum()
    150                 WriteData(fid,'data',data,'enum',FlowequationVertexEquationEnum(),'format','DoubleMat','mattype',1)
    151                 data=copy.deepcopy(self.element_equation)
    152                 data[numpy.nonzero(data==0)]=NoneApproximationEnum()
    153                 data[numpy.nonzero(data==1)]=SIAApproximationEnum()
    154                 data[numpy.nonzero(data==2)]=SSAApproximationEnum()
    155                 data[numpy.nonzero(data==3)]=L1L2ApproximationEnum()
    156                 data[numpy.nonzero(data==4)]=HOApproximationEnum()
    157                 data[numpy.nonzero(data==5)]=FSApproximationEnum()
    158                 data[numpy.nonzero(data==6)]=SSAHOApproximationEnum()
    159                 data[numpy.nonzero(data==7)]=SSAFSApproximationEnum()
    160                 data[numpy.nonzero(data==8)]=HOFSApproximationEnum()
    161                 WriteData(fid,'data',data,'enum',FlowequationElementEquationEnum(),'format','DoubleMat','mattype',2)
     142                WriteData(fid,prefix,'data',self.vertex_equation,'name','md.flowequation.vertex_equation','format','DoubleMat','mattype',1)
     143                WriteData(fid,prefix,'data',self.element_equation,'name','md.flowequation.element_equation','format','DoubleMat','mattype',2)
     144
    162145        # }}}
  • issm/trunk-jpl/src/py3/classes/friction.py

    r19898 r23670  
     1import numpy as np
    12from fielddisplay import fielddisplay
    23from project3d import project3d
    3 from EnumDefinitions import *
    44from checkfield import checkfield
    55from WriteData import WriteData
     
    1717                self.p           = float('NaN')
    1818                self.q           = float('NaN')
    19 
     19                self.coupling    = 0
     20                self.effective_pressure = float('NaN')
    2021                #set defaults
    2122                self.setdefaultparameters()
     
    2324                #}}}
    2425        def __repr__(self): # {{{
    25                 string="Basal shear stress parameters: Sigma_b = coefficient^2 * Neff ^r * |u_b|^(s-1) * u_b,\n(effective stress Neff=rho_ice*g*thickness+rho_water*g*bed, r=q/p and s=1/p)"
     26                string="Basal shear stress parameters: Sigma_b = coefficient^2 * Neff ^r * |u_b|^(s-1) * u_b,\n(effective stress Neff=rho_ice*g*thickness+rho_water*g*base, r=q/p and s=1/p)"
    2627
    2728                string="%s\n%s"%(string,fielddisplay(self,"coefficient","friction coefficient [SI]"))
    2829                string="%s\n%s"%(string,fielddisplay(self,"p","p exponent"))
    2930                string="%s\n%s"%(string,fielddisplay(self,"q","q exponent"))
     31                string="%s\n%s"%(string,fielddisplay(self,'coupling','Coupling flag 0: uniform sheet (negative pressure ok, default), 1: ice pressure only, 2: water pressure assuming uniform sheet (no negative pressure), 3: use provided effective_pressure, 4: used coupled model (not implemented yet)'))
     32                string="%s\n%s"%(string,fielddisplay(self,'effective_pressure','Effective Pressure for the forcing if not coupled [Pa]'))
    3033                return string
    3134                #}}}
     
    3437                self.p=project3d(md,'vector',self.p,'type','element')
    3538                self.q=project3d(md,'vector',self.q,'type','element')
     39                #if self.coupling==0: #doesnt work with empty loop, so just skip it?
     40                if self.coupling in[3,4]:
     41                        self.effective_pressure=project3d(md,'vector',self.effective_pressure,'type','node','layer',1)
     42                elif self.coupling > 4:
     43                        raise ValueError('md.friction.coupling larger than 4, not supported yet')
    3644                return self
    3745        #}}}
     
    4250
    4351                #Early return
    44                 if StressbalanceAnalysisEnum() not in analyses and ThermalAnalysisEnum() not in analyses:
     52                if 'StressbalanceAnalysis' not in analyses and 'ThermalAnalysis' not in analyses:
    4553                        return md
    4654
     
    4856                md = checkfield(md,'fieldname','friction.q','NaN',1,'Inf',1,'size',[md.mesh.numberofelements])
    4957                md = checkfield(md,'fieldname','friction.p','NaN',1,'Inf',1,'size',[md.mesh.numberofelements])
    50 
     58                md = checkfield(md,'fieldname','friction.coupling','numel',[1],'values',[0,1,2,3,4])
     59                if self.coupling==3:
     60                        md = checkfield(md,'fieldname','friction.effective_pressure','NaN',1,'Inf',1,'timeseries',1)
     61                elif self.coupling > 4:
     62                        raise ValueError('md.friction.coupling larger than 4, not supported yet')
    5163                return md
    5264        # }}}
    53         def marshall(self,md,fid):    # {{{
    54                 WriteData(fid,'enum',FrictionLawEnum(),'data',1,'format','Integer')
    55                 WriteData(fid,'object',self,'fieldname','coefficient','format','DoubleMat','mattype',1)
    56                 WriteData(fid,'object',self,'fieldname','p','format','DoubleMat','mattype',2)
    57                 WriteData(fid,'object',self,'fieldname','q','format','DoubleMat','mattype',2)
     65        def marshall(self,prefix,md,fid):    # {{{
     66                WriteData(fid,prefix,'name','md.friction.law','data',1,'format','Integer')
     67                WriteData(fid,prefix,'object',self,'fieldname','coefficient','format','DoubleMat','mattype',1)
     68                WriteData(fid,prefix,'object',self,'fieldname','p','format','DoubleMat','mattype',2)
     69                WriteData(fid,prefix,'object',self,'fieldname','q','format','DoubleMat','mattype',2)
     70                WriteData(fid,prefix,'class','friction','object',self,'fieldname','coupling','format','Integer')
     71                if self.coupling in[3,4]:
     72                        WriteData(fid,prefix,'class','friction','object',self,'fieldname','effective_pressure','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     73                elif self.coupling > 4:
     74                        raise ValueError('md.friction.coupling larger than 4, not supported yet')
    5875        # }}}
  • issm/trunk-jpl/src/py3/classes/frictioncoulomb.py

    r19898 r23670  
    11from fielddisplay import fielddisplay
    22from project3d import project3d
    3 from EnumDefinitions import *
    43from checkfield import checkfield
    54from WriteData import WriteData
     
    1817        self.p = float('NaN')
    1918        self.q = float('NaN')
    20 
     19        self.coupling    = 0
     20        self.effective_pressure = float('NaN')
    2121        #set defaults
    2222        self.setdefaultparameters()
     
    3030        string="%s\n%s"%(string,fielddisplay(self,"p","p exponent"))
    3131        string="%s\n%s"%(string,fielddisplay(self,"q","q exponent"))
     32        string="%s\n%s"%(string,fielddisplay(self,'coupling','Coupling flag: 0 for default, 1 for forcing(provide md.friction.effective_pressure)  and 2 for coupled(not implemented yet)'))
     33        string="%s\n%s"%(string,fielddisplay(self,'effective_pressure','Effective Pressure for the forcing if not coupled [Pa]'))
    3234        return string
    3335    #}}}
     
    3739        self.p=project3d(md,'vector',self.p,'type','element')
    3840        self.q=project3d(md,'vector',self.q,'type','element')
     41        if self.coupling==1:
     42                self.effective_pressure=project3d(md,'vector',self.effective_pressure,'type','node','layer',1)
     43        elif self.coupling==2:
     44                raise ValueError('coupling not supported yet')
     45        elif self.coupling > 2:
     46                raise ValueError('md.friction.coupling larger than 2, not supported yet')       
    3947        return self
    4048    #}}}
     
    4553
    4654        #Early return
    47         if StressbalanceAnalysisEnum() not in analyses and ThermalAnalysisEnum() not in analyses:
     55        if 'StressbalanceAnalysis' not in analyses and 'ThermalAnalysis' not in analyses:
    4856            return md
    4957
     
    5260        md = checkfield(md,'fieldname','friction.q','NaN',1,'Inf',1,'size',[md.mesh.numberofelements])
    5361        md = checkfield(md,'fieldname','friction.p','NaN',1,'Inf',1,'size',[md.mesh.numberofelements])
     62        if self.coupling==1:
     63                md = checkfield(md,'fieldname','friction.effective_pressure','NaN',1,'Inf',1,'timeseries',1)
     64        elif self.coupling==2:
     65                raise ValueError('coupling not supported yet')
     66        elif self.coupling > 2:
     67                raise ValueError('md.friction.coupling larger than 2, not supported yet')
     68        return md
    5469
    55         return md
    5670    # }}}
    57     def marshall(self,md,fid):    # {{{
    58         WriteData(fid,'enum',FrictionLawEnum(),'data',1,'format','Integer')
    59         WriteData(fid,'object',self,'fieldname','coefficient','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'enum',FrictionCoefficientEnum())
    60         WriteData(fid,'object',self,'fieldname','coefficientcoulomb','format','DoubleMat','mattype',1,'enum',FrictionCoefficientcoulombEnum())
    61         WriteData(fid,'object',self,'fieldname','p','format','DoubleMat','mattype',2,'enum',FrictionPEnum())
    62         WriteData(fid,'object',self,'fieldname','q','format','DoubleMat','mattype',2,'enum',FrictionQEnum())
     71    def marshall(self,prefix,md,fid):    # {{{
     72        WriteData(fid,prefix,'name','md.friction.law','data',7,'format','Integer')
     73        WriteData(fid,prefix,'object',self,'fieldname','coefficient','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     74        WriteData(fid,prefix,'object',self,'fieldname','coefficientcoulomb','format','DoubleMat','mattype',1)
     75        WriteData(fid,prefix,'object',self,'fieldname','p','format','DoubleMat','mattype',2)
     76        WriteData(fid,prefix,'object',self,'fieldname','q','format','DoubleMat','mattype',2)
     77        WriteData(fid,prefix,'class','friction','object',self,'fieldname','coupling','format','Integer')
     78        if self.coupling==1:
     79                WriteData(fid,prefix,'class','friction','object',self,'fieldname','effective_pressure','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     80        elif self.coupling==2:
     81                raise ValueError('coupling not supported yet')
     82        elif self.coupling > 2:
     83                raise ValueError('md.friction.coupling larger than 2, not supported yet')       
    6384    # }}}
  • issm/trunk-jpl/src/py3/classes/frictionweertman.py

    r19898 r23670  
    11from fielddisplay import fielddisplay
    22from project3d import project3d
    3 from EnumDefinitions import *
    43from checkfield import checkfield
    54from WriteData import WriteData
     
    3433
    3534                #Early return
    36                 if StressbalanceAnalysisEnum() not in analyses and ThermalAnalysisEnum() not in analyses:
     35                if 'StressbalanceAnalysis' not in analyses and 'ThermalAnalysis' not in analyses:
    3736                        return md
    3837
     
    4241                return md
    4342        # }}}
    44         def marshall(self,md,fid):    # {{{
    45                 WriteData(fid,'enum',FrictionLawEnum(),'data',2,'format','Integer')
    46                 WriteData(fid,'class','friction','object',self,'fieldname','C','format','DoubleMat','mattype',1)
    47                 WriteData(fid,'class','friction','object',self,'fieldname','m','format','DoubleMat','mattype',2)
     43        def marshall(self,prefix,md,fid):    # {{{
     44                WriteData(fid,prefix,'name','md.friction.law','data',2,'format','Integer')
     45                WriteData(fid,prefix,'class','friction','object',self,'fieldname','C','format','DoubleMat','mattype',1)
     46                WriteData(fid,prefix,'class','friction','object',self,'fieldname','m','format','DoubleMat','mattype',2)
    4847        # }}}
  • issm/trunk-jpl/src/py3/classes/geometry.py

    r19898 r23670  
    11from project3d import project3d
    22from fielddisplay import fielddisplay
    3 from EnumDefinitions import *
    43from checkfield import checkfield
    54from WriteData import WriteData
     
    1413
    1514        def __init__(self): # {{{
    16                 self.surface           = float('NaN')
    17                 self.thickness         = float('NaN')
     15                self.surface            = float('NaN')
     16                self.thickness          = float('NaN')
    1817                self.base               = float('NaN')
    19                 self.bed        = float('NaN')
    20                 self.hydrostatic_ratio = float('NaN')
     18                self.bed                = float('NaN')
     19                self.hydrostatic_ratio  = float('NaN')
    2120
    2221                #set defaults
     
    4645        def checkconsistency(self,md,solution,analyses):    # {{{
    4746
    48                 md = checkfield(md,'fieldname','geometry.surface'  ,'NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
    49                 md = checkfield(md,'fieldname','geometry.base'      ,'NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
    50                 md = checkfield(md,'fieldname','geometry.thickness','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices],'>',0,'timeseries',1)
    51                 if any(abs(self.thickness-self.surface+self.base)>10**-9):
    52                         md.checkmessage("equality thickness=surface-base violated")
    53                 if solution==TransientSolutionEnum() and md.transient.isgroundingline:
    54                         md = checkfield(md,'fieldname','geometry.bed','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
     47                if (solution=='TransientSolution' and md.transient.isgia) or (solution=='GiaSolution'):
     48                        md = checkfield(md,'fieldname','geometry.thickness','NaN',1,'Inf',1,'>=',0,'timeseries',1)
     49                elif solution=='LoveSolution':
     50                        return
     51                else:
     52                        md = checkfield(md,'fieldname','geometry.surface'  ,'NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
     53                        md = checkfield(md,'fieldname','geometry.base'      ,'NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
     54                        md = checkfield(md,'fieldname','geometry.thickness','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices],'>',0,'timeseries',1)
     55                        if any(abs(self.thickness-self.surface+self.base)>10**-9):
     56                                md.checkmessage("equality thickness=surface-base violated")
     57                        if solution=='TransientSolution' and md.transient.isgroundingline:
     58                                md = checkfield(md,'fieldname','geometry.bed','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
    5559
    5660                return md
    5761        # }}}
    58         def marshall(self,md,fid):    # {{{
    59                 WriteData(fid,'data',self.surface,'format','DoubleMat','mattype',1,'enum',SurfaceEnum())
    60                 WriteData(fid,'data',self.thickness,'format','DoubleMat','mattype',1,'enum',ThicknessEnum(),'timeserieslength',md.mesh.numberofvertices+1)
    61                 WriteData(fid,'data',self.base,'format','DoubleMat','mattype',1,'enum',BaseEnum())
    62                 WriteData(fid,'data',self.bed,'format','DoubleMat','mattype',1,'enum',BedEnum())
    63                 WriteData(fid,'object',self,'fieldname','hydrostatic_ratio','format','DoubleMat','mattype',1)
     62        def marshall(self,prefix,md,fid):    # {{{
     63                WriteData(fid,prefix,'object',self,'fieldname','surface','format','DoubleMat','mattype',1)
     64                WriteData(fid,prefix,'object',self,'fieldname','thickness','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     65                WriteData(fid,prefix,'object',self,'fieldname','base','format','DoubleMat','mattype',1)
     66                WriteData(fid,prefix,'object',self,'fieldname','bed','format','DoubleMat','mattype',1)
     67                WriteData(fid,prefix,'object',self,'fieldname','hydrostatic_ratio','format','DoubleMat','mattype',1)
    6468        # }}}
  • issm/trunk-jpl/src/py3/classes/groundingline.py

    r19895 r23670  
    1 import numpy
     1import numpy as np
    22from fielddisplay import fielddisplay
    3 from EnumDefinitions import *
    4 from StringToEnum import StringToEnum
    53from checkfield import checkfield
    64from WriteData import WriteData
     
    1715        def __init__(self): # {{{
    1816                self.migration=''
     17                self.friction_interpolation=''
     18                self.melt_interpolation=''
    1919
    2020                #set defaults
     
    2525                string='   grounding line migration parameters:'
    2626
    27                 string="%s\n%s"%(string,fielddisplay(self,'migration','type of grounding line migration: ''SoftMigration'',''AggressiveMigration'',''SubelementMigration'',''SubelementMigration2'',''Contact'',''None'''))
     27                string="%s\n%s"%(string,fielddisplay(self,'migration','type of grounding line migration: ''SoftMigration'',''SubelementMigration'',''AggressiveMigration'',''Contact'',''None'''))
     28                string="%s\n%s"%(string,fielddisplay(self,'migration','type of friction interpolation on partially floating elements: ''SubelementFriction1'',''SubelementFriction2'',''NoFrictionOnPartiallyFloating'''))
     29                string="%s\n%s"%(string,fielddisplay(self,'migration','type of melt interpolation on partially floating elements: ''SubelementMelt1'',''SubelementMelt2'',''NoMeltOnPartiallyFloating'',''FullMeltOnPartiallyFloating'''))
    2830                return string
    2931                #}}}   
     
    3133
    3234                #Type of migration
    33                 self.migration='None'
     35                self.migration='SubelementMigration'
     36                self.friction_interpolation='SubelementFriction1'
     37                self.melt_interpolation='NoMeltOnPartiallyFloating'
    3438
    3539                return self
     
    3741        def checkconsistency(self,md,solution,analyses):    # {{{
    3842
    39                 md = checkfield(md,fieldname='groundingline.migration',values=['None','AggressiveMigration','SoftMigration','SubelementMigration','SubelementMigration2','Contact','GroundingOnly'])
     43                md = checkfield(md,'fieldname','groundingline.migration','values',['None','SubelementMigration','AggressiveMigration','SoftMigration','Contact','GroundingOnly'])
     44                md = checkfield(md,'fieldname','groundingline.friction_interpolation','values',['SubelementFriction1','SubelementFriction2','NoFrictionOnPartiallyFloating'])
     45                md = checkfield(md,'fieldname','groundingline.melt_interpolation','values',['SubelementMelt1','SubelementMelt2','NoMeltOnPartiallyFloating','FullMeltOnPartiallyFloating'])
    4046
    41                 if not m.strcmp(self.migration,'None'):
    42                         if numpy.any(numpy.isnan(md.geometry.bed)):
     47                if(not m.strcmp(self.migration,'None') and md.transient.isgroundingline and solution=='TransientSolution'):
     48                        if np.any(np.isnan(md.geometry.bed)):
    4349                                md.checkmessage("requesting grounding line migration, but bathymetry is absent!")
    44                         pos=numpy.nonzero(md.mask.groundedice_levelset>0.)[0]
    45                         if any(numpy.abs(md.geometry.base[pos]-md.geometry.bed[pos])>10**-10):
     50                        pos=np.nonzero(md.mask.groundedice_levelset>0.)[0]
     51                        if any(np.abs(md.geometry.base[pos]-md.geometry.bed[pos])>10**-10):
    4652                                md.checkmessage("base not equal to bed on grounded ice!")
    4753                        if any(md.geometry.bed - md.geometry.base > 10**-9):
     
    5056                return md
    5157        # }}}
    52         def marshall(self,md,fid):    # {{{
    53                 WriteData(fid,'data',StringToEnum(self.migration)[0],'enum',GroundinglineMigrationEnum(),'format','Integer')
     58        def marshall(self,prefix,md,fid):    # {{{
     59                WriteData(fid,prefix,'data',self.migration,'name','md.groundingline.migration','format','String')
     60                WriteData(fid,prefix,'data',self.friction_interpolation,'name','md.groundingline.friction_interpolation','format','String')
     61                WriteData(fid,prefix,'data',self.melt_interpolation,'name','md.groundingline.melt_interpolation','format','String')
    5462        # }}}
  • issm/trunk-jpl/src/py3/classes/hydrologydc.py

    r19903 r23670  
    1 import numpy
     1import numpy as np
    22from project3d import project3d
    33from fielddisplay import fielddisplay
    4 from EnumDefinitions import *
    54from checkfield import checkfield
    65from WriteData import WriteData
     
    2120                self.rel_tol                  = 0
    2221                self.max_iter                 = 0
     22                self.steps_per_step           = 0
    2323                self.sedimentlimit_flag       = 0
    2424                self.sedimentlimit            = 0
    2525                self.transfer_flag            = 0
     26                self.unconfined_flag          = 0
    2627                self.leakage_factor           = 0
    27                 self.basal_moulin_input       = float('NaN')
    28 
    29                 self.spcsediment_head         = float('NaN')
    30                 self.sediment_transmitivity   = float('NaN')
     28                self.basal_moulin_input       = np.nan
     29                self.requested_outputs        = []
     30
     31                self.spcsediment_head         = np.nan
     32                self.mask_thawed_node         = np.nan
     33                self.sediment_transmitivity   = np.nan
    3134                self.sediment_compressibility = 0
    3235                self.sediment_porosity        = 0
    3336                self.sediment_thickness       = 0
    3437
    35 
    36                 self.spcepl_head              = float('NaN')
    37                 self.mask_eplactive_node      = float('NaN')
     38                self.spcepl_head              = np.nan
     39                self.mask_eplactive_node      = np.nan
    3840                self.epl_compressibility      = 0
    3941                self.epl_porosity             = 0
     
    4446                self.epl_conductivity         = 0
    4547                self.eplflip_lock             = 0
    46                                  
     48
    4749                #set defaults
    4850                self.setdefaultparameters()
     
    5759                string="%s\n%s"%(string,fielddisplay(self,'rel_tol','tolerance of the nonlinear iteration for the transfer between layers [dimensionless]'))
    5860                string="%s\n%s"%(string,fielddisplay(self,'max_iter','maximum number of nonlinear iteration'))
     61                string="%s\n%s"%(string,fielddisplay(self,'steps_per_step','number of hydrology steps per time step'))
    5962                string="%s\n%s"%(string,fielddisplay(self,'basal_moulin_input','water flux at a given point [m3 s-1]'))
     63                string="%s\n%s"%(string,fielddisplay(self,'requested_outputs','additional outputs requested'))
    6064                string="%s\n%s"%(string,fielddisplay(self,'sedimentlimit_flag','what kind of upper limit is applied for the inefficient layer'))
    6165                string="%s\n\t\t%s"%(string,'0: no limit')
     
    6367                string="%s\n\t\t%s"%(string,'2: hydrostatic pressure')
    6468                string="%s\n\t\t%s"%(string,'3: normal stress')
    65        
     69
    6670                if self.sedimentlimit_flag==1:
    6771                        string="%s\n%s"%(string,fielddisplay(self,'sedimentlimit','user defined upper limit for the inefficient layer [m]'))
     
    7074                string="%s\n\t\t%s"%(string,'0: no transfer')
    7175                string="%s\n\t\t%s"%(string,'1: constant leakage factor: leakage_factor')
    72                          
     76
    7377                if self.transfer_flag is 1:
    7478                        string="%s\n%s"%(string,fielddisplay(self,'leakage_factor','user defined leakage factor [m]'))
     79
     80                string="%s\n%s"%(string,fielddisplay(self,'unconfined_flag','using an unconfined scheme or not (transitory)'))
     81                string="%s\n\t\t%s"%(string,'0: Confined only')
     82                string="%s\n\t\t%s"%(string,'1: Confined-Unconfined')
    7583
    7684                string="%s\n%s"%(string,'   - for the sediment layer')
     
    8088                string="%s\n%s"%(string,fielddisplay(self,'sediment_thickness','sediment thickness [m]'))
    8189                string="%s\n%s"%(string,fielddisplay(self,'sediment_transmitivity','sediment transmitivity [m^2/s]'))
     90                string="%s\n%s"%(string,fielddisplay(self,'mask_thawed_node','IDS is deactivaed (0) on frozen nodes'))
    8291
    8392                if self.isefficientlayer==1:
     
    8796                        string="%s\n%s"%(string,fielddisplay(self,'epl_compressibility','epl compressibility [Pa^-1]'))
    8897                        string="%s\n%s"%(string,fielddisplay(self,'epl_porosity','epl [dimensionless]'))
    89                         string="%s\n%s"%(string,fielddisplay(self,'epl_max_thickness','epl initial thickness [m]'))
    90                         string="%s\n%s"%(string,fielddisplay(self,'epl_initial_thickness','epl initial thickness [m]'))                 
     98                        string="%s\n%s"%(string,fielddisplay(self,'epl_max_thickness','epl maximal thickness [m]'))
     99                        string="%s\n%s"%(string,fielddisplay(self,'epl_initial_thickness','epl initial thickness [m]'))
    91100                        string="%s\n%s"%(string,fielddisplay(self,'epl_colapse_thickness','epl colapsing thickness [m]'))
    92101                        string="%s\n%s"%(string,fielddisplay(self,'epl_thick_comp','epl thickness computation flag'))
     
    97106        def extrude(self,md): # {{{
    98107                self.spcsediment_head=project3d(md,'vector',self.spcsediment_head,'type','node','layer',1)
    99                 self.spcepl_head=project3d(md,'vector',self.spcepl_head,'type','node','layer',1)
    100                 self.mask_eplactive_node=project3d(md,'vector',self.mask_eplactive_node,'type','node','layer',1)
    101108                self.sediment_transmitivity=project3d(md,'vector',self.sediment_transmitivity,'type','node','layer',1)
    102109                self.basal_moulin_input=project3d(md,'vector',self.basal_moulin_input,'type','node','layer',1)
     110                self.mask_thawed_node=project3d(md,'vector',self.mask_thawed_node,'type','node','layer',1)
    103111                if self.isefficientlayer==1 :
    104112                        self.spcepl_head=project3d(md,'vector',self.spcepl_head,'type','node','layer',1)
     113                        self.mask_eplactive_node=project3d(md,'vector',self.mask_eplactive_node,'type','node','layer',1)
    105114                return self
    106115        #}}}
    107         def setdefaultparameters(self): #{{{
    108 
     116        def setdefaultparameters(self): #{{{
    109117                #Parameters from de Fleurian 2014
    110118                self.water_compressibility    = 5.04e-10
     
    114122                self.rel_tol                  = 1.0e-06
    115123                self.max_iter                 = 100
     124                self.steps_per_step           = 1
    116125                self.sedimentlimit_flag       = 0
    117126                self.sedimentlimit            = 0
    118127                self.transfer_flag            = 0
     128                self.unconfined_flag          = 0
    119129                self.leakage_factor           = 10.0
     130                self.requested_outputs        = ['default']
    120131
    121132                self.sediment_compressibility = 1.0e-08
     
    125136
    126137                self.epl_compressibility      = 1.0e-08
     138                self.epl_conductivity         = 8.0e-02
    127139                self.epl_porosity             = 0.4
    128140                self.epl_initial_thickness    = 1.0
    129                 self.epl_colapse_thickness    = 1.0e-3
     141                self.epl_colapse_thickness    = self.sediment_transmitivity/self.epl_conductivity
    130142                self.epl_thick_comp           = 1
    131143                self.epl_max_thickness        = 5.0
    132                 self.epl_conductivity         = 8.0e-02
    133144                self.eplflip_lock             = 0
    134                
     145
    135146                return self
    136147        # }}}
     148
     149        def defaultoutputs(self,md): # {{{
     150                list = ['SedimentHeadHydrostep','SedimentHeadResidual','EffectivePressureHydrostep']
     151                if self.isefficientlayer==1:
     152                        list.extend(['EplHeadHydrostep','HydrologydcMaskEplactiveNode','HydrologydcMaskEplactiveElt','EplHeadSlopeX','EplHeadSlopeY','HydrologydcEplThicknessHydrostep'])
     153                if self.steps_per_step>1:
     154                        list.extend(['EffectivePressure','SedimentHead'])
     155                        if self.isefficientlayer==1:
     156                                list.extend(['EplHead','HydrologydcEplThickness'])
     157                return list
     158        #}}}
     159
    137160        def initialize(self,md): # {{{
    138                 if numpy.all(numpy.isnan(self.basal_moulin_input)):
    139                         self.basal_moulin_input=numpy.zeros((md.mesh.numberofvertices,1))
     161                self.epl_colapse_thickness = self.sediment_transmitivity/self.epl_conductivity
     162                if np.all(np.isnan(self.basal_moulin_input)):
     163                        self.basal_moulin_input=np.zeros((md.mesh.numberofvertices))
    140164                        print("      no hydrology.basal_moulin_input specified: values set as zero")
    141165
    142166                return self
    143167        # }}}
    144         def checkconsistency(self,md,solution,analyses): #{{{ 
     168        def checkconsistency(self,md,solution,analyses): #{{{
    145169
    146170                #Early return
    147                 if HydrologyDCInefficientAnalysisEnum() not in analyses and HydrologyDCEfficientAnalysisEnum() not in analyses:
     171                if 'HydrologyDCInefficientAnalysis' not in analyses and 'HydrologyDCEfficientAnalysis' not in analyses:
    148172                        return md
    149173
     
    154178                md = checkfield(md,'fieldname','hydrology.rel_tol','>',0.,'numel',[1])
    155179                md = checkfield(md,'fieldname','hydrology.max_iter','>',0.,'numel',[1])
     180                md = checkfield(md,'fieldname','hydrology.steps_per_step','>',0.,'numel',[1])
    156181                md = checkfield(md,'fieldname','hydrology.sedimentlimit_flag','numel',[1],'values',[0,1,2,3])
    157182                md = checkfield(md,'fieldname','hydrology.transfer_flag','numel',[1],'values',[0,1])
     183                md = checkfield(md,'fieldname','hydrology.unconfined_flag','numel',[1],'values',[0,1])
     184                md = checkfield(md,'fieldname','hydrology.requested_outputs','stringrow',1)
    158185
    159186                if self.sedimentlimit_flag==1:
     
    168195                md = checkfield(md,'fieldname','hydrology.sediment_porosity','>',0.,'numel',[1])
    169196                md = checkfield(md,'fieldname','hydrology.sediment_thickness','>',0.,'numel',[1])
    170                 md = checkfield(md,'fieldname','hydrology.sediment_transmitivity','>=',0,'size',[md.mesh.numberofvertices,1])
     197                md = checkfield(md,'fieldname','hydrology.sediment_transmitivity','>=',0,'size',[md.mesh.numberofvertices])
     198                md = checkfield(md,'fieldname','hydrology.mask_thawed_node','size',[md.mesh.numberofvertices],'values',[0,1])
    171199                if self.isefficientlayer==1:
    172200                        md = checkfield(md,'fieldname','hydrology.spcepl_head','Inf',1,'timeseries',1)
    173                         md = checkfield(md,'fieldname','hydrology.mask_eplactive_node','size',[md.mesh.numberofvertices,1],'values',[0,1])
     201                        md = checkfield(md,'fieldname','hydrology.mask_eplactive_node','size',[md.mesh.numberofvertices],'values',[0,1])
    174202                        md = checkfield(md,'fieldname','hydrology.epl_compressibility','>',0.,'numel',[1])
    175203                        md = checkfield(md,'fieldname','hydrology.epl_porosity','>',0.,'numel',[1])
     
    183211                        md = checkfield(md,'fieldname','hydrology.epl_conductivity','numel',[1],'>',0.)
    184212        # }}}
    185         def marshall(self,md,fid): #{{{
    186                 WriteData(fid,'enum',HydrologyModelEnum(),'data',HydrologydcEnum(),'format','Integer')
    187                 WriteData(fid,'object',self,'fieldname','water_compressibility','format','Double')
    188                 WriteData(fid,'object',self,'fieldname','isefficientlayer','format','Boolean')
    189                 WriteData(fid,'object',self,'fieldname','penalty_factor','format','Double')
    190                 WriteData(fid,'object',self,'fieldname','penalty_lock','format','Integer')
    191                 WriteData(fid,'object',self,'fieldname','rel_tol','format','Double')
    192                 WriteData(fid,'object',self,'fieldname','max_iter','format','Integer')
    193                 WriteData(fid,'object',self,'fieldname','sedimentlimit_flag','format','Integer')
    194                 WriteData(fid,'object',self,'fieldname','transfer_flag','format','Integer')
     213        def marshall(self,prefix,md,fid): #{{{
     214                WriteData(fid,prefix,'name','md.hydrology.model','data',1,'format','Integer')
     215                WriteData(fid,prefix,'object',self,'fieldname','water_compressibility','format','Double')
     216                WriteData(fid,prefix,'object',self,'fieldname','isefficientlayer','format','Boolean')
     217                WriteData(fid,prefix,'object',self,'fieldname','penalty_factor','format','Double')
     218                WriteData(fid,prefix,'object',self,'fieldname','penalty_lock','format','Integer')
     219                WriteData(fid,prefix,'object',self,'fieldname','rel_tol','format','Double')
     220                WriteData(fid,prefix,'object',self,'fieldname','max_iter','format','Integer')
     221                WriteData(fid,prefix,'object',self,'fieldname','steps_per_step','format','Integer')
     222                WriteData(fid,prefix,'object',self,'fieldname','sedimentlimit_flag','format','Integer')
     223                WriteData(fid,prefix,'object',self,'fieldname','transfer_flag','format','Integer')
     224                WriteData(fid,prefix,'object',self,'fieldname','unconfined_flag','format','Integer')
    195225                if self.sedimentlimit_flag==1:
    196                         WriteData(fid,'object',self,'fieldname','sedimentlimit','format','Double')
     226                        WriteData(fid,prefix,'object',self,'fieldname','sedimentlimit','format','Double')
    197227
    198228                if self.transfer_flag==1:
    199                         WriteData(fid,'object',self,'fieldname','leakage_factor','format','Double')
    200 
    201                 WriteData(fid,'object',self,'fieldname','basal_moulin_input','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1)
    202                 WriteData(fid,'object',self,'fieldname','spcsediment_head','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1)
    203                 WriteData(fid,'object',self,'fieldname','sediment_compressibility','format','Double')
    204                 WriteData(fid,'object',self,'fieldname','sediment_porosity','format','Double')                 
    205                 WriteData(fid,'object',self,'fieldname','sediment_thickness','format','Double')
    206                 WriteData(fid,'object',self,'fieldname','sediment_transmitivity','format','DoubleMat','mattype',1)             
    207 
    208                 if self.isefficientlayer==1:   
    209                         WriteData(fid,'object',self,'fieldname','spcepl_head','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1)   
    210                         WriteData(fid,'object',self,'fieldname','mask_eplactive_node','format','DoubleMat','mattype',1)
    211                         WriteData(fid,'object',self,'fieldname','epl_compressibility','format','Double')                       
    212                         WriteData(fid,'object',self,'fieldname','epl_porosity','format','Double')                       
    213                         WriteData(fid,'object',self,'fieldname','epl_max_thickness','format','Double')
    214                         WriteData(fid,'object',self,'fieldname','epl_initial_thickness','format','Double')                     
    215                         WriteData(fid,'object',self,'fieldname','epl_colapse_thickness','format','Double')
    216                         WriteData(fid,'object',self,'fieldname','epl_thick_comp','format','Integer')                   
    217                         WriteData(fid,'object',self,'fieldname','epl_conductivity','format','Double')
    218                         WriteData(fid,'object',self,'fieldname','eplflip_lock','format','Integer')
    219         # }}}
     229                        WriteData(fid,prefix,'object',self,'fieldname','leakage_factor','format','Double')
     230
     231                WriteData(fid,prefix,'object',self,'fieldname','basal_moulin_input','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     232                WriteData(fid,prefix,'object',self,'fieldname','spcsediment_head','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     233                WriteData(fid,prefix,'object',self,'fieldname','sediment_compressibility','format','Double')
     234                WriteData(fid,prefix,'object',self,'fieldname','sediment_porosity','format','Double')
     235                WriteData(fid,prefix,'object',self,'fieldname','sediment_thickness','format','Double')
     236                WriteData(fid,prefix,'object',self,'fieldname','sediment_transmitivity','format','DoubleMat','mattype',1)
     237                WriteData(fid,prefix,'object',self,'fieldname','mask_thawed_node','format','DoubleMat','mattype',1)
     238
     239                if self.isefficientlayer==1:
     240                        WriteData(fid,prefix,'object',self,'fieldname','spcepl_head','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     241                        WriteData(fid,prefix,'object',self,'fieldname','mask_eplactive_node','format','DoubleMat','mattype',1)
     242                        WriteData(fid,prefix,'object',self,'fieldname','epl_compressibility','format','Double')
     243                        WriteData(fid,prefix,'object',self,'fieldname','epl_porosity','format','Double')
     244                        WriteData(fid,prefix,'object',self,'fieldname','epl_max_thickness','format','Double')
     245                        WriteData(fid,prefix,'object',self,'fieldname','epl_initial_thickness','format','Double')
     246                        WriteData(fid,prefix,'object',self,'fieldname','epl_colapse_thickness','format','Double')
     247                        WriteData(fid,prefix,'object',self,'fieldname','epl_thick_comp','format','Integer')
     248                        WriteData(fid,prefix,'object',self,'fieldname','epl_conductivity','format','Double')
     249                        WriteData(fid,prefix,'object',self,'fieldname','eplflip_lock','format','Integer')
     250
     251                #process requested outputs
     252                outputs = self.requested_outputs
     253                indices = [i for i, x in enumerate(outputs) if x == 'default']
     254                if len(indices) > 0:
     255                        outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:]
     256                        outputs    =outputscopy
     257                WriteData(fid,prefix,'data',outputs,'name','md.hydrology.requested_outputs','format','StringArray')
     258        # }}}
  • issm/trunk-jpl/src/py3/classes/hydrologyshreve.py

    r19903 r23670  
    11from fielddisplay import fielddisplay
    2 from EnumDefinitions import *
    32from checkfield import checkfield
    43from WriteData import WriteData
     
    1514                self.spcwatercolumn = float('NaN')
    1615                self.stabilization  = 0
    17 
     16                self.requested_outputs = []
    1817                #set defaults
    1918                self.setdefaultparameters()
     
    2524                string="%s\n%s"%(string,fielddisplay(self,'spcwatercolumn','water thickness constraints (NaN means no constraint) [m]'))
    2625                string="%s\n%s"%(string,fielddisplay(self,'stabilization','artificial diffusivity (default is 1). can be more than 1 to increase diffusivity.'))
     26                string="%s\n%s"%(string,fielddisplay(self,'requested_outputs','additional outputs requested'))
    2727                return string
    2828                #}}}
     
    3434                #Type of stabilization to use 0:nothing 1:artificial_diffusivity
    3535                self.stabilization=1
    36 
     36                self.requested_outputs= ['default']
    3737                return self
    3838        #}}}
     39        def defaultoutputs(self,md): # {{{
     40                list = ['Watercolumn','HydrologyWaterVx','HydrologyWaterVy']
     41                return list
     42        #}}}
     43
    3944        def checkconsistency(self,md,solution,analyses):    # {{{
    4045               
    4146                #Early return
    42                 if HydrologyShreveAnalysisEnum() not in analyses:
     47                if 'HydrologyShreveAnalysis' not in analyses:
    4348                        return md
    4449
    4550                md = checkfield(md,'fieldname','hydrology.spcwatercolumn','Inf',1,'timeseries',1)
    4651                md = checkfield(md,'fieldname','hydrology.stabilization','>=',0)
    47 
     52                md = checkfield(md,'fieldname','hydrology.requested_outputs','stringrow',1)
    4853                return md
    4954        # }}}
    50         def marshall(self,md,fid):    # {{{
    51                 WriteData(fid,'enum',HydrologyModelEnum(),'data',HydrologyshreveEnum(),'format','Integer');
    52                 WriteData(fid,'object',self,'fieldname','spcwatercolumn','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1)
    53                 WriteData(fid,'object',self,'fieldname','stabilization','format','Double')
     55        def marshall(self,prefix,md,fid):    # {{{
     56                WriteData(fid,prefix,'name','md.hydrology.model','data',2,'format','Integer');
     57                WriteData(fid,prefix,'object',self,'fieldname','spcwatercolumn','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     58                WriteData(fid,prefix,'object',self,'fieldname','stabilization','format','Double')
     59                #process requested outputs
     60                outputs = self.requested_outputs
     61                indices = [i for i, x in enumerate(outputs) if x == 'default']
     62                if len(indices) > 0:
     63                        outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:]
     64                        outputs    =outputscopy
     65                WriteData(fid,prefix,'data',outputs,'name','md.hydrology.requested_outputs','format','StringArray')
     66
    5467        # }}}
  • issm/trunk-jpl/src/py3/classes/independent.py

    r19895 r23670  
    1 import numpy
     1import numpy as np
    22from pairoptions import pairoptions
    33from fielddisplay import fielddisplay
    4 import MatlabFuncs as m
    5 from EnumDefinitions import *
     4from checkfield import checkfield
     5from MatlabFuncs import *
    66
    77class independent(object):
     
    1313        """
    1414
    15         def __init__(self,**kwargs):    # {{{
     15        def __init__(self,*args):    # {{{
    1616                self.name                 = ''
    1717                self.type                 = ''
    1818                self.fos_forward_index    = float('NaN')
    19                 self.fov_forward_indices  = numpy.array([])
     19                self.fov_forward_indices  = np.array([])
    2020                self.nods                 = 0
    2121
     
    2424
    2525                #use provided options to change fields
    26                 options=pairoptions(**kwargs)
     26                options=pairoptions(*args)
    2727
    2828                #OK get other fields
     
    3232                s ="   independent variable:\n"
    3333
    34                 s+="%s\n" % fielddisplay(self,'name',"variable name (must match corresponding Enum)")
     34                s+="%s\n" % fielddisplay(self,'name',"variable name (must match corresponding String)")
    3535                s+="%s\n" % fielddisplay(self,'type',"type of variable ('vertex' or 'scalar')")
    36                 if not numpy.isnan(self.fos_forward_index):
     36                if not np.isnan(self.fos_forward_index):
    3737                        s+="%s\n" % fielddisplay(self,'fos_forward_index',"index for fos_foward driver of ADOLC")
    38                 if numpy.any(numpy.logical_not(numpy.isnan(self.fov_forward_indices))):
     38                if np.any(np.logical_not(np.isnan(self.fov_forward_indices))):
    3939                        s+="%s\n" % fielddisplay(self,'fov_forward_indices',"indices for fov_foward driver of ADOLC")
    4040
     
    4646        # }}}
    4747        def checkconsistency(self,md,i,solution,analyses,driver):    # {{{
    48                 if not numpy.isnan(self.fos_forward_index):
     48                if not np.isnan(self.fos_forward_index):
    4949                        if not strcmpi(driver,'fos_forward'):
    5050                                raise TypeError("cannot declare an independent with a fos_forward_index when the driver is not fos_forward!")
     
    5252                                raise TypeError("independent checkconsistency error: nods should be set to the size of the independent variable")
    5353
    54                 if self.fov_forward_indices:
     54                if len(self.fov_forward_indices) > 0:
    5555                        if not strcmpi(driver,'fov_forward'):
    5656                                raise TypeError("cannot declare an independent with fov_forward_indices when the driver is not fov_forward!")
    5757                        if self.nods==0:
    5858                                raise TypeError("independent checkconsistency error: nods should be set to the size of the independent variable")
    59                         md = checkfield(md,'fieldname',"autodiff.independents[%d].fov_forward_indices" % i,'>=',1,'<=',self.nods,'size',[float('NaN'),1])
     59                        md = checkfield(md,'fieldname',"autodiff.independents[%d].fov_forward_indices" % i,'>=',1,'<=',self.nods)
    6060
    6161                return md
  • issm/trunk-jpl/src/py3/classes/initialization.py

    r19898 r23670  
    1 import numpy
     1import numpy as np
    22from project3d import project3d
    33from fielddisplay import fielddisplay
    4 from EnumDefinitions import *
    54from checkfield import checkfield
    65from WriteData import WriteData
     
    6261
    6362                #Lithostatic pressure by default
    64                 self.pressure=md.constants.g*md.materials.rho_ice*(md.geometry.surface-md.mesh.z.reshape(-1,1))
     63                #               self.pressure=md.constants.g*md.materials.rho_ice*(md.geometry.surface[:,0]-md.mesh.z)
     64                #self.pressure=md.constants.g*md.materials.rho_ice*(md.geometry.surface-md.mesh.z.reshape(-1,))
     65
     66                if np.ndim(md.geometry.surface)==2:
     67                        print('Reshaping md.geometry.surface for you convenience but you should fix it in you files')
     68                        self.pressure=md.constants.g*md.materials.rho_ice*(md.geometry.surface.reshape(-1,)-md.mesh.z)
     69                else:
     70                        self.pressure=md.constants.g*md.materials.rho_ice*(md.geometry.surface-md.mesh.z)
     71
    6572                return self
    6673        #}}}
     
    6976        #}}}
    7077        def checkconsistency(self,md,solution,analyses):    # {{{
    71                 if StressbalanceAnalysisEnum() in analyses:
    72                         if not numpy.any(numpy.logical_or(numpy.isnan(md.initialization.vx),numpy.isnan(md.initialization.vy))):
     78                if 'StressbalanceAnalysis' in analyses:
     79                        if not np.any(np.logical_or(np.isnan(md.initialization.vx),np.isnan(md.initialization.vy))):
    7380                                md = checkfield(md,'fieldname','initialization.vx','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
    7481                                md = checkfield(md,'fieldname','initialization.vy','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
    75                 if MasstransportAnalysisEnum() in analyses:
     82                if 'MasstransportAnalysis' in analyses:
    7683                        md = checkfield(md,'fieldname','initialization.vx','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
    7784                        md = checkfield(md,'fieldname','initialization.vy','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
    78                 if BalancethicknessAnalysisEnum() in analyses:
     85                if 'BalancethicknessAnalysis' in analyses:
    7986                        md = checkfield(md,'fieldname','initialization.vx','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
    8087                        md = checkfield(md,'fieldname','initialization.vy','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
    8188                        #Triangle with zero velocity
    82                         if numpy.any(numpy.logical_and(numpy.sum(numpy.abs(md.initialization.vx[md.mesh.elements-1]),axis=1)==0,\
    83                                                        numpy.sum(numpy.abs(md.initialization.vy[md.mesh.elements-1]),axis=1)==0)):
     89                        if np.any(np.logical_and(np.sum(np.abs(md.initialization.vx[md.mesh.elements-1]),axis=1)==0,\
     90                                                       np.sum(np.abs(md.initialization.vy[md.mesh.elements-1]),axis=1)==0)):
    8491                                md.checkmessage("at least one triangle has all its vertices with a zero velocity")
    85                 if ThermalAnalysisEnum() in analyses:
     92                if 'ThermalAnalysis' in analyses:
    8693                        md = checkfield(md,'fieldname','initialization.vx','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
    8794                        md = checkfield(md,'fieldname','initialization.vy','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
     
    9097                                md = checkfield(md,'fieldname','initialization.vz','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
    9198                        md = checkfield(md,'fieldname','initialization.pressure','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
    92                         if (EnthalpyAnalysisEnum() in analyses and md.thermal.isenthalpy):
     99                        if ('EnthalpyAnalysis' in analyses and md.thermal.isenthalpy):
    93100                                md = checkfield(md,'fieldname','initialization.waterfraction','>=',0,'size',[md.mesh.numberofvertices])
    94101                                md = checkfield(md,'fieldname','initialization.watercolumn'  ,'>=',0,'size',[md.mesh.numberofvertices])
    95                 if HydrologyShreveAnalysisEnum() in analyses:
     102                                pos = np.nonzero(md.initialization.waterfraction > 0.)[0]
     103                                if(pos.size):
     104                                        md = checkfield(md,'fieldname', 'delta Tpmp', 'field', np.absolute(md.initialization.temperature[pos]-(md.materials.meltingpoint-md.materials.beta*md.initialization.pressure[pos])),'<',1e-11, 'message','set temperature to pressure melting point at locations with waterfraction>0');
     105                if 'HydrologyShreveAnalysis' in analyses:
    96106                        if hasattr(md.hydrology,'hydrologyshreve'):
    97107                                md = checkfield(md,'fieldname','initialization.watercolumn','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
    98                 if HydrologyDCInefficientAnalysisEnum() in analyses:
     108                if 'HydrologyDCInefficientAnalysis' in analyses:
    99109                        if hasattr(md.hydrology,'hydrologydc'):
    100                                 md = checkfield(md,'fieldname','initialization.sediment_head','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices,1])
    101                 if HydrologyDCEfficientAnalysisEnum() in analyses:
     110                                md = checkfield(md,'fieldname','initialization.sediment_head','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
     111                if 'HydrologyDCEfficientAnalysis' in analyses:
    102112                        if hasattr(md.hydrology,'hydrologydc'):
    103113                                if md.hydrology.isefficientlayer==1:
    104                                         md = checkfield(md,'fieldname','initialization.epl_head','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices,1])
    105                                         md = checkfield(md,'fieldname','initialization.epl_thickness','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices,1])
     114                                        md = checkfield(md,'fieldname','initialization.epl_head','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
     115                                        md = checkfield(md,'fieldname','initialization.epl_thickness','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
    106116
    107117                return md
    108118        # }}}
    109         def marshall(self,md,fid):    # {{{
     119        def marshall(self,prefix,md,fid):    # {{{
    110120
    111                 yts=365.0*24.0*3600.0
     121                yts=md.constants.yts
    112122
    113                 WriteData(fid,'data',self.vx,'format','DoubleMat','mattype',1,'enum',VxEnum(),'scale',1./yts)
    114                 WriteData(fid,'data',self.vy,'format','DoubleMat','mattype',1,'enum',VyEnum(),'scale',1./yts)
    115                 WriteData(fid,'data',self.vz,'format','DoubleMat','mattype',1,'enum',VzEnum(),'scale',1./yts)
    116                 WriteData(fid,'data',self.pressure,'format','DoubleMat','mattype',1,'enum',PressureEnum())
    117                 WriteData(fid,'data',self.temperature,'format','DoubleMat','mattype',1,'enum',TemperatureEnum())
    118                 WriteData(fid,'data',self.waterfraction,'format','DoubleMat','mattype',1,'enum',WaterfractionEnum())
    119                 WriteData(fid,'data',self.watercolumn,'format','DoubleMat','mattype',1,'enum',WatercolumnEnum())
    120                 WriteData(fid,'data',self.sediment_head,'format','DoubleMat','mattype',1,'enum',SedimentHeadEnum())
    121                 WriteData(fid,'data',self.epl_head,'format','DoubleMat','mattype',1,'enum',EplHeadEnum())
    122                 WriteData(fid,'data',self.epl_thickness,'format','DoubleMat','mattype',1,'enum',HydrologydcEplThicknessEnum())
    123 
     123                WriteData(fid,prefix,'object',self,'fieldname','vx','format','DoubleMat','mattype',1,'scale',1./yts)
     124                WriteData(fid,prefix,'object',self,'fieldname','vy','format','DoubleMat','mattype',1,'scale',1./yts)
     125                WriteData(fid,prefix,'object',self,'fieldname','vz','format','DoubleMat','mattype',1,'scale',1./yts)
     126                WriteData(fid,prefix,'object',self,'fieldname','pressure','format','DoubleMat','mattype',1)
     127                WriteData(fid,prefix,'object',self,'fieldname','temperature','format','DoubleMat','mattype',1)
     128                WriteData(fid,prefix,'object',self,'fieldname','waterfraction','format','DoubleMat','mattype',1)
     129                WriteData(fid,prefix,'object',self,'fieldname','sediment_head','format','DoubleMat','mattype',1)
     130                WriteData(fid,prefix,'object',self,'fieldname','epl_head','format','DoubleMat','mattype',1)
     131                WriteData(fid,prefix,'object',self,'fieldname','epl_thickness','format','DoubleMat','mattype',1)
     132                WriteData(fid,prefix,'object',self,'fieldname','watercolumn','format','DoubleMat','mattype',1)
    124133               
    125134                if md.thermal.isenthalpy:
    126135                        tpmp = md.materials.meltingpoint - md.materials.beta*md.initialization.pressure;
    127                         pos  = numpy.nonzero(md.initialization.temperature > tpmp)[0]
     136                        pos  = np.nonzero(md.initialization.waterfraction > 0.)[0]
    128137                        enthalpy      = md.materials.heatcapacity*(md.initialization.temperature-md.constants.referencetemperature);
    129                         enthalpy[pos] = md.materials.heatcapacity*tpmp[pos].reshape(-1,1) - md.constants.referencetemperature + md.materials.latentheat*md.initialization.waterfraction[pos].reshape(-1,1)
    130                         WriteData(fid,'data',enthalpy,'format','DoubleMat','mattype',1,'enum',EnthalpyEnum());
     138                        enthalpy[pos] = md.materials.heatcapacity*(tpmp[pos].reshape(-1,) - md.constants.referencetemperature) + md.materials.latentheat*md.initialization.waterfraction[pos].reshape(-1,)
     139                        WriteData(fid,prefix,'data',enthalpy,'format','DoubleMat','mattype',1,'name','md.initialization.enthalpy');
    131140
    132141        # }}}
  • issm/trunk-jpl/src/py3/classes/inversion.py

    r19898 r23670  
    1 import numpy
     1import numpy as np
    22from project3d import project3d
    33from fielddisplay import fielddisplay
    4 from EnumDefinitions import *
    5 from StringToEnum import StringToEnum
    64from checkfield import checkfield
    75from WriteData import WriteData
     
    2422                self.nsteps                      = 0
    2523                self.maxiter_per_step            = float('NaN')
    26                 self.cost_functions              = float('NaN')
     24                self.cost_functions              = ''
    2725                self.cost_functions_coefficients = float('NaN')
    2826                self.gradient_scaling            = float('NaN')
     
    7876                self.vel_obs=project3d(md,'vector',self.vel_obs,'type','node')
    7977                self.thickness_obs=project3d(md,'vector',self.thickness_obs,'type','node')
    80                 if not numpy.any(numpy.isnan(self.cost_functions_coefficients)):
     78                if not np.any(np.isnan(self.cost_functions_coefficients)):
    8179                        self.cost_functions_coefficients=project3d(md,'vector',self.cost_functions_coefficients,'type','node')
    82                 if not numpy.any(numpy.isnan(self.min_parameters)):
     80                if not np.any(np.isnan(self.min_parameters)):
    8381                        self.min_parameters=project3d(md,'vector',self.min_parameters,'type','node')
    84                 if not numpy.any(numpy.isnan(self.max_parameters)):
     82                if not np.any(np.isnan(self.max_parameters)):
    8583                        self.max_parameters=project3d(md,'vector',self.max_parameters,'type','node')
    8684                return self
     
    10098                #maximum number of iteration in the optimization algorithm for
    10199                #each step
    102                 self.maxiter_per_step=20*numpy.ones(self.nsteps)
     100                self.maxiter_per_step=20*np.ones(self.nsteps)
    103101
    104102                #the inversed parameter is updated as follows:
     
    107105                #inversed parameter (10^8 for B, 50 for drag) and can be decreased
    108106                #after the first iterations
    109                 self.gradient_scaling=50*numpy.ones((self.nsteps,1))
     107                self.gradient_scaling=50*np.ones((self.nsteps,1))
    110108
    111109                #several responses can be used:
    112                 self.cost_functions=101
     110                self.cost_functions=[101,]
    113111
    114112                #step_threshold is used to speed up control method. When
    115113                #misfit(1)/misfit(0) < self.step_threshold, we go directly to
    116114                #the next step
    117                 self.step_threshold=.7*numpy.ones(self.nsteps) #30 per cent decrement
     115                self.step_threshold=.7*np.ones(self.nsteps) #30 per cent decrement
    118116
    119117                #cost_function_threshold is a criteria to stop the control methods.
     
    130128                        return md
    131129
    132                 num_controls=numpy.size(md.inversion.control_parameters)
    133                 num_costfunc=numpy.size(md.inversion.cost_functions)
     130                num_controls=np.size(md.inversion.control_parameters)
     131                num_costfunc=np.size(md.inversion.cost_functions)
    134132
    135133                md = checkfield(md,'fieldname','inversion.iscontrol','values',[0,1])
     
    146144
    147145                #Only SSA, HO and FS are supported right now
    148                 if solution==StressbalanceSolutionEnum():
     146                if solution=='StressbalanceSolution':
    149147                        if not (md.flowequation.isSSA or md.flowequation.isHO or md.flowequation.isFS or md.flowequation.isL1L2):
    150148                                md.checkmessage("'inversion can only be performed for SSA, HO or FS ice flow models");
    151149
    152                 if solution==BalancethicknessSolutionEnum():
     150                if solution=='BalancethicknessSolution':
    153151                        md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices],'NaN',1,'Inf',1)
    154152                else:
     
    158156                return md
    159157        # }}}
    160         def marshall(self,md,fid):    # {{{
     158        def marshall(self,prefix,md,fid):    # {{{
    161159
    162                 yts=365.0*24.0*3600.0
     160                yts=md.constants.yts
    163161
    164                 WriteData(fid,'enum',InversionTypeEnum(),'data',0,'format','Integer')
    165                 WriteData(fid,'object',self,'fieldname','iscontrol','format','Boolean')
    166                 WriteData(fid,'object',self,'fieldname','incomplete_adjoint','format','Boolean')
     162                WriteData(fid,prefix,'name','md.inversion.type','data',0,'format','Integer')
     163                WriteData(fid,prefix,'object',self,'fieldname','iscontrol','format','Boolean')
     164                WriteData(fid,prefix,'object',self,'fieldname','incomplete_adjoint','format','Boolean')
     165                WriteData(fid,prefix,'object',self,'fieldname','vel_obs','format','DoubleMat','mattype',1,'scale',1./yts)
    167166                if not self.iscontrol:
    168167                        return
    169                 WriteData(fid,'object',self,'fieldname','nsteps','format','Integer')
    170                 WriteData(fid,'object',self,'fieldname','maxiter_per_step','format','DoubleMat','mattype',3)
    171                 WriteData(fid,'object',self,'fieldname','cost_functions_coefficients','format','DoubleMat','mattype',1)
    172                 WriteData(fid,'object',self,'fieldname','gradient_scaling','format','DoubleMat','mattype',3)
    173                 WriteData(fid,'object',self,'fieldname','cost_function_threshold','format','Double')
    174                 WriteData(fid,'object',self,'fieldname','min_parameters','format','DoubleMat','mattype',3)
    175                 WriteData(fid,'object',self,'fieldname','max_parameters','format','DoubleMat','mattype',3)
    176                 WriteData(fid,'object',self,'fieldname','step_threshold','format','DoubleMat','mattype',3)
    177                 WriteData(fid,'object',self,'fieldname','vx_obs','format','DoubleMat','mattype',1,'scale',1./yts)
    178                 WriteData(fid,'object',self,'fieldname','vy_obs','format','DoubleMat','mattype',1,'scale',1./yts)
    179                 WriteData(fid,'object',self,'fieldname','vz_obs','format','DoubleMat','mattype',1,'scale',1./yts)
    180                 WriteData(fid,'object',self,'fieldname','thickness_obs','format','DoubleMat','mattype',1)
    181                 WriteData(fid,'object',self,'fieldname','surface_obs','format','DoubleMat','mattype',1)
     168                WriteData(fid,prefix,'object',self,'fieldname','nsteps','format','Integer')
     169                WriteData(fid,prefix,'object',self,'fieldname','maxiter_per_step','format','DoubleMat','mattype',3)
     170                WriteData(fid,prefix,'object',self,'fieldname','cost_functions_coefficients','format','DoubleMat','mattype',1)
     171                WriteData(fid,prefix,'object',self,'fieldname','gradient_scaling','format','DoubleMat','mattype',3)
     172                WriteData(fid,prefix,'object',self,'fieldname','cost_function_threshold','format','Double')
     173                WriteData(fid,prefix,'object',self,'fieldname','min_parameters','format','DoubleMat','mattype',3)
     174                WriteData(fid,prefix,'object',self,'fieldname','max_parameters','format','DoubleMat','mattype',3)
     175                WriteData(fid,prefix,'object',self,'fieldname','step_threshold','format','DoubleMat','mattype',3)
     176                WriteData(fid,prefix,'object',self,'fieldname','vx_obs','format','DoubleMat','mattype',1,'scale',1./yts)
     177                WriteData(fid,prefix,'object',self,'fieldname','vy_obs','format','DoubleMat','mattype',1,'scale',1./yts)
     178                WriteData(fid,prefix,'object',self,'fieldname','vz_obs','format','DoubleMat','mattype',1,'scale',1./yts)
     179                WriteData(fid,prefix,'object',self,'fieldname','thickness_obs','format','DoubleMat','mattype',1)
     180                WriteData(fid,prefix,'object',self,'fieldname','surface_obs','format','DoubleMat','mattype',1)
    182181
    183182                #process control parameters
    184183                num_control_parameters=len(self.control_parameters)
    185                 data=numpy.array([StringToEnum(control_parameter)[0] for control_parameter in self.control_parameters]).reshape(1,-1)
    186                 WriteData(fid,'data',data,'enum',InversionControlParametersEnum(),'format','DoubleMat','mattype',3)
    187                 WriteData(fid,'data',num_control_parameters,'enum',InversionNumControlParametersEnum(),'format','Integer')
     184                WriteData(fid,prefix,'object',self,'fieldname','control_parameters','format','StringArray')
     185                WriteData(fid,prefix,'data',num_control_parameters,'name','md.inversion.num_control_parameters','format','Integer')
    188186
    189187                #process cost functions
    190                 num_cost_functions=numpy.size(self.cost_functions)
     188                num_cost_functions=np.size(self.cost_functions)
    191189                data=marshallcostfunctions(self.cost_functions)
    192                 WriteData(fid,'data',numpy.array(data).reshape(1,-1),'enum',InversionCostFunctionsEnum(),'format','DoubleMat','mattype',3)
    193                 WriteData(fid,'data',num_cost_functions,'enum',InversionNumCostFunctionsEnum(),'format','Integer')
     190                WriteData(fid,prefix,'data',data,'name','md.inversion.cost_functions','format','StringArray')
     191                WriteData(fid,prefix,'data',num_cost_functions,'name','md.inversion.num_cost_functions','format','Integer')
    194192        # }}}
  • issm/trunk-jpl/src/py3/classes/linearbasalforcings.py

    r19898 r23670  
    11from fielddisplay import fielddisplay
    2 from EnumDefinitions import *
    32from checkfield import checkfield
    43from WriteData import WriteData
    5 import numpy
     4import numpy as np
    65
    76class linearbasalforcings(object):
     
    5251        def initialize(self,md): # {{{
    5352
    54                 if numpy.all(numpy.isnan(self.groundedice_melting_rate)):
    55                         self.groundedice_melting_rate=numpy.zeros((md.mesh.numberofvertices,1))
     53                if np.all(np.isnan(self.groundedice_melting_rate)):
     54                        self.groundedice_melting_rate=np.zeros((md.mesh.numberofvertices))
    5655                        print("      no basalforcings.groundedice_melting_rate specified: values set as zero")
    5756
     
    6867        def checkconsistency(self,md,solution,analyses):    # {{{
    6968
    70                 if MasstransportAnalysisEnum() in analyses and not (solution==TransientSolutionEnum() and not md.transient.ismasstransport):
     69                if 'MasstransportAnalysis' in analyses and not (solution=='TransientSolution' and not md.transient.ismasstransport):
    7170                        md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'Inf',1,'timeseries',1)
    72                         md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','>=',0);
    73                         md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','<',md.basalforcings.upperwater_elevation);
    74                         md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','<',0);
     71                        md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','>=',0,'singletimeseries',1)
     72                        md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','<','basalforcings.upperwater_elevation','singletimeseries',1)
     73                        md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','<=',0,'singletimeseries',1)
    7574
    76                 if BalancethicknessAnalysisEnum() in analyses:
     75                if 'BalancethicknessAnalysis' in analyses:
    7776                        md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
    78                         md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','>=',0);
    79                         md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','<',md.basalforcings.upperwater_elevation);
    80                         md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','<',0);
     77                        md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','>=',0,'singletimeseries',1)
     78                        md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','<','basalforcings.upperwater_elevation','singletimeseries',1)
     79                        md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','<=',0,'singletimeseries',1)
    8180
    82                 if ThermalAnalysisEnum() in analyses and not (solution==TransientSolutionEnum() and not md.transient.isthermal):
     81                if 'ThermalAnalysis' in analyses and not (solution=='TransientSolution' and not md.transient.isthermal):
    8382                        md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'Inf',1,'timeseries',1)
    84                         md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','>=',0);
    85                         md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','<',md.basalforcings.upperwater_elevation);
    86                         md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','<',0);
     83                        md = checkfield(md,'fieldname','basalforcings.deepwater_melting_rate','>=',0,'singletimeseries',1)
     84                        md = checkfield(md,'fieldname','basalforcings.deepwater_elevation','<','basalforcings.upperwater_elevation','singletimeseries',1)
     85                        md = checkfield(md,'fieldname','basalforcings.upperwater_elevation','<=',0,'singletimeseries',1)
    8786                        md = checkfield(md,'fieldname','basalforcings.geothermalflux','NaN',1,'Inf',1,'timeseries',1,'>=',0)
    8887
    8988                return md
    9089        # }}}
    91         def marshall(self,md,fid):    # {{{
     90        def marshall(self,prefix,md,fid):    # {{{
    9291
    93                 yts=365.0*24.0*3600.0
     92                yts=md.constants.yts
    9493
    95                 floatingice_melting_rate = numpy.zeros((md.mesh.numberofvertices,1))
    96                 pos=numpy.nonzero(md.geometry.base<=md.basalforcings.deepwater_elevation)
    97                 floatingice_melting_rate[pos]=md.basalforcings.deepwater_melting_rate
    98                 pos=numpy.nonzero(numpy.logical_and(md.geometry.base>md.basalforcings.deepwater_elevation,md.geometry.base<md.basalforcings.upperwater_elevation))
    99                 floatingice_melting_rate[pos]=md.basalforcings.deepwater_melting_rate*(md.geometry.base[pos]-md.basalforcings.upperwater_elevation)/(md.basalforcings.deepwater_elevation-md.basalforcings.upperwater_elevation)
    100 
    101                 WriteData(fid,'enum',BasalforcingsEnum(),'data',LinearFloatingMeltRateEnum(),'format','Integer');
    102                 WriteData(fid,'object',self,'fieldname','groundedice_melting_rate','enum',BasalforcingsGroundediceMeltingRateEnum(),'format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
    103                 WriteData(fid,'data',floatingice_melting_rate,'enum',BasalforcingsFloatingiceMeltingRateEnum(),'format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
    104                 WriteData(fid,'object',self,'fieldname','geothermalflux','enum',BasalforcingsGeothermalfluxEnum(),'format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1)
    105                 WriteData(fid,'object',self,'fieldname','deepwater_melting_rate','enum',BasalforcingsDeepwaterMeltingRateEnum(),'format','Double','scale',1./yts)
    106                 WriteData(fid,'object',self,'fieldname','deepwater_elevation','enum',BasalforcingsDeepwaterElevationEnum(),'format','Double')
    107                 WriteData(fid,'object',self,'fieldname','upperwater_elevation','enum',BasalforcingsUpperwaterElevationEnum(),'format','Double')
     94                WriteData(fid,prefix,'name','md.basalforcings.model','data',2,'format','Integer')
     95                WriteData(fid,prefix,'object',self,'fieldname','groundedice_melting_rate','name','md.basalforcings.groundedice_melting_rate','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     96                WriteData(fid,prefix,'object',self,'fieldname','geothermalflux','name','md.basalforcings.geothermalflux','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     97                WriteData(fid,prefix,'object',self,'fieldname','deepwater_melting_rate','format','DoubleMat','mattype',3,'timeserieslength',2,'name','md.basalforcings.deepwater_melting_rate','scale',1./yts,'yts',md.constants.yts)
     98                WriteData(fid,prefix,'object',self,'fieldname','deepwater_elevation','format','DoubleMat','mattype',3,'name','md.basalforcings.deepwater_elevation','yts',md.constants.yts)
     99                WriteData(fid,prefix,'object',self,'fieldname','upperwater_elevation','format','DoubleMat','mattype',3,'name','md.basalforcings.upperwater_elevation','yts',md.constants.yts)
    108100        # }}}
  • issm/trunk-jpl/src/py3/classes/m1qn3inversion.py

    r19898 r23670  
    1 import numpy
     1import numpy as np
    22from project3d import project3d
    33from fielddisplay import fielddisplay
    4 from EnumDefinitions import *
    5 from StringToEnum import StringToEnum
    64from checkfield import checkfield
    75from WriteData import WriteData
     
    10098                self.vel_obs=project3d(md,'vector',self.vel_obs,'type','node')
    10199                self.thickness_obs=project3d(md,'vector',self.thickness_obs,'type','node')
    102                 if not numpy.any(numpy.isnan(self.cost_functions_coefficients)):
     100                if not np.any(np.isnan(self.cost_functions_coefficients)):
    103101                        self.cost_functions_coefficients=project3d(md,'vector',self.cost_functions_coefficients,'type','node')
    104                 if not numpy.any(numpy.isnan(self.min_parameters)):
     102                if not np.any(np.isnan(self.min_parameters)):
    105103                        self.min_parameters=project3d(md,'vector',self.min_parameters,'type','node')
    106                 if not numpy.any(numpy.isnan(self.max_parameters)):
     104                if not np.any(np.isnan(self.max_parameters)):
    107105                        self.max_parameters=project3d(md,'vector',self.max_parameters,'type','node')
    108106                return self
     
    139137                        return md
    140138
    141                 num_controls=numpy.size(md.inversion.control_parameters)
    142                 num_costfunc=numpy.size(md.inversion.cost_functions)
     139                num_controls=np.size(md.inversion.control_parameters)
     140                num_costfunc=np.size(md.inversion.cost_functions)
    143141
    144142                md = checkfield(md,'fieldname','inversion.iscontrol','values',[0,1])
     
    155153                md = checkfield(md,'fieldname','inversion.max_parameters','size',[md.mesh.numberofvertices,num_controls])
    156154
    157                 if solution==BalancethicknessSolutionEnum():
     155                if solution=='BalancethicknessSolution':
    158156                        md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices],'NaN',1,'Inf',1)
    159157                else:
     
    163161                return md
    164162        # }}}
    165         def marshall(self,md,fid):    # {{{
     163        def marshall(self,prefix,md,fid):    # {{{
    166164
    167                 yts=365.0*24.0*3600.0
     165                yts=md.constants.yts
    168166
    169                 WriteData(fid,'object',self,'class','inversion','fieldname','iscontrol','format','Boolean')
    170                 WriteData(fid,'enum',InversionTypeEnum(),'data',2,'format','Integer')
     167                WriteData(fid,prefix,'object',self,'class','inversion','fieldname','iscontrol','format','Boolean')
     168                WriteData(fid,prefix,'name','md.inversion.type','data',2,'format','Integer')
    171169                if not self.iscontrol:
    172170                        return
    173                 WriteData(fid,'object',self,'class','inversion','fieldname','incomplete_adjoint','format','Boolean')
    174                 WriteData(fid,'object',self,'class','inversion','fieldname','control_scaling_factors','format','DoubleMat','mattype',3)
    175                 WriteData(fid,'object',self,'class','inversion','fieldname','maxsteps','format','Integer')
    176                 WriteData(fid,'object',self,'class','inversion','fieldname','maxiter','format','Integer')
    177                 WriteData(fid,'object',self,'class','inversion','fieldname','dxmin','format','Double')
    178                 WriteData(fid,'object',self,'class','inversion','fieldname','gttol','format','Double')
    179                 WriteData(fid,'object',self,'class','inversion','fieldname','cost_functions_coefficients','format','DoubleMat','mattype',1)
    180                 WriteData(fid,'object',self,'class','inversion','fieldname','min_parameters','format','DoubleMat','mattype',3)
    181                 WriteData(fid,'object',self,'class','inversion','fieldname','max_parameters','format','DoubleMat','mattype',3)
    182                 WriteData(fid,'object',self,'class','inversion','fieldname','vx_obs','format','DoubleMat','mattype',1,'scale',1./yts)
    183                 WriteData(fid,'object',self,'class','inversion','fieldname','vy_obs','format','DoubleMat','mattype',1,'scale',1./yts)
    184                 WriteData(fid,'object',self,'class','inversion','fieldname','vz_obs','format','DoubleMat','mattype',1,'scale',1./yts)
    185                 WriteData(fid,'object',self,'class','inversion','fieldname','thickness_obs','format','DoubleMat','mattype',1)
     171                WriteData(fid,prefix,'object',self,'class','inversion','fieldname','incomplete_adjoint','format','Boolean')
     172                WriteData(fid,prefix,'object',self,'class','inversion','fieldname','control_scaling_factors','format','DoubleMat','mattype',3)
     173                WriteData(fid,prefix,'object',self,'class','inversion','fieldname','maxsteps','format','Integer')
     174                WriteData(fid,prefix,'object',self,'class','inversion','fieldname','maxiter','format','Integer')
     175                WriteData(fid,prefix,'object',self,'class','inversion','fieldname','dxmin','format','Double')
     176                WriteData(fid,prefix,'object',self,'class','inversion','fieldname','gttol','format','Double')
     177                WriteData(fid,prefix,'object',self,'class','inversion','fieldname','cost_functions_coefficients','format','DoubleMat','mattype',1)
     178                WriteData(fid,prefix,'object',self,'class','inversion','fieldname','min_parameters','format','DoubleMat','mattype',3)
     179                WriteData(fid,prefix,'object',self,'class','inversion','fieldname','max_parameters','format','DoubleMat','mattype',3)
     180                WriteData(fid,prefix,'object',self,'class','inversion','fieldname','vx_obs','format','DoubleMat','mattype',1,'scale',1./yts)
     181                WriteData(fid,prefix,'object',self,'class','inversion','fieldname','vy_obs','format','DoubleMat','mattype',1,'scale',1./yts)
     182                WriteData(fid,prefix,'object',self,'class','inversion','fieldname','vz_obs','format','DoubleMat','mattype',1,'scale',1./yts)
     183                WriteData(fid,prefix,'object',self,'class','inversion','fieldname','thickness_obs','format','DoubleMat','mattype',1)
    186184
    187185                #process control parameters
    188186                num_control_parameters=len(self.control_parameters)
    189                 data=numpy.array([StringToEnum(control_parameter)[0] for control_parameter in self.control_parameters]).reshape(1,-1)
    190                 WriteData(fid,'data',data,'enum',InversionControlParametersEnum(),'format','DoubleMat','mattype',3)
    191                 WriteData(fid,'data',num_control_parameters,'enum',InversionNumControlParametersEnum(),'format','Integer')
     187                WriteData(fid,prefix,'object',self,'fieldname','control_parameters','format','StringArray')
     188                WriteData(fid,prefix,'data',num_control_parameters,'name','md.inversion.num_control_parameters','format','Integer')
    192189
    193190                #process cost functions
    194                 num_cost_functions=numpy.size(self.cost_functions)
     191                num_cost_functions=np.size(self.cost_functions)
    195192                data=marshallcostfunctions(self.cost_functions)
    196                 WriteData(fid,'data',numpy.array(data).reshape(1,-1),'enum',InversionCostFunctionsEnum(),'format','DoubleMat','mattype',3)
    197                 WriteData(fid,'data',num_cost_functions,'enum',InversionNumCostFunctionsEnum(),'format','Integer')
     193                WriteData(fid,prefix,'data',data,'name','md.inversion.cost_functions','format','StringArray')
     194                WriteData(fid,prefix,'data',num_cost_functions,'name','md.inversion.num_cost_functions','format','Integer')
    198195        # }}}
  • issm/trunk-jpl/src/py3/classes/mask.py

    r19895 r23670  
    1 import numpy
     1import numpy as np
    22from fielddisplay import fielddisplay
    33from project3d import project3d
    4 from EnumDefinitions import *
    54from checkfield import checkfield
    65from WriteData import WriteData
     
    3938        #}}}
    4039        def checkconsistency(self,md,solution,analyses):    # {{{
     40                if(solution=='LoveSolution'):
     41                        return
    4142
    4243                md = checkfield(md,'fieldname','mask.ice_levelset'        ,'size',[md.mesh.numberofvertices])
    43                 isice=numpy.array(md.mask.ice_levelset<=0,int)
    44                 if numpy.sum(isice)==0:
     44                isice=np.array(md.mask.ice_levelset<=0,int)
     45                if np.sum(isice)==0:
    4546                        raise TypeError("no ice present in the domain")
    46 
    47                 icefront=numpy.sum(md.mask.ice_levelset[md.mesh.elements-1]==0,axis=1)
    48                 if (max(icefront)==3 and m.strcmp(md.mesh.elementtype(),'Tria')) or (max(icefront==6) and m.strcmp(md.mesh.elementtype(),'Penta')):
    49                         raise TypeError("At least one element has all nodes on ice front, change md.mask.ice_levelset to fix it")
    5047
    5148                return md
    5249        # }}}
    53         def marshall(self,md,fid):    # {{{
    54                 WriteData(fid,'object',self,'fieldname','groundedice_levelset','format','DoubleMat','mattype',1)
    55                 WriteData(fid,'object',self,'fieldname','ice_levelset','format','DoubleMat','mattype',1)
    56 
    57                 # get mask of vertices of elements with ice
    58                 isice=numpy.array(md.mask.ice_levelset<0.,int)
    59                 vlist = numpy.zeros((md.mesh.numberofvertices,1), dtype=int)
    60                 pos=numpy.nonzero(numpy.sum(isice[md.mesh.elements-1],axis=1))[0]
    61                 vlist[md.mesh.elements[pos,:]-1]=1
    62                 WriteData(fid,'data',vlist,'enum',IceMaskNodeActivationEnum(),'format','DoubleMat','mattype',1);
     50        def marshall(self,prefix,md,fid):    # {{{
     51                WriteData(fid,prefix,'object',self,'fieldname','groundedice_levelset','format','DoubleMat','mattype',1)
     52                WriteData(fid,prefix,'object',self,'fieldname','ice_levelset','format','DoubleMat','mattype',1)
    6353        # }}}
  • issm/trunk-jpl/src/py3/classes/massfluxatgate.py

    r19895 r23670  
    11from fielddisplay import fielddisplay
    2 from EnumDefinitions import *
    32from pairoptions import pairoptions
    43from checkfield import checkfield
     
    1514        """
    1615
    17         def __init__(self,**kwargs): # {{{
     16        def __init__(self,*args): # {{{
    1817
    1918                self.name            = ''
    20                 self.definitionenum  = 0
     19                self.definitionstring  = ''
    2120                self.profilename     = ''
    2221                self.segments        = float('NaN')
     
    2625
    2726                #use provided options to change fields
    28                 options=pairoptions(**kwargs)
     27                options=pairoptions(*args)
    2928
    3029                #OK get other fields
     
    3635                string="   Massfluxatgate:"
    3736                string="%s\n%s"%(string,fielddisplay(self,'name','identifier for this massfluxatgate response'))
    38                 string="%s\n%s"%(string,fielddisplay(self,'definitionenum','enum that identifies this output definition uniquely, from Outputdefinition[1-10]Enum'))
     37                string="%s\n%s"%(string,fielddisplay(self,'definitionstring','string that identifies this output definition uniquely, from Outputdefinition[1-100]'))
    3938                string="%s\n%s"%(string,fielddisplay(self,'profilename','name of file (shapefile or argus file) defining a profile (or gate)'))
    4039                return string
    4140                #}}}
     41        def extrude(self,md): # {{{
     42                return self
     43           #}}}
    4244        def setdefaultparameters(self): # {{{
    4345                return self
     
    5052                if  not isinstance(self.profilename, str):
    5153                        raise RuntimeError("massfluxatgate error message: 'profilename' field should be a string!")
    52 
    53                         md = checkfield(md,'field',self.definitionenum,'values',[Outputdefinition1Enum(),Outputdefinition2Enum(),Outputdefinition3Enum(),Outputdefinition4Enum(),Outputdefinition5Enum(),Outputdefinition6Enum(),Outputdefinition7Enum(),Outputdefinition8Enum(),Outputdefinition9Enum(),Outputdefinition10Enum()])
     54               
     55                OutputdefinitionStringArray=[]
     56                for i in range(1,100):
     57                        x='Outputdefinition'+str(i)
     58                        OutputdefinitionStringArray.append(x)
     59                       
     60                md = checkfield(md,'field',self.definitionstring,'values',OutputdefinitionStringArray)
    5461               
    5562                #check the profilename points to a file!:
     
    5966                return md
    6067        # }}}
    61         def marshall(self,md,fid):    # {{{
     68        def marshall(self,prefix,md,fid):    # {{{
    6269               
    6370                #before marshalling, we need to create the segments out of the profilename:
     
    6572
    6673                #ok, marshall name and segments:
    67                 WriteData(fid,'object',self,'fieldname','name','format','String')
    68                 WriteData(fid,'object',self,'fieldname','definitionenum','format','Integer')
    69                 WriteData(fid,'object',self,'fieldname','segments','format','DoubleMat','mattype',1)
     74                WriteData(fid,prefix,'data',self.name,'name','md.massfluxatgate.name','format','String');
     75                WriteData(fid,prefix,'data',self.definitionstring,'name','md.massfluxatgate.definitionstring','format','String');
     76                WriteData(fid,prefix,'data',self.segments,'name','md.massfluxatgate.segments','format','DoubleMat','mattype',1);
    7077
    7178        # }}}
  • issm/trunk-jpl/src/py3/classes/masstransport.py

    r19903 r23670  
    11from fielddisplay import fielddisplay
    22from project3d import project3d
    3 from EnumDefinitions import *
    4 from StringToEnum import StringToEnum
    53from checkfield import checkfield
    64from WriteData import WriteData
     
    6967
    7068                #Early return
    71                 if (MasstransportAnalysisEnum() not in analyses) or (solution==TransientSolutionEnum() and not md.transient.ismasstransport):
     69                if ('MasstransportAnalysis' not in analyses) or (solution=='TransientSolution' and not md.transient.ismasstransport):
    7270                        return md
    7371
     
    8179                return md
    8280        # }}}
    83         def marshall(self,md,fid):    # {{{
     81        def marshall(self,prefix,md,fid):    # {{{
    8482
    85                 yts=365.*24.*3600.
     83                yts=md.constants.yts
    8684
    87                 WriteData(fid,'object',self,'fieldname','spcthickness','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1)
    88                 WriteData(fid,'object',self,'fieldname','isfreesurface','format','Boolean')
    89                 WriteData(fid,'object',self,'fieldname','min_thickness','format','Double')
    90                 WriteData(fid,'data',StringToEnum(self.hydrostatic_adjustment)[0],'format','Integer','enum',MasstransportHydrostaticAdjustmentEnum())
    91                 WriteData(fid,'object',self,'fieldname','stabilization','format','Integer')
    92                 WriteData(fid,'object',self,'fieldname','vertex_pairing','format','DoubleMat','mattype',3)
    93                 WriteData(fid,'object',self,'fieldname','penalty_factor','format','Double')
     85                WriteData(fid,prefix,'object',self,'fieldname','spcthickness','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     86                WriteData(fid,prefix,'object',self,'fieldname','isfreesurface','format','Boolean')
     87                WriteData(fid,prefix,'object',self,'fieldname','min_thickness','format','Double')
     88                WriteData(fid,prefix,'data',self.hydrostatic_adjustment,'format','String','name','md.masstransport.hydrostatic_adjustment')
     89                WriteData(fid,prefix,'object',self,'fieldname','stabilization','format','Integer')
     90                WriteData(fid,prefix,'object',self,'fieldname','vertex_pairing','format','DoubleMat','mattype',3)
     91                WriteData(fid,prefix,'object',self,'fieldname','penalty_factor','format','Double')
    9492
    9593                #process requested outputs
     
    9997                        outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:]
    10098                        outputs    =outputscopy
    101                 WriteData(fid,'data',outputs,'enum',MasstransportRequestedOutputsEnum(),'format','StringArray')
     99                WriteData(fid,prefix,'data',outputs,'name','md.masstransport.requested_outputs','format','StringArray')
    102100        # }}}
  • issm/trunk-jpl/src/py3/classes/matdamageice.py

    r19895 r23670  
    11from fielddisplay import fielddisplay
    22from project3d import project3d
    3 from EnumDefinitions import MaterialsEnum, MatdamageiceEnum, MaterialsRheologyLawEnum, MaterialsRhoSeawaterEnum
    4 from StringToEnum import StringToEnum
    53from checkfield import checkfield
    64from WriteData import WriteData
     
    3129                self.rheology_law              = ''
    3230
    33                 #gia:
     31                #giaivins:
    3432                self.lithosphere_shear_modulus  = 0.
    3533                self.lithosphere_density        = 0.
    3634                self.mantle_shear_modulus       = 0.
    3735                self.mantle_density             = 0.
     36               
     37                #SLR
     38                self.earth_density= 5512;  # average density of the Earth, (kg/m^3)
     39
    3840
    3941                self.setdefaultparameters()
     
    5456                string="%s\n%s"%(string,fielddisplay(self,"mixed_layer_capacity","mixed layer capacity [W/kg/K]"))
    5557                string="%s\n%s"%(string,fielddisplay(self,"thermal_exchange_velocity","thermal exchange velocity [m/s]"))
    56                 string="%s\n%s"%(string,fielddisplay(self,"rheology_B","flow law parameter [Pa/s^(1/n)]"))
     58                string="%s\n%s"%(string,fielddisplay(self,"rheology_B","flow law parameter [Pa s^(1/n)]"))
    5759                string="%s\n%s"%(string,fielddisplay(self,"rheology_n","Glen's flow law exponent"))
    58                 string="%s\n%s"%(string,fielddisplay(self,"rheology_law","law for the temperature dependance of the rheology: 'None', 'Cuffey', 'Paterson', 'Arrhenius' or 'LliboutryDuval'"))
     60                string="%s\n%s"%(string,fielddisplay(self,"rheology_law","law for the temperature dependance of the rheology: 'None', 'BuddJacka', 'Cuffey', 'CuffeyTemperate', 'Paterson', 'Arrhenius' or 'LliboutryDuval'"))
    5961                string="%s\n%s"%(string,fielddisplay(self,"lithosphere_shear_modulus","Lithosphere shear modulus [Pa]"))
    6062                string="%s\n%s"%(string,fielddisplay(self,"lithosphere_density","Lithosphere density [g/cm^-3]"))
    6163                string="%s\n%s"%(string,fielddisplay(self,"mantle_shear_modulus","Mantle shear modulus [Pa]"))
    6264                string="%s\n%s"%(string,fielddisplay(self,"mantle_density","Mantle density [g/cm^-3]"))
     65                string="%s\n%s"%(string,fielddisplay(self,"earth_density","Mantle density [kg/m^-3]"))
     66
    6367
    6468                return string
     
    115119                self.mantle_shear_modulus       = 1.45*10**11 # (Pa)
    116120                self.mantle_density             = 3.34        # (g/cm^-3)
     121               
     122                #SLR
     123                self.earth_density= 5512;  #average density of the Earth, (kg/m^3)
     124
    117125
    118126                return self
     
    125133                md = checkfield(md,'fieldname','materials.rheology_B','>',0,'size',[md.mesh.numberofvertices])
    126134                md = checkfield(md,'fieldname','materials.rheology_n','>',0,'size',[md.mesh.numberofelements])
    127                 md = checkfield(md,'fieldname','materials.rheology_law','values',['None','Cuffey','Paterson','Arrhenius','LliboutryDuval'])
     135                md = checkfield(md,'fieldname','materials.rheology_law','values',['None', 'BuddJacka', 'Cuffey', 'CuffeyTemperate', 'Paterson','Arrhenius','LliboutryDuval'])
    128136                md = checkfield(md,'fieldname','materials.lithosphere_shear_modulus','>',0,'numel',[1]);
    129137                md = checkfield(md,'fieldname','materials.lithosphere_density','>',0,'numel',[1]);
    130138                md = checkfield(md,'fieldname','materials.mantle_shear_modulus','>',0,'numel',[1]);
    131139                md = checkfield(md,'fieldname','materials.mantle_density','>',0,'numel',[1]);
     140                md = checkfield(md,'fieldname','materials.earth_density','>',0,'numel',[1]);
     141
    132142                return md
    133143        # }}}
    134         def marshall(self,md,fid):    # {{{
    135                 WriteData(fid,'enum',MaterialsEnum(),'data',MatdamageiceEnum(),'format','Integer');
    136                 WriteData(fid,'object',self,'class','materials','fieldname','rho_ice','format','Double')
    137                 WriteData(fid,'object',self,'class','materials','fieldname','rho_water','enum',MaterialsRhoSeawaterEnum(),'format','Double')
    138                 WriteData(fid,'object',self,'class','materials','fieldname','rho_freshwater','format','Double')
    139                 WriteData(fid,'object',self,'class','materials','fieldname','mu_water','format','Double')
    140                 WriteData(fid,'object',self,'class','materials','fieldname','heatcapacity','format','Double')
    141                 WriteData(fid,'object',self,'class','materials','fieldname','latentheat','format','Double')
    142                 WriteData(fid,'object',self,'class','materials','fieldname','thermalconductivity','format','Double')
    143                 WriteData(fid,'object',self,'class','materials','fieldname','temperateiceconductivity','format','Double')
    144                 WriteData(fid,'object',self,'class','materials','fieldname','meltingpoint','format','Double')
    145                 WriteData(fid,'object',self,'class','materials','fieldname','beta','format','Double')
    146                 WriteData(fid,'object',self,'class','materials','fieldname','mixed_layer_capacity','format','Double')
    147                 WriteData(fid,'object',self,'class','materials','fieldname','thermal_exchange_velocity','format','Double')
    148                 WriteData(fid,'object',self,'class','materials','fieldname','rheology_B','format','DoubleMat','mattype',1)
    149                 WriteData(fid,'object',self,'class','materials','fieldname','rheology_n','format','DoubleMat','mattype',2)
    150                 WriteData(fid,'data',StringToEnum(self.rheology_law)[0],'enum',MaterialsRheologyLawEnum(),'format','Integer')
     144        def marshall(self,prefix,md,fid):    # {{{
     145                WriteData(fid,prefix,'name','md.materials.type','data',1,'format','Integer');
     146                WriteData(fid,prefix,'object',self,'class','materials','fieldname','rho_ice','format','Double')
     147                WriteData(fid,prefix,'object',self,'class','materials','fieldname','rho_water','format','Double')
     148                WriteData(fid,prefix,'object',self,'class','materials','fieldname','rho_freshwater','format','Double')
     149                WriteData(fid,prefix,'object',self,'class','materials','fieldname','mu_water','format','Double')
     150                WriteData(fid,prefix,'object',self,'class','materials','fieldname','heatcapacity','format','Double')
     151                WriteData(fid,prefix,'object',self,'class','materials','fieldname','latentheat','format','Double')
     152                WriteData(fid,prefix,'object',self,'class','materials','fieldname','thermalconductivity','format','Double')
     153                WriteData(fid,prefix,'object',self,'class','materials','fieldname','temperateiceconductivity','format','Double')
     154                WriteData(fid,prefix,'object',self,'class','materials','fieldname','meltingpoint','format','Double')
     155                WriteData(fid,prefix,'object',self,'class','materials','fieldname','beta','format','Double')
     156                WriteData(fid,prefix,'object',self,'class','materials','fieldname','mixed_layer_capacity','format','Double')
     157                WriteData(fid,prefix,'object',self,'class','materials','fieldname','thermal_exchange_velocity','format','Double')
     158                WriteData(fid,prefix,'object',self,'class','materials','fieldname','rheology_B','format','DoubleMat','mattype',1)
     159                WriteData(fid,prefix,'object',self,'class','materials','fieldname','rheology_n','format','DoubleMat','mattype',2)
     160                WriteData(fid,prefix,'data',self.rheology_law,'name','md.materials.rheology_law','format','String')
    151161
    152                 WriteData(fid,'object',self,'class','materials','fieldname','lithosphere_shear_modulus','format','Double');
    153                 WriteData(fid,'object',self,'class','materials','fieldname','lithosphere_density','format','Double','scale',10.**3.);
    154                 WriteData(fid,'object',self,'class','materials','fieldname','mantle_shear_modulus','format','Double');
    155                 WriteData(fid,'object',self,'class','materials','fieldname','mantle_density','format','Double','scale',10.**3.);
     162                WriteData(fid,prefix,'object',self,'class','materials','fieldname','lithosphere_shear_modulus','format','Double');
     163                WriteData(fid,prefix,'object',self,'class','materials','fieldname','lithosphere_density','format','Double','scale',10.**3.);
     164                WriteData(fid,prefix,'object',self,'class','materials','fieldname','mantle_shear_modulus','format','Double');
     165                WriteData(fid,prefix,'object',self,'class','materials','fieldname','mantle_density','format','Double','scale',10.**3.);
     166                WriteData(fid,prefix,'object',self,'class','materials','fieldname','earth_density','format','Double');
     167
    156168        # }}}
  • issm/trunk-jpl/src/py3/classes/matice.py

    r19898 r23670  
    11from fielddisplay import fielddisplay
    22from project3d import project3d
    3 from EnumDefinitions import *
    4 from StringToEnum import StringToEnum
    53from checkfield import checkfield
    64from WriteData import WriteData
     
    3129                self.rheology_law              = ''
    3230
    33                 #gia:
     31                #giaivins:
    3432                self.lithosphere_shear_modulus  = 0.
    3533                self.lithosphere_density        = 0.
    3634                self.mantle_shear_modulus       = 0.
    37                 self.mantle_density             = 0.
     35                self.mantle_density             = 0. 
     36               
     37                #SLR
     38                self.earth_density= 5512; 
     39
     40
    3841
    3942                self.setdefaultparameters()
     
    5457                string="%s\n%s"%(string,fielddisplay(self,"mixed_layer_capacity","mixed layer capacity [W/kg/K]"))
    5558                string="%s\n%s"%(string,fielddisplay(self,"thermal_exchange_velocity","thermal exchange velocity [m/s]"))
    56                 string="%s\n%s"%(string,fielddisplay(self,"rheology_B","flow law parameter [Pa/s^(1/n)]"))
     59                string="%s\n%s"%(string,fielddisplay(self,"rheology_B","flow law parameter [Pa s^(1/n)]"))
    5760                string="%s\n%s"%(string,fielddisplay(self,"rheology_n","Glen's flow law exponent"))
    58                 string="%s\n%s"%(string,fielddisplay(self,"rheology_law","law for the temperature dependance of the rheology: 'None', 'Cuffey', 'Paterson', 'Arrhenius' or 'LliboutryDuval'"))
     61                string="%s\n%s"%(string,fielddisplay(self,"rheology_law","law for the temperature dependance of the rheology: 'None', 'BuddJacka', 'Cuffey', 'CuffeyTemperate', 'Paterson', 'Arrhenius' or 'LliboutryDuval'"))
    5962                string="%s\n%s"%(string,fielddisplay(self,"lithosphere_shear_modulus","Lithosphere shear modulus [Pa]"))
    6063                string="%s\n%s"%(string,fielddisplay(self,"lithosphere_density","Lithosphere density [g/cm^-3]"))
    6164                string="%s\n%s"%(string,fielddisplay(self,"mantle_shear_modulus","Mantle shear modulus [Pa]"))
    6265                string="%s\n%s"%(string,fielddisplay(self,"mantle_density","Mantle density [g/cm^-3]"))
     66                string="%s\n%s"%(string,fielddisplay(self,"earth_density","Mantle density [kg/m^-3]"))
     67
    6368
    6469                return string
     
    115120                self.mantle_shear_modulus       = 1.45*10**11 # (Pa)
    116121                self.mantle_density             = 3.34        # (g/cm^-3)
     122               
     123                #SLR
     124                self.earth_density= 5512;  # average density of the Earth, (kg/m^3)
     125
    117126
    118127                return self
     
    125134                md = checkfield(md,'fieldname','materials.rheology_B','>',0,'timeseries',1,'NaN',1,'Inf',1)
    126135                md = checkfield(md,'fieldname','materials.rheology_n','>',0,'size',[md.mesh.numberofelements])
    127                 md = checkfield(md,'fieldname','materials.rheology_law','values',['None','Cuffey','Paterson','Arrhenius','LliboutryDuval'])
     136                md = checkfield(md,'fieldname','materials.rheology_law','values',['None','BuddJacka','Cuffey','CuffeyTemperate','Paterson','Arrhenius','LliboutryDuval'])
    128137                md = checkfield(md,'fieldname','materials.lithosphere_shear_modulus','>',0,'numel',[1]);
    129138                md = checkfield(md,'fieldname','materials.lithosphere_density','>',0,'numel',[1]);
    130139                md = checkfield(md,'fieldname','materials.mantle_shear_modulus','>',0,'numel',[1]);
    131140                md = checkfield(md,'fieldname','materials.mantle_density','>',0,'numel',[1]);
     141                md = checkfield(md,'fieldname','materials.earth_density','>',0,'numel',[1]);
     142
    132143                return md
    133144        # }}}
    134         def marshall(self,md,fid):    # {{{
    135                 WriteData(fid,'enum',MaterialsEnum(),'data',MaticeEnum(),'format','Integer');
    136                 WriteData(fid,'object',self,'class','materials','fieldname','rho_ice','format','Double')
    137                 WriteData(fid,'object',self,'class','materials','fieldname','rho_water','enum',MaterialsRhoSeawaterEnum(),'format','Double')
    138                 WriteData(fid,'object',self,'class','materials','fieldname','rho_freshwater','format','Double')
    139                 WriteData(fid,'object',self,'class','materials','fieldname','mu_water','format','Double')
    140                 WriteData(fid,'object',self,'class','materials','fieldname','heatcapacity','format','Double')
    141                 WriteData(fid,'object',self,'class','materials','fieldname','latentheat','format','Double')
    142                 WriteData(fid,'object',self,'class','materials','fieldname','thermalconductivity','format','Double')
    143                 WriteData(fid,'object',self,'class','materials','fieldname','temperateiceconductivity','format','Double')
    144                 WriteData(fid,'object',self,'class','materials','fieldname','meltingpoint','format','Double')
    145                 WriteData(fid,'object',self,'class','materials','fieldname','beta','format','Double')
    146                 WriteData(fid,'object',self,'class','materials','fieldname','mixed_layer_capacity','format','Double')
    147                 WriteData(fid,'object',self,'class','materials','fieldname','thermal_exchange_velocity','format','Double')
    148                 WriteData(fid,'object',self,'class','materials','fieldname','rheology_B','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1)
    149                 WriteData(fid,'object',self,'class','materials','fieldname','rheology_B','format','DoubleMat','mattype',1)
    150                 WriteData(fid,'object',self,'class','materials','fieldname','rheology_n','format','DoubleMat','mattype',2)
    151                 WriteData(fid,'data',StringToEnum(self.rheology_law)[0],'enum',MaterialsRheologyLawEnum(),'format','Integer')
     145        def marshall(self,prefix,md,fid):    # {{{
     146                WriteData(fid,prefix,'name','md.materials.type','data',3,'format','Integer');
     147                WriteData(fid,prefix,'object',self,'class','materials','fieldname','rho_ice','format','Double')
     148                WriteData(fid,prefix,'object',self,'class','materials','fieldname','rho_water','format','Double')
     149                WriteData(fid,prefix,'object',self,'class','materials','fieldname','rho_freshwater','format','Double')
     150                WriteData(fid,prefix,'object',self,'class','materials','fieldname','mu_water','format','Double')
     151                WriteData(fid,prefix,'object',self,'class','materials','fieldname','heatcapacity','format','Double')
     152                WriteData(fid,prefix,'object',self,'class','materials','fieldname','latentheat','format','Double')
     153                WriteData(fid,prefix,'object',self,'class','materials','fieldname','thermalconductivity','format','Double')
     154                WriteData(fid,prefix,'object',self,'class','materials','fieldname','temperateiceconductivity','format','Double')
     155                WriteData(fid,prefix,'object',self,'class','materials','fieldname','meltingpoint','format','Double')
     156                WriteData(fid,prefix,'object',self,'class','materials','fieldname','beta','format','Double')
     157                WriteData(fid,prefix,'object',self,'class','materials','fieldname','mixed_layer_capacity','format','Double')
     158                WriteData(fid,prefix,'object',self,'class','materials','fieldname','thermal_exchange_velocity','format','Double')
     159                WriteData(fid,prefix,'object',self,'class','materials','fieldname','rheology_B','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     160                WriteData(fid,prefix,'object',self,'class','materials','fieldname','rheology_n','format','DoubleMat','mattype',2)
     161                WriteData(fid,prefix,'data',self.rheology_law,'name','md.materials.rheology_law','format','String')
    152162
    153                 WriteData(fid,'object',self,'class','materials','fieldname','lithosphere_shear_modulus','format','Double');
    154                 WriteData(fid,'object',self,'class','materials','fieldname','lithosphere_density','format','Double','scale',10.**3.);
    155                 WriteData(fid,'object',self,'class','materials','fieldname','mantle_shear_modulus','format','Double');
    156                 WriteData(fid,'object',self,'class','materials','fieldname','mantle_density','format','Double','scale',10.**3.);
     163                WriteData(fid,prefix,'object',self,'class','materials','fieldname','lithosphere_shear_modulus','format','Double');
     164                WriteData(fid,prefix,'object',self,'class','materials','fieldname','lithosphere_density','format','Double','scale',10.**3.);
     165                WriteData(fid,prefix,'object',self,'class','materials','fieldname','mantle_shear_modulus','format','Double');
     166                WriteData(fid,prefix,'object',self,'class','materials','fieldname','mantle_density','format','Double','scale',10.**3.);
     167                WriteData(fid,prefix,'object',self,'class','materials','fieldname','earth_density','format','Double');
     168
    157169        # }}}
  • issm/trunk-jpl/src/py3/classes/mesh2d.py

    r19898 r23670  
    1 import numpy
     1import numpy as np
    22from fielddisplay import fielddisplay
    33from checkfield import checkfield
     4import MatlabFuncs as m
    45from WriteData import WriteData
    5 from EnumDefinitions import *
    6 import MatlabFuncs as m
    76
    87class mesh2d(object):
     
    2524                self.long                        = float('NaN');
    2625                self.epsg                        = 0;
     26                self.scale_factor                = float('NaN');
    2727
    2828                self.vertexonboundary            = float('NaN');
     
    5757                string="%s\n%s"%(string,fielddisplay(self,"segments","edges on domain boundary (vertex1 vertex2 element)"))
    5858                string="%s\n%s"%(string,fielddisplay(self,"segmentmarkers","number associated to each segment"))
    59                 string="%s\n%s"%(string,fielddisplay(self,"vertexconnectivity","list of vertices connected to vertex_i"))
    60                 string="%s\n%s"%(string,fielddisplay(self,"elementconnectivity","list of vertices connected to element_i"))
     59                string="%s\n%s"%(string,fielddisplay(self,"vertexconnectivity","list of elements connected to vertex_i"))
     60                string="%s\n%s"%(string,fielddisplay(self,"elementconnectivity","list of elements adjacent to element_i"))
    6161                string="%s\n%s"%(string,fielddisplay(self,"average_vertex_connectivity","average number of vertices connected to one vertex"))
    6262
     
    6969                string="%s\n%s"%(string,fielddisplay(self,"long","vertices longitude [degrees]"))
    7070                string="%s\n%s"%(string,fielddisplay(self,"epsg","EPSG code (ex: 3413 for UPS Greenland, 3031 for UPS Antarctica)"))
     71                string="%s\n%s"%(string,fielddisplay(self,"scale_factor","Projection correction for volume, area, etc. computation"))
    7172                return string
    7273                #}}}
     
    8384        #}}}
    8485        def checkconsistency(self,md,solution,analyses):    # {{{
     86                if(solution=='LoveSolution'):
     87                        return
    8588
    8689                md = checkfield(md,'fieldname','mesh.x','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
    8790                md = checkfield(md,'fieldname','mesh.y','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
    88                 md = checkfield(md,'fieldname','mesh.elements','NaN',1,'Inf',1,'>',0,'values',numpy.arange(1,md.mesh.numberofvertices+1))
     91                md = checkfield(md,'fieldname','mesh.elements','NaN',1,'Inf',1,'>',0,'values',np.arange(1,md.mesh.numberofvertices+1))
    8992                md = checkfield(md,'fieldname','mesh.elements','size',[md.mesh.numberofelements,3])
    90 #               if numpy.any(numpy.logical_not(m.ismember(numpy.arange(1,md.mesh.numberofvertices+1),md.mesh.elements))):
    91                 if any(numpy.logical_not(m.ismember(numpy.arange(1,md.mesh.numberofvertices+1),md.mesh.elements))):
    92                         [x for x in A if not x in B]
     93                if np.any(np.logical_not(m.ismember(np.arange(1,md.mesh.numberofvertices+1),md.mesh.elements))):
    9394                        md.checkmessage("orphan nodes have been found. Check the mesh outline")
    9495                md = checkfield(md,'fieldname','mesh.numberofelements','>',0)
    9596                md = checkfield(md,'fieldname','mesh.numberofvertices','>',0)
    9697                md = checkfield(md,'fieldname','mesh.average_vertex_connectivity','>=',9,'message',"'mesh.average_vertex_connectivity' should be at least 9 in 2d")
    97                 if solution==ThermalSolutionEnum():
     98                md = checkfield(md,'fieldname','mesh.segments','NaN',1,'Inf',1,'>',0,'size',[np.nan,3]);
     99                if(np.size(self.scale_factor)>1):
     100                        md = checkfield(md,'fieldname','mesh.scale_factor','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
     101               
     102                if solution=='ThermalSolution':
    98103                        md.checkmessage("thermal not supported for 2d mesh")
    99104
     
    109114                return "Tria"
    110115        #}}}
    111         def marshall(self,md,fid):    # {{{
    112                 WriteData(fid,'enum',DomainTypeEnum(),'data',StringToEnum("Domain"+self.domaintype())[0],'format','Integer');
    113                 WriteData(fid,'enum',DomainDimensionEnum(),'data',self.dimension(),'format','Integer');
    114                 WriteData(fid,'enum',MeshElementtypeEnum(),'data',StringToEnum(self.elementtype())[0],'format','Integer');
    115                 WriteData(fid,'object',self,'class','mesh','fieldname','x','format','DoubleMat','mattype',1)
    116                 WriteData(fid,'object',self,'class','mesh','fieldname','y','format','DoubleMat','mattype',1)
    117                 WriteData(fid,'enum',MeshZEnum(),'data',numpy.zeros(self.numberofvertices),'format','DoubleMat','mattype',1);
    118                 WriteData(fid,'object',self,'class','mesh','fieldname','elements','format','DoubleMat','mattype',2)
    119                 WriteData(fid,'object',self,'class','mesh','fieldname','numberofelements','format','Integer')
    120                 WriteData(fid,'object',self,'class','mesh','fieldname','numberofvertices','format','Integer')
    121                 WriteData(fid,'object',self,'class','mesh','fieldname','average_vertex_connectivity','format','Integer')
     116        def marshall(self,prefix,md,fid):    # {{{
     117                WriteData(fid,prefix,'name','md.mesh.domain_type','data',"Domain"+self.domaintype(),'format','String');
     118                WriteData(fid,prefix,'name','md.mesh.domain_dimension','data',self.dimension(),'format','Integer');
     119                WriteData(fid,prefix,'name','md.mesh.elementtype','data',self.elementtype(),'format','String');
     120                WriteData(fid,prefix,'object',self,'class','mesh','fieldname','x','format','DoubleMat','mattype',1)
     121                WriteData(fid,prefix,'object',self,'class','mesh','fieldname','y','format','DoubleMat','mattype',1)
     122                WriteData(fid,prefix,'name','md.mesh.z','data',np.zeros(self.numberofvertices),'format','DoubleMat','mattype',1);
     123                WriteData(fid,prefix,'object',self,'class','mesh','fieldname','elements','format','DoubleMat','mattype',2)
     124                WriteData(fid,prefix,'object',self,'class','mesh','fieldname','numberofelements','format','Integer')
     125                WriteData(fid,prefix,'object',self,'class','mesh','fieldname','numberofvertices','format','Integer')
     126                WriteData(fid,prefix,'object',self,'class','mesh','fieldname','average_vertex_connectivity','format','Integer')
     127                WriteData(fid,prefix,'object',self,'class','mesh','fieldname','vertexonboundary','format','DoubleMat','mattype',1)
     128                WriteData(fid,prefix,'object',self,'class','mesh','fieldname','segments','format','DoubleMat','mattype',3)
     129                WriteData(fid,prefix,'object',self,'class','mesh','fieldname','scale_factor','format','DoubleMat','mattype',1)
     130                if md.transient.isoceancoupling:
     131                        WriteData(fid,prefix,'object',self,'class','mesh','fieldname','lat','format','DoubleMat','mattype',1)
     132                        WriteData(fid,prefix,'object',self,'class','mesh','fieldname','long','format','DoubleMat','mattype',1)
    122133        # }}}
  • issm/trunk-jpl/src/py3/classes/mesh3dprisms.py

    r19898 r23670  
    1 import numpy
     1import numpy as np
    22from fielddisplay import fielddisplay
    3 from EnumDefinitions import *
    43from checkfield import *
    54import MatlabFuncs as m
     
    2625                self.long                        = float('NaN');
    2726                self.epsg                        = 0;
     27                self.scale_factor                = float('NaN');
    2828
    2929                self.vertexonbase                = float('NaN');
     
    7474                string="%s\n%s"%(string,fielddisplay(self,"vertexonbase","lower vertices flags list"))
    7575                string="%s\n%s"%(string,fielddisplay(self,"vertexonsurface","upper vertices flags list"))
    76                 string="%s\n%s"%(string,fielddisplay(self,"uppervertex","upper vertex list (-1 for vertex on the upper surface)"))
    77                 string="%s\n%s"%(string,fielddisplay(self,"upperelements","upper element list (-1 for element on the upper layer)"))
    78                 string="%s\n%s"%(string,fielddisplay(self,"lowervertex","lower vertex list (-1 for vertex on the lower surface)"))
    79                 string="%s\n%s"%(string,fielddisplay(self,"lowerelements","lower element list (-1 for element on the lower layer)"))
     76                string="%s\n%s"%(string,fielddisplay(self,"uppervertex","upper vertex list (NaN for vertex on the upper surface)"))
     77                string="%s\n%s"%(string,fielddisplay(self,"upperelements","upper element list (NaN for element on the upper layer)"))
     78                string="%s\n%s"%(string,fielddisplay(self,"lowervertex","lower vertex list (NaN for vertex on the lower surface)"))
     79                string="%s\n%s"%(string,fielddisplay(self,"lowerelements","lower element list (NaN for element on the lower layer)"))
    8080                string="%s\n%s"%(string,fielddisplay(self,"vertexonboundary","vertices on the boundary of the domain flag list"))
    81                 string="%s\n%s"%(string,fielddisplay(self,"vertexconnectivity","list of vertices connected to vertex_i"))
    82                 string="%s\n%s"%(string,fielddisplay(self,"elementconnectivity","list of vertices connected to element_i"))
     81                string="%s\n%s"%(string,fielddisplay(self,"vertexconnectivity","list of elements connected to vertex_i"))
     82                string="%s\n%s"%(string,fielddisplay(self,"elementconnectivity","list of elements adjacent to element_i"))
    8383                string="%s\n%s"%(string,fielddisplay(self,"average_vertex_connectivity","average number of vertices connected to one vertex"))
    8484
     
    9191                string="%s\n%s"%(string,fielddisplay(self,"long","vertices longitude [degrees]"))
    9292                string="%s\n%s"%(string,fielddisplay(self,"epsg","EPSG code (ex: 3413 for UPS Greenland, 3031 for UPS Antarctica)"))
     93                string="%s\n%s"%(string,fielddisplay(self,"scale_factor","Projection correction for volume, area, etc. computation"))
    9394                return string
    9495                #}}}
     
    109110                md = checkfield(md,'fieldname','mesh.y','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
    110111                md = checkfield(md,'fieldname','mesh.z','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
    111                 md = checkfield(md,'fieldname','mesh.elements','NaN',1,'Inf',1,'>',0,'values',numpy.arange(1,md.mesh.numberofvertices+1))
     112                md = checkfield(md,'fieldname','mesh.elements','NaN',1,'Inf',1,'>',0,'values',np.arange(1,md.mesh.numberofvertices+1))
    112113                md = checkfield(md,'fieldname','mesh.elements','size',[md.mesh.numberofelements,6])
    113                 if numpy.any(numpy.logical_not(m.ismember(numpy.arange(1,md.mesh.numberofvertices+1),md.mesh.elements))):
     114                if np.any(np.logical_not(m.ismember(np.arange(1,md.mesh.numberofvertices+1),md.mesh.elements))):
    114115                        md.checkmessage("orphan nodes have been found. Check the mesh3dprisms outline")
    115116                md = checkfield(md,'fieldname','mesh.numberoflayers','>=',0)
     
    119120                md = checkfield(md,'fieldname','mesh.vertexonsurface','size',[md.mesh.numberofvertices],'values',[0,1])
    120121                md = checkfield(md,'fieldname','mesh.average_vertex_connectivity','>=',24,'message',"'mesh.average_vertex_connectivity' should be at least 24 in 3d")
     122                if(np.size(self.scale_factor)>1):
     123                        md = checkfield(md,'fieldname','mesh.scale_factor','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
    121124
    122125                return md
     
    131134                return "Penta"
    132135        #}}}
    133         def marshall(self,md,fid):    # {{{
    134                 WriteData(fid,'enum',DomainTypeEnum(),'data',StringToEnum("Domain"+self.domaintype())[0],'format','Integer');
    135                 WriteData(fid,'enum',DomainDimensionEnum(),'data',self.dimension(),'format','Integer');
    136                 WriteData(fid,'enum',MeshElementtypeEnum(),'data',StringToEnum(self.elementtype())[0],'format','Integer');
    137                 WriteData(fid,'object',self,'class','mesh','fieldname','x','format','DoubleMat','mattype',1)
    138                 WriteData(fid,'object',self,'class','mesh','fieldname','y','format','DoubleMat','mattype',1)
    139                 WriteData(fid,'object',self,'class','mesh','fieldname','z','format','DoubleMat','mattype',1)
    140                 WriteData(fid,'object',self,'class','mesh','fieldname','elements','format','DoubleMat','mattype',2)
    141                 WriteData(fid,'object',self,'class','mesh','fieldname','numberoflayers','format','Integer')
    142                 WriteData(fid,'object',self,'class','mesh','fieldname','numberofelements','format','Integer')
    143                 WriteData(fid,'object',self,'class','mesh','fieldname','numberofvertices','format','Integer')
    144                 WriteData(fid,'object',self,'class','mesh','fieldname','vertexonbase','format','BooleanMat','mattype',1)
    145                 WriteData(fid,'object',self,'class','mesh','fieldname','vertexonsurface','format','BooleanMat','mattype',1)
    146                 WriteData(fid,'object',self,'class','mesh','fieldname','lowerelements','format','DoubleMat','mattype',2)
    147                 WriteData(fid,'object',self,'class','mesh','fieldname','upperelements','format','DoubleMat','mattype',2)
    148                 WriteData(fid,'object',self,'class','mesh','fieldname','average_vertex_connectivity','format','Integer')
    149                 WriteData(fid,'object',self,'class','mesh','fieldname','elements2d','format','DoubleMat','mattype',3)
    150                 WriteData(fid,'object',self,'class','mesh','fieldname','numberofvertices2d','format','Integer')
    151                 WriteData(fid,'object',self,'class','mesh','fieldname','numberofelements2d','format','Integer')
     136        def marshall(self,prefix,md,fid):    # {{{
     137                WriteData(fid,prefix,'name','md.mesh.domain_type','data',"Domain"+self.domaintype(),'format','String');
     138                WriteData(fid,prefix,'name','md.mesh.domain_dimension','data',self.dimension(),'format','Integer');
     139                WriteData(fid,prefix,'name','md.mesh.elementtype','data',self.elementtype(),'format','String');
     140                WriteData(fid,prefix,'object',self,'class','mesh','fieldname','x','format','DoubleMat','mattype',1)
     141                WriteData(fid,prefix,'object',self,'class','mesh','fieldname','y','format','DoubleMat','mattype',1)
     142                WriteData(fid,prefix,'object',self,'class','mesh','fieldname','z','format','DoubleMat','mattype',1)
     143                WriteData(fid,prefix,'object',self,'class','mesh','fieldname','elements','format','DoubleMat','mattype',2)
     144                WriteData(fid,prefix,'object',self,'class','mesh','fieldname','numberoflayers','format','Integer')
     145                WriteData(fid,prefix,'object',self,'class','mesh','fieldname','numberofelements','format','Integer')
     146                WriteData(fid,prefix,'object',self,'class','mesh','fieldname','numberofvertices','format','Integer')
     147                WriteData(fid,prefix,'object',self,'class','mesh','fieldname','vertexonbase','format','BooleanMat','mattype',1)
     148                WriteData(fid,prefix,'object',self,'class','mesh','fieldname','vertexonsurface','format','BooleanMat','mattype',1)
     149                WriteData(fid,prefix,'object',self,'class','mesh','fieldname','lowerelements','format','DoubleMat','mattype',2)
     150                WriteData(fid,prefix,'object',self,'class','mesh','fieldname','upperelements','format','DoubleMat','mattype',2)
     151                WriteData(fid,prefix,'object',self,'class','mesh','fieldname','average_vertex_connectivity','format','Integer')
     152                WriteData(fid,prefix,'object',self,'class','mesh','fieldname','elements2d','format','DoubleMat','mattype',3)
     153                WriteData(fid,prefix,'object',self,'class','mesh','fieldname','numberofvertices2d','format','Integer')
     154                WriteData(fid,prefix,'object',self,'class','mesh','fieldname','numberofelements2d','format','Integer')
     155                WriteData(fid,prefix,'object',self,'class','mesh','fieldname','scale_factor','format','DoubleMat','mattype',1)
     156                if md.transient.isoceancoupling:
     157                        WriteData(fid,prefix,'object',self,'class','mesh','fieldname','lat','format','DoubleMat','mattype',1)
     158                        WriteData(fid,prefix,'object',self,'class','mesh','fieldname','long','format','DoubleMat','mattype',1)
    152159        # }}}
  • issm/trunk-jpl/src/py3/classes/miscellaneous.py

    r19895 r23670  
    11from collections import OrderedDict
    22from fielddisplay import fielddisplay
    3 from EnumDefinitions import *
    43from checkfield import checkfield
    54from WriteData import WriteData
     
    3736                return md
    3837        # }}}
    39         def marshall(self,md,fid):    #  {{{
    40                 WriteData(fid,'object',self,'fieldname','name','format','String')
     38        def marshall(self,prefix,md,fid):    #  {{{
     39                WriteData(fid,prefix,'object',self,'fieldname','name','format','String');
    4140        # }}}
  • issm/trunk-jpl/src/py3/classes/mismipbasalforcings.py

    r19898 r23670  
    11from fielddisplay import fielddisplay
    2 from EnumDefinitions import *
     2from project3d import project3d
    33from checkfield import checkfield
    44from WriteData import WriteData
    5 import numpy
     5import numpy as np
    66
    77class mismipbasalforcings(object):
    8     """
     8    """ 
    99    MISMIP Basal Forcings class definition
    1010
     
    1313    """
    1414
    15     def __init__(self,md): # {{{
     15    def __init__(self): # {{{
    1616
    1717        self.groundedice_melting_rate = float('NaN')
     
    2020        self.upperdepth_melt = float('NaN')
    2121        self.geothermalflux = float('NaN')
    22 
    23         if numpy.all(numpy.isnan(self.groundedice_melting_rate)):
    24             self.groundedice_melting_rate=numpy.zeros(md.mesh.numberofvertices)
    25             print(' no basalforcings.groundedice_melting_rate specified: values set as zero')
    2622
    2723        self.setdefaultparameters()
     
    3531        string="%s\n%s"%(string,fielddisplay(self,"upperdepth_melt","Depth above which melt rate is zero [m]"))
    3632        string="%s\n%s"%(string,fielddisplay(self,"geothermalflux","Geothermal heat flux [W/m^2]"))
    37 
    3833        return string
    3934    #}}}
    4035    def extrude(self,md): # {{{
    41         self.coefficient=project3d(md,'vector',self.coefficient,'type','node','layer',1)
    42         self.p=project3d(md,'vector',self.p,'type','element')
    43         self.q=project3d(md,'vector',self.q,'type','element')
     36        self.groundedice_melting_rate=project3d(md,'vector',self.groundedice_melting_rate,'type','node','layer',1)
     37        self.geothermalflux=project3d(md,'vector',self.geothermalflux,'type','node','layer',1)    #bedrock only gets geothermal flux
    4438        return self
    4539    #}}}
     40    def initialize(self,md): # {{{
     41        if np.all(np.isnan(self.groundedice_melting_rate)):
     42            self.groundedice_melting_rate=np.zeros((md.mesh.numberofvertices))
     43            print(' no basalforcings.groundedice_melting_rate specified: values set as zero')
     44        if np.all(np.isnan(self.geothermalflux)):
     45                        self.geothermalflux=np.zeros((md.mesh.numberofvertices))
     46                        print("      no basalforcings.geothermalflux specified: values set as zero")
     47        return self
     48    #}}}
    4649    def setdefaultparameters(self): # {{{
    47 
    4850        # default values for melting parameterization
    4951        self.meltrate_factor = 0.2
    5052        self.threshold_thickness = 75.
    5153        self.upperdepth_melt = -100.
    52 
    5354        return self
    5455    #}}}
     
    5657
    5758        #Early return
    58         if MasstransportAnalysisEnum() in analyses and not (solution==TransientSolutionEnum() and md.transient.ismasstransport==0):
     59        if 'MasstransportAnalysis' in analyses and not (solution=='TransientSolution' and md.transient.ismasstransport==0):
    5960
    6061            md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'Inf',1,'timeseries',1)
     
    6364            md = checkfield(md,'fieldname','basalforcings.upperdepth_melt','<=',0,'numel',[1])
    6465
    65         if BalancethicknessAnalysisEnum() in analyses:
     66        if 'BalancethicknessAnalysis' in analyses:
    6667
    6768            md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
     
    7071            md = checkfield(md,'fieldname','basalforcings.upperdepth_melt','<=',0,'numel',[1])
    7172
    72         if ThermalAnalysisEnum() in analyses and not (solution==TransientSolutionEnum() and md.transient.isthermal==0):
     73        if 'ThermalAnalysis' in analyses and not (solution=='TransientSolution' and md.transient.isthermal==0):
    7374
    7475            md = checkfield(md,'fieldname','basalforcings.groundedice_melting_rate','NaN',1,'Inf',1,'timeseries',1)
     
    7980        return md
    8081    # }}}
    81     def marshall(self,md,fid):    # {{{
     82    def marshall(self,prefix,md,fid):    # {{{
    8283
    8384        yts=md.constants.yts
     
    8586            print('WARNING: value of yts for MISMIP+ runs different from ISSM default!')
    8687
    87         floatingice_melting_rate = numpy.zeros((md.mesh.numberofvertices,1))
    88         floatingice_melting_rate = md.basalforcings.meltrate_factor*numpy.tanh((md.geometry.base-md.geometry.bed)/md.basalforcings.threshold_thickness)*numpy.amax(md.basalforcings.upperdepth_melt-md.geometry.base,0)
    89 
    90         WriteData(fid,'enum',BasalforcingsEnum(),'data',MismipFloatingMeltRateEnum(),'format','Integer')
    91         WriteData(fid,'data',floatingice_melting_rate,'format','DoubleMat','enum',BasalforcingsFloatingiceMeltingRateEnum(),'mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
    92         WriteData(fid,'object',self,'fieldname','groundedice_melting_rate','format','DoubleMat','enum',BasalforcingsGroundediceMeltingRateEnum(),'mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
    93         WriteData(fid,'object',self,'fieldname','geothermalflux','enum',BasalforcingsGeothermalfluxEnum(),'format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1)
    94         WriteData(fid,'object',self,'fieldname','meltrate_factor','format','Double','enum',BasalforcingsMeltrateFactorEnum(),'scale',1./yts)
    95         WriteData(fid,'object',self,'fieldname','threshold_thickness','format','Double','enum',BasalforcingsThresholdThicknessEnum())
    96         WriteData(fid,'object',self,'fieldname','upperdepth_melt','format','Double','enum',BasalforcingsUpperdepthMeltEnum())
     88        WriteData(fid,prefix,'name','md.basalforcings.model','data',3,'format','Integer')
     89        WriteData(fid,prefix,'object',self,'fieldname','groundedice_melting_rate','format','DoubleMat','name','md.basalforcings.groundedice_melting_rate','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     90        WriteData(fid,prefix,'object',self,'fieldname','geothermalflux','name','md.basalforcings.geothermalflux','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     91        WriteData(fid,prefix,'object',self,'fieldname','meltrate_factor','format','Double','scale',1./yts)
     92        WriteData(fid,prefix,'object',self,'fieldname','threshold_thickness','format','Double')
     93        WriteData(fid,prefix,'object',self,'fieldname','upperdepth_melt','format','Double')
    9794
    9895    # }}}
  • issm/trunk-jpl/src/py3/classes/model.py

    r19895 r23670  
    11#module imports {{{
    2 import numpy
     2import numpy as np
    33import copy
    44import sys
    5 import MatlabFuncs as m
     5from mesh2d import mesh2d
     6from mesh3dprisms import mesh3dprisms
     7from mask import mask
     8from geometry import geometry
     9from constants import constants
     10from SMBforcing import SMBforcing
     11from SMBpdd import SMBpdd
     12from SMBd18opdd import SMBd18opdd
     13from SMBgradients import SMBgradients
     14from SMBcomponents import SMBcomponents
     15from SMBmeltcomponents import SMBmeltcomponents
     16from basalforcings import basalforcings
     17from matice import matice
     18from levelset import levelset
     19from calving import calving
     20from fourierlove import fourierlove
     21from calvinglevermann import calvinglevermann
     22#from calvingpi import calvingpi
     23from frontalforcings import frontalforcings
     24from damage import damage
     25from friction import friction
     26from flowequation import flowequation
     27from timestepping import timestepping
     28from timesteppingadaptive import timesteppingadaptive
     29from initialization import initialization
     30from rifts import rifts
     31from slr import slr
     32from debug import debug
     33from verbose import verbose
     34from issmsettings import issmsettings
     35from toolkits import toolkits
     36from generic import generic
     37from pfe import pfe
     38from vilje import vilje
     39from hexagon import hexagon
     40from cyclone import cyclone
     41from stallo import stallo
     42from balancethickness import balancethickness
     43from stressbalance import stressbalance
     44from groundingline import groundingline
     45from hydrologyshreve import hydrologyshreve
     46from hydrologydc import hydrologydc
     47from masstransport import masstransport
     48from thermal import thermal
     49from steadystate import steadystate
     50from transient import transient
     51from giaivins import giaivins
     52from esa import esa
     53from autodiff import autodiff
     54from inversion import inversion
     55from outputdefinition import outputdefinition
     56from qmu import qmu
     57from amr import amr
     58from results import results
     59from radaroverlay import radaroverlay
     60from miscellaneous import miscellaneous
     61from private import private
     62from mumpsoptions import mumpsoptions
     63from iluasmoptions import iluasmoptions
     64from project3d import project3d
     65from project2d import project2d
     66from FlagElements import FlagElements
     67from NodeConnectivity import NodeConnectivity
     68from ElementConnectivity import ElementConnectivity
     69from contourenvelope import contourenvelope
     70from DepthAverage import DepthAverage
    671#}}}
    772
    873class model(object):
    974        #properties
    10         def __init__(self,*filename):#{{{
    11 
    12                 def netCDFread(filename):
    13                         def walktree(data):
    14                                 keys = data.groups.keys()
    15                                 yield keys
    16                                 for key in keys:
    17                                         for children in walktree(data.groups[str(key)]):
    18                                                 yield children
    19 
    20                         if path.exists(filename):
    21                                 print ('Opening {} for reading '.format(filename))
    22                                 NCData=Dataset(filename, 'r')
    23                                 class_dict={}
    24                                
    25                                 for children in walktree(NCData):
    26                                         for child in children:
    27                                                 class_dict[str(child)]=str(getattr(NCData.groups[str(child)],'classtype'))
    28 
    29                                 return class_dict
    30 
    31                 if filename:           
    32                         classtype=netCDFread(filename[0])
    33                 else:
    34                         classtype=self.properties()
    35                        
    36                 VT=[v[0] for v in dict.values(classtype)]
    37                 classnames=[classname for classname in dict.keys(classtype)]
    38                 module=map(__import__,VT)
    39 
    40                 for i,mod in enumerate(module):
    41                         self.__dict__[classnames[i]] = getattr(mod,str(classtype[str(classnames[i])][0]))()
    42 
    43         #}}}
    44 
     75        def __init__(self):#{{{
     76
     77                # classtype=model.properties
     78
     79                # for classe in dict.keys(classtype):
     80                #       print classe
     81                #       self.__dict__[classe] = classtype[str(classe)]
     82
     83                self.mesh           = mesh2d()
     84                self.mask           = mask()
     85                self.geometry       = geometry()
     86                self.constants      = constants()
     87                self.smb            = SMBforcing()
     88                self.basalforcings  = basalforcings()
     89                self.materials      = matice()
     90                self.damage         = damage()
     91                self.friction       = friction()
     92                self.flowequation   = flowequation()
     93                self.timestepping   = timestepping()
     94                self.initialization = initialization()
     95                self.rifts          = rifts()
     96                self.slr            = slr()
     97
     98                self.debug    = debug()
     99                self.verbose  = verbose()
     100                self.settings = issmsettings()
     101                self.toolkits = toolkits()
     102                self.cluster  = generic()
     103
     104                self.balancethickness = balancethickness()
     105                self.stressbalance    = stressbalance()
     106                self.groundingline    = groundingline()
     107                self.hydrology        = hydrologyshreve()
     108                self.masstransport    = masstransport()
     109                self.thermal          = thermal()
     110                self.steadystate      = steadystate()
     111                self.transient        = transient()
     112                self.levelset         = levelset()
     113                self.calving          = calving()
     114                self.frontalforcings  = frontalforcings()
     115                self.gia              = giaivins()
     116                self.love                                                       = fourierlove()
     117                self.esa                                                        = esa()
     118                self.autodiff                                   = autodiff()
     119                self.inversion                          = inversion()
     120                self.qmu                                                        = qmu()
     121                self.amr                                                        = amr()
     122
     123                self.results          = results()
     124                self.outputdefinition = outputdefinition()
     125                self.radaroverlay     = radaroverlay()
     126                self.miscellaneous    = miscellaneous()
     127                self.private          = private()
     128                #}}}
    45129        def properties(self):    # {{{
    46130                # ordered list of properties since vars(self) is random
    47                 return {'mesh':['mesh2d','mesh properties'],\
    48                         'mask':['mask','defines grounded and floating elements'],\
    49                         'geometry':['geometry','surface elevation, bedrock topography, ice thickness,...'],\
    50                         'constants':['constants','physical constants'],\
    51                         'smb':['SMBpdd','surface forcings'],\
    52                         'basalforcings':['basalforcings','bed forcings'],\
    53                         'materials':['matice','material properties'],\
    54                         'damage':['damage','damage propagation laws'],\
    55                         'friction':['friction','basal friction/drag properties'],\
    56                         'flowequation':['flowequation','flow equations'],\
    57                         'timestepping':['timestepping','time stepping for transient models'],\
    58                         'initialization':['initialization','initial guess/state'],\
    59                         'rifts':['rifts','rifts properties'],\
    60                         'debug':['debug','debugging tools (valgrind, gprof)'],\
    61                         'verbose':['verbose','verbosity level in solve'],\
    62                         'settings':['settings','settings properties'],\
    63                         'toolkits':['toolkits','PETSc options for each solution'],\
    64                         'cluster':['generic','cluster parameters (number of cpus...)'],\
    65                         'balancethickness':['balancethickness','parameters for balancethickness solution'],\
    66                         'stressbalance':['stressbalance','parameters for stressbalance solution'],\
    67                         'groundingline':['groundingline','parameters for groundingline solution'],\
    68                         'hydrology':['hydrologyshreve','parameters for hydrology solution'],\
    69                         'masstransport':['masstransport','parameters for masstransport solution'],\
    70                         'thermal':['thermal','parameters for thermal solution'],\
    71                         'steadystate':['steadystate','parameters for steadystate solution'],\
    72                         'transient':['transient','parameters for transient solution'],\
    73                         'calving':['calving','parameters for calving'],\
    74                                                 'gia':['gia','Parameters for gia model'],\
    75                         'autodiff':['autodiff','automatic differentiation parameters'],\
    76                         'flaim':['flaim','flaim parameters'],\
    77                         'inversion':['inversion','parameters for inverse methods'],\
    78                         'qmu':['qmu','dakota properties'],\
    79                         'outputdefinition':['outputdefinition','output definition'],\
    80                         'results':['results','model results'],\
    81                         'radaroverlay':['radaroverlay','radar image for plot overlay'],\
    82                         'miscellaneous':['miscellaneous','miscellaneous fields'],\
    83                         'private':['private','...']}
     131                return ['mesh',
     132                        'mask',
     133                        'geometry',
     134                        'constants',
     135                        'smb',
     136                        'basalforcings',
     137                        'materials',
     138                        'damage',
     139                        'friction',
     140                        'flowequation',
     141                        'timestepping',
     142                        'initialization',
     143                        'rifts',
     144                        'slr',
     145                        'debug',
     146                        'verbose',
     147                        'settings',
     148                        'toolkits',
     149                        'cluster',
     150                        'balancethickness',
     151                        'stressbalance',
     152                        'groundingline',
     153                        'hydrology',
     154                        'masstransport',
     155                        'thermal',
     156                        'steadystate',
     157                        'transient',
     158                        'levelset',
     159                        'calving',
     160                                                'frontalforcings',
     161                                                'love',
     162                                                'gia',
     163                                                'esa',
     164                        'autodiff',
     165                        'inversion',
     166                        'qmu',
     167                        'amr',
     168                        'outputdefinition',
     169                        'results',
     170                        'radaroverlay',
     171                        'miscellaneous',
     172                        'private']
    84173        # }}}
    85 
    86174        def __repr__(obj): #{{{
    87                 string = "Model Description"
    88                 for i,mod in enumerate(dict.keys(obj.properties())):
    89                         tmp="%19s: %-22s -- %s" % (mod,"[%s,%s]" % ("1x1",obj.__dict__[mod].__class__.__name__),obj.properties()[mod][1])
    90                         string="\n".join([string, tmp])
     175                #print "Here %s the number: %d" % ("is", 37)
     176                string="%19s: %-22s -- %s" % ("mesh","[%s,%s]" % ("1x1",obj.mesh.__class__.__name__),"mesh properties")
     177                string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("mask","[%s,%s]" % ("1x1",obj.mask.__class__.__name__),"defines grounded and floating elements"))
     178                string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("geometry","[%s,%s]" % ("1x1",obj.geometry.__class__.__name__),"surface elevation, bedrock topography, ice thickness,..."))
     179                string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("constants","[%s,%s]" % ("1x1",obj.constants.__class__.__name__),"physical constants"))
     180                string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("smb","[%s,%s]" % ("1x1",obj.smb.__class__.__name__),"surface mass balance"))
     181                string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("basalforcings","[%s,%s]" % ("1x1",obj.basalforcings.__class__.__name__),"bed forcings"))
     182                string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("materials","[%s,%s]" % ("1x1",obj.materials.__class__.__name__),"material properties"))
     183                string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("damage","[%s,%s]" % ("1x1",obj.damage.__class__.__name__),"damage propagation laws"))
     184                string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("friction","[%s,%s]" % ("1x1",obj.friction.__class__.__name__),"basal friction/drag properties"))
     185                string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("flowequation","[%s,%s]" % ("1x1",obj.flowequation.__class__.__name__),"flow equations"))
     186                string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("timestepping","[%s,%s]" % ("1x1",obj.timestepping.__class__.__name__),"time stepping for transient models"))
     187                string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("initialization","[%s,%s]" % ("1x1",obj.initialization.__class__.__name__),"initial guess/state"))
     188                string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("rifts","[%s,%s]" % ("1x1",obj.rifts.__class__.__name__),"rifts properties"))
     189                string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("slr","[%s,%s]" % ("1x1",obj.slr.__class__.__name__),"slr forcings"))
     190                string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("debug","[%s,%s]" % ("1x1",obj.debug.__class__.__name__),"debugging tools (valgrind, gprof)"))
     191                string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("verbose","[%s,%s]" % ("1x1",obj.verbose.__class__.__name__),"verbosity level in solve"))
     192                string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("settings","[%s,%s]" % ("1x1",obj.settings.__class__.__name__),"settings properties"))
     193                string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("toolkits","[%s,%s]" % ("1x1",obj.toolkits.__class__.__name__),"PETSc options for each solution"))
     194                string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("cluster","[%s,%s]" % ("1x1",obj.cluster.__class__.__name__),"cluster parameters (number of cpus...)"))
     195                string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("balancethickness","[%s,%s]" % ("1x1",obj.balancethickness.__class__.__name__),"parameters for balancethickness solution"))
     196                string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("stressbalance","[%s,%s]" % ("1x1",obj.stressbalance.__class__.__name__),"parameters for stressbalance solution"))
     197                string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("groundingline","[%s,%s]" % ("1x1",obj.groundingline.__class__.__name__),"parameters for groundingline solution"))
     198                string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("hydrology","[%s,%s]" % ("1x1",obj.hydrology.__class__.__name__),"parameters for hydrology solution"))
     199                string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("masstransport","[%s,%s]" % ("1x1",obj.masstransport.__class__.__name__),"parameters for masstransport solution"))
     200                string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("thermal","[%s,%s]" % ("1x1",obj.thermal.__class__.__name__),"parameters for thermal solution"))
     201                string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("steadystate","[%s,%s]" % ("1x1",obj.steadystate.__class__.__name__),"parameters for steadystate solution"))
     202                string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("transient","[%s,%s]" % ("1x1",obj.transient.__class__.__name__),"parameters for transient solution"))
     203                string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("levelset","[%s,%s]" % ("1x1",obj.levelset.__class__.__name__),"parameters for moving boundaries (level-set method)"))
     204                string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("calving","[%s,%s]" % ("1x1",obj.calving.__class__.__name__),"parameters for calving"))
     205                string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("frontalforcings","[%s,%s]" % ("1x1",obj.frontalforcings.__class__.__name__),"parameters for frontalforcings"))
     206                string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("gia","[%s,%s]" % ("1x1",obj.gia.__class__.__name__),"parameters for gia solution"))
     207                string="%s\n%s" % (string,'%19s: %-22s -- %s' % ("love","[%s,%s]" % ("1x1",obj.love.__class__.__name__),"parameters for love solution"))
     208                string="%s\n%s" % (string,'%19s: %-22s -- %s' % ("esa","[%s,%s]" % ("1x1",obj.esa.__class__.__name__),"parameters for elastic adjustment solution"))
     209                string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("autodiff","[%s,%s]" % ("1x1",obj.autodiff.__class__.__name__),"automatic differentiation parameters"))
     210                string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("inversion","[%s,%s]" % ("1x1",obj.inversion.__class__.__name__),"parameters for inverse methods"))
     211                string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("qmu","[%s,%s]" % ("1x1",obj.qmu.__class__.__name__),"dakota properties"))
     212                string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("amr","[%s,%s]" % ("1x1",obj.amr.__class__.__name__),"adaptive mesh refinement properties"))
     213                string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("outputdefinition","[%s,%s]" % ("1x1",obj.outputdefinition.__class__.__name__),"output definition"))
     214                string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("results","[%s,%s]" % ("1x1",obj.results.__class__.__name__),"model results"))
     215                string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("radaroverlay","[%s,%s]" % ("1x1",obj.radaroverlay.__class__.__name__),"radar image for plot overlay"))
     216                string="%s\n%s" % (string,"%19s: %-22s -- %s" % ("miscellaneous","[%s,%s]" % ("1x1",obj.miscellaneous.__class__.__name__),"miscellaneous fields"))
    91217                return string
    92218        # }}}
    93 
    94219        def checkmessage(self,string):    # {{{
    95                 print(("model not consistent: ", string))
     220                print("model not consistent: ", string)
    96221                self.private.isconsistent=False
    97222                return self
    98223        # }}}
    99 
    100         def extract(md,area):    # {{{
     224        #@staticmethod
     225        def extract(self,area):    # {{{
    101226                """
    102227                extract - extract a model according to an Argus contour or flag list
    103228
    104    This routine extracts a submodel from a bigger model with respect to a given contour
    105    md must be followed by the corresponding exp file or flags list
    106    It can either be a domain file (argus type, .exp extension), or an array of element flags.
    107    If user wants every element outside the domain to be
    108    extract2d, add '~' to the name of the domain file (ex: '~HO.exp')
    109    an empty string '' will be considered as an empty domain
    110    a string 'all' will be considered as the entire domain
    111 
    112    Usage:
    113       md2=extract(md,area)
    114 
    115    Examples:
    116       md2=extract(md,'Domain.exp')
    117 
    118    See also: EXTRUDE, COLLAPSE
     229                   This routine extracts a submodel from a bigger model with respect to a given contour
     230                   md must be followed by the corresponding exp file or flags list
     231                   It can either be a domain file (argus type, .exp extension), or an array of element flags.
     232                   If user wants every element outside the domain to be
     233                   extract2d, add '~' to the name of the domain file (ex: '~HO.exp')
     234                   an empty string '' will be considered as an empty domain
     235                   a string 'all' will be considered as the entire domain
     236
     237                   Usage:
     238                      md2=extract(md,area)
     239
     240                   Examples:
     241                      md2=extract(md,'Domain.exp')
     242
     243                   See also: EXTRUDE, COLLAPSE
    119244                """
    120245
    121246                #copy model
    122                 md1=copy.deepcopy(md)
     247                md1=copy.deepcopy(self)
    123248
    124249                #get elements that are inside area
    125250                flag_elem=FlagElements(md1,area)
    126                 if not numpy.any(flag_elem):
     251                if not np.any(flag_elem):
    127252                        raise RuntimeError("extracted model is empty")
    128253
    129254                #kick out all elements with 3 dirichlets
    130                 spc_elem=numpy.nonzero(numpy.logical_not(flag_elem))[0]
    131                 spc_node=numpy.unique(md1.mesh.elements[spc_elem,:])-1
    132                 flag=numpy.ones(md1.mesh.numberofvertices)
     255                spc_elem=np.nonzero(np.logical_not(flag_elem))[0]
     256                spc_node=np.unique(md1.mesh.elements[spc_elem,:])-1
     257                flag=np.ones(md1.mesh.numberofvertices)
    133258                flag[spc_node]=0
    134                 pos=numpy.nonzero(numpy.logical_not(numpy.sum(flag[md1.mesh.elements-1],axis=1)))[0]
     259                pos=np.nonzero(np.logical_not(np.sum(flag[md1.mesh.elements-1],axis=1)))[0]
    135260                flag_elem[pos]=0
    136        
     261
    137262                #extracted elements and nodes lists
    138                 pos_elem=numpy.nonzero(flag_elem)[0]
    139                 pos_node=numpy.unique(md1.mesh.elements[pos_elem,:])-1
    140        
     263                pos_elem=np.nonzero(flag_elem)[0]
     264                pos_node=np.unique(md1.mesh.elements[pos_elem,:])-1
     265
    141266                #keep track of some fields
    142267                numberofvertices1=md1.mesh.numberofvertices
    143268                numberofelements1=md1.mesh.numberofelements
    144                 numberofvertices2=numpy.size(pos_node)
    145                 numberofelements2=numpy.size(pos_elem)
    146                 flag_node=numpy.zeros(numberofvertices1)
     269                numberofvertices2=np.size(pos_node)
     270                numberofelements2=np.size(pos_elem)
     271                flag_node=np.zeros(numberofvertices1)
    147272                flag_node[pos_node]=1
    148        
     273
    149274                #Create Pelem and Pnode (transform old nodes in new nodes and same thing for the elements)
    150                 Pelem=numpy.zeros(numberofelements1,int)
    151                 Pelem[pos_elem]=numpy.arange(1,numberofelements2+1)
    152                 Pnode=numpy.zeros(numberofvertices1,int)
    153                 Pnode[pos_node]=numpy.arange(1,numberofvertices2+1)
    154        
     275                Pelem=np.zeros(numberofelements1,int)
     276                Pelem[pos_elem]=np.arange(1,numberofelements2+1)
     277                Pnode=np.zeros(numberofvertices1,int)
     278                Pnode[pos_node]=np.arange(1,numberofvertices2+1)
     279
    155280                #renumber the elements (some node won't exist anymore)
    156281                elements_1=copy.deepcopy(md1.mesh.elements)
     
    165290
    166291                #OK, now create the new model!
     292
    167293                #take every field from model
    168294                md2=copy.deepcopy(md1)
    169295
    170296                #automatically modify fields
     297
    171298                #loop over model fields
    172299                model_fields=vars(md1)
     
    174301                        #get field
    175302                        field=getattr(md1,fieldi)
    176                         fieldsize=numpy.shape(field)
    177                         if hasattr(field,'__dict__') and not m.ismember(fieldi,['results'])[0]:    #recursive call
     303                        fieldsize=np.shape(field)
     304                        if hasattr(field,'__dict__') and not fieldi in ['results']:    #recursive call
    178305                                object_fields=vars(field)
    179306                                for fieldj in object_fields:
    180307                                        #get field
    181308                                        field=getattr(getattr(md1,fieldi),fieldj)
    182                                         fieldsize=numpy.shape(field)
     309                                        fieldsize=np.shape(field)
    183310                                        if len(fieldsize):
    184311                                                #size = number of nodes * n
    185                                                 if   fieldsize[0]==numberofvertices1:
     312                                                if fieldsize[0]==numberofvertices1:
    186313                                                        setattr(getattr(md2,fieldi),fieldj,field[pos_node])
    187314                                                elif fieldsize[0]==numberofvertices1+1:
    188                                                         setattr(getattr(md2,fieldi),fieldj,numpy.vstack((field[pos_node],field[-1,:])))
    189                                                         #size = number of elements * n
     315                                                        setattr(getattr(md2,fieldi),fieldj,np.vstack((field[pos_node],field[-1,:])))
     316                                                #size = number of elements * n
    190317                                                elif fieldsize[0]==numberofelements1:
    191318                                                        setattr(getattr(md2,fieldi),fieldj,field[pos_elem])
     
    196323                                                setattr(md2,fieldi,field[pos_node])
    197324                                        elif fieldsize[0]==numberofvertices1+1:
    198                                                 setattr(md2,fieldi,numpy.hstack((field[pos_node],field[-1,:])))
    199                                                 #size = number of elements * n
     325                                                setattr(md2,fieldi,np.hstack((field[pos_node],field[-1,:])))
     326                                        #size = number of elements * n
    200327                                        elif fieldsize[0]==numberofelements1:
    201328                                                setattr(md2,fieldi,field[pos_elem])
     
    207334                md2.mesh.numberofvertices=numberofvertices2
    208335                md2.mesh.elements=elements_2
    209                
     336
    210337                #mesh.uppervertex mesh.lowervertex
    211338                if md1.mesh.__class__.__name__=='mesh3dprisms':
    212339                        md2.mesh.uppervertex=md1.mesh.uppervertex[pos_node]
    213                         pos=numpy.nonzero(numpy.logical_not(md2.mesh.uppervertex==-1))[0]
    214                         md2.mesh.uppervertex[pos]=Pnode[md2.mesh.uppervertex[pos]-1]
    215                        
     340                        pos=np.where(~np.isnan(md2.mesh.uppervertex))[0]
     341                        md2.mesh.uppervertex[pos]=Pnode[md2.mesh.uppervertex[pos].astype(int)-1]
     342
    216343                        md2.mesh.lowervertex=md1.mesh.lowervertex[pos_node]
    217                         pos=numpy.nonzero(numpy.logical_not(md2.mesh.lowervertex==-1))[0]
    218                         md2.mesh.lowervertex[pos]=Pnode[md2.mesh.lowervertex[pos]-1]
    219                        
     344                        pos=np.where(~np.isnan(md2.mesh.lowervertex))[0]
     345                        md2.mesh.lowervertex[pos]=Pnode[md2.mesh.lowervertex[pos].astype(int)-1]
     346
    220347                        md2.mesh.upperelements=md1.mesh.upperelements[pos_elem]
    221                         pos=numpy.nonzero(numpy.logical_not(md2.mesh.upperelements==-1))[0]
    222                         md2.mesh.upperelements[pos]=Pelem[md2.mesh.upperelements[pos]-1]
    223                        
     348                        pos=np.where(~np.isnan(md2.mesh.upperelements))[0]
     349                        md2.mesh.upperelements[pos]=Pelem[md2.mesh.upperelements[pos].astype(int)-1]
     350
    224351                        md2.mesh.lowerelements=md1.mesh.lowerelements[pos_elem]
    225                         pos=numpy.nonzero(numpy.logical_not(md2.mesh.lowerelements==-1))[0]
    226                         md2.mesh.lowerelements[pos]=Pelem[md2.mesh.lowerelements[pos]-1]
    227                        
    228                 #Initial 2d mesh 
     352                        pos=np.where(~np.isnan(md2.mesh.lowerelements))[0]
     353                        md2.mesh.lowerelements[pos]=Pelem[md2.mesh.lowerelements[pos].astype(int)-1]
     354
     355                #Initial 2d mesh
    229356                if md1.mesh.__class__.__name__=='mesh3dprisms':
    230                         flag_elem_2d=flag_elem[numpy.arange(0,md1.mesh.numberofelements2d)]
    231                         pos_elem_2d=numpy.nonzero(flag_elem_2d)[0]
    232                         flag_node_2d=flag_node[numpy.arange(0,md1.mesh.numberofvertices2d)]
    233                         pos_node_2d=numpy.nonzero(flag_node_2d)[0]
    234                
    235                         md2.mesh.numberofelements2d=numpy.size(pos_elem_2d)
    236                         md2.mesh.numberofvertices2d=numpy.size(pos_node_2d)
     357                        flag_elem_2d=flag_elem[np.arange(0,md1.mesh.numberofelements2d)]
     358                        pos_elem_2d=np.nonzero(flag_elem_2d)[0]
     359                        flag_node_2d=flag_node[np.arange(0,md1.mesh.numberofvertices2d)]
     360                        pos_node_2d=np.nonzero(flag_node_2d)[0]
     361
     362                        md2.mesh.numberofelements2d=np.size(pos_elem_2d)
     363                        md2.mesh.numberofvertices2d=np.size(pos_node_2d)
    237364                        md2.mesh.elements2d=md1.mesh.elements2d[pos_elem_2d,:]
    238365                        md2.mesh.elements2d[:,0]=Pnode[md2.mesh.elements2d[:,0]-1]
    239366                        md2.mesh.elements2d[:,1]=Pnode[md2.mesh.elements2d[:,1]-1]
    240367                        md2.mesh.elements2d[:,2]=Pnode[md2.mesh.elements2d[:,2]-1]
    241                
     368
    242369                        md2.mesh.x2d=md1.mesh.x[pos_node_2d]
    243370                        md2.mesh.y2d=md1.mesh.y[pos_node_2d]
    244                
     371
    245372                #Edges
    246                 if m.strcmp(md.mesh.domaintype(),'2Dhorizontal'):
    247                         if numpy.ndim(md2.mesh.edges)>1 and numpy.size(md2.mesh.edges,axis=1)>1:   
    248                                 #do not use ~isnan because there are some numpy.nans...
     373                if md1.mesh.domaintype()=='2Dhorizontal':
     374                        if np.ndim(md2.mesh.edges)>1 and np.size(md2.mesh.edges,axis=1)>1:    #do not use ~isnan because there are some np.nans...
    249375                                #renumber first two columns
    250                                 pos=numpy.nonzero(md2.mesh.edges[:,3]!=-1)[0]
    251                                 md2.mesh.edges[:  ,0]=Pnode[md2.mesh.edges[:,0]-1]
    252                                 md2.mesh.edges[:  ,1]=Pnode[md2.mesh.edges[:,1]-1]
    253                                 md2.mesh.edges[:  ,2]=Pelem[md2.mesh.edges[:,2]-1]
     376                                pos=np.nonzero(md2.mesh.edges[:,3]!=-1)[0]
     377                                md2.mesh.edges[:,0]=Pnode[md2.mesh.edges[:,0]-1]
     378                                md2.mesh.edges[:,1]=Pnode[md2.mesh.edges[:,1]-1]
     379                                md2.mesh.edges[:,2]=Pelem[md2.mesh.edges[:,2]-1]
    254380                                md2.mesh.edges[pos,3]=Pelem[md2.mesh.edges[pos,3]-1]
    255381                                #remove edges when the 2 vertices are not in the domain.
    256                                 md2.mesh.edges=md2.mesh.edges[numpy.nonzero(numpy.logical_and(md2.mesh.edges[:,0],md2.mesh.edges[:,1]))[0],:]
     382                                md2.mesh.edges=md2.mesh.edges[np.nonzero(np.logical_and(md2.mesh.edges[:,0],md2.mesh.edges[:,1]))[0],:]
    257383                                #Replace all zeros by -1 in the last two columns
    258                                 pos=numpy.nonzero(md2.mesh.edges[:,2]==0)[0]
     384                                pos=np.nonzero(md2.mesh.edges[:,2]==0)[0]
    259385                                md2.mesh.edges[pos,2]=-1
    260                                 pos=numpy.nonzero(md2.mesh.edges[:,3]==0)[0]
     386                                pos=np.nonzero(md2.mesh.edges[:,3]==0)[0]
    261387                                md2.mesh.edges[pos,3]=-1
    262388                                #Invert -1 on the third column with last column (Also invert first two columns!!)
    263                                 pos=numpy.nonzero(md2.mesh.edges[:,2]==-1)[0]
     389                                pos=np.nonzero(md2.mesh.edges[:,2]==-1)[0]
    264390                                md2.mesh.edges[pos,2]=md2.mesh.edges[pos,3]
    265391                                md2.mesh.edges[pos,3]=-1
     
    268394                                md2.mesh.edges[pos,0]=values
    269395                                #Finally remove edges that do not belong to any element
    270                                 pos=numpy.nonzero(numpy.logical_and(md2.mesh.edges[:,1]==-1,md2.mesh.edges[:,2]==-1))[0]
    271                                 md2.mesh.edges=numpy.delete(md2.mesh.edges,pos,axis=0)
     396                                pos=np.nonzero(np.logical_and(md2.mesh.edges[:,1]==-1,md2.mesh.edges[:,2]==-1))[0]
     397                                md2.mesh.edges=np.delete(md2.mesh.edges,pos,axis=0)
    272398
    273399                #Penalties
    274                 if numpy.any(numpy.logical_not(numpy.isnan(md2.stressbalance.vertex_pairing))):
    275                         for i in range(numpy.size(md1.stressbalance.vertex_pairing,axis=0)):
     400                if np.any(np.logical_not(np.isnan(md2.stressbalance.vertex_pairing))):
     401                        for i in range(np.size(md1.stressbalance.vertex_pairing,axis=0)):
    276402                                md2.stressbalance.vertex_pairing[i,:]=Pnode[md1.stressbalance.vertex_pairing[i,:]]
    277                         md2.stressbalance.vertex_pairing=md2.stressbalance.vertex_pairing[numpy.nonzero(md2.stressbalance.vertex_pairing[:,0])[0],:]
    278                 if numpy.any(numpy.logical_not(numpy.isnan(md2.masstransport.vertex_pairing))):
    279                         for i in range(numpy.size(md1.masstransport.vertex_pairing,axis=0)):
     403                        md2.stressbalance.vertex_pairing=md2.stressbalance.vertex_pairing[np.nonzero(md2.stressbalance.vertex_pairing[:,0])[0],:]
     404                if np.any(np.logical_not(np.isnan(md2.masstransport.vertex_pairing))):
     405                        for i in range(np.size(md1.masstransport.vertex_pairing,axis=0)):
    280406                                md2.masstransport.vertex_pairing[i,:]=Pnode[md1.masstransport.vertex_pairing[i,:]]
    281                                 md2.masstransport.vertex_pairing=md2.masstransport.vertex_pairing[numpy.nonzero(md2.masstransport.vertex_pairing[:,0])[0],:]
     407                        md2.masstransport.vertex_pairing=md2.masstransport.vertex_pairing[np.nonzero(md2.masstransport.vertex_pairing[:,0])[0],:]
    282408
    283409                #recreate segments
    284410                if md1.mesh.__class__.__name__=='mesh2d':
    285                         [md2.mesh.vertexconnectivity]=NodeConnectivity(md2.mesh.elements,md2.mesh.numberofvertices)
    286                         [md2.mesh.elementconnectivity]=ElementConnectivity(md2.mesh.elements,md2.mesh.vertexconnectivity)
     411                        md2.mesh.vertexconnectivity=NodeConnectivity(md2.mesh.elements,md2.mesh.numberofvertices)[0]
     412                        md2.mesh.elementconnectivity=ElementConnectivity(md2.mesh.elements,md2.mesh.vertexconnectivity)[0]
    287413                        md2.mesh.segments=contourenvelope(md2)
    288                         md2.mesh.vertexonboundary=numpy.zeros(numberofvertices2,bool)
     414                        md2.mesh.vertexonboundary=np.zeros(numberofvertices2,bool)
    289415                        md2.mesh.vertexonboundary[md2.mesh.segments[:,0:2]-1]=True
    290416                else:
    291417                        #First do the connectivity for the contourenvelope in 2d
    292                         [md2.mesh.vertexconnectivity]=NodeConnectivity(md2.mesh.elements2d,md2.mesh.numberofvertices2d)
    293                         [md2.mesh.elementconnectivity]=ElementConnectivity(md2.mesh.elements2d,md2.mesh.vertexconnectivity)
     418                        md2.mesh.vertexconnectivity=NodeConnectivity(md2.mesh.elements2d,md2.mesh.numberofvertices2d)[0]
     419                        md2.mesh.elementconnectivity=ElementConnectivity(md2.mesh.elements2d,md2.mesh.vertexconnectivity)[0]
    294420                        segments=contourenvelope(md2)
    295                         md2.mesh.vertexonboundary=numpy.zeros(numberofvertices2/md2.mesh.numberoflayers,bool)
     421                        md2.mesh.vertexonboundary=np.zeros(numberofvertices2/md2.mesh.numberoflayers,bool)
    296422                        md2.mesh.vertexonboundary[segments[:,0:2]-1]=True
    297                         md2.mesh.vertexonboundary=numpy.tile(md2.mesh.vertexonboundary,md2.mesh.numberoflayers)
     423                        md2.mesh.vertexonboundary=np.tile(md2.mesh.vertexonboundary,md2.mesh.numberoflayers)
    298424                        #Then do it for 3d as usual
    299                         [md2.mesh.vertexconnectivity]=NodeConnectivity(md2.mesh.elements,md2.mesh.numberofvertices)
    300                         [md2.mesh.elementconnectivity]=ElementConnectivity(md2.mesh.elements,md2.mesh.vertexconnectivity)
     425                        md2.mesh.vertexconnectivity=NodeConnectivity(md2.mesh.elements,md2.mesh.numberofvertices)[0]
     426                        md2.mesh.elementconnectivity=ElementConnectivity(md2.mesh.elements,md2.mesh.vertexconnectivity)[0]
    301427
    302428                #Boundary conditions: Dirichlets on new boundary
    303429                #Catch the elements that have not been extracted
    304                 orphans_elem=numpy.nonzero(numpy.logical_not(flag_elem))[0]
    305                 orphans_node=numpy.unique(md1.mesh.elements[orphans_elem,:])-1
     430                orphans_elem=np.nonzero(np.logical_not(flag_elem))[0]
     431                orphans_node=np.unique(md1.mesh.elements[orphans_elem,:])-1
    306432                #Figure out which node are on the boundary between md2 and md1
    307                 nodestoflag1=numpy.intersect1d(orphans_node,pos_node)
     433                nodestoflag1=np.intersect1d(orphans_node,pos_node)
    308434                nodestoflag2=Pnode[nodestoflag1].astype(int)-1
    309                 if numpy.size(md1.stressbalance.spcvx)>1 and numpy.size(md1.stressbalance.spcvy)>2 and numpy.size(md1.stressbalance.spcvz)>2:
    310                         if numpy.size(md1.inversion.vx_obs)>1 and numpy.size(md1.inversion.vy_obs)>1:
    311                                 md2.stressbalance.spcvx[nodestoflag2]=md2.inversion.vx_obs[nodestoflag2] 
     435                if np.size(md1.stressbalance.spcvx)>1 and np.size(md1.stressbalance.spcvy)>2 and np.size(md1.stressbalance.spcvz)>2:
     436                        if np.size(md1.inversion.vx_obs)>1 and np.size(md1.inversion.vy_obs)>1:
     437                                md2.stressbalance.spcvx[nodestoflag2]=md2.inversion.vx_obs[nodestoflag2]
    312438                                md2.stressbalance.spcvy[nodestoflag2]=md2.inversion.vy_obs[nodestoflag2]
    313439                        else:
    314                                 md2.stressbalance.spcvx[nodestoflag2]=numpy.nan
    315                                 md2.stressbalance.spcvy[nodestoflag2]=numpy.nan
     440                                md2.stressbalance.spcvx[nodestoflag2]=np.nan
     441                                md2.stressbalance.spcvy[nodestoflag2]=np.nan
    316442                                print("\n!! extract warning: spc values should be checked !!\n\n")
    317443                        #put 0 for vz
    318444                        md2.stressbalance.spcvz[nodestoflag2]=0
    319                 if numpy.any(numpy.logical_not(numpy.isnan(md1.thermal.spctemperature))):
    320                         md2.thermal.spctemperature[nodestoflag2,0]=1
     445                if np.any(np.logical_not(np.isnan(md1.thermal.spctemperature))):
     446                        md2.thermal.spctemperature[nodestoflag2]=1
    321447
    322448                #Results fields
    323449                if md1.results:
    324450                        md2.results=results()
    325                         for solutionfield,field in list(md1.results.__dict__.items()):
     451                        for solutionfield,field in md1.results.__dict__.items():
    326452                                if   isinstance(field,list):
    327453                                        setattr(md2.results,solutionfield,[])
     
    332458                                                        fieldr=getattr(md2.results,solutionfield)[i]
    333459                                                        #get subfields
    334                                                         for solutionsubfield,subfield in list(fieldi.__dict__.items()):
    335                                                                 if   numpy.size(subfield)==numberofvertices1:
     460                                                        for solutionsubfield,subfield in fieldi.__dict__.items():
     461                                                                if   np.size(subfield)==numberofvertices1:
    336462                                                                        setattr(fieldr,solutionsubfield,subfield[pos_node])
    337                                                                 elif numpy.size(subfield)==numberofelements1:
     463                                                                elif np.size(subfield)==numberofelements1:
    338464                                                                        setattr(fieldr,solutionsubfield,subfield[pos_elem])
    339465                                                                else:
     
    346472                                                fieldr=getattr(md2.results,solutionfield)
    347473                                                #get subfields
    348                                                 for solutionsubfield,subfield in list(field.__dict__.items()):
    349                                                         if   numpy.size(subfield)==numberofvertices1:
     474                                                for solutionsubfield,subfield in field.__dict__.items():
     475                                                        if   np.size(subfield)==numberofvertices1:
    350476                                                                setattr(fieldr,solutionsubfield,subfield[pos_node])
    351                                                         elif numpy.size(subfield)==numberofelements1:
     477                                                        elif np.size(subfield)==numberofelements1:
    352478                                                                setattr(fieldr,solutionsubfield,subfield[pos_elem])
    353479                                                        else:
    354480                                                                setattr(fieldr,solutionsubfield,subfield)
    355481
     482                #OutputDefinitions fields
     483                if md1.outputdefinition.definitions:
     484                        for solutionfield,field in md1.outputdefinition.__dict__.items():
     485                                if isinstance(field,list):
     486                                        #get each definition
     487                                        for i,fieldi in enumerate(field):
     488                                                if fieldi:
     489                                                        fieldr=getattr(md2.outputdefinition,solutionfield)[i]
     490                                                        #get subfields
     491                                                        for solutionsubfield,subfield in fieldi.__dict__.items():
     492                                                                if   np.size(subfield)==numberofvertices1:
     493                                                                        setattr(fieldr,solutionsubfield,subfield[pos_node])
     494                                                                elif np.size(subfield)==numberofelements1:
     495                                                                        setattr(fieldr,solutionsubfield,subfield[pos_elem])
     496                                                                else:
     497                                                                        setattr(fieldr,solutionsubfield,subfield)
     498
    356499                #Keep track of pos_node and pos_elem
    357500                md2.mesh.extractedvertices=pos_node+1
    358501                md2.mesh.extractedelements=pos_elem+1
     502
    359503                return md2
    360504        # }}}
    361 
    362505        def extrude(md,*args):    # {{{
    363506                """
     
    369512                    - follow two polynomial laws, one for the lower part and one for the upper part of the mesh
    370513                    - be discribed by a list of coefficients (between 0 and 1)
    371  
     514
    372515
    373516                   Usage:
     
    402545                                raise TypeError("extrusionexponent must be >=0")
    403546                        numlayers=args[0]
    404                         extrusionlist=(numpy.arange(0.,float(numlayers-1)+1.,1.)/float(numlayers-1))**args[1]
     547                        extrusionlist=(np.arange(0.,float(numlayers-1)+1.,1.)/float(numlayers-1))**args[1]
    405548
    406549                elif len(args)==3:    #two polynomial laws
     
    412555                                raise TypeError("lower and upper extrusionexponents must be >=0")
    413556
    414                         lowerextrusionlist=(numpy.arange(0.,1.+2./float(numlayers-1),2./float(numlayers-1)))**lowerexp/2.
    415                         upperextrusionlist=(numpy.arange(0.,1.+2./float(numlayers-1),2./float(numlayers-1)))**upperexp/2.
    416                         extrusionlist=numpy.unique(numpy.concatenate((lowerextrusionlist,1.-upperextrusionlist)))
     557                        lowerextrusionlist=(np.arange(0.,1.+2./float(numlayers-1),2./float(numlayers-1)))**lowerexp/2.
     558                        upperextrusionlist=(np.arange(0.,1.+2./float(numlayers-1),2./float(numlayers-1)))**upperexp/2.
     559                        extrusionlist=np.unique(np.concatenate((lowerextrusionlist,1.-upperextrusionlist)))
    417560
    418561                if numlayers<2:
     
    429572                md.mesh.numberofelements            = mesh2d.numberofelements
    430573                md.mesh.numberofvertices            = mesh2d.numberofvertices
    431                
     574
    432575                md.mesh.lat                         = mesh2d.lat
    433576                md.mesh.long                        = mesh2d.long
    434577                md.mesh.epsg                        = mesh2d.epsg
    435                
     578                md.mesh.scale_factor                = mesh2d.scale_factor
     579
    436580                md.mesh.vertexonboundary            = mesh2d.vertexonboundary
    437581                md.mesh.vertexconnectivity          = mesh2d.vertexconnectivity
    438582                md.mesh.elementconnectivity         = mesh2d.elementconnectivity
    439583                md.mesh.average_vertex_connectivity = mesh2d.average_vertex_connectivity
    440                
     584
    441585                md.mesh.extractedvertices           = mesh2d.extractedvertices
    442586                md.mesh.extractedelements           = mesh2d.extractedelements
    443                
    444                 x3d=numpy.empty((0))
    445                 y3d=numpy.empty((0))
    446                 z3d=numpy.empty((0))    #the lower node is on the bed
     587
     588                x3d=np.empty((0))
     589                y3d=np.empty((0))
     590                z3d=np.empty((0))    #the lower node is on the bed
    447591                thickness3d=md.geometry.thickness    #thickness and bed for these nodes
    448592                bed3d=md.geometry.base
     
    450594                #Create the new layers
    451595                for i in range(numlayers):
    452                         x3d=numpy.concatenate((x3d,md.mesh.x))
    453                         y3d=numpy.concatenate((y3d,md.mesh.y))
     596                        x3d=np.concatenate((x3d,md.mesh.x))
     597                        y3d=np.concatenate((y3d,md.mesh.y))
    454598                        #nodes are distributed between bed and surface accordingly to the given exponent
    455                         z3d=numpy.concatenate((z3d,(bed3d+thickness3d*extrusionlist[i]).reshape(-1)))
    456                 number_nodes3d=numpy.size(x3d)    #number of 3d nodes for the non extruded part of the mesh
    457 
    458                 #Extrude elements 
    459                 elements3d=numpy.empty((0,6),int)
     599                        z3d=np.concatenate((z3d,(bed3d+thickness3d*extrusionlist[i]).reshape(-1)))
     600                number_nodes3d=np.size(x3d)    #number of 3d nodes for the non extruded part of the mesh
     601
     602                #Extrude elements
     603                elements3d=np.empty((0,6),int)
    460604                for i in range(numlayers-1):
    461                         elements3d=numpy.vstack((elements3d,numpy.hstack((md.mesh.elements+i*md.mesh.numberofvertices,md.mesh.elements+(i+1)*md.mesh.numberofvertices))))    #Create the elements of the 3d mesh for the non extruded part
    462                 number_el3d=numpy.size(elements3d,axis=0)    #number of 3d nodes for the non extruded part of the mesh
     605                        elements3d=np.vstack((elements3d,np.hstack((md.mesh.elements+i*md.mesh.numberofvertices,md.mesh.elements+(i+1)*md.mesh.numberofvertices))))    #Create the elements of the 3d mesh for the non extruded part
     606                number_el3d=np.size(elements3d,axis=0)    #number of 3d nodes for the non extruded part of the mesh
    463607
    464608                #Keep a trace of lower and upper nodes
    465                 lowervertex=-1*numpy.ones(number_nodes3d,int)
    466                 uppervertex=-1*numpy.ones(number_nodes3d,int)
    467                 lowervertex[md.mesh.numberofvertices:]=numpy.arange(1,(numlayers-1)*md.mesh.numberofvertices+1)
    468                 uppervertex[:(numlayers-1)*md.mesh.numberofvertices]=numpy.arange(md.mesh.numberofvertices+1,number_nodes3d+1)
     609                lowervertex=np.nan*np.ones(number_nodes3d,int)
     610                uppervertex=np.nan*np.ones(number_nodes3d,int)
     611                lowervertex[md.mesh.numberofvertices:]=np.arange(1,(numlayers-1)*md.mesh.numberofvertices+1)
     612                uppervertex[:(numlayers-1)*md.mesh.numberofvertices]=np.arange(md.mesh.numberofvertices+1,number_nodes3d+1)
    469613                md.mesh.lowervertex=lowervertex
    470614                md.mesh.uppervertex=uppervertex
    471615
    472616                #same for lower and upper elements
    473                 lowerelements=-1*numpy.ones(number_el3d,int)
    474                 upperelements=-1*numpy.ones(number_el3d,int)
    475                 lowerelements[md.mesh.numberofelements:]=numpy.arange(1,(numlayers-2)*md.mesh.numberofelements+1)
    476                 upperelements[:(numlayers-2)*md.mesh.numberofelements]=numpy.arange(md.mesh.numberofelements+1,(numlayers-1)*md.mesh.numberofelements+1)
     617                lowerelements=np.nan*np.ones(number_el3d,int)
     618                upperelements=np.nan*np.ones(number_el3d,int)
     619                lowerelements[md.mesh.numberofelements:]=np.arange(1,(numlayers-2)*md.mesh.numberofelements+1)
     620                upperelements[:(numlayers-2)*md.mesh.numberofelements]=np.arange(md.mesh.numberofelements+1,(numlayers-1)*md.mesh.numberofelements+1)
    477621                md.mesh.lowerelements=lowerelements
    478622                md.mesh.upperelements=upperelements
    479623
    480                 #Save old mesh 
     624                #Save old mesh
    481625                md.mesh.x2d=md.mesh.x
    482626                md.mesh.y2d=md.mesh.y
     
    485629                md.mesh.numberofvertices2d=md.mesh.numberofvertices
    486630
    487                 #Build global 3d mesh 
     631                #Build global 3d mesh
    488632                md.mesh.elements=elements3d
    489633                md.mesh.x=x3d
     
    497641
    498642                #bedinfo and surface info
    499                 md.mesh.vertexonbase=project3d(md,'vector',numpy.ones(md.mesh.numberofvertices2d,bool),'type','node','layer',1)
    500                 md.mesh.vertexonsurface=project3d(md,'vector',numpy.ones(md.mesh.numberofvertices2d,bool),'type','node','layer',md.mesh.numberoflayers)
     643                md.mesh.vertexonbase=project3d(md,'vector',np.ones(md.mesh.numberofvertices2d,bool),'type','node','layer',1)
     644                md.mesh.vertexonsurface=project3d(md,'vector',np.ones(md.mesh.numberofvertices2d,bool),'type','node','layer',md.mesh.numberoflayers)
    501645                md.mesh.vertexonboundary=project3d(md,'vector',md.mesh.vertexonboundary,'type','node')
    502646
     
    504648                md.mesh.lat=project3d(md,'vector',md.mesh.lat,'type','node')
    505649                md.mesh.long=project3d(md,'vector',md.mesh.long,'type','node')
     650                md.mesh.scale_factor=project3d(md,'vector',md.mesh.scale_factor,'type','node')
    506651
    507652                md.geometry.extrude(md)
     
    518663                # Calving variables
    519664                md.hydrology.extrude(md)
     665                md.levelset.extrude(md)
    520666                md.calving.extrude(md)
     667                md.frontalforcings.extrude(md)
    521668
    522669                #connectivity
    523                 md.mesh.elementconnectivity=numpy.tile(md.mesh.elementconnectivity,(numlayers-1,1))
    524                 md.mesh.elementconnectivity[numpy.nonzero(md.mesh.elementconnectivity==0)]=-sys.maxsize-1
    525                 if not numpy.isnan(md.mesh.elementconnectivity).all():
     670                md.mesh.elementconnectivity=np.tile(md.mesh.elementconnectivity,(numlayers-1,1))
     671                md.mesh.elementconnectivity[np.nonzero(md.mesh.elementconnectivity==0)]=-sys.maxsize-1
     672                if not np.isnan(md.mesh.elementconnectivity).all():
    526673                        for i in range(1,numlayers-1):
    527674                                md.mesh.elementconnectivity[i*md.mesh.numberofelements2d:(i+1)*md.mesh.numberofelements2d,:] \
    528                                         =md.mesh.elementconnectivity[i*md.mesh.numberofelements2d:(i+1)*md.mesh.numberofelements2d,:]+md.mesh.numberofelements2d
    529                                 md.mesh.elementconnectivity[numpy.nonzero(md.mesh.elementconnectivity<0)]=0
     675                                                =md.mesh.elementconnectivity[i*md.mesh.numberofelements2d:(i+1)*md.mesh.numberofelements2d,:]+md.mesh.numberofelements2d
     676                                md.mesh.elementconnectivity[np.nonzero(md.mesh.elementconnectivity<0)]=0
    530677
    531678                md.materials.extrude(md)
    532                 md.damage.extrude(md)
     679                if md.damage.isdamage==1:
     680                        md.damage.extrude(md)
    533681                md.gia.extrude(md)
    534682                md.mask.extrude(md)
    535683                md.qmu.extrude(md)
    536684                md.basalforcings.extrude(md)
     685                md.outputdefinition.extrude(md)
    537686
    538687                #increase connectivity if less than 25:
     
    541690
    542691                return md
    543         # }}}
     692                # }}}
    544693        def collapse(md): #{{{
    545694                '''
    546695                collapses a 3d mesh into a 2d mesh
    547                        
     696
    548697                This routine collapses a 3d model into a 2d model and collapses all
    549698                the fileds of the 3d model by taking their depth-averaged values
    550                        
     699
    551700                Usage:
    552701                        md=collapse(md)
    553                 '''     
     702                '''
    554703
    555704                #Check that the model is really a 3d model
    556705                if md.mesh.domaintype().lower() != '3d':
    557706                        raise Exception("only a 3D model can be collapsed")
    558                
     707
     708                #dealing with the friction law
    559709                #drag is limited to nodes that are on the bedrock.
    560                 md.friction.coefficient=project2d(md,md.friction.coefficient,1)
     710                if hasattr(md.friction,'coefficient'):
     711                        md.friction.coefficient=project2d(md,md.friction.coefficient,1)
    561712
    562713                #p and q (same deal, except for element that are on the bedrock: )
    563                 md.friction.p=project2d(md,md.friction.p,1)
    564                 md.friction.q=project2d(md,md.friction.q,1)
     714                if hasattr(md.friction,'p'):
     715                        md.friction.p=project2d(md,md.friction.p,1)
     716                if hasattr(md.friction,'q'):
     717                        md.friction.q=project2d(md,md.friction.q,1)
     718
     719                if hasattr(md.friction,'coefficientcoulomb'):
     720                        md.friction.coefficientcoulomb=project2d(md,md.friction.coefficientcoulomb,1)
     721                if hasattr(md.friction,'C'):
     722                        md.friction.C=project2d(md,md.friction.C,1)
     723                if hasattr(md.friction,'As'):
     724                        md.friction.As=project2d(md,md.friction.As,1)
     725                if hasattr(md.friction,'effective_pressure') and not np.isnan(md.friction.effective_pressure).all():
     726                        md.friction.effective_pressure=project2d(md,md.friction.effective_pressure,1)
     727                if hasattr(md.friction,'water_layer'):
     728                        md.friction.water_layer=project2d(md,md.friction.water_layer,1)
     729                if hasattr(md.friction,'m'):
     730                        md.friction.m=project2d(md,md.friction.m,1)
    565731
    566732                #observations
    567                 if not numpy.isnan(md.inversion.vx_obs).all(): md.inversion.vx_obs=project2d(md,md.inversion.vx_obs,md.mesh.numberoflayers)
    568                 if not numpy.isnan(md.inversion.vy_obs).all(): md.inversion.vy_obs=project2d(md,md.inversion.vy_obs,md.mesh.numberoflayers)
    569                 if not numpy.isnan(md.inversion.vel_obs).all(): md.inversion.vel_obs=project2d(md,md.inversion.vel_obs,md.mesh.numberoflayers)
    570                 if not numpy.isnan(md.inversion.cost_functions_coefficients).all(): md.inversion.cost_functions_coefficients=project2d(md,md.inversion.cost_functions_coefficients,md.mesh.numberoflayers)
    571                 if isinstance(md.inversion.min_parameters,numpy.ndarray):
    572                         if md.inversion.min_parameters.size>1: md.inversion.min_parameters=project2d(md,md.inversion.min_parameters,md.mesh.numberoflayers)
    573                         if isinstance(md.inversion.max_parameters,numpy.ndarray):
    574                                 if md.inversion.max_parameters.size>1: md.inversion.max_parameters=project2d(md,md.inversion.max_parameters,md.mesh.numberoflayers)
    575                                 if not numpy.isnan(md.smb.mass_balance).all():
    576                                         md.smb.mass_balance=project2d(md,md.smb.mass_balance,md.mesh.numberoflayers)
    577                                        
    578                 if not numpy.isnan(md.balancethickness.thickening_rate).all(): md.balancethickness.thickening_rate=project2d(md,md.balancethickness.thickening_rate,md.mesh.numberoflayers)
     733                if not np.isnan(md.inversion.vx_obs).all():
     734                        md.inversion.vx_obs=project2d(md,md.inversion.vx_obs,md.mesh.numberoflayers)
     735                if not np.isnan(md.inversion.vy_obs).all():
     736                        md.inversion.vy_obs=project2d(md,md.inversion.vy_obs,md.mesh.numberoflayers)
     737                if not np.isnan(md.inversion.vel_obs).all():
     738                        md.inversion.vel_obs=project2d(md,md.inversion.vel_obs,md.mesh.numberoflayers)
     739                if not np.isnan(md.inversion.cost_functions_coefficients).all():
     740                        md.inversion.cost_functions_coefficients=project2d(md,md.inversion.cost_functions_coefficients,md.mesh.numberoflayers)
     741                if isinstance(md.inversion.min_parameters,np.ndarray):
     742                        if md.inversion.min_parameters.size>1:
     743                                md.inversion.min_parameters=project2d(md,md.inversion.min_parameters,md.mesh.numberoflayers)
     744                if isinstance(md.inversion.max_parameters,np.ndarray):
     745                        if md.inversion.max_parameters.size>1:
     746                                md.inversion.max_parameters=project2d(md,md.inversion.max_parameters,md.mesh.numberoflayers)
     747                if not np.isnan(md.smb.mass_balance).all():
     748                        md.smb.mass_balance=project2d(md,md.smb.mass_balance,md.mesh.numberoflayers)
    579749
    580750                #results
    581                 if not numpy.isnan(md.initialization.vx).all(): md.initialization.vx=DepthAverage(md,md.initialization.vx)
    582                 if not numpy.isnan(md.initialization.vy).all(): md.initialization.vy=DepthAverage(md,md.initialization.vy)
    583                 if not numpy.isnan(md.initialization.vz).all(): md.initialization.vz=DepthAverage(md,md.initialization.vz)
    584                 if not numpy.isnan(md.initialization.vel).all(): md.initialization.vel=DepthAverage(md,md.initialization.vel)
    585                 if not numpy.isnan(md.initialization.temperature).all(): md.initialization.temperature=DepthAverage(md,md.initialization.temperature)
    586                 if not numpy.isnan(md.initialization.pressure).all(): md.initialization.pressure=project2d(md,md.initialization.pressure,1)
    587                 if not numpy.isnan(md.initialization.sediment_head).all(): md.initialization.sediment_head=project2d(md,md.initialization.sediment_head,1)
    588                 if not numpy.isnan(md.initialization.epl_head).all(): md.initialization.epl_head=project2d(md,md.initialization.epl_head,1)
    589                 if not numpy.isnan(md.initialization.epl_thickness).all(): md.initialization.epl_thickness=project2d(md,md.initialization.epl_thickness,1)
    590 
    591                 #gia
    592                 if not numpy.isnan(md.gia.mantle_viscosity).all(): md.gia.mantle_viscosity=project2d(md,md.gia.mantle_viscosity,1)
    593                 if not numpy.isnan(md.gia.lithosphere_thickness).all(): md.gia.lithosphere_thickness=project2d(md,md.gia.lithosphere_thickness,1)
     751                if not np.isnan(md.initialization.vx).all():
     752                        md.initialization.vx=DepthAverage(md,md.initialization.vx)
     753                if not np.isnan(md.initialization.vy).all():
     754                        md.initialization.vy=DepthAverage(md,md.initialization.vy)
     755                if not np.isnan(md.initialization.vz).all():
     756                        md.initialization.vz=DepthAverage(md,md.initialization.vz)
     757                if not np.isnan(md.initialization.vel).all():
     758                        md.initialization.vel=DepthAverage(md,md.initialization.vel)
     759                if not np.isnan(md.initialization.temperature).all():
     760                        md.initialization.temperature=DepthAverage(md,md.initialization.temperature)
     761                if not np.isnan(md.initialization.pressure).all():
     762                        md.initialization.pressure=project2d(md,md.initialization.pressure,1)
     763                if not np.isnan(md.initialization.sediment_head).all():
     764                        md.initialization.sediment_head=project2d(md,md.initialization.sediment_head,1)
     765                if not np.isnan(md.initialization.epl_head).all():
     766                        md.initialization.epl_head=project2d(md,md.initialization.epl_head,1)
     767                if not np.isnan(md.initialization.epl_thickness).all():
     768                        md.initialization.epl_thickness=project2d(md,md.initialization.epl_thickness,1)
     769
     770                #giaivins
     771                if not np.isnan(md.gia.mantle_viscosity).all():
     772                        md.gia.mantle_viscosity=project2d(md,md.gia.mantle_viscosity,1)
     773                if not np.isnan(md.gia.lithosphere_thickness).all():
     774                        md.gia.lithosphere_thickness=project2d(md,md.gia.lithosphere_thickness,1)
    594775
    595776                #elementstype
    596                 if not numpy.isnan(md.flowequation.element_equation).all():
     777                if not np.isnan(md.flowequation.element_equation).all():
    597778                        md.flowequation.element_equation=project2d(md,md.flowequation.element_equation,1)
    598779                        md.flowequation.vertex_equation=project2d(md,md.flowequation.vertex_equation,1)
     
    602783
    603784                # Hydrologydc variables
    604                 if hasattr(md.hydrology,'hydrologydc'):
     785                if type(md.hydrology) is 'hydrologydc':
    605786                        md.hydrology.spcsediment_head=project2d(md,md.hydrology.spcsediment_head,1)
    606                         md.hydrology.mask_eplactive_node=project2d(md,md.hydrology.mask_eplactive_node,1)
    607787                        md.hydrology.sediment_transmitivity=project2d(md,md.hydrology.sediment_transmitivity,1)
    608788                        md.hydrology.basal_moulin_input=project2d(md,md.hydrology.basal_moulin_input,1)
     789                        md.hydrology.mask_thawed_node=project2d(md,md.hydrology.mask_thawed_node,1)
    609790                        if md.hydrology.isefficientlayer == 1:
     791                                md.hydrology.mask_eplactive_node=project2d(md,md.hydrology.mask_eplactive_node,1)
    610792                                md.hydrology.spcepl_head=project2d(md,md.hydrology.spcepl_head,1)
    611793
     
    617799                md.stressbalance.loadingforce=project2d(md,md.stressbalance.loadingforce,md.mesh.numberoflayers)
    618800                md.masstransport.spcthickness=project2d(md,md.masstransport.spcthickness,md.mesh.numberoflayers)
    619                 if not numpy.isnan(md.damage.spcdamage).all(): md.damage.spcdamage=project2d(md,md.damage.spcdamage,md.mesh.numberoflayers-1)
    620801                md.thermal.spctemperature=project2d(md,md.thermal.spctemperature,md.mesh.numberoflayers-1)
     802                if not np.isnan(md.damage.spcdamage).all():
     803                        md.damage.spcdamage=project2d(md,md.damage.spcdamage,md.mesh.numberoflayers-1)
    621804
    622805                #materials
    623806                md.materials.rheology_B=DepthAverage(md,md.materials.rheology_B)
    624807                md.materials.rheology_n=project2d(md,md.materials.rheology_n,1)
    625                
    626                 #damage: 
     808
     809                #damage:
    627810                if md.damage.isdamage:
    628811                        md.damage.D=DepthAverage(md,md.damage.D)
    629812
    630813                #special for thermal modeling:
    631                 md.basalforcings.groundedice_melting_rate=project2d(md,md.basalforcings.groundedice_melting_rate,1) 
    632                 md.basalforcings.floatingice_melting_rate=project2d(md,md.basalforcings.floatingice_melting_rate,1) 
     814                md.basalforcings.groundedice_melting_rate=project2d(md,md.basalforcings.groundedice_melting_rate,1)
     815                md.basalforcings.floatingice_melting_rate=project2d(md,md.basalforcings.floatingice_melting_rate,1)
    633816                md.basalforcings.geothermalflux=project2d(md,md.basalforcings.geothermalflux,1) #bedrock only gets geothermal flux
    634817
     
    644827                md.geometry.thickness=project2d(md,md.geometry.thickness,1)
    645828                md.geometry.base=project2d(md,md.geometry.base,1)
    646                 if isinstance(md.geometry.bed,numpy.ndarray):
     829                if isinstance(md.geometry.bed,np.ndarray):
    647830                        md.geometry.bed=project2d(md,md.geometry.bed,1)
    648                         md.mask.groundedice_levelset=project2d(md,md.mask.groundedice_levelset,1)
    649                         md.mask.ice_levelset=project2d(md,md.mask.ice_levelset,1)
    650 
    651                 #lat long
    652                 if isinstance(md.mesh.lat,numpy.ndarray):
    653                         if md.mesh.lat.size==md.mesh.numberofvertices:  md.mesh.lat=project2d(md,md.mesh.lat,1)
    654                         if isinstance(md.mesh.long,numpy.ndarray):
    655                                 if md.mesh.long.size==md.mesh.numberofvertices: md.mesh.long=project2d(md,md.mesh.long,1)
     831                md.mask.groundedice_levelset=project2d(md,md.mask.groundedice_levelset,1)
     832                md.mask.ice_levelset=project2d(md,md.mask.ice_levelset,1)
     833
     834                #OutputDefinitions
     835                if md.outputdefinition.definitions:
     836                        for solutionfield,field in md.outputdefinition.__dict__.items():
     837                                if isinstance(field,list):
     838                                        #get each definition
     839                                        for i,fieldi in enumerate(field):
     840                                                if fieldi:
     841                                                        fieldr=getattr(md.outputdefinition,solutionfield)[i]
     842                                                        #get subfields
     843                                                        for solutionsubfield,subfield in fieldi.__dict__.items():
     844                                                                if   np.size(subfield)==md.mesh.numberofvertices:
     845                                                                        setattr(fieldr,solutionsubfield,project2d(md,subfield,1))
     846                                                                elif np.size(subfield)==md.mesh.numberofelements:
     847                                                                        setattr(fieldr,solutionsubfield,project2d(md,subfield,1))
     848
    656849
    657850                #Initialize with the 2d mesh
     
    662855                mesh.numberofelements=md.mesh.numberofelements2d
    663856                mesh.elements=md.mesh.elements2d
    664                 if not numpy.isnan(md.mesh.vertexonboundary).all(): mesh.vertexonboundary=project2d(md,md.mesh.vertexonboundary,1)
    665                 if not numpy.isnan(md.mesh.elementconnectivity).all(): mesh.elementconnectivity=project2d(md,md.mesh.elementconnectivity,1)
     857                if not np.isnan(md.mesh.vertexonboundary).all():
     858                        mesh.vertexonboundary=project2d(md,md.mesh.vertexonboundary,1)
     859                if not np.isnan(md.mesh.elementconnectivity).all():
     860                        mesh.elementconnectivity=project2d(md,md.mesh.elementconnectivity,1)
     861                if isinstance(md.mesh.lat,np.ndarray):
     862                        if md.mesh.lat.size==md.mesh.numberofvertices:
     863                                mesh.lat=project2d(md,md.mesh.lat,1)
     864                if isinstance(md.mesh.long,np.ndarray):
     865                        if md.mesh.long.size==md.mesh.numberofvertices:
     866                                md.mesh.long=project2d(md,md.mesh.long,1)
     867                mesh.epsg=md.mesh.epsg
     868                if isinstance(md.mesh.scale_factor,np.ndarray):
     869                        if md.mesh.scale_factor.size==md.mesh.numberofvertices:
     870                                md.mesh.scale_factor=project2d(md,md.mesh.scale_factor,1)
    666871                md.mesh=mesh
     872                md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices)[0]
     873                md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity)[0]
     874                md.mesh.segments=contourenvelope(md)
    667875
    668876                return md
  • issm/trunk-jpl/src/py3/classes/organizer.py

    r19895 r23670  
    66from savevars import savevars
    77from model import model
    8 from dbm.ndbm import whichdb
     8from dbm import whichdb
    99import MatlabFuncs as m
    1010
     
    2626        """
    2727
    28         def __init__(self,**kwargs):    # {{{
     28        def __init__(self,*args):    # {{{
    2929                self._currentstep  =0
    3030                self.repository    ='./'
     
    3535
    3636                #process options
    37                 options=pairoptions.pairoptions(**kwargs)
     37                options=pairoptions.pairoptions(*args)
    3838
    3939                #Get prefix
     
    8686                if os.path.exists(path):
    8787                        struc=loadvars(path)
    88                         name=name=[key for key in list(struc.keys())]
     88                        name=name=[key for key in struc.keys()]
    8989                        md=struc.name[0]
    9090                else:
     
    9898                if not isinstance(string,str):
    9999                        raise TypeError("argument provided is not a string")
    100                 path1=os.path.join(self.repository,self.prefix+'.step#'+string+'.python')
     100                path1=os.path.join(self.repository,self.prefix+string+'.python')
    101101                path2=os.path.join(self.repository,string)
    102102
     
    115115                                raise IOError("Could find neither '%s' nor '%s'" % (path,path2))
    116116                        else:
    117                                 print(("--> Branching '%s' from trunk '%s'" % (self.prefix,self.trunkprefix)))
     117                                print("--> Branching '%s' from trunk '%s'" % (self.prefix,self.trunkprefix))
    118118                                md=loadmodel(path2)
    119119                                return md
     
    142142                if 0 in self.requestedsteps:
    143143                        if self._currentstep==1:
    144                                 print(("   prefix: %s" % self.prefix))
    145                         print(("   step #%i : %s" % (self.steps[self._currentstep-1]['id'],self.steps[self._currentstep-1]['string'])))
     144                                print("   prefix: %s" % self.prefix)
     145                        print("   step #%i : %s" % (self.steps[self._currentstep-1]['id'],self.steps[self._currentstep-1]['string']))
    146146
    147147                #Ok, now if _currentstep is a member of steps, return true
    148148                if self._currentstep in self.requestedsteps:
    149                         print(("\n   step #%i : %s\n" % (self.steps[self._currentstep-1]['id'],self.steps[self._currentstep-1]['string'])))
     149                        print("\n   step #%i : %s\n" % (self.steps[self._currentstep-1]['id'],self.steps[self._currentstep-1]['string']))
    150150                        bool=True
    151151
     
    164164
    165165                if (name=='default'):
    166                         name=os.path.join(self.repository,self.prefix+'step#'+self.steps[self._currentstep-1]['string']+'.python')
    167                 else:
    168                     name=os.path.join(self.repository,name)
    169                 print(("saving model as: '%s'" % name))
     166                        name=os.path.join(self.repository,self.prefix+self.steps[self._currentstep-1]['string']+'.python')
     167                else:
     168                        name=os.path.join(self.repository,name)
     169                print("saving model as: '%s'" % name)
    170170
    171171                #check that md is a model
  • issm/trunk-jpl/src/py3/classes/outputdefinition.py

    r21255 r23670  
    11from fielddisplay import fielddisplay
    2 from EnumDefinitions import *
    3 from StringToEnum import StringToEnum
    42from checkfield import checkfield
    53from WriteData import WriteData
    6 import numpy as np
     4import numpy as  np
    75
    86class outputdefinition(object):
     
    2422                return string
    2523                #}}}
     24        def extrude(self,md): # {{{
     25                for definition in self.definitions:
     26                        definition.extrude(md);
     27
     28                return self
     29         #}}}
    2630        def setdefaultparameters(self): # {{{
    2731                return self
     
    3438
    3539        # }}}
    36         def marshall(self,md,fid):    # {{{
    37                
    38                 enums=np.zeros(len(self.definitions),)
    39                
     40        def marshall(self,prefix,md,fid):    # {{{
     41                data=[];
    4042                for i in range(len(self.definitions)):
    41                         self.definitions[i].marshall(md,fid);
    42                         classdefinition=self.definitions[i].__class__.__name__
     43                        self.definitions[i].marshall(prefix,md,fid);
     44                        classdefinition=self.definitions[i].__class__.__name__;
    4345                        classdefinition=classdefinition[0].upper()+classdefinition[1:]
    44                         enums[i]=StringToEnum(classdefinition)[0]
    45                
    46                 enums=np.unique(enums);
    47                
    48                 WriteData(fid,'data',enums,'enum',OutputdefinitionListEnum(),'format','DoubleMat','mattype',1);
     46                        data.append(classdefinition)
     47
     48                data=np.unique(data);
     49                WriteData(fid,prefix,'data',data,'name','md.outputdefinition.list','format','StringArray');
    4950        # }}}
  • issm/trunk-jpl/src/py3/classes/pairoptions.py

    r19895 r23670  
    1111        """
    1212
    13         def __init__(self,**kwargs): # {{{
     13        def __init__(self,*arg): # {{{
    1414                self.functionname = ''
    1515                self.list         = OrderedDict()
     
    2121
    2222                #initialize list
    23                 if not len(kwargs):
     23                if not len(arg):
    2424                        pass    #Do nothing,
    2525                else:
    26                         self.buildlist(**kwargs)
     26                        self.buildlist(*arg)
    2727        # }}}
    2828        def __repr__(self):    # {{{
     
    3030                if self.list:
    3131                        s+="   list: (%ix%i)\n\n" % (len(self.list),2)
    32                         for item in list(self.list.items()):
     32                        for item in self.list.items():
    3333                                if   isinstance(item[1],str):
    3434                                        s+="     field: %-10s value: '%s'\n" % (item[0],item[1])
     
    4141                return s
    4242        # }}}
    43         def buildlist(self,**kwargs):    # {{{
     43        def buildlist(self,*arg):    # {{{
    4444                """BUILDLIST - build list of objects from input"""
    45                 # #check length of input
    46                 # if len(arg) % 2:
    47                 #       raise TypeError('Invalid parameter/value pair arguments')
    48                 # numoptions = len(arg)/2
    4945
    50                 # #go through arg and build list of objects
    51                 # for i in xrange(numoptions):
    52                 #       if isinstance(arg[2*i],(str,unicode)):
    53                 #               self.list[arg[2*i]] = arg[2*i+1];
    54                 #       else:
    55                 #               #option is not a string, ignore it
    56                 #               print "WARNING: option number %d is not a string and will be ignored." % (i+1)
     46                #check length of input
     47                if len(arg) % 2:
     48                        raise TypeError('Invalid parameter/value pair arguments')
     49                numoptions = len(arg)/2
    5750
    5851                #go through arg and build list of objects
    59                 print(kwargs)
    60                 for name,value in kwargs.items():
    61                         self.list[name] = value
    62                 # }}}
     52                for i in range(numoptions):
     53                        if isinstance(arg[2*i],str):
     54                                self.list[arg[2*i]] = arg[2*i+1];
     55                        else:
     56                                #option is not a string, ignore it
     57                                print("WARNING: option number %d is not a string and will be ignored." % (i+1))
     58        # }}}
    6359        def addfield(self,field,value):    # {{{
    6460                """ADDFIELD - add a field to an options list"""
    6561                if isinstance(field,str):
    6662                        if field in self.list:
    67                                 print(("WARNING: field '%s' with value=%s exists and will be overwritten with value=%s." % (field,str(self.list[field]),str(value))))
     63                                print("WARNING: field '%s' with value=%s exists and will be overwritten with value=%s." % (field,str(self.list[field]),str(value)))
    6864                        self.list[field] = value
    6965        # }}}
     
    7672        def AssignObjectFields(self,obj2):    # {{{
    7773                """ASSIGNOBJECTFIELDS - assign object fields from options"""
    78                 for item in list(self.list.items()):
     74                for item in self.list.items():
    7975                        if item[0] in dir(obj2):
    8076                                setattr(obj2,item[0],item[1])
    8177                        else:
    82                                 print(("WARNING: field '%s' is not a property of '%s'." % (item[0],type(obj2))))
     78                                print("WARNING: field '%s' is not a property of '%s'." % (item[0],type(obj2)))
    8379                return obj2
    8480        # }}}
     
    154150                        #warn user if requested
    155151                        if warn:
    156                                 print(("removefield info: option '%s' has been removed from the list of options." % field))
     152                                print("removefield info: option '%s' has been removed from the list of options." % field)
    157153        # }}}
    158154        def marshall(self,md,fid,firstindex):    # {{{
     
    162158                        value = item[1]
    163159
    164                         #Write option name
    165                         WriteData(fid,'enum',(firstindex-1)+2*i+1,'data',name,'format','String')
     160                        raise NameError('need to sync with MATLAB')
    166161
    167                         #Write option value
    168                         if   isinstance(value,str):
    169                                 WriteData(fid,'enum',(firstindex-1)+2*i+2,'data',value,'format','String')
    170                         elif isinstance(value,(bool,int,float)):
    171                                 WriteData(fid,'enum',(firstindex-1)+2*i+2,'data',value,'format','Double')
    172                         else:
    173                                 raise TypeError("Cannot marshall option '%s': format not supported yet." % name)
     162                        ##Write option name
     163                        #WriteData(fid,prefix,'enum',(firstindex-1)+2*i+1,'data',name,'format','String')
     164
     165                        ##Write option value
     166                        #if   isinstance(value,(str,unicode)):
     167                        #       WriteData(fid,prefix,'enum',(firstindex-1)+2*i+2,'data',value,'format','String')
     168                        #elif isinstance(value,(bool,int,long,float)):
     169                        #       WriteData(fid,prefix,'enum',(firstindex-1)+2*i+2,'data',value,'format','Double')
     170                        #else:
     171                                #raise TypeError("Cannot marshall option '%s': format not supported yet." % name)
    174172        # }}}
  • issm/trunk-jpl/src/py3/classes/plotoptions.py

    r19895 r23670  
    77
    88                Usage:
    9                         plotoptions=plotoptions(**kwargs)
     9                        plotoptions=plotoptions(*arg)
    1010        '''
    1111
    12         def __init__(self,**kwargs):# {{{
     12        def __init__(self,*arg):# {{{
    1313                self.numberofplots = 0
    1414                self.figurenumber  = 1
    1515                self.list          = OrderedDict()
    1616
    17                 self.buildlist(**kwargs)
     17                self.buildlist(*arg)
    1818                #}}}
    1919        def __repr__(self): #{{{
     
    2323                if self.list:
    2424                        s+="    list: (%ix%i)\n" % (len(self.list),2)
    25                         for item in list(self.list.items()):
     25                        for item in self.list.items():
    2626                                #s+="   options of plot number %i\n" % item
    2727                                if   isinstance(item[1],str):
     
    3535                return s
    3636        #}}}
    37         def buildlist(self,**kwargs): #{{{
     37        def buildlist(self,*arg): #{{{
     38                #check length of input
     39                if len(arg) % 2:
     40                        raise TypeError('Invalid parameter/value pair arguments')
    3841
    39                 for name,value in kwargs.items():
    40                         self.rawlist[name] = value
     42                #go through args and build list (like pairoptions)
     43                rawoptions=pairoptions.pairoptions(*arg)
     44                numoptions=len(arg)/2
     45                rawlist=[] # cannot be a dict since they do not support duplicate keys
    4146
    42                 #get figure number
     47                for i in range(numoptions):
     48                        if isinstance(arg[2*i],str):
     49                                rawlist.append([arg[2*i],arg[2*i+1]])
     50                        else:
     51                                #option is not a string, ignore it
     52                                print("WARNING: option number %d is not a string and will be ignored." % (i+1))
     53
     54                #get figure number
    4355                self.figurenumber=rawoptions.getfieldvalue('figure',1)
    4456                rawoptions.removefield('figure',0)
    4557
    46                 #get number of subplots 
    47                 numberofplots=Counter(x for sublist in rawlist for x in sublist if isinstance(x,str))['data']
     58                #get number of subplots
     59                numberofplots=len([1 for sublist in rawlist for x in sublist if str(x)=='data'])
    4860                self.numberofplots=numberofplots
    4961
     
    6476                        #if alloptions flag is on, apply to all plots
    6577                        if (allflag and 'data' not in rawlist[i][0] and '#' not in rawlist[i][0]):
    66                                
     78
    6779                                for j in range(numberofplots):
    6880                                        self.list[j].addfield(rawlist[i][0],rawlist[i][1])
     
    94106                                                        raise ValueError('error: in option i-j both i and j must be integers')
    95107                                                for j in range(int(nums[0])-1,int(nums[1])):
    96                                                         self.list[j].addfield(field,rawlist[i][1])     
     108                                                        self.list[j].addfield(field,rawlist[i][1])
    97109
    98110                                        # Deal with #i
     
    103115                                                self.list[int(plotnum)-1].addfield(field,rawlist[i][1])
    104116                        else:
    105                                
     117
    106118                                #go through all subplots and assign key-value pairs
    107119                                j=0
     
    113125                                                j=j+1
    114126                                if j+1>numberofplots:
    115                                         print(("WARNING: too many instances of '%s' in options" % rawlist[i][0]))
     127                                        print("WARNING: too many instances of '%s' in options" % rawlist[i][0])
    116128        #}}}
  • issm/trunk-jpl/src/py3/classes/private.py

    r19895 r23670  
    11from collections import OrderedDict
    22from fielddisplay import fielddisplay
    3 from EnumDefinitions import *
    43from checkfield import checkfield
    54
     
    2019                #set defaults
    2120                self.setdefaultparameters()
     21
    2222                #}}}
    2323        def __repr__(self): # {{{
  • issm/trunk-jpl/src/py3/classes/qmu.py

    r19895 r23670  
    1 import numpy
     1import numpy as np
     2from MatlabFuncs import *
     3from IssmConfig import *
    24from project3d import project3d
    35from collections import OrderedDict
    46from fielddisplay import fielddisplay
    5 from EnumDefinitions import *
    67from checkfield import checkfield
    78from WriteData import WriteData
    8 import MatlabFuncs as m
     9from helpers import *
     10from dakota_method import *
    911
    1012class qmu(object):
     
    1820        def __init__(self): # {{{
    1921                self.isdakota                    = 0
    20                 self.variables                   = OrderedDict()
    21                 self.responses                   = OrderedDict()
     22                self.variables                   = OrderedStruct()
     23                self.responses                   = OrderedStruct()
    2224                self.method                      = OrderedDict()
    23                 self.params                      = OrderedDict()
     25                self.params                      = OrderedStruct()
    2426                self.results                     = OrderedDict()
    2527                self.partition                   = float('NaN')
     
    4244
    4345                s+="%s\n" % fielddisplay(self,'isdakota','is qmu analysis activated?')
    44                 for i,variable in enumerate(self.variables.items()):
    45                         s+="         variables%s:  (arrays of each variable class)\n" % \
    46                                         string_dim(self.variables,i)
    47                         fnames=vars(variable)
    48                         maxlen=0
    49                         for fname in fnames:
    50                                 maxlen=max(maxlen,len(fname))
     46                maxlen = 0
     47                s+="         variables:  (arrays of each variable class)\n"
    5148
    52                         for fname in fnames:
    53                                 s+="'            %-*s:    [%ix%i]    '%s'\n" % \
    54                                                 (maxlen+1,fname,size(getattr(variable,fname)),type(getattr(variable,fname)))
     49                # OrderedStruct's iterator returns individual name/array-of-functions pairs
     50                for variable in self.variables:
     51                        fname=variable[0]
     52                        maxlen=max(maxlen,len(fname))
     53                        size = np.shape(variable[1])
     54                        a = size[0]
     55                        b = 1 if len(size) < 2 else size[1]
     56                        s+="            %-*s:    [%ix%i]    '%s'\n" %  (maxlen+1,fname,a,b,type(variable[1][0]))
    5557
    56                 for i,response in enumerate(self.responses.items()):
    57                         s+="         responses%s:  (arrays of each response class)\n" % \
    58                                         string_dim(self.responses,i)
    59                         fnames=vars(response)
    60                         maxlen=0
    61                         for fname in fnames:
    62                                 maxlen=max(maxlen,len(fname))
     58                s+="         responses:  (arrays of each response class)\n"
     59                for response in self.responses:
     60                        fname=response[0]
     61                        maxlen=max(maxlen,len(fname))
     62                        size = np.shape(response[1])
     63                        a = size[0]
     64                        b = 1 if len(size) < 2 else size[1]
     65                        s+="            %-*s:    [%ix%i]    '%s'\n" %  (maxlen+1,fname,a,b,type(response[1][0]))
    6366
    64                         for fname in fnames:
    65                                 s+="            %-*s:    [%ix%i]    '%s'\n" % \
    66                                                 (maxlen+1,fname,size(getattr(response,fname)),type(getattr(response,fname)))
     67                s+="%s\n" % fielddisplay(self,'numberofresponses','number of responses')
    6768
    68                 s+="%s\n" % fielddisplay(self,'numberofresponses','number of responses')
     69                if type(self.method) != OrderedDict:
     70                        self.method = [self.method]
     71                # self.method must be iterable
     72                for method in self.method:
     73                        if isinstance(method,dakota_method):
     74                                s+="            method :    '%s'\n" % (method.method)
    6975
    70                 for i,method in enumerate(self.method.items()):
    71                         if isinstance(method,'dakota_method'):
    72                                 s+="            method%s :    '%s'\n" % \
    73                                                 (string_dim(method,i),method.method)
    74 
    75                 for i,param in enumerate(self.params.items()):
    76                         s+="         params%s:  (array of method-independent parameters)\n" % \
    77                                         string_dim(self.params,i)
     76                # params could be have a number of forms (mainly 1 struct or many)
     77                if type(self.params) == OrderedStruct:
     78                        params = [self.params]
     79                else:
     80                        params = np.hstack(np.atleast_1d(np.array(self.params)))
     81                for param in params:
     82                        print(type(param))
     83                        print(param)
     84                        s+="         params:  (array of method-independent parameters)\n"
    7885                        fnames=vars(param)
    7986                        maxlen=0
     
    8289
    8390                        for fname in fnames:
    84                                 s+="            %-*s: %s\n" % \
    85                                                 (maxlen+1,fname,any2str(getattr(param,fname)))
     91                                s+="            %-*s: %s\n" %  (maxlen+1,fname,str(getattr(param,fname)))
    8692
    87                 for i,result in enumerate(self.results.items()):
    88                         s+="         results%s:  (information from dakota files)\n" % \
    89                                         string_dim(self.results,i)
     93                # results could be have a number of forms (mainly 1 struct or many)
     94                results = np.hstack(np.atleast_1d(np.array(self.results)))
     95                for result in results:
     96                        s+="         results:  (information from dakota files)\n"
    9097                        fnames=vars(result)
    9198                        maxlen=0
     
    94101
    95102                        for fname in fnames:
    96                                 s+="            %-*s:    [%ix%i]    '%s'\n" % \
    97                                                 (maxlen+1,fname,size(getattr(result,fname)),type(getattr(result,fname)))
     103                                size = np.shape(response[1])
     104                                a = size[0]
     105                                b = 0 if len(size) < 2 else size[1]
     106                                size = np.shape(getattr(result,fname))
     107                                s+="            %-*s:    [%ix%i]    '%s'\n" % (maxlen+1,fname,a,b,type(getattr(result,fname)))
    98108
    99109                s+="%s\n" % fielddisplay(self,'partition','user provided mesh partitioning, defaults to metis if not specified')
     
    111121        # }}}
    112122        def extrude(self,md): # {{{
    113                 self.partition=project3d(md,'vector',numpy.transpose(self.partition),'type','node')
     123                self.partition=project3d(md,'vector',np.transpose(self.partition),'type','node')
    114124                return self
    115125        #}}}
     
    123133                        return
    124134
    125                 if not md.qmu.params.evaluation_concurrency==1:
    126                         md.checkmessage("concurrency should be set to 1 when running dakota in library mode")
    127                 if md.qmu.partition:
    128                         if not numpy.size(md.qmu.partition)==md.mesh.numberofvertices:
    129                                 md.checkmessage("user supplied partition for qmu analysis should have size md.mesh.numberofvertices x 1")
    130                         if not min(md.qmu.partition)==0:
     135                version=IssmConfig('_DAKOTA_VERSION_')
     136                version=float(version[0])
     137
     138                if version < 6:
     139                        if not md.qmu.params.evaluation_concurrency==1:
     140                                md.checkmessage("concurrency should be set to 1 when running dakota in library mode")
     141                else:
     142                        if not strcmpi(self.params.evaluation_scheduling,'master'):
     143                                md.checkmessage('evaluation_scheduling in qmu.params should be set to "master"')
     144
     145                        if md.cluster.np <= 1:
     146                                md.checkmessage('in parallel library mode, Dakota needs to run on at least 2 cpus, 1 cpu for the master, 1 cpu for the slave. Modify md.cluser.np accordingly.')
     147                                       
     148                        if self.params.processors_per_evaluation < 1:
     149                                md.checkmessage('in parallel library mode, Dakota needs to run at least one slave on one cpu (md.qmu.params.processors_per_evaluation >=1)!')
     150                               
     151                        if np.mod(md.cluster.np-1,self.params.processors_per_evaluation):
     152                                md.checkmessage('in parallel library mode, the requirement is for md.cluster.np = md.qmu.params.processors_per_evaluation * number_of_slaves, where number_of_slaves will automatically be determined by Dakota. Modify md.cluster.np accordingly')
     153               
     154                if np.size(md.qmu.partition) > 0:
     155                        if np.size(md.qmu.partition)!=md.mesh.numberofvertices and np.size(md.qmu.partition) != md.mesh.numberofelements:
     156                                md.checkmessage("user supplied partition for qmu analysis should have size (md.mesh.numberofvertices x 1) or (md.mesh.numberofelements x 1)")
     157                        if not min(md.qmu.partition.flatten())==0:
    131158                                md.checkmessage("partition vector not indexed from 0 on")
    132                         if max(md.qmu.partition)>=md.qmu.numberofpartitions:
     159                        if max(md.qmu.partition.flatten())>=md.qmu.numberofpartitions:
    133160                                md.checkmessage("for qmu analysis, partitioning vector cannot go over npart, number of partition areas")
    134 
    135                 if not m.strcmpi(md.cluster.name,'none'):
    136                         if not md.settings.waitonlock:
    137                                 md.checkmessage("waitonlock should be activated when running qmu in parallel mode!")
    138161
    139162                return md
    140163        # }}}
    141         def marshall(self,md,fid):    # {{{
    142                 WriteData(fid,'object',self,'fieldname','isdakota','format','Boolean')
     164        def marshall(self,prefix,md,fid):    # {{{
     165                WriteData(fid,prefix,'object',self,'fieldname','isdakota','format','Boolean')
    143166                if not self.isdakota:
    144                         WriteData(fid,'data',False,'enum',QmuMassFluxSegmentsPresentEnum(),'format','Boolean');
     167                        WriteData(fid,prefix,'data',False,'name','md.qmu.mass_flux_segments_present','format','Boolean');
    145168                        return
    146                 WriteData(fid,'object',self,'fieldname','partition','format','DoubleMat','mattype',2)
    147                 WriteData(fid,'object',self,'fieldname','numberofpartitions','format','Integer')
    148                 WriteData(fid,'object',self,'fieldname','numberofresponses','format','Integer')
    149                 WriteData(fid,'object',self,'fieldname','variabledescriptors','format','StringArray')
    150                 WriteData(fid,'object',self,'fieldname','responsedescriptors','format','StringArray')
    151                 if not self.mass_flux_segments:
    152                         WriteData(fid,'data',self.mass_flux_segments,'enum',MassFluxSegmentsEnum(),'format','MatArray');
     169                WriteData(fid,prefix,'object',self,'fieldname','partition','format','DoubleMat','mattype',2)
     170                WriteData(fid,prefix,'object',self,'fieldname','numberofpartitions','format','Integer')
     171                WriteData(fid,prefix,'object',self,'fieldname','numberofresponses','format','Integer')
     172                WriteData(fid,prefix,'object',self,'fieldname','variabledescriptors','format','StringArray')
     173                WriteData(fid,prefix,'object',self,'fieldname','responsedescriptors','format','StringArray')
     174                if not isempty(self.mass_flux_segments):
     175                        WriteData(fid,prefix,'data',self.mass_flux_segments,'name','md.qmu.mass_flux_segments','format','MatArray');
    153176                        flag=True;
    154177                else:
    155178                        flag=False;
    156                 WriteData(fid,'data',flag,'enum',QmuMassFluxSegmentsPresentEnum(),'format','Boolean');
     179                WriteData(fid,prefix,'data',flag,'name','md.qmu.mass_flux_segments_present','format','Boolean');
    157180        # }}}
  • issm/trunk-jpl/src/py3/classes/results.py

    r19895 r23670  
    1 import numpy
     1import numpy as np
     2from pairoptions import pairoptions
    23from fielddisplay import fielddisplay
    34import MatlabFuncs as m
    4 from EnumDefinitions import *
    55
    66class results(object):
     
    1212        """
    1313
    14         def __init__(self):    # {{{
     14        def __init__(self,*args):    # {{{
    1515                pass
    1616        # }}}
     
    2525                        s+="%s\n" % fielddisplay(self,'SolutionType',"solution type")
    2626
    27                 for name in list(self.__dict__.keys()):
     27                for name in self.__dict__.keys():
    2828                        if name not in ['step','time','SolutionType','errlog','outlog']:
    2929                                if   isinstance(getattr(self,name),list):
     
    4848                return md
    4949        # }}}
    50         def marshall(self,md,fid):    # {{{
     50        def marshall(self,prefix,md,fid):    # {{{
    5151                pass
    5252        # }}}
  • issm/trunk-jpl/src/py3/classes/rifts.py

    r19895 r23670  
    1 import numpy
     1import numpy as np
    22from fielddisplay import fielddisplay
    3 from EnumDefinitions import *
    43from checkfield import checkfield
    54from WriteData import WriteData
     
    3433        #}}}
    3534        def checkconsistency(self,md,solution,analyses):    # {{{
    36                 if (not self.riftstruct) or numpy.any(isnans(self.riftstruct)):
     35                if (not self.riftstruct) or np.any(isnans(self.riftstruct)):
    3736                        numrifts=0
    3837                else:
     
    4443                        if not isinstance(self.riftstruct,list):
    4544                                md.checkmessage("rifts.riftstruct should be a structure!")
    46                         if numpy.any(md.mesh.segmentmarkers>=2):
     45                        if np.any(md.mesh.segmentmarkers>=2):
    4746                                #We have segments with rift markers, but no rift structure!
    4847                                md.checkmessage("model should be processed for rifts (run meshprocessrifts)!")
    4948                        for i,rift in enumerate(self.riftstruct):
    50                                 md = checkfield(md,'fieldname',"rifts.riftstruct[%d]['fill']" % i,'values',[WaterEnum(),AirEnum(),IceEnum(),MelangeEnum()])
     49                                md = checkfield(md,'fieldname',"rifts.riftstruct[%d]['fill']" % i,'values',['Water','Air','Ice','Melange',0,1,2,3])
    5150                else:
    52                         if self.riftstruct and numpy.any(numpy.logical_not(isnans(self.riftstruct))):
     51                        if self.riftstruct and np.any(np.logical_not(isnans(self.riftstruct))):
    5352                                md.checkmessage("riftstruct should be NaN since numrifts is 0!")
    5453
    5554                return md
    5655        # }}}
    57         def marshall(self,md,fid):    # {{{
     56        def marshall(self,prefix,md,fid):    # {{{
    5857
    5958                #Process rift info
    60                 if (not self.riftstruct) or numpy.any(isnans(self.riftstruct)):
     59                if (not self.riftstruct) or np.any(isnans(self.riftstruct)):
    6160                        numrifts=0
    6261                else:
     
    6564                numpairs=0
    6665                for rift in self.riftstruct:
    67                         numpairs+=numpy.size(rift['penaltypairs'],axis=0)
     66                        numpairs+=np.size(rift['penaltypairs'],axis=0)
     67
     68                # Convert strings in riftstruct to hard coded numbers
     69                FillDict={'Air':0,
     70                                                        'Ice':1,
     71                                                        'Melange':2,
     72                                                        'Water':3}
     73                for rift in self.riftstruct:
     74                        if rift['fill'] in ['Air','Ice','Melange','Water']:
     75                                rift['fill'] = FillDict[rift['fill']]
    6876
    6977                # 2 for nodes + 2 for elements+ 2 for  normals + 1 for length + 1 for fill + 1 for friction + 1 for fraction + 1 for fractionincrement + 1 for state.
    70                 data=numpy.zeros((numpairs,12))
     78                data=np.zeros((numpairs,12))
    7179                count=0
    7280                for rift in self.riftstruct:
    73                         numpairsforthisrift=numpy.size(rift['penaltypairs'],0)
     81                        numpairsforthisrift=np.size(rift['penaltypairs'],0)
    7482                        data[count:count+numpairsforthisrift,0:7]=rift['penaltypairs']
    7583                        data[count:count+numpairsforthisrift,7]=rift['fill']
     
    8088                        count+=numpairsforthisrift
    8189
    82                 WriteData(fid,'data',numrifts,'enum',RiftsNumriftsEnum(),'format','Integer')
    83                 WriteData(fid,'data',data,'enum',RiftsRiftstructEnum(),'format','DoubleMat','mattype',3)
     90                WriteData(fid,prefix,'data',numrifts,'name','md.rifts.numrifts','format','Integer')
     91                WriteData(fid,prefix,'data',data,'name','md.rifts.riftstruct','format','DoubleMat','mattype',3)
    8492        # }}}
  • issm/trunk-jpl/src/py3/classes/steadystate.py

    r19895 r23670  
    1 import numpy
     1import numpy as np
    22from fielddisplay import fielddisplay
    3 from EnumDefinitions import *
    43from checkfield import checkfield
    54from WriteData import WriteData
     
    4948
    5049                #Early return
    51                 if not solution==SteadystateSolutionEnum():
     50                if not solution=='SteadystateSolution':
    5251                        return md
    5352
     
    5554                        md.checkmessage("for a steadystate computation, timestepping.time_step must be zero.")
    5655
    57                 if numpy.isnan(md.stressbalance.reltol):
     56                if np.isnan(md.stressbalance.reltol):
    5857                        md.checkmessage("for a steadystate computation, stressbalance.reltol (relative convergence criterion) must be defined!")
    5958
     
    6261                return md
    6362        # }}}
    64         def marshall(self,md,fid):    # {{{
    65                 WriteData(fid,'object',self,'fieldname','reltol','format','Double')
    66                 WriteData(fid,'object',self,'fieldname','maxiter','format','Integer')
     63        def marshall(self,prefix,md,fid):    # {{{
     64                WriteData(fid,prefix,'object',self,'fieldname','reltol','format','Double')
     65                WriteData(fid,prefix,'object',self,'fieldname','maxiter','format','Integer')
    6766
    6867                #process requested outputs
     
    7271                        outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:]
    7372                        outputs    =outputscopy
    74                 WriteData(fid,'data',outputs,'enum',SteadystateRequestedOutputsEnum(),'format','StringArray')
     73                WriteData(fid,prefix,'data',outputs,'name','md.steadystate.requested_outputs','format','StringArray')
    7574        # }}}
  • issm/trunk-jpl/src/py3/classes/stressbalance.py

    r22576 r23670  
    1 import numpy
     1import numpy as np
    22import sys
    33import copy
    44from project3d import project3d
    55from fielddisplay import fielddisplay
    6 from EnumDefinitions import *
    76from checkfield import checkfield
    87from WriteData import WriteData
     
    123122
    124123                #Early return
    125                 if StressbalanceAnalysisEnum() not in analyses:
     124                if 'StressbalanceAnalysis' not in analyses:
    126125                        return md
    127126
     
    142141                #singular solution
    143142#               if ~any((~isnan(md.stressbalance.spcvx)+~isnan(md.stressbalance.spcvy))==2),
    144                 if not numpy.any(numpy.logical_and(numpy.logical_not(numpy.isnan(md.stressbalance.spcvx)),numpy.logical_not(numpy.isnan(md.stressbalance.spcvy)))):
     143                if not np.any(np.logical_and(np.logical_not(np.isnan(md.stressbalance.spcvx)),np.logical_not(np.isnan(md.stressbalance.spcvy)))):
    145144                        print("\n !!! Warning: no spc applied, model might not be well posed if no basal friction is applied, check for solution crash\n")
    146145                #CHECK THAT EACH LINES CONTAINS ONLY NAN VALUES OR NO NAN VALUES
    147146#               if any(sum(isnan(md.stressbalance.referential),2)~=0 & sum(isnan(md.stressbalance.referential),2)~=6),
    148                 if numpy.any(numpy.logical_and(numpy.sum(numpy.isnan(md.stressbalance.referential),axis=1)!=0,numpy.sum(numpy.isnan(md.stressbalance.referential),axis=1)!=6)):
     147                if np.any(np.logical_and(np.sum(np.isnan(md.stressbalance.referential),axis=1)!=0,np.sum(np.isnan(md.stressbalance.referential),axis=1)!=6)):
    149148                        md.checkmessage("Each line of stressbalance.referential should contain either only NaN values or no NaN values")
    150149                #CHECK THAT THE TWO VECTORS PROVIDED ARE ORTHOGONAL
    151150#               if any(sum(isnan(md.stressbalance.referential),2)==0),
    152                 if numpy.any(numpy.sum(numpy.isnan(md.stressbalance.referential),axis=1)==0):
    153                         pos=[i for i,item in enumerate(numpy.sum(numpy.isnan(md.stressbalance.referential),axis=1)) if item==0]
    154 #                       numpy.inner (and numpy.dot) calculate all the dot product permutations, resulting in a full matrix multiply
    155 #                       if numpy.any(numpy.abs(numpy.inner(md.stressbalance.referential[pos,0:2],md.stressbalance.referential[pos,3:5]).diagonal())>sys.float_info.epsilon):
     151                if np.any(np.sum(np.isnan(md.stressbalance.referential),axis=1)==0):
     152                        pos=[i for i,item in enumerate(np.sum(np.isnan(md.stressbalance.referential),axis=1)) if item==0]
     153#                       np.inner (and np.dot) calculate all the dot product permutations, resulting in a full matrix multiply
     154#                       if np.any(np.abs(np.inner(md.stressbalance.referential[pos,0:2],md.stressbalance.referential[pos,3:5]).diagonal())>sys.float_info.epsilon):
    156155#                               md.checkmessage("Vectors in stressbalance.referential (columns 1 to 3 and 4 to 6) must be orthogonal")
    157156                        for item in md.stressbalance.referential[pos,:]:
    158                                 if numpy.abs(numpy.inner(item[0:2],item[3:5]))>sys.float_info.epsilon:
     157                                if np.abs(np.inner(item[0:2],item[3:5]))>sys.float_info.epsilon:
    159158                                        md.checkmessage("Vectors in stressbalance.referential (columns 1 to 3 and 4 to 6) must be orthogonal")
    160159                #CHECK THAT NO rotation specified for FS Grounded ice at base
    161160                if m.strcmp(md.mesh.domaintype(),'3D') and md.flowequation.isFS:
    162                         pos=numpy.nonzero(numpy.logical_and(md.mask.groundedice_levelset,md.mesh.vertexonbase))
    163                         if numpy.any(numpy.logical_not(numpy.isnan(md.stressbalance.referential[pos,:]))):
     161                        pos=np.nonzero(np.logical_and(md.mask.groundedice_levelset,md.mesh.vertexonbase))
     162                        if np.any(np.logical_not(np.isnan(md.stressbalance.referential[pos,:]))):
    164163                                md.checkmessage("no referential should be specified for basal vertices of grounded ice")
    165164
    166165                return md
    167166        # }}}
    168         def marshall(self,md,fid):    # {{{
    169 
    170                 yts=365.0*24.0*3600.0
    171 
    172                 WriteData(fid,'object',self,'class','stressbalance','fieldname','spcvx','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
    173                 WriteData(fid,'object',self,'class','stressbalance','fieldname','spcvy','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
    174                 WriteData(fid,'object',self,'class','stressbalance','fieldname','spcvz','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1)
    175                 WriteData(fid,'object',self,'class','stressbalance','fieldname','restol','format','Double')
    176                 WriteData(fid,'object',self,'class','stressbalance','fieldname','reltol','format','Double')
    177                 WriteData(fid,'object',self,'class','stressbalance','fieldname','abstol','format','Double','scale',1./yts)
    178                 WriteData(fid,'object',self,'class','stressbalance','fieldname','isnewton','format','Integer')
    179                 WriteData(fid,'object',self,'class','stressbalance','fieldname','FSreconditioning','format','Double')
    180                 WriteData(fid,'object',self,'class','stressbalance','fieldname','maxiter','format','Integer')
    181                 WriteData(fid,'object',self,'class','stressbalance','fieldname','shelf_dampening','format','Integer')
    182                 WriteData(fid,'object',self,'class','stressbalance','fieldname','vertex_pairing','format','DoubleMat','mattype',3)
    183                 WriteData(fid,'object',self,'class','stressbalance','fieldname','penalty_factor','format','Double')
    184                 WriteData(fid,'object',self,'class','stressbalance','fieldname','rift_penalty_lock','format','Integer')
    185                 WriteData(fid,'object',self,'class','stressbalance','fieldname','rift_penalty_threshold','format','Integer')
    186                 WriteData(fid,'object',self,'class','stressbalance','fieldname','referential','format','DoubleMat','mattype',1)
    187 
    188                 WriteData(fid,'data',self.loadingforce[:,0],'format','DoubleMat','mattype',1,'enum',LoadingforceXEnum())
    189                 WriteData(fid,'data',self.loadingforce[:,1],'format','DoubleMat','mattype',1,'enum',LoadingforceYEnum())
    190                 WriteData(fid,'data',self.loadingforce[:,2],'format','DoubleMat','mattype',1,'enum',LoadingforceZEnum())
     167        def marshall(self,prefix,md,fid):    # {{{
     168
     169                WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','vertex_pairing','format','DoubleMat','mattype',3)
     170
     171                yts=md.constants.yts
     172
     173                WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','spcvx','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     174                WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','spcvy','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     175                WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','spcvz','format','DoubleMat','mattype',1,'scale',1./yts,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     176                WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','restol','format','Double')
     177                WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','reltol','format','Double')
     178                WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','abstol','format','Double','scale',1./yts)
     179                WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','isnewton','format','Integer')
     180                WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','FSreconditioning','format','Double')
     181                WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','maxiter','format','Integer')
     182                WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','shelf_dampening','format','Integer')
     183                WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','penalty_factor','format','Double')
     184                WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','rift_penalty_lock','format','Integer')
     185                WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','rift_penalty_threshold','format','Integer')
     186                WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','referential','format','DoubleMat','mattype',1)
     187
     188                if isinstance(self.loadingforce, (list, tuple, np.ndarray)) and np.size(self.loadingforce,1) == 3:
     189                        WriteData(fid,prefix,'data',self.loadingforce[:,0],'format','DoubleMat','mattype',1,'name','md.stressbalance.loadingforcex')
     190                        WriteData(fid,prefix,'data',self.loadingforce[:,1],'format','DoubleMat','mattype',1,'name','md.stressbalance.loadingforcey')
     191                        WriteData(fid,prefix,'data',self.loadingforce[:,2],'format','DoubleMat','mattype',1,'name','md.stressbalance.loadingforcez')
    191192
    192193                #process requested outputs
     
    196197                        outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:]
    197198                        outputs    =outputscopy
    198                 WriteData(fid,'data',outputs,'enum',StressbalanceRequestedOutputsEnum(),'format','StringArray')
     199                WriteData(fid,prefix,'data',outputs,'name','md.stressbalance.requested_outputs','format','StringArray')
    199200        # }}}
  • issm/trunk-jpl/src/py3/classes/taoinversion.py

    r19898 r23670  
    1 import numpy
     1import numpy as np
    22from project3d import project3d
    33from WriteData import WriteData
     
    55from fielddisplay import fielddisplay
    66from IssmConfig import IssmConfig
    7 from EnumDefinitions import *
    87from marshallcostfunctions import marshallcostfunctions
     8from supportedcontrols import *
     9from supportedcostfunctions import *
    910
    10 
    11 class taoinversion:
     11class taoinversion(object):
    1212        def __init__(self):
    13                 iscontrol                   = 0
    14                 incomplete_adjoint          = 0
    15                 control_parameters          = float('NaN')
    16                 maxsteps                    = 0
    17                 maxiter                     = 0
    18                 fatol                       = 0
    19                 frtol                       = 0
    20                 gatol                       = 0
    21                 grtol                       = 0
    22                 gttol                       = 0
    23                 algorithm                   = ''
    24                 cost_functions              = float('NaN')
    25                 cost_functions_coefficients = float('NaN')
    26                 min_parameters              = float('NaN')
    27                 max_parameters              = float('NaN')
    28                 vx_obs                      = float('NaN')
    29                 vy_obs                      = float('NaN')
    30                 vz_obs                      = float('NaN')
    31                 vel_obs                     = float('NaN')
    32                 thickness_obs               = float('NaN')
    33                 surface_obs                 = float('NaN')
     13                self.iscontrol                   = 0
     14                self.incomplete_adjoint          = 0
     15                self.control_parameters          = float('NaN')
     16                self.maxsteps                    = 0
     17                self.maxiter                     = 0
     18                self.fatol                       = 0
     19                self.frtol                       = 0
     20                self.gatol                       = 0
     21                self.grtol                       = 0
     22                self.gttol                       = 0
     23                self.algorithm                   = ''
     24                self.cost_functions              = float('NaN')
     25                self.cost_functions_coefficients = float('NaN')
     26                self.min_parameters              = float('NaN')
     27                self.max_parameters              = float('NaN')
     28                self.vx_obs                      = float('NaN')
     29                self.vy_obs                      = float('NaN')
     30                self.vz_obs                      = float('NaN')
     31                self.vel_obs                     = float('NaN')
     32                self.thickness_obs               = float('NaN')
     33                self.surface_obs                 = float('NaN')
     34                self.setdefaultparameters()
    3435
    3536        def __repr__(self):
     
    9091
    9192                #minimization algorithm
    92                 PETSCMAJOR = IssmConfig('_PETSC_MAJOR_')
    93                 PETSCMINOR = IssmConfig('_PETSC_MINOR_')
     93                PETSCMAJOR = IssmConfig('_PETSC_MAJOR_')[0]
     94                PETSCMINOR = IssmConfig('_PETSC_MINOR_')[0]
    9495                if(PETSCMAJOR>3 or (PETSCMAJOR==3 and PETSCMINOR>=5)):
    9596                        self.algorithm = 'blmvm';
    9697                else:
    9798                        self.algorithm = 'tao_blmvm';
    98                
     99
    99100                #several responses can be used:
    100101                self.cost_functions=101;
    101 
    102102                return self
    103103
     
    110110                if numel(self.cost_functions_coefficients) > 1:
    111111                        self.cost_functions_coefficients=project3d(md,'vector',self.cost_functions_coefficients,'type','node')
    112                
     112
    113113                if numel(self.min_parameters) > 1:
    114114                        self.min_parameters=project3d(md,'vector',self.min_parameters,'type','node')
    115                
     115
    116116                if numel(self.max_parameters)>1:
    117117                        self.max_parameters=project3d(md,'vector',self.max_parameters,'type','node')
     
    120120
    121121        def checkconsistency(self,md,solution,analyses):
    122                 if not self.control:
     122                if not self.iscontrol:
    123123                        return md
    124                 if not IssmConfig('_HAVE_TAO_'):
    125                         md = checkmessage(md,['TAO has not been installed, ISSM needs to be reconfigured and recompiled with TAO'])
     124                if not IssmConfig('_HAVE_TAO_')[0]:
     125                        md = md.checkmessage('TAO has not been installed, ISSM needs to be reconfigured and recompiled with TAO')
    126126
    127127
    128                 num_controls= numpy.numel(md.inversion.control_parameters)
    129                 num_costfunc= numpy.size(md.inversion.cost_functions,2)
     128                num_controls= np.size(md.inversion.control_parameters)
     129                num_costfunc= np.size(md.inversion.cost_functions)
    130130
    131131                md = checkfield(md,'fieldname','inversion.iscontrol','values',[0, 1])
    132                 md = checkfield(md,'fieldname','inversion.incomplete_adjoint','values',[0, 1])
     132                md = checkfield(md,'fieldname','inversion.incomplete_adjoint','values',[0,1])
    133133                md = checkfield(md,'fieldname','inversion.control_parameters','cell',1,'values',supportedcontrols())
    134134                md = checkfield(md,'fieldname','inversion.maxsteps','numel',1,'>=',0)
     
    141141
    142142
    143                 PETSCMAJOR = IssmConfig('_PETSC_MAJOR_')
    144                 PETSCMINOR = IssmConfig('_PETSC_MINOR_')
     143                PETSCMAJOR = IssmConfig('_PETSC_MAJOR_')[0]
     144                PETSCMINOR = IssmConfig('_PETSC_MINOR_')[0]
    145145                if(PETSCMAJOR>3 or (PETSCMAJOR==3 and PETSCMINOR>=5)):
    146                         md = checkfield(md,'fieldname','inversion.algorithm','values',{'blmvm','cg','lmvm'})
     146                        md = checkfield(md,'fieldname','inversion.algorithm','values',['blmvm','cg','lmvm'])
    147147                else:
    148                         md = checkfield(md,'fieldname','inversion.algorithm','values',{'tao_blmvm','tao_cg','tao_lmvm'})
     148                        md = checkfield(md,'fieldname','inversion.algorithm','values',['tao_blmvm','tao_cg','tao_lmvm'])
    149149
    150150
    151                 md = checkfield(md,'fieldname','inversion.cost_functions','size',[1, num_costfunc],'values',supportedcostfunctions())
     151                md = checkfield(md,'fieldname','inversion.cost_functions','size', [num_costfunc],'values',supportedcostfunctions())
    152152                md = checkfield(md,'fieldname','inversion.cost_functions_coefficients','size',[md.mesh.numberofvertices, num_costfunc],'>=',0)
    153153                md = checkfield(md,'fieldname','inversion.min_parameters','size',[md.mesh.numberofvertices, num_controls])
     
    155155
    156156
    157                 if solution==BalancethicknessSolutionEnum():
    158                         md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices, 1],'NaN',1,'Inf',1)
    159                 elif solution==BalancethicknessSoftSolutionEnum():
    160                         md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices, 1],'NaN',1,'Inf',1)
     157                if solution=='BalancethicknessSolution':
     158                        md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices],'NaN',1,'Inf',1)
     159                elif solution=='BalancethicknessSoftSolution':
     160                        md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices],'NaN',1,'Inf',1)
    161161                else:
    162                         md = checkfield(md,'fieldname','inversion.vx_obs','size',[md.mesh.numberofvertices, 1],'NaN',1,'Inf',1)
    163                         md = checkfield(md,'fieldname','inversion.vy_obs','size',[md.mesh.numberofvertices, 1],'NaN',1,'Inf',1)
     162                        md = checkfield(md,'fieldname','inversion.vx_obs','size',[md.mesh.numberofvertices],'NaN',1,'Inf',1)
     163                        md = checkfield(md,'fieldname','inversion.vy_obs','size',[md.mesh.numberofvertices],'NaN',1,'Inf',1)
    164164
    165                 def marshall(self, md, fid):
     165        def marshall(self,prefix,md,fid):
    166166
    167                         yts=365.0*24.0*3600.0;
    168                         WriteData(fid,'object',self,'class','inversion','fieldname','iscontrol','format','Boolean')
    169                         WriteData(fid,'enum',InversionTypeEnum(),'data',1,'format','Integer')
    170                         if not self.iscontrol:
    171                                 return
    172                         WriteData(fid,'object',self,'class','inversion','fieldname','incomplete_adjoint','format','Boolean')
    173                         WriteData(fid,'object',self,'class','inversion','fieldname','maxsteps','format','Integer')
    174                         WriteData(fid,'object',self,'class','inversion','fieldname','maxiter','format','Integer')
    175                         WriteData(fid,'object',self,'class','inversion','fieldname','fatol','format','Double')
    176                         WriteData(fid,'object',self,'class','inversion','fieldname','frtol','format','Double')
    177                         WriteData(fid,'object',self,'class','inversion','fieldname','gatol','format','Double')
    178                         WriteData(fid,'object',self,'class','inversion','fieldname','grtol','format','Double')
    179                         WriteData(fid,'object',self,'class','inversion','fieldname','gttol','format','Double')
    180                         WriteData(fid,'object',self,'class','inversion','fieldname','algorithm','format','String')
    181                         WriteData(fid,'object',self,'class','inversion','fieldname','cost_functions_coefficients','format','DoubleMat','mattype',1)
    182                         WriteData(fid,'object',self,'class','inversion','fieldname','min_parameters','format','DoubleMat','mattype',3)
    183                         WriteData(fid,'object',self,'class','inversion','fieldname','max_parameters','format','DoubleMat','mattype',3)
    184                         WriteData(fid,'object',self,'class','inversion','fieldname','vx_obs','format','DoubleMat','mattype',1,'scale',1./yts)
    185                         WriteData(fid,'object',self,'class','inversion','fieldname','vy_obs','format','DoubleMat','mattype',1,'scale',1./yts)
    186                         WriteData(fid,'object',self,'class','inversion','fieldname','vz_obs','format','DoubleMat','mattype',1,'scale',1./yts)
    187                         WriteData(fid,'object',self,'class','inversion','fieldname','thickness_obs','format','DoubleMat','mattype',1)
    188                         WriteData(fid,'object',self,'class','inversion','fieldname','surface_obs','format','DoubleMat','mattype',1)
     167                yts=md.constants.yts;
     168                WriteData(fid,prefix,'object',self,'class','inversion','fieldname','iscontrol','format','Boolean')
     169                WriteData(fid,prefix,'name','md.inversion.type','data',1,'format','Integer')
     170                if not self.iscontrol:
     171                        return
     172                WriteData(fid,prefix,'object',self,'class','inversion','fieldname','incomplete_adjoint','format','Boolean')
     173                WriteData(fid,prefix,'object',self,'class','inversion','fieldname','maxsteps','format','Integer')
     174                WriteData(fid,prefix,'object',self,'class','inversion','fieldname','maxiter','format','Integer')
     175                WriteData(fid,prefix,'object',self,'class','inversion','fieldname','fatol','format','Double')
     176                WriteData(fid,prefix,'object',self,'class','inversion','fieldname','frtol','format','Double')
     177                WriteData(fid,prefix,'object',self,'class','inversion','fieldname','gatol','format','Double')
     178                WriteData(fid,prefix,'object',self,'class','inversion','fieldname','grtol','format','Double')
     179                WriteData(fid,prefix,'object',self,'class','inversion','fieldname','gttol','format','Double')
     180                WriteData(fid,prefix,'object',self,'class','inversion','fieldname','algorithm','format','String')
     181                WriteData(fid,prefix,'object',self,'class','inversion','fieldname','cost_functions_coefficients','format','DoubleMat','mattype',1)
     182                WriteData(fid,prefix,'object',self,'class','inversion','fieldname','min_parameters','format','DoubleMat','mattype',3)
     183                WriteData(fid,prefix,'object',self,'class','inversion','fieldname','max_parameters','format','DoubleMat','mattype',3)
     184                WriteData(fid,prefix,'object',self,'class','inversion','fieldname','vx_obs','format','DoubleMat','mattype',1,'scale',1./yts)
     185                WriteData(fid,prefix,'object',self,'class','inversion','fieldname','vy_obs','format','DoubleMat','mattype',1,'scale',1./yts)
     186                WriteData(fid,prefix,'object',self,'class','inversion','fieldname','vz_obs','format','DoubleMat','mattype',1,'scale',1./yts)
     187                WriteData(fid,prefix,'object',self,'class','inversion','fieldname','thickness_obs','format','DoubleMat','mattype',1)
     188                WriteData(fid,prefix,'object',self,'class','inversion','fieldname','surface_obs','format','DoubleMat','mattype',1)
    189189
    190                         #process control parameters
    191                         num_control_parameters = numpy.numel(self.control_parameters)
    192                         data = numpy.array([StringToEnum(self.control_parameter[0]) for control_parameter in self.control_parameters]).reshape(1,-1)
    193                         WriteData(fid,'data',data,'enum',InversionControlParametersEnum(),'format','DoubleMat','mattype',3)
    194                         WriteData(fid,'data',num_control_parameters,'enum',InversionNumControlParametersEnum(),'format','Integer')
     190                #process control parameters
     191                num_control_parameters = np.size(self.control_parameters)
     192                WriteData(fid,prefix,'object',self,'fieldname','control_parameters','format','StringArray')
     193                WriteData(fid,prefix,'data',num_control_parameters,'name','md.inversion.num_control_parameters','format','Integer')
    195194
    196                         #process cost functions
    197                         num_cost_functions = numpy.size(self.cost_functions,2)
    198                         data= marshallcostfunctions(self.cost_functions)
    199                         WriteData(fid,'data',data,'enum',InversionCostFunctionsEnum(),'format','DoubleMat','mattype',3)
    200                         WriteData(fid,'data',num_cost_functions,'enum',InversionNumCostFunctionsEnum(),'format','Integer')
     195                #process cost functions
     196                num_cost_functions = np.size(self.cost_functions)
     197                data= marshallcostfunctions(self.cost_functions)
     198                WriteData(fid,prefix,'data',data,'name','md.inversion.cost_functions','format','StringArray')
     199                WriteData(fid,prefix,'data',num_cost_functions,'name','md.inversion.num_cost_functions','format','Integer')
  • issm/trunk-jpl/src/py3/classes/thermal.py

    r19903 r23670  
    1 import numpy
     1import numpy as  np
    22from project3d import project3d
    33from fielddisplay import fielddisplay
    4 from EnumDefinitions import *
    54from checkfield import checkfield
    65from WriteData import WriteData
    7 import MatlabFuncs as m
    86
    97class thermal(object):
     
    2422                self.penalty_factor    = 0
    2523                self.isenthalpy        = 0
    26                 self.isdynamicbasalspc = 0;
     24                self.isdynamicbasalspc = 0
     25                self.fe                = 'P1'
    2726                self.requested_outputs = []
    2827
     
    4544                #}}}
    4645        def extrude(self,md): # {{{
    47                 self.spctemperature=project3d(md,'vector',self.spctemperature,'type','node','layer',md.mesh.numberoflayers,'padding',numpy.nan)
    48                 if isinstance(md.initialization.temperature,numpy.ndarray) and numpy.size(md.initialization.temperature,axis=0)==md.mesh.numberofvertices:
    49                         self.spctemperature=numpy.nan*numpy.ones((md.mesh.numberofvertices,1))
    50                         pos=numpy.nonzero(md.mesh.vertexonsurface)[0]
     46                self.spctemperature=project3d(md,'vector',self.spctemperature,'type','node','layer',md.mesh.numberoflayers,'padding',np.nan)
     47                if isinstance(md.initialization.temperature,np.ndarray) and np.size(md.initialization.temperature,axis=0)==md.mesh.numberofvertices:
     48                        self.spctemperature=float('NaN')*np.ones((md.mesh.numberofvertices))
     49                        pos=np.where(md.mesh.vertexonsurface)[0]
    5150                        self.spctemperature[pos]=md.initialization.temperature[pos]    #impose observed temperature on surface
    5251                return self
     
    8180
    8281                #will basal boundary conditions be set dynamically
    83                 self.isdynamicbasalspc=0;
     82                self.isdynamicbasalspc=0
     83
     84                #Finite element interpolation
     85                self.fe='P1'
    8486
    8587                #default output
     
    9193
    9294                #Early return
    93                 if (ThermalAnalysisEnum() not in analyses and EnthalpyAnalysisEnum() not in analyses) or (solution==TransientSolutionEnum() and not md.transient.isthermal):
     95                if ('ThermalAnalysis' not in analyses and 'EnthalpyAnalysis' not in analyses) or (solution=='TransientSolution' and not md.transient.isthermal):
    9496                        return md
    9597
    9698                md = checkfield(md,'fieldname','thermal.stabilization','numel',[1],'values',[0,1,2])
    9799                md = checkfield(md,'fieldname','thermal.spctemperature','Inf',1,'timeseries',1)
    98                 if EnthalpyAnalysisEnum() in analyses and md.thermal.isenthalpy and md.mesh.dimension()==3:
    99                         pos=numpy.nonzero(numpy.logical_not(numpy.isnan(md.thermal.spctemperature[0:md.mesh.numberofvertices])))
    100                         replicate=numpy.tile(md.geometry.surface-md.mesh.z,(1,numpy.size(md.thermal.spctemperature,axis=1)))
    101                         md = checkfield(md,'fieldname','thermal.spctemperature[numpy.nonzero(numpy.logical_not(numpy.isnan(md.thermal.spctemperature[0:md.mesh.numberofvertices,:])))]','<',md.materials.meltingpoint-md.materials.beta*md.materials.rho_ice*md.constants.g*replicate[pos],'message',"spctemperature should be below the adjusted melting point")
     100                md = checkfield(md,'fieldname','thermal.requested_outputs','stringrow',1)
     101
     102                if 'EnthalpyAnalysis' in analyses and md.thermal.isenthalpy and md.mesh.dimension()==3:
     103                        TEMP = md.thermal.spctemperature[:-1].flatten(-1)
     104                        pos=np.where(~np.isnan(TEMP))
     105                        try:
     106                                spccol=np.size(md.thermal.spctemperature,1)
     107                        except IndexError:
     108                                spccol=1
     109
     110                        replicate=np.tile(md.geometry.surface-md.mesh.z,(spccol)).flatten(-1)
     111
     112                        control=md.materials.meltingpoint-md.materials.beta*md.materials.rho_ice*md.constants.g*replicate+10**-5
     113
     114                        md = checkfield(md,'fieldname','thermal.spctemperature','field',md.thermal.spctemperature.flatten(-1)[pos],'<=',control[pos],'message',"spctemperature should be below the adjusted melting point")
    102115                        md = checkfield(md,'fieldname','thermal.isenthalpy','numel',[1],'values',[0,1])
    103116                        md = checkfield(md,'fieldname','thermal.isdynamicbasalspc','numel',[1],'values',[0,1]);
    104117                        if(md.thermal.isenthalpy):
    105                                 if numpy.isnan(md.stressbalance.reltol):
     118                                if np.isnan(md.stressbalance.reltol):
    106119                                        md.checkmessage("for a steadystate computation, thermal.reltol (relative convergence criterion) must be defined!")
    107120                                md = checkfield(md,'fieldname','thermal.reltol','>',0.,'message',"reltol must be larger than zero");
    108                 md = checkfield(md,'fieldname','thermal.requested_outputs','stringrow',1)
     121
    109122
    110123                return md
    111124        # }}}
    112         def marshall(self,md,fid):    # {{{
    113                 WriteData(fid,'object',self,'fieldname','spctemperature','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1)
    114                 WriteData(fid,'object',self,'fieldname','penalty_threshold','format','Integer')
    115                 WriteData(fid,'object',self,'fieldname','stabilization','format','Integer')
    116                 WriteData(fid,'object',self,'fieldname','reltol','format','Double');
    117                 WriteData(fid,'object',self,'fieldname','maxiter','format','Integer')
    118                 WriteData(fid,'object',self,'fieldname','penalty_lock','format','Integer')
    119                 WriteData(fid,'object',self,'fieldname','penalty_factor','format','Double')
    120                 WriteData(fid,'object',self,'fieldname','isenthalpy','format','Boolean')
    121                 WriteData(fid,'object',self,'fieldname','isdynamicbasalspc','format','Boolean');
     125        def marshall(self,prefix,md,fid):    # {{{
     126                WriteData(fid,prefix,'object',self,'fieldname','spctemperature','format','DoubleMat','mattype',1,'timeserieslength',md.mesh.numberofvertices+1,'yts',md.constants.yts)
     127                WriteData(fid,prefix,'object',self,'fieldname','penalty_threshold','format','Integer')
     128                WriteData(fid,prefix,'object',self,'fieldname','stabilization','format','Integer')
     129                WriteData(fid,prefix,'object',self,'fieldname','reltol','format','Double');
     130                WriteData(fid,prefix,'object',self,'fieldname','maxiter','format','Integer')
     131                WriteData(fid,prefix,'object',self,'fieldname','penalty_lock','format','Integer')
     132                WriteData(fid,prefix,'object',self,'fieldname','penalty_factor','format','Double')
     133                WriteData(fid,prefix,'object',self,'fieldname','isenthalpy','format','Boolean')
     134                WriteData(fid,prefix,'object',self,'fieldname','fe','format','String');
     135                WriteData(fid,prefix,'object',self,'fieldname','isdynamicbasalspc','format','Boolean');
    122136
    123137                #process requested outputs
     
    127141                        outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:]
    128142                        outputs    =outputscopy
    129                 WriteData(fid,'data',outputs,'enum',ThermalRequestedOutputsEnum(),'format','StringArray')
     143                WriteData(fid,prefix,'data',outputs,'name','md.thermal.requested_outputs','format','StringArray')
    130144        # }}}
  • issm/trunk-jpl/src/py3/classes/timestepping.py

    r19898 r23670  
    11from fielddisplay import fielddisplay
    2 from EnumDefinitions import *
    32from checkfield import checkfield
    43from WriteData import WriteData
     
    1615                self.final_time      = 0.
    1716                self.time_step       = 0.
    18                 self.time_adapt      = 0
    19                 self.cfl_coefficient = 0.
    2017                self.interp_forcings = 1
     18                self.coupling_time   = 0.
    2119               
    2220                #set defaults
     
    2927                string="%s\n%s"%(string,fielddisplay(self,"final_time","final time to stop the simulation [yr]"))
    3028                string="%s\n%s"%(string,fielddisplay(self,"time_step","length of time steps [yr]"))
    31                 string="%s\n%s"%(string,fielddisplay(self,"time_adapt","use cfl condition to define time step ? (0 or 1) "))
    32                 string="%s\n%s"%(string,fielddisplay(self,"cfl_coefficient","coefficient applied to cfl condition"))
    3329                string="%s\n%s"%(string,fielddisplay(self,"interp_forcings","interpolate in time between requested forcing values ? (0 or 1)"))
     30                string="%s\n%s"%(string,fielddisplay(self,"coupling_time","length of coupling time steps with ocean model [yr]"))
    3431                return string
    3532                #}}}
     
    4239                self.final_time=10.*self.time_step
    4340
    44                 #time adaptation?
    45                 self.time_adapt=0
    46                 self.cfl_coefficient=0.5
    47                
    4841                #should we interpolate forcings between timesteps?
    4942                self.interp_forcings=1
     
    5649                md = checkfield(md,'fieldname','timestepping.final_time','numel',[1],'NaN',1,'Inf',1)
    5750                md = checkfield(md,'fieldname','timestepping.time_step','numel',[1],'>=',0,'NaN',1,'Inf',1)
    58                 md = checkfield(md,'fieldname','timestepping.time_adapt','numel',[1],'values',[0,1])
    59                 md = checkfield(md,'fieldname','timestepping.cfl_coefficient','numel',[1],'>',0,'<=',1)
    6051                if self.final_time-self.start_time<0:
    6152                        md.checkmessage("timestepping.final_time should be larger than timestepping.start_time")
     53                        md = checkfield(md,'fieldname','timestepping.coupling_time','numel',[1],'>=',0,'NaN',1,'Inf',1)
    6254                md = checkfield(md,'fieldname','timestepping.interp_forcings','numel',[1],'values',[0,1])
    6355
    6456                return md
    6557        # }}}
    66         def marshall(self,md,fid):    # {{{
     58        def marshall(self,prefix,md,fid):    # {{{
    6759
    6860                yts=md.constants.yts
    69                
    70                 WriteData(fid,'object',self,'fieldname','start_time','format','Double','scale',yts)
    71                 WriteData(fid,'object',self,'fieldname','final_time','format','Double','scale',yts)
    72                 WriteData(fid,'object',self,'fieldname','time_step','format','Double','scale',yts)
    73                 WriteData(fid,'object',self,'fieldname','time_adapt','format','Boolean')
    74                 WriteData(fid,'object',self,'fieldname','cfl_coefficient','format','Double')
    75                 WriteData(fid,'object',self,'fieldname','interp_forcings','format','Boolean')
     61                WriteData(fid,prefix,'name','md.timestepping.type','data',1,'format','Integer');
     62                WriteData(fid,prefix,'object',self,'fieldname','start_time','format','Double','scale',yts)
     63                WriteData(fid,prefix,'object',self,'fieldname','final_time','format','Double','scale',yts)
     64                WriteData(fid,prefix,'object',self,'fieldname','time_step','format','Double','scale',yts)
     65                WriteData(fid,prefix,'object',self,'fieldname','interp_forcings','format','Boolean')
     66                WriteData(fid,prefix,'object',self,'fieldname','coupling_time','format','Double','scale',yts)
    7667        # }}}
  • issm/trunk-jpl/src/py3/classes/toolkits.py

    r19895 r23670  
    22from mumpsoptions import mumpsoptions
    33from iluasmoptions import iluasmoptions
    4 from EnumToString import EnumToString
    54from fielddisplay import fielddisplay
    6 from EnumDefinitions import *
    75from checkfield import checkfield
     6from issmgslsolver import issmgslsolver
     7from issmmumpssolver import issmmumpssolver
    88
    99class toolkits(object):
     
    3030                        else:
    3131                                raise IOError("ToolkitsFile error: need at least Mumps or Gsl to define issm solver type")
     32
    3233                #The other properties are dynamic
    3334        # }}}
    3435        def __repr__(self):    # {{{
    35                 print('enter repr')
    3636                s ="List of toolkits options per analysis:\n\n"
    37                 for analysis in list(vars(self).keys()):
     37                for analysis in vars(self).keys():
    3838                        s+="%s\n" % fielddisplay(self,analysis,'')
    3939
     
    4141        # }}}
    4242        def addoptions(self,analysis,*args):    # {{{
    43                 print('enter addoption')
    4443                # Usage example:
    45                 #    md.toolkits=addoptions(md.toolkits,StressbalanceAnalysisEnum(),FSoptions());
    46                 #    md.toolkits=addoptions(md.toolkits,StressbalanceAnalysisEnum());
    47 
    48                 #Convert analysis from enum to string
    49                 [analysis]=EnumToString(analysis)
     44                #    md.toolkits=addoptions(md.toolkits,'StressbalanceAnalysis',FSoptions());
     45                #    md.toolkits=addoptions(md.toolkits,'StressbalanceAnalysis');
    5046
    5147                #Create dynamic property if property does not exist yet
    5248                if not hasattr(self,analysis):
    53 #                       exec("self.%s = None" % analysis)
    5449                        setattr(self,analysis,None)
    5550
     
    6156        # }}}
    6257        def checkconsistency(self,md,solution,analyses):    # {{{
    63                 print('enter check')
    64                 for analysis in list(vars(self).keys()):
     58                for analysis in vars(self).keys():
    6559                        if not getattr(self,analysis):
    6660                                md.checkmessage("md.toolkits.%s is empty" % analysis)
     
    8680
    8781                #write header
    88                 fid.write("%s%s%s\n" % ('%Petsc options file: ',filename,' written from Matlab toolkits array'))
     82                fid.write("%s%s%s\n" % ('%Toolkits options file: ',filename,' written from Python toolkits array'))
    8983
    9084                #start writing options
    91                 for analysis in list(vars(self).keys()):
     85                for analysis in vars(self).keys():
    9286                        options=getattr(self,analysis)
    9387
    9488                        #first write analysis:
    9589                        fid.write("\n+%s\n" % analysis)    #append a + to recognize it's an analysis enum
    96 
    9790                        #now, write options
    98                         for optionname,optionvalue in list(options.items()):
     91                        for optionname,optionvalue in options.items():
    9992
    10093                                if not optionvalue:
  • issm/trunk-jpl/src/py3/classes/transient.py

    r19895 r23670  
    11from fielddisplay import fielddisplay
    2 from EnumDefinitions import *
    32from checkfield import checkfield
    43from WriteData import WriteData
     
    1312
    1413        def __init__(self): # {{{
    15                 self.issmb   = False
     14                self.issmb             = False
    1615                self.ismasstransport   = False
    1716                self.isstressbalance   = False
     
    1918                self.isgroundingline   = False
    2019                self.isgia             = False
     20                self.isesa             = False
    2121                self.isdamageevolution = False
    22                 self.islevelset        = False
    23                 self.iscalving         = False
     22                self.ismovingfront     = False
    2423                self.ishydrology       = False
     24                self.isslr             = False
     25                self.iscoupler         = False
     26                self.amr_frequency     = 0
     27                self.isoceancoupling   = False
    2528                self.requested_outputs = []
    2629
     
    3740                string="%s\n%s"%(string,fielddisplay(self,'isgroundingline','indicates if a groundingline migration is used in the transient'))
    3841                string="%s\n%s"%(string,fielddisplay(self,'isgia','indicates if a postglacial rebound is used in the transient'))
     42                string="%s\n%s"%(string,fielddisplay(self,'isesa','indicates whether an elastic adjustment model is used in the transient'))
    3943                string="%s\n%s"%(string,fielddisplay(self,'isdamageevolution','indicates whether damage evolution is used in the transient'))
    40                 string="%s\n%s"%(string,fielddisplay(self,'islevelset','LEVELSET METHOD DESCRIPTION'))
    41                 string="%s\n%s"%(string,fielddisplay(self,'iscalving','indicates whether calving is used in the transient'))
     44                string="%s\n%s"%(string,fielddisplay(self,'ismovingfront','indicates whether a moving front capability is used in the transient'))
    4245                string="%s\n%s"%(string,fielddisplay(self,'ishydrology','indicates whether an hydrology model is used'))
     46                string="%s\n%s"%(string,fielddisplay(self,'isslr','indicates if a sea level rise solution is used in the transient'))
     47                string="%s\n%s"%(string,fielddisplay(self,'isoceancoupling','indicates whether coupling with an ocean model is used in the transient'))
     48                string="%s\n%s"%(string,fielddisplay(self,'iscoupler','indicates whether different models are being run with need for coupling'))
     49                string="%s\n%s"%(string,fielddisplay(self,'amr_frequency','frequency at which mesh is refined in simulations with multiple time_steps'))
    4350                string="%s\n%s"%(string,fielddisplay(self,'requested_outputs','list of additional outputs requested'))
    4451                return string
     
    6168                self.isgroundingline   = False
    6269                self.isgia             = False
     70                self.isesa             = False
    6371                self.isdamageevolution = False
    64                 self.islevelset        = False
    65                 self.iscalving         = False
     72                self.ismovingfront     = False
    6673                self.ishydrology       = False
     74                self.isoceancoupling   = False
     75                self.isslr             = False
     76                self.iscoupler         = False
     77                self.amr_frequency        = 0
     78
     79                #default output
     80                self.requested_outputs=[]
     81                return self
     82        #}}}
     83        def deactivateall(self):#{{{
     84                self.issmb             = False
     85                self.ismasstransport   = False
     86                self.isstressbalance   = False
     87                self.isthermal         = False
     88                self.isgroundingline   = False
     89                self.isgia             = False
     90                self.isesa             = False
     91                self.isdamageevolution = False
     92                self.ismovingfront     = False
     93                self.ishydrology       = False
     94                self.isslr             = False
     95                self.isoceancoupling   = False
     96                self.iscoupler         = False
     97                self.amr_frequency     = 0
    6798
    6899                #default output
     
    73104               
    74105                #full analysis: Stressbalance, Masstransport and Thermal but no groundingline migration for now
    75                 self.issmb = True
    76                 self.ismasstransport = True
    77                 self.isstressbalance = True
    78                 self.isthermal       = True
    79                 self.isgroundingline = False
    80                 self.isgia           = False
     106                self.issmb             = True
     107                self.ismasstransport   = True
     108                self.isstressbalance   = True
     109                self.isthermal         = True
     110                self.isgroundingline   = False
     111                self.isgia             = False
     112                self.isesa             = False
    81113                self.isdamageevolution = False
    82                 self.islevelset      = False
    83                 self.iscalving       = False
    84                 self.ishydrology     = False
     114                self.ismovingfront     = False
     115                self.ishydrology       = False
     116                self.isslr             = False
     117                self.isoceancoupling   = False
     118                self.iscoupler         = False
     119                self.amr_frequency     = 0
    85120
    86121                #default output
     
    91126
    92127                #Early return
    93                 if not solution==TransientSolutionEnum():
     128                if not solution=='TransientSolution':
    94129                        return md
    95130
     
    100135                md = checkfield(md,'fieldname','transient.isgroundingline','numel',[1],'values',[0,1])
    101136                md = checkfield(md,'fieldname','transient.isgia','numel',[1],'values',[0,1])
     137                md = checkfield(md,'fieldname','transient.isesa','numel',[1],'values',[0,1])
    102138                md = checkfield(md,'fieldname','transient.isdamageevolution','numel',[1],'values',[0,1])
    103                 md = checkfield(md,'fieldname','transient.islevelset','numel',[1],'values',[0,1])
    104139                md = checkfield(md,'fieldname','transient.ishydrology','numel',[1],'values',[0,1])
    105                 md = checkfield(md,'fieldname','transient.iscalving','numel',[1],'values',[0,1]);
     140                md = checkfield(md,'fieldname','transient.ismovingfront','numel',[1],'values',[0,1]);
     141                md = checkfield(md,'fieldname','transient.isslr','numel',[1],'values',[0,1])
     142                md = checkfield(md,'fieldname','transient.isoceancoupling','numel',[1],'values',[0,1])
     143                md = checkfield(md,'fieldname','transient.iscoupler','numel',[1],'values',[0,1])
     144                md = checkfield(md,'fieldname','transient.amr_frequency','numel',[1],'>=',0,'NaN',1,'Inf',1)
    106145                md = checkfield(md,'fieldname','transient.requested_outputs','stringrow',1)
     146
     147                if (solution!='TransientSolution') and (md.transient.iscoupling):
     148                                md.checkmessage("Coupling with ocean can only be done in transient simulations!")
    107149
    108150                return md
    109151        # }}}
    110         def marshall(self,md,fid):    # {{{
    111                 WriteData(fid,'object',self,'fieldname','issmb','format','Boolean')
    112                 WriteData(fid,'object',self,'fieldname','ismasstransport','format','Boolean')
    113                 WriteData(fid,'object',self,'fieldname','isstressbalance','format','Boolean')
    114                 WriteData(fid,'object',self,'fieldname','isthermal','format','Boolean')
    115                 WriteData(fid,'object',self,'fieldname','isgroundingline','format','Boolean')
    116                 WriteData(fid,'object',self,'fieldname','isgia','format','Boolean')
    117                 WriteData(fid,'object',self,'fieldname','isdamageevolution','format','Boolean')
    118                 WriteData(fid,'object',self,'fieldname','islevelset','format','Boolean')
    119                 WriteData(fid,'object',self,'fieldname','ishydrology','format','Boolean')
    120                 WriteData(fid,'object',self,'fieldname','iscalving','format','Boolean')
     152        def marshall(self,prefix,md,fid):    # {{{
     153                WriteData(fid,prefix,'object',self,'fieldname','issmb','format','Boolean')
     154                WriteData(fid,prefix,'object',self,'fieldname','ismasstransport','format','Boolean')
     155                WriteData(fid,prefix,'object',self,'fieldname','isstressbalance','format','Boolean')
     156                WriteData(fid,prefix,'object',self,'fieldname','isthermal','format','Boolean')
     157                WriteData(fid,prefix,'object',self,'fieldname','isgroundingline','format','Boolean')
     158                WriteData(fid,prefix,'object',self,'fieldname','isgia','format','Boolean')
     159                WriteData(fid,prefix,'object',self,'fieldname','isesa','format','Boolean')
     160                WriteData(fid,prefix,'object',self,'fieldname','isdamageevolution','format','Boolean')
     161                WriteData(fid,prefix,'object',self,'fieldname','ishydrology','format','Boolean')
     162                WriteData(fid,prefix,'object',self,'fieldname','ismovingfront','format','Boolean')
     163                WriteData(fid,prefix,'object',self,'fieldname','isslr','format','Boolean')
     164                WriteData(fid,prefix,'object',self,'fieldname','isoceancoupling','format','Boolean')
     165                WriteData(fid,prefix,'object',self,'fieldname','iscoupler','format','Boolean')
     166                WriteData(fid,prefix,'object',self,'fieldname','amr_frequency','format','Integer')
    121167
    122168                #process requested outputs
     
    126172                        outputscopy=outputs[0:max(0,indices[0]-1)]+self.defaultoutputs(md)+outputs[indices[0]+1:]
    127173                        outputs    =outputscopy
    128                 WriteData(fid,'data',outputs,'enum',TransientRequestedOutputsEnum(),'format','StringArray')
     174                WriteData(fid,prefix,'data',outputs,'name','md.transient.requested_outputs','format','StringArray')
    129175        # }}}
  • issm/trunk-jpl/src/py3/classes/verbose.py

    r19895 r23670  
    11from pairoptions import pairoptions
    22import MatlabFuncs as m
    3 from EnumDefinitions import *
    43from WriteData import WriteData
    54
     
    2928        """
    3029
    31         def __init__(self,*args,**kwargs):    # {{{
     30        def __init__(self,*args):    # {{{
    3231                #BEGINFIELDS
    3332                self.mprocessor  = False
     
    4241                #ENDFIELDS
    4342
    44                 if not kwargs and not args:
     43                if not len(args):
    4544                        #Don't do anything
    4645                        self.solution=True;
     
    6463                else:
    6564                        #Use options to initialize object
    66                         self=pairoptions(**kwargs).AssignObjectFields(self)
     65                        self=pairoptions(*args).AssignObjectFields(self)
    6766
    6867                        #Cast to logicals
    6968                        listproperties=vars(self)
    70                         for fieldname,fieldvalue in list(listproperties.items()):
     69                        for fieldname,fieldvalue in listproperties.items():
    7170                                if isinstance(fieldvalue,bool) or isinstance(fieldvalue,(int,float)):
    7271                                        setattr(self,fieldname,bool(fieldvalue))
     
    134133                return md
    135134        # }}}
    136         def marshall(self,md,fid):    # {{{
    137                 WriteData(fid,'data',self.VerboseToBinary(),'enum',VerboseEnum(),'format','Integer')
     135        def marshall(self,prefix,md,fid):    # {{{
     136                WriteData(fid,prefix,'data',self.VerboseToBinary(),'name','md.verbose','format','Integer')
    138137        # }}}
  • issm/trunk-jpl/src/py3/consistency/checkfield.py

    r19899 r23670  
    1 import numpy
     1import numpy as np
    22import os
    33from pairoptions import pairoptions
    44import MatlabFuncs as m
    55
    6 def checkfield(md,**kwargs):
     6def checkfield(md,*args):
    77        """
    88        CHECKFIELD - check field consistency
    99
    1010           Used to check model consistency.,
    11            Requires: 
    12            'field' or 'fieldname' option. If 'fieldname' is provided, it will retrieve it from the model md. (md.(fieldname)) 
     11           Requires:
     12           'field' or 'fieldname' option. If 'fieldname' is provided, it will retrieve it from the model md. (md.(fieldname))
    1313             If 'field' is provided, it will assume the argument following 'field' is a numeric array.
    1414
     
    3333
    3434        #get options
    35         options=pairoptions(**kwargs)
     35        options=pairoptions(*args)
    3636
    3737        #get field from model
     
    4040                fieldname=options.getfieldvalue('fieldname','no fieldname')
    4141        else:
    42                 fieldname=options.getfieldvalue('fieldname') 
    43                 exec("field=md.%s" % fieldname)
     42                fieldname=options.getfieldvalue('fieldname')
     43                exec("field=md.{}".format(fieldname))
    4444
    4545        if isinstance(field,(bool,int,float)):
    46                 field=numpy.array([field])
     46                field=np.array([field])
    4747
    4848        #check empty
     
    5555        if options.exist('size'):
    5656                fieldsize=options.getfieldvalue('size')
    57                 if   len(fieldsize) == 1:
    58                         if   numpy.isnan(fieldsize[0]):
     57                if len(fieldsize) == 1:
     58                        if np.isnan(fieldsize[0]):
    5959                                pass
    60                         elif not numpy.size(field,0)==fieldsize[0]:
    61                                 md = md.checkmessage(options.getfieldvalue('message',\
    62                                         "field '%s' size should be %d" % (fieldname,fieldsize[0])))
     60                        elif np.ndim(field)==1:
     61                                if not np.size(field)==fieldsize[0]:
     62                                        md = md.checkmessage(options.getfieldvalue('message',"field {} size should be {}".format(fieldname,fieldsize[0])))
     63                        else:
     64                                try:
     65                                        exec("md.{}=np.squeeze(field)".format(fieldname))
     66                                        print(('{} had been squeezed if it was a matrix with only one column'.format(fieldname)))
     67                                except IndexError:
     68                                        md = md.checkmessage(options.getfieldvalue('message',"field {} should have {} dimension".format(fieldname,len(fieldsize))))
    6369                elif len(fieldsize) == 2:
    64                         if   numpy.isnan(fieldsize[0]):
    65                                 if not numpy.size(field,1)==fieldsize[1]:
    66                                         md = md.checkmessage(options.getfieldvalue('message',\
    67                                                 "field '%s' should have %d columns" % (fieldname,fieldsize[1])))
    68                         elif numpy.isnan(fieldsize[1]):
    69                                 if not numpy.size(field,0)==fieldsize[0]:
    70                                         md = md.checkmessage(options.getfieldvalue('message',\
    71                                                 "field '%s' should have %d lines" % (fieldname,fieldsize[0])))
    72                         else:
    73                                 if (not numpy.size(field,0)==fieldsize[0]) or (not numpy.size(field,1)==fieldsize[1]):
    74                                         md = md.checkmessage(options.getfieldvalue('message',\
    75                                                 "field '%s' size should be %d x %d" % (fieldname,fieldsize[0],fieldsize[1])))
    76        
     70                        if   np.isnan(fieldsize[0]):
     71                                if not np.size(field,1)==fieldsize[1]:
     72                                        md = md.checkmessage(options.getfieldvalue('message',"field '%s' should have %d columns" % (fieldname,fieldsize[1])))
     73                        elif np.isnan(fieldsize[1]):
     74                                if not np.size(field,0)==fieldsize[0]:
     75                                        md = md.checkmessage(options.getfieldvalue('message',"field '%s' should have %d lines" % (fieldname,fieldsize[0])))
     76                        elif fieldsize[1]==1:
     77                                if (not np.size(field,0)==fieldsize[0]):
     78                                        md = md.checkmessage(options.getfieldvalue('message',"field '%s' size should be %d x %d" % (fieldname,fieldsize[0],fieldsize[1])))
     79                        else:
     80                                if (not np.size(field,0)==fieldsize[0]) or (not np.size(field,1)==fieldsize[1]):
     81                                        md = md.checkmessage(options.getfieldvalue('message',"field '%s' size should be %d x %d" % (fieldname,fieldsize[0],fieldsize[1])))
     82
    7783        #Check numel
    7884        if options.exist('numel'):
    7985                fieldnumel=options.getfieldvalue('numel')
    80                 if numpy.size(field) not in fieldnumel:
     86                if (type(fieldnumel) == int and np.size(field) != fieldnumel) or (type(fieldnumel) == list and np.size(field) not in fieldnumel):
    8187                        if   len(fieldnumel)==1:
    8288                                md = md.checkmessage(options.getfieldvalue('message',\
     
    9197        #check NaN
    9298        if options.getfieldvalue('NaN',0):
    93                 if numpy.any(numpy.isnan(field)):
     99                if np.any(np.isnan(field)):
    94100                        md = md.checkmessage(options.getfieldvalue('message',\
    95101                                "NaN values found in field '%s'" % fieldname))
     102
    96103
    97104        #check Inf
    98105        if options.getfieldvalue('Inf',0):
    99                 if numpy.any(numpy.isinf(field)):
     106                if np.any(np.isinf(field)):
    100107                        md = md.checkmessage(options.getfieldvalue('message',\
    101108                                "Inf values found in field '%s'" % fieldname))
     109
    102110
    103111        #check cell
     
    123131        #check greater
    124132        if options.exist('>='):
    125                 lowerbound=options.getfieldvalue('>=')
    126                 if numpy.any(field<lowerbound):
    127                         md = md.checkmessage(options.getfieldvalue('message',\
    128                                 "field '%s' should have values above %d" % (fieldname,lowerbound)))
     133                lowerbound = options.getfieldvalue('>=')
     134                if np.size(lowerbound)>1: #checking elementwise
     135                        if any(field<upperbound):
     136                                md = md.checkmessage(options.getfieldvalue('message',"field '%s' should have values below %d" % (fieldname,upperbound)))
     137                else:
     138                        minval=np.nanmin(field)
     139                        if options.getfieldvalue('timeseries',0):
     140                                minval=np.nanmin(field[:-1])
     141                        elif options.getfieldvalue('singletimeseries',0):
     142                                if np.size(field)==1: #some singletimeseries are just one value
     143                                        minval=field
     144                                else:
     145                                        minval=np.nanmin(field[0])
     146
     147                        if minval<lowerbound:
     148                                md = md.checkmessage(options.getfieldvalue('message',"field '%s' should have values above %d" % (fieldname,lowerbound)))
     149
    129150        if options.exist('>'):
    130151                lowerbound=options.getfieldvalue('>')
    131                 if numpy.any(field<=lowerbound):
    132                         md = md.checkmessage(options.getfieldvalue('message',\
    133                                 "field '%s' should have values above %d" % (fieldname,lowerbound)))
     152                if np.size(lowerbound)>1: #checking elementwise
     153                        if any(field<=upperbound):
     154                                md = md.checkmessage(options.getfieldvalue('message',"field '%s' should have values below %d" % (fieldname,upperbound)))
     155                else:
     156                        minval=np.nanmin(field)
     157                        if options.getfieldvalue('timeseries',0) :
     158                                minval=np.nanmin(field[:-1])
     159                        elif options.getfieldvalue('singletimeseries',0):
     160                                if np.size(field)==1: #some singletimeseries are just one value
     161                                        minval=field
     162                                else:
     163                                        minval=np.nanmin(field[0])
     164
     165                        if minval<=lowerbound:
     166                                md = md.checkmessage(options.getfieldvalue('message',"field '%s' should have values above %d" % (fieldname,lowerbound)))
    134167
    135168        #check smaller
    136169        if options.exist('<='):
    137170                upperbound=options.getfieldvalue('<=')
    138                 if numpy.any(field>upperbound):
    139                         md = md.checkmessage(options.getfieldvalue('message',\
    140                                 "field '%s' should have values below %d" % (fieldname,upperbound)))
     171                if np.size(upperbound)>1: #checking elementwise
     172                        if any(field>upperbound):
     173                                md = md.checkmessage(options.getfieldvalue('message',"field '%s' should have values below %d" % (fieldname,upperbound)))
     174                else:
     175                        maxval=np.nanmax(field)
     176                        if options.getfieldvalue('timeseries',0):
     177                                maxval=np.nanmax(field[:-1])
     178                        elif  options.getfieldvalue('singletimeseries',0):
     179                                if np.size(field)==1: #some singletimeseries are just one value
     180                                        maxval=field
     181                                else:
     182                                        maxval=np.nanmax(field[0])
     183                        if maxval>upperbound:
     184                                md = md.checkmessage(options.getfieldvalue('message',"field '%s' should have values below %d" % (fieldname,upperbound)))
     185
    141186        if options.exist('<'):
    142187                upperbound=options.getfieldvalue('<')
    143                 if numpy.any(field>=upperbound):
    144                         md = md.checkmessage(options.getfieldvalue('message',\
    145                                 "field '%s' should have values below %d" % (fieldname,upperbound)))
     188                if np.size(upperbound)>1: #checking elementwise
     189                        if any(field>=upperbound):
     190                                md = md.checkmessage(options.getfieldvalue('message',"field '%s' should have values below %d" % (fieldname,upperbound)))
     191
     192                else:
     193                        maxval=np.nanmax(field)
     194                        if options.getfieldvalue('timeseries',0):
     195                                maxval=np.nanmax(field[:-1])
     196                        elif options.getfieldvalue('singletimeseries',0):
     197                                if np.size(field)==1: #some singletimeseries are just one value
     198                                        maxval=field.copy()
     199                                else:
     200                                        maxval=np.nanmax(field[0])
     201
     202                                if maxval>=upperbound:
     203                                        md = md.checkmessage(options.getfieldvalue('message',"field '%s' should have values below %d" % (fieldname,upperbound)))
    146204
    147205        #check file
     
    158216        #Check forcings (size and times)
    159217        if options.getfieldvalue('timeseries',0):
    160                 if   numpy.size(field,0)==md.mesh.numberofvertices:
    161                         if numpy.ndim(field)>1 and not numpy.size(field,1)==1:
     218                if np.size(field,0)==md.mesh.numberofvertices or np.size(field,0)==md.mesh.numberofelements:
     219                        if np.ndim(field)>1 and not np.size(field,1)==1:
    162220                                md = md.checkmessage(options.getfieldvalue('message',\
    163221                                        "field '%s' should have only one column as there are md.mesh.numberofvertices lines" % fieldname))
    164                 elif numpy.size(field,0)==md.mesh.numberofvertices+1 or numpy.size(field,0)==2:
    165                         if not all(field[-1,:]==numpy.sort(field[-1,:])):
     222                elif np.size(field,0)==md.mesh.numberofvertices+1 or np.size(field,0)==md.mesh.numberofelements+1:
     223                        if np.ndim(field) > 1 and not all(field[-1,:]==np.sort(field[-1,:])):
    166224                                md = md.checkmessage(options.getfieldvalue('message',\
    167225                                        "field '%s' columns should be sorted chronologically" % fieldname))
    168                         if any(field[-1,0:-1]==field[-1,1:]):
     226                        if np.ndim(field) > 1 and any(field[-1,0:-1]==field[-1,1:]):
    169227                                md = md.checkmessage(options.getfieldvalue('message',\
    170228                                        "field '%s' columns must not contain duplicate timesteps" % fieldname))
     
    175233        #Check single value forcings (size and times)
    176234        if options.getfieldvalue('singletimeseries',0):
    177                 if numpy.size(field,0)==2:
    178                         if not all(field[-1,:]==numpy.sort(field[-1,:])):
     235                if np.size(field,0)==2:
     236                        if not all(field[-1,:]==np.sort(field[-1,:])):
    179237                                md = md.checkmessage(options.getfieldvalue('message',\
    180238                                                "field '%s' columns should be sorted chronologically" % fieldname))
     
    182240                                md = md.checkmessage(options.getfieldvalue('message',\
    183241                                                "field '%s' columns must not contain duplicate timesteps" % fieldname))
    184                 else:
    185                                 md = md.checkmessage(options.getfieldvalue('message',\
    186                                 "field '%s' should have 2 lines" % fieldname))
     242                elif np.size(field,0) == 1:
     243                        if np.ndim(field) > 1 and not np.size(field,1) == 1:
     244                                md = md.checkmessage(options.getfieldvalue('message',\
     245                                "field '%s' should be either a scalar or have 2 lines" % fieldname))
     246                else:
     247                                md = md.checkmessage(options.getfieldvalue('message',\
     248                                "field '%s' should have 2 lines or be a scalar" % fieldname))
    187249
    188250        return md
    189 
  • issm/trunk-jpl/src/py3/consistency/ismodelselfconsistent.py

    r19895 r23670  
    1 from EnumDefinitions import *
    2 from EnumToString import EnumToString
    3 
    41def AnalysisConfiguration(solutiontype): #{{{
    52        """
     
    107        """
    118
    12         if   solutiontype == StressbalanceSolutionEnum():
    13                 analyses=[StressbalanceAnalysisEnum(),StressbalanceVerticalAnalysisEnum(),StressbalanceSIAAnalysisEnum(),L2ProjectionBaseAnalysisEnum()]
     9        if   solutiontype == 'StressbalanceSolution':
     10                analyses=['StressbalanceAnalysis','StressbalanceVerticalAnalysis','StressbalanceSIAAnalysis','L2ProjectionBaseAnalysis']
    1411
    15         elif solutiontype == SteadystateSolutionEnum():
    16                 analyses=[StressbalanceAnalysisEnum(),StressbalanceVerticalAnalysisEnum(),StressbalanceSIAAnalysisEnum(),L2ProjectionBaseAnalysisEnum(),ThermalAnalysisEnum(),MeltingAnalysisEnum()]
     12        elif solutiontype == 'SteadystateSolution':
     13                analyses=['StressbalanceAnalysis','StressbalanceVerticalAnalysis','StressbalanceSIAAnalysis','L2ProjectionBaseAnalysis','ThermalAnalysis','MeltingAnalysis','EnthalpyAnalysis']
    1714
    18         elif solutiontype == ThermalSolutionEnum():
    19                 analyses=[EnthalpyAnalysisEnum(),ThermalAnalysisEnum(),MeltingAnalysisEnum()]
     15        elif solutiontype == 'ThermalSolution':
     16                analyses=['EnthalpyAnalysis','ThermalAnalysis','MeltingAnalysis']
    2017
    21         elif solutiontype == MasstransportSolutionEnum():
    22                 analyses=[MasstransportAnalysisEnum()]
     18        elif solutiontype == 'MasstransportSolution':
     19                analyses=['MasstransportAnalysis']
    2320
    24         elif solutiontype == BalancethicknessSolutionEnum():
    25                 analyses=[BalancethicknessAnalysisEnum()]
     21        elif solutiontype == 'BalancethicknessSolution':
     22                analyses=['BalancethicknessAnalysis']
    2623
    27         elif solutiontype == SurfaceSlopeSolutionEnum():
    28                 analyses=[L2ProjectionBaseAnalysisEnum()]
     24        elif solutiontype == 'SurfaceSlopeSolution':
     25                analyses=['L2ProjectionBaseAnalysis']
    2926
    30         elif solutiontype == BalancevelocitySolutionEnum():
    31                 analyses=[BalancevelocityAnalysisEnum()]
     27        elif solutiontype == 'BalancevelocitySolution':
     28                analyses=['BalancevelocityAnalysis']
    3229
    33         elif solutiontype == BedSlopeSolutionEnum():
    34                 analyses=[L2ProjectionBaseAnalysisEnum()]
     30        elif solutiontype == 'BedSlopeSolution':
     31                analyses=['L2ProjectionBaseAnalysis']
    3532
    36         elif solutiontype == GiaSolutionEnum():
    37                 analyses=[GiaAnalysisEnum()]
     33        elif solutiontype == 'GiaSolution':
     34                analyses=['GiaIvinsAnalysis']
    3835
    39         elif solutiontype == TransientSolutionEnum():
    40                 analyses=[StressbalanceAnalysisEnum(),StressbalanceVerticalAnalysisEnum(),StressbalanceSIAAnalysisEnum(),L2ProjectionBaseAnalysisEnum(),ThermalAnalysisEnum(),MeltingAnalysisEnum(),EnthalpyAnalysisEnum(),MasstransportAnalysisEnum()]
     36        elif solutiontype == 'LoveSolution':
     37                analyses=['LoveAnalysis']
    4138
    42         elif solutiontype == FlaimSolutionEnum():
    43                 analyses=[FlaimAnalysisEnum()]
     39        elif solutiontype == 'TransientSolution':
     40                analyses=['StressbalanceAnalysis','StressbalanceVerticalAnalysis','StressbalanceSIAAnalysis','L2ProjectionBaseAnalysis','ThermalAnalysis','MeltingAnalysis','EnthalpyAnalysis','MasstransportAnalysis']
    4441
    45         elif solutiontype == HydrologySolutionEnum():
    46                 analyses=[L2ProjectionBaseAnalysisEnum(),HydrologyShreveAnalysisEnum(),HydrologyDCInefficientAnalysisEnum(),HydrologyDCEfficientAnalysisEnum()]
     42        elif solutiontype == 'HydrologySolution':
     43                analyses=['L2ProjectionBaseAnalysis','HydrologyShreveAnalysis','HydrologyDCInefficientAnalysis','HydrologyDCEfficientAnalysis']
    4744
    48         elif DamageEvolutionSolutionEnum():
    49                 analyses=[DamageEvolutionAnalysisEnum()]
     45        elif 'DamageEvolutionSolution':
     46                analyses=['DamageEvolutionAnalysis']
    5047
    5148        else:
    52                 raise TypeError("solution type: '%s' not supported yet!" % EnumToString(solutiontype)[0])
     49                raise TypeError("solution type: '%s' not supported yet!" % solutiontype)
    5350
    5451        return analyses
     
    8481
    8582                #Check consistency of the object
    86                 exec("md.%s.checkconsistency(md,solution,analyses)" % field)
     83                exec("md.{}.checkconsistency(md,solution,analyses)".format(field))
    8784
    8885        #error message if mode is not consistent
  • issm/trunk-jpl/src/py3/contrib/bamg/YamsCall.py

    r19895 r23670  
    2929        #Compute Hessian
    3030        t1=time.time()
    31         print("%s" % '      computing Hessian...')
     31        print(("%s" % '      computing Hessian...'))
    3232        hessian=ComputeHessian(md.mesh.elements,md.mesh.x,md.mesh.y,field,'node')
    3333        t2=time.time()
    34         print("%s%d%s\n" % (' done (',t2-t1,' seconds)'))
     34        print(("%s%d%s\n" % (' done (',t2-t1,' seconds)')))
    3535
    3636        #Compute metric
    3737        t1=time.time()
    38         print("%s" % '      computing metric...')
     38        print(("%s" % '      computing metric...'))
    3939        metric=ComputeMetric(hessian,scale,epsilon,hmin,hmax,numpy.empty(0,int))
    4040        t2=time.time()
    41         print("%s%d%s\n" % (' done (',t2-t1,' seconds)'))
     41        print(("%s%d%s\n" % (' done (',t2-t1,' seconds)')))
    4242
    4343        #write files
    4444        t1=time.time()
    45         print("%s" % '      writing initial mesh files...')
     45        print(("%s" % '      writing initial mesh files...'))
    4646        numpy.savetxt('carre0.met',metric)
    4747
     
    8080        f.close()
    8181        t2=time.time()
    82         print("%s%d%s\n" % (' done (',t2-t1,' seconds)'))
     82        print(("%s%d%s\n" % (' done (',t2-t1,' seconds)')))
    8383
    8484        #call yams
    85         print("%s\n" % '      call Yams...')
     85        print(("%s\n" % '      call Yams...'))
    8686        if   m.ispc():
    8787                #windows
     
    9696        #plug new mesh
    9797        t1=time.time()
    98         print("\n%s" % '      reading final mesh files...')
     98        print(("\n%s" % '      reading final mesh files...'))
    9999        Tria=numpy.loadtxt('carre1.tria',int)
    100100        Coor=numpy.loadtxt('carre1.coor',float)
     
    107107        numberofelements2=md.mesh.numberofelements
    108108        t2=time.time()
    109         print("%s%d%s\n\n" % (' done (',t2-t1,' seconds)'))
     109        print(("%s%d%s\n\n" % (' done (',t2-t1,' seconds)')))
    110110
    111111        #display number of elements
    112         print("\n%s %i" % ('      inital number of elements:',numberofelements1))
    113         print("\n%s %i\n\n" % ('      new    number of elements:',numberofelements2))
     112        print(("\n%s %i" % ('      inital number of elements:',numberofelements1)))
     113        print(("\n%s %i\n\n" % ('      new    number of elements:',numberofelements2)))
    114114
    115115        #clean up:
  • issm/trunk-jpl/src/py3/contrib/netCDF/export_netCDF.py

    r19895 r23670  
    1212        if path.exists(filename):
    1313                print(('File {} allready exist'.format(filename)))
    14                 newname=input('Give a new name or "delete" to replace: ')
     14                newname=eval(input('Give a new name or "delete" to replace: '))
    1515                if newname=='delete':
    1616                        remove(filename)
     
    7272                                        for field in subfields:
    7373                                                if str(field)!='errlog' and str(field)!='outlog' and str(field)!='SolutionType':
    74                                                         print('Treating '+str(group)+'.'+str(supfield)+'.'+str(field))
     74                                                        print(('Treating '+str(group)+'.'+str(supfield)+'.'+str(field)))
    7575                                                        Var=md.results.__dict__[supfield].__dict__[field]
    7676                                                        DimDict=CreateVar(NCData,Var,field,NCgroup,DimDict,False)
     
    8080                       
    8181                        for field in fields:
    82                                 print('Treating ' +str(group)+'.'+str(field))
     82                                print(('Treating ' +str(group)+'.'+str(field)))
    8383                                NCgroup.__setattr__('classtype', md.__dict__[group].__class__.__name__)
    8484                                Var=md.__dict__[group].__dict__[field]
     
    119119                charvar=stringtochar(numpy.array(var))
    120120                print(charvar)
    121                 print(charvar.shape)
     121                print((charvar.shape))
    122122                for elt in range(0,val_dim):
    123123                        try:
     
    152152                                if time!=0:
    153153                                        timevar=md.results.__dict__[supfield].__getitem__(time).__dict__[field]
    154                                         print('Treating results.'+str(supfield)+'.'+str(field)+' for time '+str(time))
     154                                        print(('Treating results.'+str(supfield)+'.'+str(field)+' for time '+str(time)))
    155155                                        vartab=numpy.column_stack((vartab,timevar))
    156                         print(numpy.shape(vartab))
     156                        print((numpy.shape(vartab)))
    157157                        try:
    158158                                ncvar[:,:]=vartab[:,:]
     
    190190                                        DimDict[len(NewDim)]='Dimension'+str(index)
    191191                                        output=output+[str(DimDict[shape[dim]])]
    192                                         print('Defining dimension ' +'Dimension'+str(index))
     192                                        print(('Defining dimension ' +'Dimension'+str(index)))
    193193                elif type(shape[0])==str:#dealling with a dictionnary
    194194                        try:
     
    199199                                DimDict[len(NewDim)]='Dimension'+str(index)
    200200                                output=[str(DimDict[numpy.shape(dict.keys(var))[0]])]+['Dimension6']
    201                                 print('Defining dimension ' +'Dimension'+str(index))
     201                                print(('Defining dimension ' +'Dimension'+str(index)))
    202202                        break
    203203        if istime:
     
    215215                                DimDict[len(NewDim)]='Dimension'+str(index)
    216216                                output=output+[str(DimDict[stringlength])]
    217                                 print('Defining dimension ' +'Dimension'+str(index))
     217                                print(('Defining dimension ' +'Dimension'+str(index)))
    218218        return tuple(output), DimDict
  • issm/trunk-jpl/src/py3/contrib/paraview/exportVTK.py

    r19895 r23670  
    2828        if os.path.exists(filename):
    2929                print(('File {} allready exist'.format(filename)))
    30                 newname=input('Give a new name or "delete" to replace: ')
     30                newname=eval(input('Give a new name or "delete" to replace: '))
    3131                if newname=='delete':
    3232                        filelist = glob.glob(filename+'/*')
  • issm/trunk-jpl/src/py3/coordsystems/ll2xy.py

    r21255 r23670  
    1 import numpy as np
     1import numpy as  np
    22
    33def ll2xy(lat,lon,sgn=-1,central_meridian=0,standard_parallel=71):
  • issm/trunk-jpl/src/py3/coordsystems/xy2ll.py

    r21255 r23670  
    1 import numpy as np
     1import numpy as  np
    22from math import pi
    33
     
    3737                raise Exception('bad usage: type "help(xy2ll)" for details')
    3838
    39         # if x,y passed as lists, convert to numpy arrays
    40         if type(x) != "numpy.ndarray":
     39        # if x,y passed as lists, convert to np.arrays
     40        if type(x) != "np.ndarray":
    4141                x=np.array(x)
    42         if type(y) != "numpy.ndarray":
     42        if type(y) != "np.ndarray":
    4343                y=np.array(y)
    4444
     
    7373        res1 = np.nonzero(rho <= 0.1)[0]
    7474        if len(res1) > 0:
    75                 lat[res1] = 90. * sgn
     75                lat[res1] = pi/2. * sgn
    7676                lon[res1] = 0.0
    7777       
  • issm/trunk-jpl/src/py3/dev/devpath.py

    r19895 r23670  
    44
    55#Recover ISSM_DIR and USERNAME
    6 ISSM_DIR = os.getenv('ISSM_DIRPY3')
     6ISSM_DIR = os.getenv('ISSM_DEV_DIR')
    77USERNAME = os.getenv('USER')
    88JPL_SVN  = os.getenv('JPL_SVN')
    99if(ISSM_DIR==None):
    1010        raise NameError('"ISSM_DIR" environment variable is empty! You should define ISSM_DIR in your .cshrc or .bashrc!')
    11 if(JPL_SVN==None):
    12         warnings.warn('"JPL_SVN" environment variable is empty! add it to your .cshrc or .bashrc if you want to do distant computing')
    1311
    14 #Go through src/m and append any directory that contains a *.py file to PATH 
     12#Go through src/m and append any directory that contains a *.py file to PATH
    1513for root,dirs,files in os.walk(ISSM_DIR+ '/src/py3'):
    1614        if '.svn' in dirs:
     
    2119                                if root not in sys.path:
    2220                                        sys.path.append(root)
    23                                
     21
     22#Also add the Nightly run directory
     23sys.path.append(ISSM_DIR + '/test/NightlyRun')
     24
    2425sys.path.append(ISSM_DIR + '/lib')
    2526sys.path.append(ISSM_DIR + '/src/wrappers/python/.libs')
     
    2930                sys.path.append(JPL_SVN + '/usr/' + USERNAME)
    3031        else:
    31                 raise NameError ('cluster settings should be in, '+ JPL_SVN +'/usr/' + USERNAME)
     32                warnings.warn('cluster settings should be in, '+ JPL_SVN +'/usr/' + USERNAME)
    3233
    3334#Manual imports for commonly used functions
    34 #from plotmodel import plotmodel
     35from runme import runme         #first because plotmodel may fail
     36from plotmodel import plotmodel
    3537
    3638#c = get_ipython().config
     
    4042#c.InteractiveShellApp.exec_lines.append('print "Warning: disable autoreload in startup.py to improve performance." ')
    4143
    42 print("\n  ISSM development path correctly loaded\n\n")
     44print("\n  ISSM development path correctly loaded")
     45print(("Current path is {}\n\n".format(ISSM_DIR)))
  • issm/trunk-jpl/src/py3/dev/issmversion.py

    r19895 r23670  
    1515print(' ')
    1616print('Build date: '+IssmConfig('PACKAGE_BUILD_DATE')[0])
    17 print('Copyright (c) 2009-2015 California Institute of Technology')
     17print('Copyright (c) 2009-2018 California Institute of Technology')
    1818print(' ')
    1919print('    to get started type: issmdoc')
  • issm/trunk-jpl/src/py3/exp/expcoarsen.py

    r21255 r23670  
    11import os.path
    2 import numpy as np
     2import numpy as  np
    33from collections import OrderedDict
    44from expread import expread
  • issm/trunk-jpl/src/py3/exp/expdisp.py

    r21255 r23670  
    11from expread import expread
    2 import numpy as np
     2import numpy as  np
     3from matplotlib.path import Path
     4import matplotlib.patches as patches
    35
    4 def expdisp(domainoutline,ax,linestyle='--k',linewidth=1,unitmultiplier=1.):
     6def expdisp(ax,options):
    57    '''
    68    plot the contents of a domain outline file
    79
    8     This routine reads in a domain outline file and plots all of the x,y contours
     10    This routine reads in an exp file and plots all of the x,y points/lines/patches
    911
    10     'ax' is a handle to the current plot axes, onto which the contours are to be drawn
     12    'ax' is a handle to the current plot axes, onto which we want to plot
    1113
    1214    Usage:
    13         expdisp(domainoutline,ax)
     15        expdisp(ax,options)
    1416
    15     Example:
    16         expdisp('domain.exp',plt.gca(),linestyle='--k',linewidth=2,unitmultiplier=1.e3)
     17    List of options passable to plotmodel:
     18        'expdisp'      : path (or list of paths) to the exp file to be plotted
     19        'explinewidth' : linewidth
     20        'explinestyle' : matplotlib linestyle string
     21        'explinecolor' : matplotlib color string
     22        'expfill'      : (True/False) fill a closed contour
     23        'expfillcolor' : Color for a filled contour, only used if expfill is True
     24        'expfillalpha' : alpha transparency for filled contour
     25
     26    All options should be passed as lists of length len(number of exp files passed)
    1727    '''
    1828
    19     domain=expread(domainoutline)
    20 
    21     for i in range(len(domain)):
    22         if domain[i]['nods']==1:
    23             ax.plot(domain[i]['x']*unitmultiplier,domain[i]['y']*unitmultiplier,'o',mec='k',mfc='r',ms=10)
    24         else:
    25             x=domain[i]['x'].tolist() # since expread returns a string representation of the arrays
    26             y=domain[i]['y'].tolist()
    27             ax.plot(x*unitmultiplier,y*unitmultiplier,linestyle,linewidth=linewidth)
     29    filenames=options.getfieldvalue('expdisp')
     30    linewidth=options.getfieldvalue('explinewidth',[1]*len(filenames))
     31    linestyle=options.getfieldvalue('explinestyle',['-']*len(filenames))
     32    linecolor=options.getfieldvalue('explinecolor',['k']*len(filenames))
     33    fill=options.getfieldvalue('expfill',[0]*len(filenames))
     34    alpha=options.getfieldvalue('expfillalpha',[1]*len(filenames))
     35    facecolor=options.getfieldvalue('expfillcolor',['r']*len(filenames))
     36    unitmultiplier=options.getfieldvalue('unit',1)
     37    for i in range(len(filenames)):
     38        linestylei=linestyle[i]
     39        linecolori=linecolor[i]
     40        linewidthi=linewidth[i]
     41        alphai=alpha[i]
     42        facecolori=facecolor[i]
     43        filenamei=filenames[i]
     44        filli=fill[i]
     45        domain=expread(filenamei)
     46        for j in range(len(domain)):
     47            if domain[j]['nods']==1:
     48                ax.plot(domain[j]['x']*unitmultiplier,domain[j]['y']*unitmultiplier,'o',mec='k',mfc='r',ms=10)
     49            elif filli:
     50                verts=np.column_stack((domain[j]['x'],domain[j]['y']))
     51                codes=[Path.MOVETO] + [Path.LINETO]*(len(domain[j]['x'])-2) + [Path.CLOSEPOLY]
     52                path=Path(verts, codes)
     53                patch=patches.PathPatch(path,facecolor=facecolori,edgecolor=linecolori,alpha=alphai,
     54                        lw=linewidthi)
     55                ax.add_patch(patch)
     56            else:
     57                x=domain[j]['x'].tolist() # since expread returns a string representation of the arrays
     58                y=domain[j]['y'].tolist()
     59                ax.plot(x*unitmultiplier,y*unitmultiplier,ls=linestylei,lw=linewidthi,c=linecolori)
  • issm/trunk-jpl/src/py3/exp/expread.py

    r19895 r23670  
    11import os.path
    2 import numpy
     2import numpy as np
    33from collections import OrderedDict
    44import MatlabFuncs as m
    55
    66def expread(filename):
     7
    78        """
     9
    810        EXPREAD - read a file exp and build a Structure
    911
     
    2325
    2426           See also EXPDOC, EXPWRITEASVERTICES
     27
    2528        """
    26 
    2729        #some checks
    2830        if not os.path.exists(filename):
     
    3133        #initialize number of profile
    3234        contours=[]
    33 
    3435        #open file
    3536        fid=open(filename,'r')
    36 
    3737        #loop over the number of profiles
    3838        while True:
    39 
    4039                #update number of profiles
    4140                contour=OrderedDict()
    42 
    4341                #Get file name
    4442                A=fid.readline()
     
    5048                if not (len(A) == 2 and m.strcmp(A[0],'##') and m.strncmp(A[1],'Name:',5)):
    5149                        break
     50
    5251                if len(A[1])>5:
    5352                        contour['name']=A[1][5:-1]
     
    5958                if not (len(A) == 2 and m.strcmp(A[0],'##') and m.strncmp(A[1],'Icon:',5)):
    6059                        break
    61 
    6260                #Get Info
    6361                A=fid.readline().split()
     
    7270                #Get Info
    7371                A=fid.readline().split()
    74                 if not (len(A) == 5 and m.strcmp(A[0],'#') and m.strcmp(A[1],'X') and m.strcmp(A[2],'pos') \
    75                                                          and m.strcmp(A[3],'Y') and m.strcmp(A[4],'pos')):
     72                if not (len(A) == 5 and m.strcmp(A[0],'#') and m.strcmp(A[1],'X') and m.strcmp(A[2],'pos')
     73                                                and m.strcmp(A[3],'Y') and m.strcmp(A[4],'pos')):
    7674                        break
    77 
    7875                #Get Coordinates
    79                 contour['x']=numpy.empty(contour['nods'])
    80                 contour['y']=numpy.empty(contour['nods'])
     76                contour['x']=np.empty(contour['nods'])
     77                contour['y']=np.empty(contour['nods'])
    8178                for i in range(int(contour['nods'])):
    8279                        A=fid.readline().split()
     
    9390
    9491                contours.append(contour)
    95 
    9692        #close file
    9793        fid.close()
    98 
    9994        return contours
    100 
  • issm/trunk-jpl/src/py3/exp/expwrite.py

    r19895 r23670  
    1 import numpy
     1import numpy as np
    22
    33def expwrite(contours,filename):
     
    2121        fid=open(filename,'w')
    2222        for x,y in zip(contours['x'],contours['y']):
    23                 #if numpy.size(contour['x'])!=numpy.size(contour['y']):
     23                #if np.size(contour['x'])!=np.size(contour['y']):
    2424                if len(x)!=len(y):
    2525                        raise RuntimeError("contours x and y coordinates must be of identical size")
     
    3636                fid.write("%s\n" % '## Icon:0')
    3737                fid.write("%s\n" % '# Points Count Value')
    38                 #fid.write("%i %f\n" % (numpy.size(contour['x']),contour['density']))
    39                 fid.write("%i %f\n" % (numpy.size(x),density))
     38                #fid.write("%i %f\n" % (np.size(contour['x']),contour['density']))
     39                fid.write("%i %f\n" % (np.size(x),density))
    4040                fid.write("%s\n" % '# X pos Y pos')
    4141                #for x,y in zip(contour['x'],contour['y']):
  • issm/trunk-jpl/src/py3/extrusion/DepthAverage.py

    r21255 r23670  
    1 import numpy as np
     1import numpy as  np
    22from project2d import project2d
    33
     
    4646
    4747        if vec2d:
    48                 vector_average=vector_average.reshape(-1,1)
     48                vector_average=vector_average.reshape(-1,)
    4949
    5050        return vector_average
  • issm/trunk-jpl/src/py3/extrusion/project2d.py

    r21255 r23670  
    1 import numpy as np
     1import numpy as  np
    22
    33def project2d(md3d,value,layer):
     
    4545
    4646        if vec2d:
    47                 projection_value=projection_value.reshape(-1,1)
     47                projection_value=projection_value.reshape(-1,)
    4848
    4949        return projection_value
  • issm/trunk-jpl/src/py3/extrusion/project3d.py

    r19895 r23670  
    1 import numpy
     1import numpy as np
    22from pairoptions import pairoptions
    33
    4 def project3d(md,**kwargs):
     4def project3d(md,*args):
    55        """
    66        PROJECT3D - vertically project a vector from 2d mesh
     
    3030
    3131        #retrieve parameters from options.
    32         options      = pairoptions(**kwargs)
     32        options      = pairoptions(*args)
    3333        vector2d     = options.getfieldvalue('vector')       #mandatory
    3434        vectype      = options.getfieldvalue('type')         #mandatory
     
    3737
    3838        vector1d=False
    39         if isinstance(vector2d,numpy.ndarray) and numpy.ndim(vector2d)==1:
     39        if isinstance(vector2d,np.ndarray) and np.ndim(vector2d)==1:
    4040                vector1d=True
    41                 vector2d=vector2d.reshape(-1,1)
     41                vector2d=vector2d.reshape(-1,)
    4242
    43         if isinstance(vector2d,(bool,int,float)) or numpy.size(vector2d)==1:
     43        if isinstance(vector2d,(bool,int,float)) or np.size(vector2d)==1:
    4444                projected_vector=vector2d
    4545
     
    4747
    4848                #Initialize 3d vector
    49                 if vector2d.shape[0]==md.mesh.numberofvertices2d:
    50                         projected_vector=(paddingvalue*numpy.ones((md.mesh.numberofvertices,  numpy.size(vector2d,axis=1)))).astype(vector2d.dtype)
    51                 elif vector2d.shape[0]==md.mesh.numberofvertices2d+1:
    52                         projected_vector=(paddingvalue*numpy.ones((md.mesh.numberofvertices+1,numpy.size(vector2d,axis=1)))).astype(vector2d.dtype)
    53                         projected_vector[-1,:]=vector2d[-1,:]
    54                         vector2d=vector2d[:-1,:]
     49                if np.ndim(vector2d)==1:
     50                        if vector2d.shape[0]==md.mesh.numberofvertices2d:
     51                                projected_vector=(paddingvalue*np.ones((md.mesh.numberofvertices))).astype(vector2d.dtype)
     52                        elif vector2d.shape[0]==md.mesh.numberofvertices2d+1:
     53                                projected_vector=(paddingvalue*np.ones((md.mesh.numberofvertices+1))).astype(vector2d.dtype)
     54                                projected_vector[-1]=vector2d[-1]
     55                                vector2d=vector2d[:-1]
     56                        else:
     57                                raise TypeError("vector length not supported")
     58                        #Fill in
     59                        if layer==0:
     60                                for i in range(md.mesh.numberoflayers):
     61                                        projected_vector[(i*md.mesh.numberofvertices2d):((i+1)*md.mesh.numberofvertices2d)]=vector2d
     62                        else:
     63                                projected_vector[((layer-1)*md.mesh.numberofvertices2d):(layer*md.mesh.numberofvertices2d)]=vector2d
    5564                else:
    56                         raise TypeError("vector length not supported")
     65                        if vector2d.shape[0]==md.mesh.numberofvertices2d:
     66                                projected_vector=(paddingvalue*np.ones((md.mesh.numberofvertices,np.size(vector2d,axis=1)))).astype(vector2d.dtype)
     67                        elif vector2d.shape[0]==md.mesh.numberofvertices2d+1:
     68                                projected_vector=(paddingvalue*np.ones((md.mesh.numberofvertices+1,np.size(vector2d,axis=1)))).astype(vector2d.dtype)
     69                                projected_vector[-1,:]=vector2d[-1,:]
     70                                vector2d=vector2d[:-1,:]
     71                        else:
     72                                raise TypeError("vector length not supported")
     73                        #Fill in
     74                        if layer==0:
     75                                for i in range(md.mesh.numberoflayers):
     76                                        projected_vector[(i*md.mesh.numberofvertices2d):((i+1)*md.mesh.numberofvertices2d),:]=vector2d
     77                        else:
     78                                projected_vector[((layer-1)*md.mesh.numberofvertices2d):(layer*md.mesh.numberofvertices2d),:]=vector2d
    5779
    58                 #Fill in
    59                 if layer==0:
    60                         for i in range(md.mesh.numberoflayers):
    61                                 projected_vector[(i*md.mesh.numberofvertices2d):((i+1)*md.mesh.numberofvertices2d),:]=vector2d
    62                 else:
    63                         projected_vector[((layer-1)*md.mesh.numberofvertices2d):(layer*md.mesh.numberofvertices2d),:]=vector2d
    6480
    6581        elif vectype.lower()=='element':
    6682
    6783                #Initialize 3d vector
    68                 if vector2d.shape[0]==md.mesh.numberofelements2d:
    69                         projected_vector=(paddingvalue*numpy.ones((md.mesh.numberofelements,  numpy.size(vector2d,axis=1)))).astype(vector2d.dtype)
    70                 elif vector2d.shape[0]==md.mesh.numberofelements2d+1:
    71                         projected_vector=(paddingvalue*numpy.ones((md.mesh.numberofelements+1,numpy.size(vector2d,axis=1)))).astype(vector2d.dtype)
    72                         projected_vector[-1,:]=vector2d[-1,:]
    73                         vector2d=vector2d[:-1,:]
     84                if np.ndim(vector2d)==1:
     85                        if vector2d.shape[0]==md.mesh.numberofelements2d:
     86                                projected_vector=(paddingvalue*np.ones((md.mesh.numberofelements))).astype(vector2d.dtype)
     87                        elif vector2d.shape[0]==md.mesh.numberofelements2d+1:
     88                                projected_vector=(paddingvalue*np.ones((md.mesh.numberofelements+1))).astype(vector2d.dtype)
     89                                projected_vector[-1]=vector2d[-1]
     90                                vector2d=vector2d[:-1]
     91                        else:
     92                                raise TypeError("vector length not supported")
     93                        #Fill in
     94                        if layer==0:
     95                                for i in range(md.mesh.numberoflayers-1):
     96                                        projected_vector[(i*md.mesh.numberofelements2d):((i+1)*md.mesh.numberofelements2d)]=vector2d
     97                        else:
     98                                projected_vector[((layer-1)*md.mesh.numberofelements2d):(layer*md.mesh.numberofelements2d)]=vector2d
    7499                else:
    75                         raise TypeError("vector length not supported")
    76 
    77                 #Fill in
    78                 if layer==0:
    79                         for i in range(md.mesh.numberoflayers-1):
    80                                 projected_vector[(i*md.mesh.numberofelements2d):((i+1)*md.mesh.numberofelements2d),:]=vector2d
    81                 else:
    82                         projected_vector[((layer-1)*md.mesh.numberofelements2d):(layer*md.mesh.numberofelements2d),:]=vector2d
     100                        if vector2d.shape[0]==md.mesh.numberofelements2d:
     101                                projected_vector=(paddingvalue*np.ones((md.mesh.numberofelements,  np.size(vector2d,axis=1)))).astype(vector2d.dtype)
     102                        elif vector2d.shape[0]==md.mesh.numberofelements2d+1:
     103                                projected_vector=(paddingvalue*np.ones((md.mesh.numberofelements+1,np.size(vector2d,axis=1)))).astype(vector2d.dtype)
     104                                projected_vector[-1,:]=vector2d[-1,:]
     105                                vector2d=vector2d[:-1,:]
     106                        else:
     107                                raise TypeError("vector length not supported")
     108                        #Fill in
     109                        if layer==0:
     110                                for i in range(md.mesh.numberoflayers-1):
     111                                        projected_vector[(i*md.mesh.numberofelements2d):((i+1)*md.mesh.numberofelements2d),:]=vector2d
     112                        else:
     113                                projected_vector[((layer-1)*md.mesh.numberofelements2d):(layer*md.mesh.numberofelements2d),:]=vector2d
    83114
    84115        else:
  • issm/trunk-jpl/src/py3/geometry/FlagElements.py

    r19895 r23670  
    1 import numpy
     1import numpy as np
    22import os
    33#from basinzoom import basinzoon
     
    2424        if   isinstance(region,str):
    2525                if   not region:
    26                         flag=numpy.zeros(md.mesh.numberofelements,bool)
     26                        flag=np.zeros(md.mesh.numberofelements,bool)
    2727                        invert=0
    2828                elif m.strcmpi(region,'all'):
    29                         flag=numpy.ones(md.mesh.numberofelements,bool)
     29                        flag=np.ones(md.mesh.numberofelements,bool)
    3030                        invert=0
    3131                else:
     
    4444                                xlim,ylim=basinzoom('basin',region)
    4545                                flag_nodes=p.logical_and_n(md.mesh.x<xlim[1],md.mesh.x>xlim[0],md.mesh.y<ylim[1],md.mesh.y>ylim[0])
    46                                 flag=numpy.prod(flag_nodes[md.mesh.elements],axis=1).astype(bool)
     46                                flag=np.prod(flag_nodes[md.mesh.elements],axis=1).astype(bool)
    4747                        else:
    4848                                #ok, flag elements
    49                                 [flag,dum]=ContourToMesh(md.mesh.elements[:,0:3].copy(),md.mesh.x,md.mesh.y,region,'element',1)
     49                                flag=ContourToMesh(md.mesh.elements[:,0:3].copy(),md.mesh.x,md.mesh.y,region,'element',1)
    5050                                flag=flag.astype(bool)
    5151
    5252                if invert:
    53                         flag=numpy.logical_not(flag)
     53                        flag=np.logical_not(flag)
    5454
    55         elif isinstance(region,numpy.ndarray) or isinstance(region,bool):
    56                 if numpy.size(region,0)==md.mesh.numberofelements:
     55        elif isinstance(region,np.ndarray) or isinstance(region,bool):
     56                if np.size(region,0)==md.mesh.numberofelements:
    5757                        flag=region
    58                 elif numpy.size(region,0)==md.mesh.numberofvertices:
    59                         flag=(numpy.sum(region[md.mesh.elements-1]>0,axis=1)==numpy.size(md.mesh.elements,1))
     58                elif np.size(region,0)==md.mesh.numberofvertices:
     59                        flag=(np.sum(region[md.mesh.elements-1]>0,axis=1)==np.size(md.mesh.elements,1))
    6060                else:
    6161                        raise TypeError("Flaglist for region must be of same size as number of elements in model.")
  • issm/trunk-jpl/src/py3/geometry/GetAreas.py

    r19895 r23670  
    1 import numpy
     1import numpy as np
    22
    3 def GetAreas(index,x,y,z=numpy.array([])):
     3def GetAreas(index,x,y,z=np.array([])):
    44        """
    55        GETAREAS - compute areas or volumes of elements
     
    1818
    1919        #get number of elements and number of nodes
    20         nels=numpy.size(index,axis=0)
    21         nods=numpy.size(x)
     20        nels=np.size(index,axis=0)
     21        nods=np.size(x)
    2222
    2323        #some checks
    24         if numpy.size(y)!=nods or (z and numpy.size(z)!=nods):
     24        if np.size(y)!=nods or (z and np.size(z)!=nods):
    2525                raise TypeError("GetAreas error message: x,y and z do not have the same length.")
    26         if numpy.max(index)>nods:
     26        if np.max(index)>nods:
    2727                raise TypeError("GetAreas error message: index should not have values above %d." % nods)
    28         if (not z and numpy.size(index,axis=1)!=3):
     28        if (not z and np.size(index,axis=1)!=3):
    2929                raise TypeError("GetAreas error message: index should have 3 columns for 2d meshes.")
    30         if (z and numpy.size(index,axis=1)!=6):
     30        if (z and np.size(index,axis=1)!=6):
    3131                raise TypeError("GetAreas error message: index should have 6 columns for 3d meshes.")
    3232
    3333        #initialization
    34         areas=numpy.zeros(nels)
     34        areas=np.zeros(nels)
    3535        x1=x[index[:,0]-1]
    3636        x2=x[index[:,1]-1]
     
    4646        else:
    4747                #V=area(triangle)*1/3(z1+z2+z3)
    48                 thickness=numpy.mean(z[index[:,3:6]-1])-numpy.mean(z[index[:,0:3]-1])
     48                thickness=np.mean(z[index[:,3:6]-1])-np.mean(z[index[:,0:3]-1])
    4949                areas=(0.5*((x2-x1)*(y3-y1)-(y2-y1)*(x3-x1)))*thickness
    5050
  • issm/trunk-jpl/src/py3/geometry/SegIntersect.py

    r19895 r23670  
    1 import numpy
     1import numpy as np
    22
    33def SegIntersect(seg1,seg2):
     
    2424        yD=seg2[1,1]
    2525
    26         O2A=numpy.array([xA,yA])-numpy.array([xD/2.+xC/2.,yD/2.+yC/2.])
    27         O2B=numpy.array([xB,yB])-numpy.array([xD/2.+xC/2.,yD/2.+yC/2.])
    28         O1C=numpy.array([xC,yC])-numpy.array([xA/2.+xB/2.,yB/2.+yA/2.])
    29         O1D=numpy.array([xD,yD])-numpy.array([xA/2.+xB/2.,yB/2.+yA/2.])
     26        O2A=np.array([xA,yA])-np.array([xD/2.+xC/2.,yD/2.+yC/2.])
     27        O2B=np.array([xB,yB])-np.array([xD/2.+xC/2.,yD/2.+yC/2.])
     28        O1C=np.array([xC,yC])-np.array([xA/2.+xB/2.,yB/2.+yA/2.])
     29        O1D=np.array([xD,yD])-np.array([xA/2.+xB/2.,yB/2.+yA/2.])
    3030
    31         n1=numpy.array([yA-yB,xB-xA])    #normal vector to segA
    32         n2=numpy.array([yC-yD,xD-xC])    #normal vector to segB
     31        n1=np.array([yA-yB,xB-xA])    #normal vector to segA
     32        n2=np.array([yC-yD,xD-xC])    #normal vector to segB
    3333
    34         test1=numpy.dot(n2,O2A)
    35         test2=numpy.dot(n2,O2B)
     34        test1=np.dot(n2,O2A)
     35        test2=np.dot(n2,O2B)
    3636
    3737        if test1*test2>0:
     
    3939                return bval
    4040
    41         test3=numpy.dot(n1,O1C)
    42         test4=numpy.dot(n1,O1D)
     41        test3=np.dot(n1,O1C)
     42        test4=np.dot(n1,O1D)
    4343
    4444        if test3*test4>0:
     
    4747
    4848        #if colinear
    49         if test1*test2==0 and test3*test4==0 and numpy.linalg.det(numpy.hstack((n1.reshape((-1,1)),n2.reshape(-1,1))))==0:
     49        if test1*test2==0 and test3*test4==0 and np.linalg.det(np.hstack((n1.reshape((-1,)),n2.reshape(-1,))))==0:
    5050
    5151                #projection on the axis O1O2
    52                 O2O1=numpy.array([xA/2.+xB/2.,yB/2.+yA/2.])-numpy.array([xD/2.+xC/2.,yD/2.+yC/2.])
    53                 O1A=numpy.dot(O2O1,(O2A-O2O1))
    54                 O1B=numpy.dot(O2O1,(O2B-O2O1))
    55                 O1C=numpy.dot(O2O1,O1C)
    56                 O1D=numpy.dot(O2O1,O1D)
     52                O2O1=np.array([xA/2.+xB/2.,yB/2.+yA/2.])-np.array([xD/2.+xC/2.,yD/2.+yC/2.])
     53                O1A=np.dot(O2O1,(O2A-O2O1))
     54                O1B=np.dot(O2O1,(O2B-O2O1))
     55                O1C=np.dot(O2O1,O1C)
     56                O1D=np.dot(O2O1,O1D)
    5757
    5858                #test if one point is included in the other segment (->bval=1)
  • issm/trunk-jpl/src/py3/geometry/slope.py

    r21255 r23670  
    1 import numpy as np
     1import numpy as  np
    22from GetNodalFunctionsCoeff import  GetNodalFunctionsCoeff
    33
     
    3434
    3535        summation=np.array([[1],[1],[1]])
    36         sx=np.dot(surf[index-1]*alpha,summation).reshape(-1,)
    37         sy=np.dot(surf[index-1]*beta,summation).reshape(-1,)
     36        sx=np.dot(surf[index-1,0]*alpha,summation).reshape(-1,)
     37        sy=np.dot(surf[index-1,0]*beta,summation).reshape(-1,)
    3838
    3939        s=np.sqrt(sx**2+sy**2)
  • issm/trunk-jpl/src/py3/interp/SectionValues.py

    r21255 r23670  
    11import os
    22from expread import expread
    3 import numpy as np
     3import numpy as  np
    44from project2d import project2d
    55#from InterpFromMesh2d import InterpFromMesh2d
     
    127127
    128128                #Interpolation of data on specified points
    129                 data_interp=InterpFromMeshToMesh3d(md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.z,data,X3,Y3,Z3,np.nan)
     129                data_interp=InterpFromMeshToMesh3d(md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.z,data,X3,Y3,Z3,np.nan)[0]
    130130       
    131131                #build outputs
  • issm/trunk-jpl/src/py3/interp/averaging.py

    r21255 r23670  
    1 import numpy as np
     1import numpy as  np
    22from GetAreas import GetAreas
    3 from scipy.sparse import csc_matrix
    43import MatlabFuncs as m
     4try:
     5        from scipy.sparse import csc_matrix
     6except ImportError:
     7        print("could not import scipy, no averaging capabilities enabled")
    58
    69def averaging(md,data,iterations,layer=0):
  • issm/trunk-jpl/src/py3/interp/holefiller.py

    r21255 r23670  
    1 import numpy as np
     1import numpy as  np
    22from scipy.spatial import cKDTree
    33
  • issm/trunk-jpl/src/py3/interp/interp.py

    r21255 r23670  
    11# module for inperpolating/smoothing data
    2 import numpy as np
     2import numpy as  np
    33from scipy.interpolate import CloughTocher2DInterpolator, Rbf
    44from scipy.spatial import cKDTree
  • issm/trunk-jpl/src/py3/inversions/marshallcostfunctions.py

    r19895 r23670  
    11import copy
    2 from EnumDefinitions import *
    32
    43def marshallcostfunctions(cost_functions):
    54
    6         #copy list first
    7         data=copy.deepcopy(cost_functions)
     5        cfDict={101:'SurfaceAbsVelMisfit',
     6                                        102:'SurfaceRelVelMisfit',
     7                                        103:'SurfaceLogVelMisfit',
     8                                        104:'SurfaceLogVxVyMisfit',
     9                                        105:'SurfaceAverageVelMisfit',
     10                                        201:'ThicknessAbsMisfit',
     11                                        501:'DragCoefficientAbsGradient',
     12                                        502:'RheologyBbarAbsGradient',
     13                                        503:'ThicknessAbsGradient',
     14                                        504:'ThicknessAlongGradient',
     15                                        505:'ThicknessAcrossGradient',}
    816
    9         #convert to  Enums
    10         pos=[i for i,x in enumerate(cost_functions) if x==101];
    11         for i in pos: data[i]=SurfaceAbsVelMisfitEnum()       
    12         pos=[i for i,x in enumerate(cost_functions) if x==102];
    13         for i in pos: data[i]=SurfaceRelVelMisfitEnum()       
    14         pos=[i for i,x in enumerate(cost_functions) if x==103];
    15         for i in pos: data[i]=SurfaceLogVelMisfitEnum()       
    16         pos=[i for i,x in enumerate(cost_functions) if x==104];
    17         for i in pos: data[i]=SurfaceLogVxVyMisfitEnum()       
    18         pos=[i for i,x in enumerate(cost_functions) if x==105];
    19         for i in pos: data[i]=SurfaceAverageVelMisfitEnum()   
    20         pos=[i for i,x in enumerate(cost_functions) if x==201];
    21         for i in pos: data[i]=ThicknessAbsMisfitEnum()         
    22         pos=[i for i,x in enumerate(cost_functions) if x==501];
    23         for i in pos: data[i]=DragCoefficientAbsGradientEnum()
    24         pos=[i for i,x in enumerate(cost_functions) if x==502];
    25         for i in pos: data[i]=RheologyBbarAbsGradientEnum()   
    26         pos=[i for i,x in enumerate(cost_functions) if x==503];
    27         for i in pos: data[i]=ThicknessAbsGradientEnum()       
    28         pos=[i for i,x in enumerate(cost_functions) if x==504];
    29         for i in pos: data[i]=ThicknessAlongGradientEnum()     
    30         pos=[i for i,x in enumerate(cost_functions) if x==505];
    31         for i in pos: data[i]=ThicknessAcrossGradientEnum()   
     17        data=[cfDict[cf] for cf in cost_functions]
     18        # #copy list first
     19        # data=copy.deepcopy(cost_functions)
     20
     21        # #convert to strings
     22        # pos=[i for i,x in enumerate(cost_functions) if x==101];
     23        # for i in pos: data[i]='SurfaceAbsVelMisfit'       
     24        # pos=[i for i,x in enumerate(cost_functions) if x==102];
     25        # for i in pos: data[i]='SurfaceRelVelMisfit'       
     26        # pos=[i for i,x in enumerate(cost_functions) if x==103];
     27        # for i in pos: data[i]='SurfaceLogVelMisfit'       
     28        # pos=[i for i,x in enumerate(cost_functions) if x==104];
     29        # for i in pos: data[i]='SurfaceLogVxVyMisfit'       
     30        # pos=[i for i,x in enumerate(cost_functions) if x==105];
     31        # for i in pos: data[i]='SurfaceAverageVelMisfit'   
     32        # pos=[i for i,x in enumerate(cost_functions) if x==201];
     33        # for i in pos: data[i]='ThicknessAbsMisfit'         
     34        # pos=[i for i,x in enumerate(cost_functions) if x==501];
     35        # for i in pos: data[i]='DragCoefficientAbsGradient'
     36        # pos=[i for i,x in enumerate(cost_functions) if x==502];
     37        # for i in pos: data[i]='RheologyBbarAbsGradient'   
     38        # pos=[i for i,x in enumerate(cost_functions) if x==503];
     39        # for i in pos: data[i]='ThicknessAbsGradient'       
     40        # pos=[i for i,x in enumerate(cost_functions) if x==504];
     41        # for i in pos: data[i]='ThicknessAlongGradient'     
     42        # pos=[i for i,x in enumerate(cost_functions) if x==505];
     43        # for i in pos: data[i]='ThicknessAcrossGradient'   
    3244
    3345        return data
  • issm/trunk-jpl/src/py3/inversions/parametercontroldrag.py

    r21255 r23670  
    2020
    2121        #process options
    22         options=pairoptions(**kwargs)
     22        options=pairoptions(*args)
    2323
    2424        #control type
  • issm/trunk-jpl/src/py3/io/loadmodel.py

    r19895 r23670  
    11from loadvars import loadvars
    22from dbm import whichdb
     3from netCDF4 import Dataset
    34
    45def loadmodel(path):
     
    1718                pass
    1819        else:
    19                 raise IOError("loadmodel error message: file '%s' does not exist" % path)
     20                try:
     21                        NCFile=Dataset(path,mode='r')
     22                        NCFile.close()
     23                        pass
     24                except RuntimeError:
     25                        raise IOError("loadmodel error message: file '%s' does not exist" % path)
     26                #       try:
     27        #recover model on file and name it md
     28        struc=loadvars(path)
     29        name=[key for key in struc.keys()]
     30        if len(name)>1:
     31                raise IOError("loadmodel error message: file '%s' contains several variables. Only one model should be present." % path)
    2032
    21         try:
    22                 #recover model on file and name it md
    23                 struc=loadvars(path)
    24 
    25                 name=[key for key in struc.keys()]
    26                 if len(name)>1:
    27                         raise IOError("loadmodel error message: file '%s' contains several variables. Only one model should be present." % path)
    28 
    29                 md=struc[name[0]]
    30                 return md
    31 
    32         except Exception as me:
    33                 print(me)
    34                 raise IOError("could not load model '%s'" % path)
    35 
     33        md=struc[name[0]]
     34        return md
  • issm/trunk-jpl/src/py3/io/loadvars.py

    r19895 r23670  
    11import shelve
    22import os.path
     3import numpy as  np
     4from netCDF4 import Dataset
     5from netCDF4 import chartostring
     6from re import findall
     7from os import path
     8from collections import OrderedDict
    39from dbm import whichdb
     10from model import *
    411
    512def loadvars(*args):
     
    5158        if whichdb(filename):
    5259                print("Loading variables from file '%s'." % filename)
    53         else:
    54                 raise IOError("File '%s' not found." % filename)
    55 
    56         my_shelf = shelve.open(filename,'r') # 'r' for read-only
    57 
    58         if nvdict:
    59                 for name in nvdict.keys():
    60                         try:
     60
     61                my_shelf = shelve.open(filename,'r') # 'r' for read-only
     62                if nvdict:
     63                        for name in nvdict.keys():
     64                                try:
     65                                        nvdict[name] = my_shelf[name]
     66                                        print("Variable '%s' loaded." % name)
     67                                except KeyError:
     68                                        value = None
     69                                        print("Variable '%s' not found." % name)
     70
     71                else:
     72                        for name in my_shelf.keys():
    6173                                nvdict[name] = my_shelf[name]
    6274                                print("Variable '%s' loaded." % name)
    63                         except KeyError:
    64                                 value = None
    65                                 print("Variable '%s' not found." % name)
     75
     76                my_shelf.close()
    6677
    6778        else:
    68                 for name in my_shelf.keys():
    69                         nvdict[name] = my_shelf[name]
    70                         print("Variable '%s' loaded." % name)
    71 
    72         my_shelf.close()
    73 
     79                try:
     80                        NCFile=Dataset(filename,mode='r')
     81                        NCFile.close()
     82                except RuntimeError:
     83                        raise IOError("File '%s' not found." % filename)
     84
     85                classtype,classtree=netCDFread(filename)
     86                nvdict['md']=model()
     87                NCFile=Dataset(filename,mode='r')
     88                for mod in dict.keys(classtype):
     89                        if np.size(classtree[mod])>1:
     90                                curclass=NCFile.groups[classtree[mod][0]].groups[classtree[mod][1]]
     91                                if classtype[mod][0]=='list':
     92                                        keylist=[key for key in curclass.groups]
     93                                        try:
     94                                                steplist=[int(key) for key in curclass.groups]
     95                                        except ValueError:
     96                                                steplist=[int(findall(r'\d+',key)[0]) for key in keylist]
     97                                        indexlist=[index*(len(curclass.groups)-1)/max(1,max(steplist)) for index in steplist]
     98                                        listtype=curclass.groups[keylist[0]].classtype
     99                                        if listtype=='dict':
     100                                                nvdict['md'].__dict__[classtree[mod][0]].__dict__[classtree[mod][1]] = [OrderedDict() for i in range(max(1,len(curclass.groups)))]
     101                                        else:
     102                                                nvdict['md'].__dict__[classtree[mod][0]].__dict__[classtree[mod][1]] = [getattr(__import__(listtype),listtype)() for i in range(max(1,len(curclass.groups)))]
     103                                        Tree=nvdict['md'].__dict__[classtree[mod][0]].__dict__[classtree[mod][1]][:]
     104                                else:
     105                                        nvdict['md'].__dict__[classtree[mod][0]].__dict__[classtree[mod][1]] = getattr(classtype[mod][1],classtype[mod][0])()
     106                                        Tree=nvdict['md'].__dict__[classtree[mod][0]].__dict__[classtree[mod][1]]
     107                        else:
     108                                curclass=NCFile.groups[classtree[mod][0]]
     109                                nvdict['md'].__dict__[mod] = getattr(classtype[mod][1],classtype[mod][0])()
     110                                Tree=nvdict['md'].__dict__[classtree[mod][0]]
     111                        #treating groups that are lists
     112                        for i in range(0,max(1,len(curclass.groups))):
     113                                if len(curclass.groups)>0:
     114                                        listclass=curclass.groups[keylist[i]]
     115                                else:
     116                                        listclass=curclass
     117                                for var in listclass.variables:
     118                                        if var not in ['errlog','outlog']:
     119                                                varval=listclass.variables[str(var)]
     120                                                vardim=varval.ndim
     121                                                try:
     122                                                        val_type=str(varval.dtype)
     123                                                except AttributeError:
     124                                                        val_type=type(varval)
     125                                                if vardim==0:
     126                                                        if type(Tree)==list:
     127                                                                t=indexlist[i]
     128                                                                if listtype=='dict':
     129                                                                        Tree[t][str(var)]=varval[0]
     130                                                                else:
     131                                                                        Tree[t].__dict__[str(var)]=varval[0]
     132                                                        else:
     133                                                                if str(varval[0])=='':
     134                                                                        Tree.__dict__[str(var)]=[]
     135                                                                elif varval[0]=='True':
     136                                                                        Tree.__dict__[str(var)]=True
     137                                                                elif varval[0]=='False':
     138                                                                        Tree.__dict__[str(var)]=False
     139                                                                else:
     140                                                                        Tree.__dict__[str(var)]=varval[0]
     141
     142                                                elif vardim==1:
     143                                                        if varval.dtype==str:
     144                                                                if varval.shape[0]==1:
     145                                                                        Tree.__dict__[str(var)]=[str(varval[0]),]
     146                                                                elif 'True' in varval[:] or 'False' in varval[:]:
     147                                                                        Tree.__dict__[str(var)]=np.asarray([V=='True' for V in varval[:]],dtype=bool)
     148                                                                else:
     149                                                                        Tree.__dict__[str(var)]=[str(vallue) for vallue in varval[:]]
     150                                                        else:
     151                                                                if type(Tree)==list:
     152                                                                        t=indexlist[i]
     153                                                                        if listtype=='dict':
     154                                                                                Tree[t][str(var)]=varval[:]
     155                                                                        else:
     156                                                                                Tree[t].__dict__[str(var)]=varval[:]
     157                                                                else:
     158                                                                        try:
     159                                                                                #some thing specifically require a list
     160                                                                                mdtype=type(Tree.__dict__[str(var)])
     161                                                                        except KeyError:
     162                                                                                mdtype=float
     163                                                                        if mdtype==list:
     164                                                                                Tree.__dict__[str(var)]=[mdval for mdval in varval[:]]
     165                                                                        else:
     166                                                                                Tree.__dict__[str(var)]=varval[:]
     167                                                elif vardim==2:
     168                                                        #dealling with dict
     169                                                        if varval.dtype==str: #that is for toolkits wich needs to be ordered
     170                                                                if any(varval[:,0]=='toolkit'):                                                         #toolkit definition have to be first
     171                                                                        Tree.__dict__[str(var)]=OrderedDict([('toolkit', str(varval[np.where(varval[:,0]=='toolkit')[0][0],1]))])
     172
     173                                                                strings1=[str(arg[0]) for arg in varval if arg[0]!='toolkits']
     174                                                                strings2=[str(arg[1]) for arg in varval if arg[0]!='toolkits']
     175                                                                Tree.__dict__[str(var)].update(list(zip(strings1, strings2)))
     176                                                        else:
     177                                                                if type(Tree)==list:
     178                                                                        #t=int(keylist[i][-1])-1
     179                                                                        t=indexlist[i]
     180                                                                        if listtype=='dict':
     181                                                                                Tree[t][str(var)]=varval[:,:]
     182                                                                        else:
     183                                                                                Tree[t].__dict__[str(var)]=varval[:,:]
     184                                                                else:
     185                                                                        Tree.__dict__[str(var)]=varval[:,:]
     186                                                elif vardim==3:
     187                                                        if type(Tree)==list:
     188                                                                t=indexlist[i]
     189                                                                if listtype=='dict':
     190                                                                        Tree[t][str(var)]=varval[:,:,:]
     191                                                                else:
     192                                                                        Tree[t].__dict__[str(var)]=varval[:,:,:]
     193                                                        else:
     194                                                                Tree.__dict__[str(var)]=varval[:,:,:]
     195                                                else:
     196                                                        print('table dimension greater than 3 not implemented yet')
     197                                for attr in listclass.ncattrs():
     198                                        if  attr!='classtype': #classtype is for treatment, don't get it back
     199                                                if type(Tree)==list:
     200                                                        t=indexlist[i]
     201                                                        if listtype=='dict':
     202                                                                Tree[t][str(attr).swapcase()]=str(listclass.getncattr(attr))
     203                                                        else:
     204                                                                Tree[t].__dict__[str(attr).swapcase()]=str(listclass.getncattr(attr))
     205                                                else:
     206                                                        Tree.__dict__[str(attr).swapcase()]=str(listclass.getncattr(attr))
     207                                                        if listclass.getncattr(attr)=='True':
     208                                                                Tree.__dict__[str(attr).swapcase()]=True
     209                                                        elif listclass.getncattr(attr)=='False':
     210                                                                Tree.__dict__[str(attr).swapcase()]=False
     211                NCFile.close()
    74212        if   len(args) >= 2 and isinstance(args[1],str):    # (value)
    75213                value=[nvdict[name] for name in args[1:]]
     
    83221                return nvdict
    84222
     223
     224def netCDFread(filename):
     225        print(('Opening {} for reading '.format(filename)))
     226        NCData=Dataset(filename, 'r')
     227        class_dict={}
     228        class_tree={}
     229
     230        for group in NCData.groups:
     231                if len(NCData.groups[group].groups)>0:
     232                        for subgroup in NCData.groups[group].groups:
     233                                classe=str(group)+'.'+str(subgroup)
     234                                class_dict[classe]=[str(getattr(NCData.groups[group].groups[subgroup],'classtype')),]
     235                                if class_dict[classe][0] not in ['dict','list','cell']:
     236                                        class_dict[classe].append(__import__(class_dict[classe][0]))
     237                                class_tree[classe]=[group,subgroup]
     238                else:
     239                        classe=str(group)
     240                        try:
     241                                class_dict[classe]=[str(getattr(NCData.groups[group],'classtype')),]
     242                                if class_dict[classe][0] not in ['dict','list','cell']:
     243                                        class_dict[classe].append(__import__(class_dict[classe][0]))
     244                                        class_tree[classe]=[group,]
     245                        except AttributeError:
     246                                print(('group {} is empty'.format(group)))
     247        NCData.close()
     248        return class_dict,class_tree
  • issm/trunk-jpl/src/py3/materials/TMeltingPoint.py

    r21255 r23670  
    1 import numpy as np
     1import numpy as  np
    22
    33def TMeltingPoint(reftemp,pressure):
  • issm/trunk-jpl/src/py3/materials/cuffey.py

    r19895 r23670  
    1 import numpy
     1import numpy as np
    22
    33def cuffey(temperature):
     
    66
    77           rigidity (in s^(1/3)Pa) is the flow law parameter in the flow law sigma=B*e(1/3)
    8                 (Cuffey and Paterson, p75). 
     8                (Cuffey and Paterson, p75).
    99           temperature is in Kelvin degrees
    1010
     
    1212              rigidity=cuffey(temperature)
    1313        """
    14        
    15         if numpy.any(temperature<0.):
     14
     15        if np.any(temperature<0.):
    1616                raise RuntimeError("input temperature should be in Kelvin (positive)")
    17        
    18         T = temperature.reshape(-1,)-273.15
    1917
    20         rigidity=numpy.zeros_like(T)
    21         pos=numpy.nonzero(T<=-45)
    22         rigidity[pos]=10**8*(-0.000396645116301*(T[pos]+50)**3+ 0.013345579471334*(T[pos]+50)**2  -0.356868703259105*(T[pos]+50)+7.272363035371383)
    23         pos=numpy.nonzero(numpy.logical_and(-45<=T,T<-40))
    24         rigidity[pos]=10**8*(-0.000396645116301*(T[pos]+45)**3+ 0.007395902726819*(T[pos]+45)**2  -0.253161292268336*(T[pos]+45)+5.772078366321591)
    25         pos=numpy.nonzero(numpy.logical_and(-40<=T,T<-35))
    26         rigidity[pos]=10**8*(0.000408322072669*(T[pos]+40)**3+  0.001446225982305*(T[pos]+40)**2  -0.208950648722716*(T[pos]+40)+4.641588833612773)
    27         pos=numpy.nonzero(numpy.logical_and(-35<=T,T<-30))
    28         rigidity[pos]=10**8*(-0.000423888728124*(T[pos]+35)**3+ 0.007571057072334*(T[pos]+35)**2  -0.163864233449525*(T[pos]+35)+3.684031498640382)
    29         pos=numpy.nonzero(numpy.logical_and(-30<=T,T<-25))
    30         rigidity[pos]=10**8*(0.000147154327025*(T[pos]+30)**3+ 0.001212726150476*(T[pos]+30)**2  -0.119945317335478*(T[pos]+30)+3.001000667185614)
    31         pos=numpy.nonzero(numpy.logical_and(-25<=T,T<-20))
    32         rigidity[pos]=10**8*(-0.000193435838672*(T[pos]+25)**3+ 0.003420041055847*(T[pos]+25)**2  -0.096781481303861*(T[pos]+25)+2.449986525148220)
    33         pos=numpy.nonzero(numpy.logical_and(-20<=T,T<-15))
    34         rigidity[pos]=10**8*(0.000219771255067*(T[pos]+20)**3+  0.000518503475772*(T[pos]+20)**2  -0.077088758645767*(T[pos]+20)+2.027400665191131)
    35         pos=numpy.nonzero(numpy.logical_and(-15<=T,T<-10))
    36         rigidity[pos]=10**8*(-0.000653438900191*(T[pos]+15)**3+ 0.003815072301777*(T[pos]+15)**2  -0.055420879758021*(T[pos]+15)+1.682390865739973)
    37         pos=numpy.nonzero(numpy.logical_and(-10<=T,T<-5))
    38         rigidity[pos]=10**8*(0.000692439419762*(T[pos]+10)**3 -0.005986511201093 *(T[pos]+10)**2 -0.066278074254598*(T[pos]+10)+1.418983411970382)
    39         pos=numpy.nonzero(numpy.logical_and(-5<=T,T<-2))
    40         rigidity[pos]=10**8*(-0.000132282004110*(T[pos]+5)**3 +0.004400080095332*(T[pos]+5)**2    -0.074210229783403*(T[pos]+5)+ 1.024485188140279)
    41         pos=numpy.nonzero(-2<=T)
    42         rigidity[pos]=10**8*(-0.000132282004110*(T[pos]+2)**3 +0.003209542058346*(T[pos]+2)**2    -0.051381363322371*(T[pos]+2)+ 0.837883605537096)
     18        if np.ndim(temperature)==2:
     19                #T = temperature.reshape(-1,)-273.15
     20                T = temperature.flatten()-273.15
     21        elif isinstance(temperature,float) or isinstance(temperature,int):
     22                T = np.array([temperature])-273.15
     23        else:
     24                T = temperature-273.15
     25
     26
     27        rigidity=np.zeros_like(T)
     28        pos=np.nonzero(T<=-45)
     29        if len(pos):
     30                rigidity[pos]=10**8*(-0.000396645116301*(T[pos]+50)**3+ 0.013345579471334*(T[pos]+50)**2  -0.356868703259105*(T[pos]+50)+7.272363035371383)
     31        pos=np.nonzero(np.logical_and(-45<=T,T<-40))
     32        if len(pos):
     33                rigidity[pos]=10**8*(-0.000396645116301*(T[pos]+45)**3+ 0.007395902726819*(T[pos]+45)**2  -0.253161292268336*(T[pos]+45)+5.772078366321591)
     34        pos=np.nonzero(np.logical_and(-40<=T,T<-35))
     35        if len(pos):
     36                rigidity[pos]=10**8*(0.000408322072669*(T[pos]+40)**3+  0.001446225982305*(T[pos]+40)**2  -0.208950648722716*(T[pos]+40)+4.641588833612773)
     37        pos=np.nonzero(np.logical_and(-35<=T,T<-30))
     38        if len(pos):
     39                rigidity[pos]=10**8*(-0.000423888728124*(T[pos]+35)**3+ 0.007571057072334*(T[pos]+35)**2  -0.163864233449525*(T[pos]+35)+3.684031498640382)
     40        pos=np.nonzero(np.logical_and(-30<=T,T<-25))
     41        if len(pos):
     42                rigidity[pos]=10**8*(0.000147154327025*(T[pos]+30)**3+ 0.001212726150476*(T[pos]+30)**2  -0.119945317335478*(T[pos]+30)+3.001000667185614)
     43        pos=np.nonzero(np.logical_and(-25<=T,T<-20))
     44        if len(pos):
     45                rigidity[pos]=10**8*(-0.000193435838672*(T[pos]+25)**3+ 0.003420041055847*(T[pos]+25)**2  -0.096781481303861*(T[pos]+25)+2.449986525148220)
     46        pos=np.nonzero(np.logical_and(-20<=T,T<-15))
     47        if len(pos):
     48                rigidity[pos]=10**8*(0.000219771255067*(T[pos]+20)**3+  0.000518503475772*(T[pos]+20)**2  -0.077088758645767*(T[pos]+20)+2.027400665191131)
     49        pos=np.nonzero(np.logical_and(-15<=T,T<-10))
     50        if len(pos):
     51                rigidity[pos]=10**8*(-0.000653438900191*(T[pos]+15)**3+ 0.003815072301777*(T[pos]+15)**2  -0.055420879758021*(T[pos]+15)+1.682390865739973)
     52        pos=np.nonzero(np.logical_and(-10<=T,T<-5))
     53        if len(pos):
     54                rigidity[pos]=10**8*(0.000692439419762*(T[pos]+10)**3 -0.005986511201093 *(T[pos]+10)**2 -0.066278074254598*(T[pos]+10)+1.418983411970382)
     55        pos=np.nonzero(np.logical_and(-5<=T,T<-2))
     56        if len(pos):
     57                rigidity[pos]=10**8*(-0.000132282004110*(T[pos]+5)**3 +0.004400080095332*(T[pos]+5)**2    -0.074210229783403*(T[pos]+5)+ 1.024485188140279)
     58        pos=np.nonzero(-2<=T)
     59        if len(pos):
     60                rigidity[pos]=10**8*(-0.000132282004110*(T[pos]+2)**3 +0.003209542058346*(T[pos]+2)**2    -0.051381363322371*(T[pos]+2)+ 0.837883605537096)
    4361
    4462        #Now make sure that rigidity is positive
    45         pos=numpy.nonzero(rigidity<0)
    46         rigidity[pos]=1**6 
     63        pos=np.nonzero(rigidity<0)
     64        rigidity[pos]=1**6
    4765
    4866        return rigidity
    49 
  • issm/trunk-jpl/src/py3/materials/paterson.py

    r19895 r23670  
    1 import numpy
     1import numpy as np
    22
    33def paterson(temperature):
     
    1212        """
    1313       
    14         if numpy.any(temperature<0.):
     14        if np.any(temperature<0.):
    1515                raise RuntimeError("input temperature should be in Kelvin (positive)")
    1616
    17         if numpy.ndim(temperature)==2:
     17        if np.ndim(temperature)==2:
    1818                #T = temperature.reshape(-1,)-273.15
    1919                T = temperature.flatten()-273.15
    2020        elif isinstance(temperature,float) or isinstance(temperature,int):
    21                 T = numpy.array([temperature])-273.15
     21                T = np.array([temperature])-273.15
    2222        else:
    2323                T = temperature-273.15
     
    3636        # rigidity=fittedmodel(temperature);
    3737
    38         rigidity=numpy.zeros_like(T)
    39         pos1=numpy.nonzero(T<=-45)[0]
     38        rigidity=np.zeros_like(T)
     39        pos1=np.nonzero(T<=-45)[0]
    4040        if len(pos1):
    4141                rigidity[pos1]=10**8*(-0.000292866376675*(T[pos1]+50)**3+ 0.011672640664130*(T[pos1]+50)**2  -0.325004442485481*(T[pos1]+50)+  6.524779401948101)
    42         pos2=numpy.nonzero(numpy.logical_and(-45<=T,T<-40))[0]
     42        pos2=np.nonzero(np.logical_and(-45<=T,T<-40))[0]
    4343        if len(pos2):
    4444                rigidity[pos2]=10**8*(-0.000292866376675*(T[pos2]+45)**3+ 0.007279645014004*(T[pos2]+45)**2  -0.230243014094813*(T[pos2]+45)+  5.154964909039554)
    45         pos3=numpy.nonzero(numpy.logical_and(-40<=T,T<-35))[0]
     45        pos3=np.nonzero(np.logical_and(-40<=T,T<-35))[0]
    4646        if len(pos3):
    4747                rigidity[pos3]=10**8*(0.000072737147457*(T[pos3]+40)**3+  0.002886649363879*(T[pos3]+40)**2  -0.179411542205399*(T[pos3]+40)+  4.149132666831214)
    48         pos4=numpy.nonzero(numpy.logical_and(-35<=T,T<-30))[0]
     48        pos4=np.nonzero(np.logical_and(-35<=T,T<-30))[0]
    4949        if len(pos4):
    5050                rigidity[pos4]=10**8*(-0.000086144770023*(T[pos4]+35)**3+ 0.003977706575736*(T[pos4]+35)**2  -0.145089762507325*(T[pos4]+35)+  3.333333333333331)
    51         pos5=numpy.nonzero(numpy.logical_and(-30<=T,T<-25))[0]
     51        pos5=np.nonzero(np.logical_and(-30<=T,T<-25))[0]
    5252        if len(pos5):
    5353                rigidity[pos5]=10**8*(-0.000043984685769*(T[pos5]+30)**3+ 0.002685535025386*(T[pos5]+30)**2  -0.111773554501713*(T[pos5]+30)+  2.696559088937191)
    54         pos6=numpy.nonzero(numpy.logical_and(-25<=T,T<-20))[0]
     54        pos6=np.nonzero(np.logical_and(-25<=T,T<-20))[0]
    5555        if len(pos6):
    5656                rigidity[pos6]=10**8*(-0.000029799523463*(T[pos6]+25)**3+ 0.002025764738854*(T[pos6]+25)**2  -0.088217055680511*(T[pos6]+25)+  2.199331606342181)
    57         pos7=numpy.nonzero(numpy.logical_and(-20<=T,T<-15))[0]
     57        pos7=np.nonzero(np.logical_and(-20<=T,T<-15))[0]
    5858        if len(pos7):
    5959                rigidity[pos7]=10**8*(0.000136920904777*(T[pos7]+20)**3+  0.001578771886910*(T[pos7]+20)**2  -0.070194372551690*(T[pos7]+20)+  1.805165505978111)
    60         pos8=numpy.nonzero(numpy.logical_and(-15<=T,T<-10))[0]
     60        pos8=np.nonzero(np.logical_and(-15<=T,T<-10))[0]
    6161        if len(pos8):
    6262                rigidity[pos8]=10**8*(-0.000899763781026*(T[pos8]+15)**3+ 0.003632585458564*(T[pos8]+15)**2  -0.044137585824322*(T[pos8]+15)+  1.510778053489523)
    63         pos9=numpy.nonzero(numpy.logical_and(-10<=T,T<-5))[0]
     63        pos9=np.nonzero(np.logical_and(-10<=T,T<-5))[0]
    6464        if len(pos9):
    6565                rigidity[pos9]=10**8*(0.001676964325070*(T[pos9]+10)**3-  0.009863871256831*(T[pos9]+10)**2  -0.075294014815659*(T[pos9]+10)+  1.268434288203714)
    66         pos10=numpy.nonzero(numpy.logical_and(-5<=T,T<-2))[0]
     66        pos10=np.nonzero(np.logical_and(-5<=T,T<-2))[0]
    6767        if len(pos10):
    6868                rigidity[pos10]=10**8*(-0.003748937622487*(T[pos10]+5)**3+0.015290593619213*(T[pos10]+5)**2  -0.048160403003748*(T[pos10]+5)+  0.854987973338348)
    69         pos11=numpy.nonzero(-2<=T)[0]
     69        pos11=np.nonzero(-2<=T)[0]
    7070        if len(pos11):
    7171                rigidity[pos11]=10**8*(-0.003748937622488*(T[pos11]+2)**3-0.018449844983174*(T[pos11]+2)**2  -0.057638157095631*(T[pos11]+2)+  0.746900791092860)
    7272
    7373        #Now make sure that rigidity is positive
    74         pos=numpy.nonzero(rigidity<0)[0]
     74        pos=np.nonzero(rigidity<0)[0]
    7575        if len(pos):
    7676                rigidity[pos]=1.e6
  • issm/trunk-jpl/src/py3/mech/analyticaldamage.py

    r21255 r23670  
    1 import numpy as np
     1import numpy as  np
    22from averaging import averaging
    33#from plotmodel import plotmodel
  • issm/trunk-jpl/src/py3/mech/backstressfrominversion.py

    r21255 r23670  
    1 import numpy as np
     1import numpy as  np
    22from averaging import averaging
    33from thomasparams import thomasparams
  • issm/trunk-jpl/src/py3/mech/calcbackstress.py

    r21255 r23670  
    1 import numpy as np
     1import numpy as  np
    22from averaging import averaging
    33from thomasparams import thomasparams
  • issm/trunk-jpl/src/py3/mech/damagefrominversion.py

    r21255 r23670  
    1 import numpy as np
     1import numpy as  np
    22
    33def damagefrominversion(md):
  • issm/trunk-jpl/src/py3/mech/mechanicalproperties.py

    r21255 r23670  
    1 import numpy as np
     1import numpy as  np
    22from GetNodalFunctionsCoeff import GetNodalFunctionsCoeff
    33from results import results
     
    109109                #eigenvalues and vectors for stress
    110110                value,directions=np.linalg.eig(stress);
    111                 idx=abs(value).argsort()[::-1] # sort in descending order
     111                idx=value.argsort()[::-1] # sort in descending algebraic (not absolute) order
    112112                value=value[idx]
    113113                directions=directions[:,idx]
     
    117117                #eigenvalues and vectors for strain
    118118                value,directions=np.linalg.eig(strain);
    119                 idx=abs(value).argsort()[::-1] # sort in descending order
     119                idx=value.argsort()[::-1] # sort in descending order
    120120                value=value[idx]
    121121                directions=directions[:,idx]
     
    125125        ##plug onto the model
    126126        ##NB: Matlab sorts the eigen value in increasing order, we want the reverse
    127         stress=results()
    128         stress.xx=tau_xx
    129         stress.yy=tau_yy
    130         stress.xy=tau_xy
    131         stress.principalvalue1=valuesstress[:,0]
    132         stress.principalaxis1=directionsstress[:,0:2]
    133         stress.principalvalue2=valuesstress[:,1]
    134         stress.principalaxis2=directionsstress[:,2:4]
    135         stress.effectivevalue=1./np.sqrt(2.)*np.sqrt(stress.xx**2+stress.yy**2+2.*stress.xy**2)
    136         md.results.stress=stress
    137127       
    138128        strainrate=results()
  • issm/trunk-jpl/src/py3/mech/robintemperature.py

    r21255 r23670  
    1 import numpy as np
     1import numpy as  np
    22from scipy.special import erf
    33
  • issm/trunk-jpl/src/py3/mech/steadystateiceshelftemp.py

    r21255 r23670  
    1 import numpy as np
     1import numpy as  np
    22
    33def steadystateiceshelftemp(md,surfacetemp,basaltemp):
     
    1818      temperature=steadystateiceshelftemp(md,surfacetemp,basaltemp)
    1919        """
    20 
    2120        if len(md.geometry.thickness)!=md.mesh.numberofvertices:
    2221                raise ValueError('steadystateiceshelftemp error message: thickness should have a length of ' + md.mesh.numberofvertices)
  • issm/trunk-jpl/src/py3/mech/thomasparams.py

    r21255 r23670  
    1 import numpy as np
     1import numpy as  np
    22from averaging import averaging
    33
  • issm/trunk-jpl/src/py3/mesh/ComputeHessian.py

    r19895 r23670  
    1 import numpy
     1import numpy as np
    22from GetNodalFunctionsCoeff import GetNodalFunctionsCoeff
    33from GetAreas import GetAreas
     
    2020
    2121        #some variables
    22         numberofnodes=numpy.size(x)
    23         numberofelements=numpy.size(index,axis=0)
     22        numberofnodes=np.size(x)
     23        numberofelements=np.size(index,axis=0)
    2424
    2525        #some checks
    26         if numpy.size(field)!=numberofnodes and numpy.size(field)!=numberofelements:
     26        if np.size(field)!=numberofnodes and np.size(field)!=numberofelements:
    2727                raise TypeError("ComputeHessian error message: the given field size not supported yet")
    2828        if not m.strcmpi(type,'node') and not m.strcmpi(type,'element'):
     
    3333        linesize=3*numberofelements
    3434
    35         #get areas and nodal functions coefficients N(x,y)=alpha x + beta y + gamma 
     35        #get areas and nodal functions coefficients N(x,y)=alpha x + beta y + gamma
    3636        [alpha,beta,dum]=GetNodalFunctionsCoeff(index,x,y)
    3737        areas=GetAreas(index,x,y)
    3838
    3939        #compute weights that hold the volume of all the element holding the node i
    40         weights=m.sparse(line,numpy.ones((linesize,1)),numpy.tile(areas.reshape(-1,1),(3,1)),numberofnodes,1)
     40        weights=m.sparse(line,np.ones((linesize,1),dtype=int),np.tile(areas,(3,1)),numberofnodes,1)
    4141
    4242        #compute field on nodes if on elements
    43         if numpy.size(field,axis=0)==numberofelements:
    44                 field=m.sparse(line,numpy.ones((linesize,1)),numpy.tile(areas*field,(3,1)),numberofnodes,1)/weights
     43        if np.size(field,axis=0)==numberofelements:
     44                field=m.sparse(line,np.ones((linesize,1),dtype=int),np.tile(areas*field,(3,1)),numberofnodes,1)/weights
    4545
    4646        #Compute gradient for each element
    47         grad_elx=numpy.sum(field[index-1,0]*alpha,axis=1)
    48         grad_ely=numpy.sum(field[index-1,0]*beta,axis=1)
     47        grad_elx=np.sum(field[index-1]*alpha,axis=1)
     48        grad_ely=np.sum(field[index-1]*beta,axis=1)
    4949
    5050        #Compute gradient for each node (average of the elements around)
    51         gradx=m.sparse(line,numpy.ones((linesize,1)),numpy.tile((areas*grad_elx).reshape(-1,1),(3,1)),numberofnodes,1)
    52         grady=m.sparse(line,numpy.ones((linesize,1)),numpy.tile((areas*grad_ely).reshape(-1,1),(3,1)),numberofnodes,1)
     51        gradx=m.sparse(line,np.ones((linesize,1),dtype=int),np.tile((areas*grad_elx),(3,1)),numberofnodes,1)
     52        grady=m.sparse(line,np.ones((linesize,1),dtype=int),np.tile((areas*grad_ely),(3,1)),numberofnodes,1)
    5353        gradx=gradx/weights
    5454        grady=grady/weights
    5555
    5656        #Compute hessian for each element
    57         hessian=numpy.hstack((numpy.sum(gradx[index-1,0]*alpha,axis=1).reshape(-1,1),numpy.sum(grady[index-1,0]*alpha,axis=1).reshape(-1,1),numpy.sum(grady[index-1,0]*beta,axis=1).reshape(-1,1)))
     57        hessian=np.vstack((np.sum(gradx[index-1,0]*alpha,axis=1),np.sum(grady[index-1,0]*alpha,axis=1),np.sum(grady[index-1,0]*beta,axis=1))).T
    5858
    5959        if m.strcmpi(type,'node'):
    6060                #Compute Hessian on the nodes (average of the elements around)
    61                 hessian=numpy.hstack((m.sparse(line,numpy.ones((linesize,1)),numpy.tile((areas*hessian[:,0]).reshape(-1,1),(3,1)),numberofnodes,1)/weights, \
    62                         m.sparse(line,numpy.ones((linesize,1)),numpy.tile((areas*hessian[:,1]).reshape(-1,1),(3,1)),numberofnodes,1)/weights, \
    63                         m.sparse(line,numpy.ones((linesize,1)),numpy.tile((areas*hessian[:,2]).reshape(-1,1),(3,1)),numberofnodes,1)/weights ))
     61                hessian=np.hstack((m.sparse(line,np.ones((linesize,1),dtype=int),np.tile((areas*hessian[:,0]),(3,1)),numberofnodes,1)/weights,
     62                                                                                         m.sparse(line,np.ones((linesize,1),dtype=int),np.tile((areas*hessian[:,1]),(3,1)),numberofnodes,1)/weights,
     63                                                                                         m.sparse(line,np.ones((linesize,1),dtype=int),np.tile((areas*hessian[:,2]),(3,1)),numberofnodes,1)/weights ))
    6464
    6565        return hessian
    66 
  • issm/trunk-jpl/src/py3/mesh/ComputeMetric.py

    r19895 r23670  
    1 import numpy
     1import numpy as np
    22
    33def ComputeMetric(hessian,scale,epsilon,hmin,hmax,pos):
     
    1717        b=hessian[:,1]
    1818        d=hessian[:,2]
    19         lambda1=0.5*((a+d)+numpy.sqrt(4.*b**2+(a-d)**2))
    20         lambda2=0.5*((a+d)-numpy.sqrt(4.*b**2+(a-d)**2))
    21         pos1=numpy.nonzero(lambda1==0.)[0]
    22         pos2=numpy.nonzero(lambda2==0.)[0]
    23         pos3=numpy.nonzero(numpy.logical_and(b==0.,lambda1==lambda2))[0]
     19        lambda1=0.5*((a+d)+np.sqrt(4.*b**2+(a-d)**2))
     20        lambda2=0.5*((a+d)-np.sqrt(4.*b**2+(a-d)**2))
     21        pos1=np.nonzero(lambda1==0.)[0]
     22        pos2=np.nonzero(lambda2==0.)[0]
     23        pos3=np.nonzero(np.logical_and(b==0.,lambda1==lambda2))[0]
    2424
    2525        #Modify the eigen values to control the shape of the elements
    26         lambda1=numpy.minimum(numpy.maximum(numpy.abs(lambda1)*scale/epsilon,1./hmax**2),1./hmin**2)
    27         lambda2=numpy.minimum(numpy.maximum(numpy.abs(lambda2)*scale/epsilon,1./hmax**2),1./hmin**2)
     26        lambda1=np.minimum(np.maximum(np.abs(lambda1)*scale/epsilon,1./hmax**2),1./hmin**2)
     27        lambda2=np.minimum(np.maximum(np.abs(lambda2)*scale/epsilon,1./hmax**2),1./hmin**2)
    2828
    2929        #compute eigen vectors
    30         norm1=numpy.sqrt(8.*b**2+2.*(d-a)**2+2.*(d-a)*numpy.sqrt((a-d)**2+4.*b**2))
     30        norm1=np.sqrt(8.*b**2+2.*(d-a)**2+2.*(d-a)*np.sqrt((a-d)**2+4.*b**2))
    3131        v1x=2.*b/norm1
    32         v1y=((d-a)+numpy.sqrt((a-d)**2+4.*b**2))/norm1
    33         norm2=numpy.sqrt(8.*b**2+2.*(d-a)**2-2.*(d-a)*numpy.sqrt((a-d)**2+4.*b**2))
     32        v1y=((d-a)+np.sqrt((a-d)**2+4.*b**2))/norm1
     33        norm2=np.sqrt(8.*b**2+2.*(d-a)**2-2.*(d-a)*np.sqrt((a-d)**2+4.*b**2))
    3434        v2x=2.*b/norm2
    35         v2y=((d-a)-numpy.sqrt((a-d)**2+4.*b**2))/norm2
     35        v2y=((d-a)-np.sqrt((a-d)**2+4.*b**2))/norm2
    3636
    3737        v1x[pos3]=1.
     
    4141
    4242        #Compute new metric (for each node M=V*Lambda*V^-1)
    43         metric=numpy.hstack((((v1x*v2y-v1y*v2x)**(-1)*( lambda1*v2y*v1x-lambda2*v1y*v2x)).reshape(-1,1), \
    44                                  ((v1x*v2y-v1y*v2x)**(-1)*( lambda1*v1y*v2y-lambda2*v1y*v2y)).reshape(-1,1), \
    45                                  ((v1x*v2y-v1y*v2x)**(-1)*(-lambda1*v2x*v1y+lambda2*v1x*v2y)).reshape(-1,1)))
     43        metric=np.vstack((((v1x*v2y-v1y*v2x)**(-1)*( lambda1*v2y*v1x-lambda2*v1y*v2x)).reshape(-1,),
     44                                                                                ((v1x*v2y-v1y*v2x)**(-1)*( lambda1*v1y*v2y-lambda2*v1y*v2y)).reshape(-1,),
     45                                                                                ((v1x*v2y-v1y*v2x)**(-1)*(-lambda1*v2x*v1y+lambda2*v1x*v2y)).reshape(-1,))).T
    4646
    4747        #some corrections for 0 eigen values
    48         metric[pos1,:]=numpy.tile(numpy.array([[1./hmax**2,0.,1./hmax**2]]),(numpy.size(pos1),1))
    49         metric[pos2,:]=numpy.tile(numpy.array([[1./hmax**2,0.,1./hmax**2]]),(numpy.size(pos2),1))
     48        metric[pos1,:]=np.tile(np.array([[1./hmax**2,0.,1./hmax**2]]),(np.size(pos1),1))
     49        metric[pos2,:]=np.tile(np.array([[1./hmax**2,0.,1./hmax**2]]),(np.size(pos2),1))
    5050
    5151        #take care of water elements
    52         metric[pos ,:]=numpy.tile(numpy.array([[1./hmax**2,0.,1./hmax**2]]),(numpy.size(pos ),1))
     52        metric[pos ,:]=np.tile(np.array([[1./hmax**2,0.,1./hmax**2]]),(np.size(pos ),1))
    5353
    5454        #take care of NaNs if any (use Numpy eig in a loop)
    55         pos=numpy.nonzero(numpy.isnan(metric))[0]
    56         if numpy.size(pos):
    57                 print((" %i NaN found in the metric. Use Numpy routine..." % numpy.size(pos)))
     55        pos=np.nonzero(np.isnan(metric))[0]
     56        if np.size(pos):
     57                print((" %i NaN found in the metric. Use Numpy routine..." % np.size(pos)))
    5858                for posi in pos:
    59                         H=numpy.array([[hessian[posi,0],hessian[posi,1]],[hessian[posi,1],hessian[posi,2]]])
    60                         [v,u]=numpy.linalg.eig(H)
    61                         v=numpy.diag(v)
     59                        H=np.array([[hessian[posi,0],hessian[posi,1]],[hessian[posi,1],hessian[posi,2]]])
     60                        [v,u]=np.linalg.eig(H)
     61                        v=np.diag(v)
    6262                        lambda1=v[0,0]
    6363                        lambda2=v[1,1]
    64                         v[0,0]=numpy.minimum(numpy.maximum(numpy.abs(lambda1)*scale/epsilon,1./hmax**2),1./hmin**2)
    65                         v[1,1]=numpy.minimum(numpy.maximum(numpy.abs(lambda2)*scale/epsilon,1./hmax**2),1./hmin**2)
     64                        v[0,0]=np.minimum(np.maximum(np.abs(lambda1)*scale/epsilon,1./hmax**2),1./hmin**2)
     65                        v[1,1]=np.minimum(np.maximum(np.abs(lambda2)*scale/epsilon,1./hmax**2),1./hmin**2)
    6666
    67                         metricTria=numpy.dot(numpy.dot(u,v),numpy.linalg.inv(u))
    68                         metric[posi,:]=numpy.array([metricTria[0,0],metricTria[0,1],metricTria[1,1]])
     67                        metricTria=np.dot(np.dot(u,v),np.linalg.inv(u))
     68                        metric[posi,:]=np.array([metricTria[0,0],metricTria[0,1],metricTria[1,1]])
    6969
    70         if numpy.any(numpy.isnan(metric)):
     70        if np.any(np.isnan(metric)):
    7171                raise RunTimeError("ComputeMetric error message: NaN in the metric despite our efforts...")
    7272
  • issm/trunk-jpl/src/py3/mesh/ElementsFromEdge.py

    r19895 r23670  
    1 import numpy
     1import numpy as np
    22import PythonFuncs as p
    33
     
    1212        """
    1313
    14         edgeelements=numpy.nonzero(\
    15                 p.logical_or_n(numpy.logical_and(elements[:,0]==A,elements[:,1]==B), \
    16                                          numpy.logical_and(elements[:,0]==A,elements[:,2]==B), \
    17                                          numpy.logical_and(elements[:,1]==A,elements[:,2]==B), \
    18                                          numpy.logical_and(elements[:,1]==A,elements[:,0]==B), \
    19                                          numpy.logical_and(elements[:,2]==A,elements[:,0]==B), \
    20                                          numpy.logical_and(elements[:,2]==A,elements[:,1]==B), \
     14        edgeelements=np.nonzero(\
     15                p.logical_or_n(np.logical_and(elements[:,0]==A,elements[:,1]==B), \
     16                                         np.logical_and(elements[:,0]==A,elements[:,2]==B), \
     17                                         np.logical_and(elements[:,1]==A,elements[:,2]==B), \
     18                                         np.logical_and(elements[:,1]==A,elements[:,0]==B), \
     19                                         np.logical_and(elements[:,2]==A,elements[:,0]==B), \
     20                                         np.logical_and(elements[:,2]==A,elements[:,1]==B), \
    2121                ))[0]+1
    2222
  • issm/trunk-jpl/src/py3/mesh/GetNodalFunctionsCoeff.py

    r19895 r23670  
    1 import numpy
     1import numpy as np
    22
    33def GetNodalFunctionsCoeff(index,x,y):
     
    2323
    2424        #get nels and nods
    25         nels=numpy.size(index,axis=0)
    26         nods=numpy.size(x)
     25        nels=np.size(index,axis=0)
     26        nods=np.size(x)
    2727
    2828        #some checks
    29         if numpy.size(y)!=nods:
     29        if np.size(y)!=nods:
    3030                raise TypeError("GetNodalFunctionsCoeff error message: x and y do not have the same length.")
    31         if numpy.max(index)>nods:
     31        if np.max(index)>nods:
    3232                raise TypeError("GetNodalFunctionsCoeff error message: index should not have values above %d." % nods)
    33         if numpy.size(index,axis=1)!=3:
     33        if np.size(index,axis=1)!=3:
    3434                raise TypeError("GetNodalFunctionsCoeff error message: only 2d meshes supported. index should have 3 columns.")
    3535
    3636        #initialize output
    37         alpha=numpy.zeros((nels,3))
    38         beta=numpy.zeros((nels,3))
     37        alpha=np.zeros((nels,3))
     38        beta=np.zeros((nels,3))
    3939
    4040        #compute nodal functions coefficients N(x,y)=alpha x + beta y +gamma
     
    4848
    4949        #get alpha and beta
    50         alpha=numpy.hstack(((invdet*(y2-y3)).reshape(-1,1),(invdet*(y3-y1)).reshape(-1,1),(invdet*(y1-y2)).reshape(-1,1)))
    51         beta =numpy.hstack(((invdet*(x3-x2)).reshape(-1,1),(invdet*(x1-x3)).reshape(-1,1),(invdet*(x2-x1)).reshape(-1,1)))
     50        alpha=np.vstack(((invdet*(y2-y3)).reshape(-1,),(invdet*(y3-y1)).reshape(-1,),(invdet*(y1-y2)).reshape(-1,))).T
     51        beta =np.vstack(((invdet*(x3-x2)).reshape(-1,),(invdet*(x1-x3)).reshape(-1,),(invdet*(x2-x1)).reshape(-1,))).T
    5252
    5353        #get gamma if requested
    54         gamma=numpy.zeros((nels,3))
    55         gamma=numpy.hstack(((invdet*(x2*y3-x3*y2)).reshape(-1,1),(invdet*(y1*x3-y3*x1)).reshape(-1,1),(invdet*(x1*y2-x2*y1)).reshape(-1,1)))
     54        gamma=np.zeros((nels,3))
     55        gamma=np.vstack(((invdet*(x2*y3-x3*y2)).reshape(-1,),(invdet*(y1*x3-y3*x1)).reshape(-1,),(invdet*(x1*y2-x2*y1)).reshape(-1,))).T
    5656
    5757        return alpha,beta,gamma
  • issm/trunk-jpl/src/py3/mesh/bamg.py

    r19895 r23670  
    11import os.path
    2 import numpy
    3 from mesh2d import mesh2d
     2import numpy as  np
     3from mesh2d import *
     4from mesh2dvertical import *
     5from mesh3dsurface import *
    46from collections import OrderedDict
    57from pairoptions import pairoptions
     
    1315from ContourToNodes import ContourToNodes
    1416
    15 def bamg(md,*kwargs):
     17def bamg(md,*args):
    1618        """
    1719        BAMG - mesh generation
     
    2022
    2123           - domain :            followed by an ARGUS file that prescribes the domain outline
     24           - holes :             followed by an ARGUS file that prescribes the holes
     25     - subdomains :        followed by an ARGUS file that prescribes the list of
     26                                 subdomains (that need to be inside domain)
     27
    2228           - hmin :              minimum edge length (default is 10^-100)
    2329           - hmax :              maximum edge length (default is 10^100)
     
    3743                                 1 -> use Green formula
    3844           - KeepVertices :      try to keep initial vertices when adaptation is done on an existing mesh (default 1)
    39            - MaxCornerAngle :    maximum angle of corners in degree (default is 10)
    4045           - maxnbv :            maximum number of vertices used to allocate memory (default is 10^6)
    4146           - maxsubdiv :         maximum subdivision of exisiting elements (default is 10)
     
    4954           - power :             power applied to the metric (default is 1)
    5055           - splitcorners :      split triangles whuch have 3 vertices on the outline (default is 1)
    51            - geometricalmetric : take the geometry into account to generate the metric (default is 0)
    5256           - verbose :           level of verbosity (default is 1)
    5357
     
    6670
    6771        #process options
    68         options=pairoptions(**kwargs)
     72        options=pairoptions(*args)
    6973#       options=deleteduplicates(options,1);
    7074
     
    7478        bamg_mesh=bamgmesh()
    7579
     80        subdomain_ref = 1
     81        hole_ref = 1
     82
    7683        # Bamg Geometry parameters {{{
    7784        if options.exist('domain'):
    78 
    7985                #Check that file exists
    8086                domainfile=options.getfieldvalue('domain')
    81                 if not os.path.exists(domainfile):
    82                         raise IOError("bamg error message: file '%s' not found" % domainfile)
    83                 domain=expread(domainfile)
     87                if type(domainfile) == str:
     88                        if not os.path.exists(domainfile):
     89                                raise IOError("bamg error message: file '%s' not found" % domainfile)
     90                        domain=expread(domainfile)
     91                else:
     92                        domain=domainfile
    8493
    8594                #Build geometry
    8695                count=0
    8796                for i,domaini in enumerate(domain):
    88 
    8997                        #Check that the domain is closed
    9098                        if (domaini['x'][0]!=domaini['x'][-1] or domaini['y'][0]!=domaini['y'][-1]):
    9199                                raise RuntimeError("bamg error message: all contours provided in ''domain'' should be closed")
    92100
    93                         #Checks that all holes are INSIDE the principle domain outline
     101                        #Checks that all holes are INSIDE the principle domain outline princial domain should be index 0
    94102                        if i:
    95                                 flags=ContourToNodes(domaini['x'],domaini['y'],domainfile,0)
    96                                 if numpy.any(numpy.logical_not(flags)):
     103                                flags=ContourToNodes(domaini['x'],domaini['y'],domainfile,0)[0]
     104                                if np.any(np.logical_not(flags)):
    97105                                        raise RuntimeError("bamg error message: All holes should be strictly inside the principal domain")
     106
     107                        #Check orientation
     108                        nods=domaini['nods']-1#the domain are closed 1=end;
     109
     110                        test = np.sum((domaini['x'][1:nods+1] - domaini['x'][0:nods])*(domaini['y'][1:nods+1] + domaini['y'][0:nods]))
     111                        if (i==0 and test>0) or (i>0 and test<0):
     112                                print('At least one contour was not correctly oriented and has been re-oriented')
     113                                domaini['x'] = np.flipud(domaini['x'])
     114                                domaini['y'] = np.flipud(domaini['y'])
     115
    98116
    99117                        #Add all points to bamg_geometry
    100118                        nods=domaini['nods']-1    #the domain are closed 0=end
    101                         bamg_geometry.Vertices=numpy.vstack((bamg_geometry.Vertices,numpy.hstack((domaini['x'][0:nods].reshape(-1,1),domaini['y'][0:nods].reshape(-1,1),numpy.ones((nods,1))))))
    102                         bamg_geometry.Edges   =numpy.vstack((bamg_geometry.Edges,   numpy.hstack((numpy.arange(count+1,count+nods+1).reshape(-1,1),numpy.hstack((numpy.arange(count+2,count+nods+1),count+1)).reshape(-1,1),1.*numpy.ones((nods,1))))))
     119                        bamg_geometry.Vertices=np.vstack((bamg_geometry.Vertices,np.vstack((domaini['x'][0:nods],domaini['y'][0:nods],np.ones((nods)))).T))
     120                        bamg_geometry.Edges   =np.vstack((bamg_geometry.Edges,np.vstack((np.arange(count+1,count+nods+1),np.hstack((np.arange(count+2,count+nods+1),count+1)),1.*np.ones((nods)))).T))
    103121                        if i:
    104                                 bamg_geometry.SubDomains=numpy.vstack((bamg_geometry.SubDomains,[2,count+1,1,1]))
    105 
     122                                bamg_geometry.SubDomains=np.vstack((bamg_geometry.SubDomains,[2,count+1,1,-subdomain_ref]))
     123                                subdomain_ref = subdomain_ref+1;
     124                        else:
     125                                bamg_geometry.SubDomains=np.vstack((bamg_geometry.SubDomains,[2,count+1,1,0]))
     126                       
    106127                        #update counter
    107128                        count+=nods
     129
     130                #Deal with domain holes
     131                if options.exist('holes'):
     132                        holesfile=options.getfieldvalue('holes')
     133                        if type(holesfile) == str:
     134                                if not os.path.exists(holesfile):
     135                                        raise IOError("bamg error message: file '%s' not found" % holesfile)
     136                                holes=expread(holesfile)
     137                        else:
     138                                holes=holesfile
     139
     140                        #Build geometry
     141                        for i,holei in enumerate(holes):
     142                                #Check that the hole is closed
     143                                if (holei['x'][0]!=holei['x'][-1] or holei['y'][0]!=holei['y'][-1]):
     144                                        raise RuntimeError("bamg error message: all contours provided in ''hole'' should be closed")
     145
     146                                #Checks that all holes are INSIDE the principle domain outline princial domain should be index 0
     147                                flags=ContourToNodes(holei['x'],holei['y'],domainfile,0)[0]
     148                                if np.any(np.logical_not(flags)):
     149                                        raise RuntimeError("bamg error message: All holes should be strictly inside the principal domain")
     150
     151                                #Check orientation
     152                                nods=holei['nods']-1#the hole are closed 1=end;
     153                                test = np.sum((holei['x'][1:nods+1] - holei['x'][0:nods])*(holei['y'][1:nods+1] + holei['y'][0:nods]))
     154                                if test<0:
     155                                        print('At least one hole was not correctly oriented and has been re-oriented')
     156                                        holei['x'] = np.flipud(holei['x'])
     157                                        holei['y'] = np.flipud(holei['y'])
     158
     159                                #Add all points to bamg_geometry
     160                                nods=holei['nods']-1    #the hole are closed 0=end
     161                                bamg_geometry.Vertices=np.vstack((bamg_geometry.Vertices,np.vstack((holei['x'][0:nods],holei['y'][0:nods],np.ones((nods)))).T))
     162                                bamg_geometry.Edges   =np.vstack((bamg_geometry.Edges,np.vstack((np.arange(count+1,count+nods+1),np.hstack((np.arange(count+2,count+nods+1),count+1)),1.*np.ones((nods)))).T))
     163                                #update counter
     164                                count+=nods
     165
     166                #And subdomains
     167                if options.exist('subdomains'):
     168                        subdomainfile=options.getfieldvalue('subdomains')
     169                        if type(subdomainfile) == str:
     170                                if not os.path.exists(subdomainfile):
     171                                        raise IOError("bamg error message: file '%s' not found" % subdomainfile)
     172                                subdomains=expread(subdomainfile)
     173                        else:
     174                                subdomains=subdomainfile
     175
     176                        #Build geometry
     177                        for i,subdomaini in enumerate(subdomains):
     178                                #Check that the subdomain is closed
     179                                if (subdomaini['x'][0]!=subdomaini['x'][-1] or subdomaini['y'][0]!=subdomaini['y'][-1]):
     180                                        raise RuntimeError("bamg error message: all contours provided in ''subdomain'' should be closed")
     181
     182                                #Checks that all subdomains are INSIDE the principle subdomain outline princial domain should be index 0
     183                                if i:
     184                                        flags=ContourToNodes(subdomaini['x'],subdomaini['y'],domainfile,0)[0]
     185                                        if np.any(np.logical_not(flags)):
     186                                                raise RuntimeError("bamg error message: All subdomains should be strictly inside the principal subdomain")
     187
     188                                #Check orientation
     189                                nods=subdomaini['nods']-1#the subdomain are closed 1=end;
     190
     191                                test = np.sum((subdomaini['x'][1:nods+1] - subdomaini['x'][0:nods])*(subdomaini['y'][1:nods+1] + subdomaini['y'][0:nods]))
     192                                if test>0:
     193                                        print('At least one subcontour was not correctly oriented and has been re-oriented')
     194                                        subdomaini['x'] = np.flipud(subdomaini['x'])
     195                                        subdomaini['y'] = np.flipud(subdomaini['y'])
     196
     197                                #Add all points to bamg_geometry
     198                                nods=subdomaini['nods']-1    #the subdomain are closed 0=end
     199                                bamg_geometry.Vertices=np.vstack((bamg_geometry.Vertices,np.vstack((subdomaini['x'][0:nods],subdomaini['y'][0:nods],np.ones((nods)))).T))
     200                                bamg_geometry.Edges   =np.vstack((bamg_geometry.Edges,np.vstack((np.arange(count+1,count+nods+1),np.hstack((np.arange(count+2,count+nods+1),count+1)),1.*np.ones((nods)))).T))
     201                                #update counter
     202                                count+=nods
     203                       
     204                if options.getfieldvalue('vertical',0):
     205                        if np.size(options.getfieldvalue('Markers',[]))!=np.size(bamg_geometry.Edges,0):
     206                                raise RuntimeError('for 2d vertical mesh, ''Markers'' option is required, and should be of size ' + str(np.size(bamg_geometry.Edges,0)))
     207                        if np.size(options.getfieldvalue('Markers',[]))==np.size(bamg_geometry.Edges,0):
     208                                bamg_geometry.Edges[:,2]=options.getfieldvalue('Markers')
    108209
    109210                #take care of rifts
     
    119220
    120221                                #detect whether all points of the rift are inside the domain
    121                                 flags=ContourToNodes(rifti['x'],rifti['y'],domain[0],0)
    122                                 if numpy.all(numpy.logical_not(flags)):
     222                                flags=ContourToNodes(rifti['x'],rifti['y'],domain[0],0)[0]
     223                                if np.all(np.logical_not(flags)):
    123224                                        raise RuntimeError("one rift has all its points outside of the domain outline")
    124225
    125                                 elif numpy.any(numpy.logical_not(flags)):
     226                                elif np.any(np.logical_not(flags)):
    126227                                        #We LOTS of work to do
    127228                                        print("Rift tip outside of or on the domain has been detected and is being processed...")
    128229
    129230                                        #check that only one point is outside (for now)
    130                                         if numpy.sum(numpy.logical_not(flags).astype(int))!=1:
     231                                        if np.sum(np.logical_not(flags).astype(int))!=1:
    131232                                                raise RuntimeError("bamg error message: only one point outside of the domain is supported yet")
    132233
     
    136237                                                pass
    137238                                        elif not flags[-1]:
    138                                                 rifti['x']=numpy.flipud(rifti['x'])
    139                                                 rifti['y']=numpy.flipud(rifti['y'])
     239                                                rifti['x']=np.flipud(rifti['x'])
     240                                                rifti['y']=np.flipud(rifti['y'])
    140241                                        else:
    141242                                                raise RuntimeError("bamg error message: only a rift tip can be outside of the domain")
     
    146247                                        x2=rifti['x'][1]
    147248                                        y2=rifti['y'][1]
    148                                         for j in range(0,numpy.size(domain[0]['x'])-1):
    149                                                 if SegIntersect(numpy.array([[x1,y1],[x2,y2]]),numpy.array([[domain[0]['x'][j],domain[0]['y'][j]],[domain[0]['x'][j+1],domain[0]['y'][j+1]]])):
     249                                        for j in range(0,np.size(domain[0]['x'])-1):
     250                                                if SegIntersect(np.array([[x1,y1],[x2,y2]]),np.array([[domain[0]['x'][j],domain[0]['y'][j]],[domain[0]['x'][j+1],domain[0]['y'][j+1]]])):
    150251
    151252                                                        #Get position of the two nodes of the edge in domain
     
    161262#                                                       x=det([det([x1 y1; x2 y2])  x1-x2;det([x3 y3; x4 y4])  x3-x4])/det([x1-x2 y1-y2;x3-x4 y3-y4]);
    162263#                                                       y=det([det([x1 y1; x2 y2])  y1-y2;det([x3 y3; x4 y4])  y3-y4])/det([x1-x2 y1-y2;x3-x4 y3-y4]);
    163                                                         x=numpy.linalg.det(numpy.array([[numpy.linalg.det(numpy.array([[x1,y1],[x2,y2]])),x1-x2],[numpy.linalg.det(numpy.array([[x3,y3],[x4,y4]])),x3-x4]]))/numpy.linalg.det(numpy.array([[x1-x2,y1-y2],[x3-x4,y3-y4]]))
    164                                                         y=numpy.linalg.det(numpy.array([[numpy.linalg.det(numpy.array([[x1,y1],[x2,y2]])),y1-y2],[numpy.linalg.det(numpy.array([[x3,y3],[x4,y4]])),y3-y4]]))/numpy.linalg.det(numpy.array([[x1-x2,y1-y2],[x3-x4,y3-y4]]))
     264                                                        x=np.linalg.det(np.array([[np.linalg.det(np.array([[x1,y1],[x2,y2]])),x1-x2],[np.linalg.det(np.array([[x3,y3],[x4,y4]])),x3-x4]]))/np.linalg.det(np.array([[x1-x2,y1-y2],[x3-x4,y3-y4]]))
     265                                                        y=np.linalg.det(np.array([[np.linalg.det(np.array([[x1,y1],[x2,y2]])),y1-y2],[np.linalg.det(np.array([[x3,y3],[x4,y4]])),y3-y4]]))/np.linalg.det(np.array([[x1-x2,y1-y2],[x3-x4,y3-y4]]))
    165266
    166267                                                        segdis= sqrt((x4-x3)**2+(y4-y3)**2)
    167                                                         tipdis=numpy.array([sqrt((x-x3)**2+(y-y3)**2),sqrt((x-x4)**2+(y-y4)**2)])
    168 
    169                                                         if numpy.min(tipdis)/segdis < options.getfieldvalue('toltip',0):
     268                                                        tipdis=np.array([sqrt((x-x3)**2+(y-y3)**2),sqrt((x-x4)**2+(y-y4)**2)])
     269
     270                                                        if np.min(tipdis)/segdis < options.getfieldvalue('toltip',0):
    170271                                                                print("moving tip-domain intersection point")
    171272
     
    179280                                                                #OK, now we can add our own rift
    180281                                                                nods=rifti['nods']-1
    181                                                                 bamg_geometry.Vertices=numpy.vstack((bamg_geometry.Vertices,numpy.hstack((rifti['x'][1:].reshape(-1,1),rifti['y'][1:].reshape(-1,1),numpy.ones((nods,1))))))
    182                                                                 bamg_geometry.Edges=numpy.vstack((bamg_geometry.Edges,\
    183                                                                         numpy.array([[pos,count+1,(1+i)]]),\
    184                                                                         numpy.hstack((numpy.arange(count+1,count+nods).reshape(-1,1),numpy.arange(count+2,count+nods+1).reshape(-1,1),(1+i)*numpy.ones((nods-1,1))))))
     282                                                                bamg_geometry.Vertices=np.vstack((bamg_geometry.Vertices,np.hstack((rifti['x'][1:].reshape(-1,),rifti['y'][1:].reshape(-1,),np.ones((nods,1))))))
     283                                                                bamg_geometry.Edges=np.vstack((bamg_geometry.Edges,\
     284                                                                        np.array([[pos,count+1,(1+i)]]),\
     285                                                                        np.hstack((np.arange(count+1,count+nods).reshape(-1,),np.arange(count+2,count+nods+1).reshape(-1,),(1+i)*np.ones((nods-1,1))))))
    185286                                                                count+=nods
    186287
     
    189290                                                        else:
    190291                                                                #Add intersection point to Vertices
    191                                                                 bamg_geometry.Vertices=numpy.vstack((bamg_geometry.Vertices,numpy.array([[x,y,1]])))
     292                                                                bamg_geometry.Vertices=np.vstack((bamg_geometry.Vertices,np.array([[x,y,1]])))
    192293                                                                count+=1
    193294
    194295                                                                #Decompose the crossing edge into 2 subedges
    195                                                                 pos=numpy.nonzero(numpy.logical_and(bamg_geometry.Edges[:,0]==i1,bamg_geometry.Edges[:,1]==i2))[0]
     296                                                                pos=np.nonzero(np.logical_and(bamg_geometry.Edges[:,0]==i1,bamg_geometry.Edges[:,1]==i2))[0]
    196297                                                                if not pos:
    197298                                                                        raise RuntimeError("bamg error message: a problem occurred...")
    198                                                                 bamg_geometry.Edges=numpy.vstack((bamg_geometry.Edges[0:pos-1,:],\
    199                                                                         numpy.array([[bamg_geometry.Edges[pos,0],count                     ,bamg_geometry.Edges[pos,2]]]),\
    200                                                                         numpy.array([[count                     ,bamg_geometry.Edges[pos,1],bamg_geometry.Edges[pos,2]]]),\
     299                                                                bamg_geometry.Edges=np.vstack((bamg_geometry.Edges[0:pos-1,:],\
     300                                                                        np.array([[bamg_geometry.Edges[pos,0],count                     ,bamg_geometry.Edges[pos,2]]]),\
     301                                                                        np.array([[count                     ,bamg_geometry.Edges[pos,1],bamg_geometry.Edges[pos,2]]]),\
    201302                                                                        bamg_geometry.Edges[pos+1:,:]))
    202303
    203304                                                                #OK, now we can add our own rift
    204305                                                                nods=rifti['nods']-1
    205                                                                 bamg_geometry.Vertices=numpy.vstack((bamg_geometry.Vertices,numpy.hstack((rifti['x'][1:].reshape(-1,1),rifti['y'][1:].reshape(-1,1),numpy.ones((nods,1))))))
    206                                                                 bamg_geometry.Edges=numpy.vstack((bamg_geometry.Edges,\
    207                                                                         numpy.array([[count,count+1,2]]),\
    208                                                                         numpy.hstack((numpy.arange(count+1,count+nods).reshape(-1,1),numpy.arange(count+2,count+nods+1).reshape(-1,1),(1+i)*numpy.ones((nods-1,1))))))
     306                                                                bamg_geometry.Vertices=np.vstack((bamg_geometry.Vertices,np.hstack((rifti['x'][1:].reshape(-1,),rifti['y'][1:].reshape(-1,),np.ones((nods,1))))))
     307                                                                bamg_geometry.Edges=np.vstack((bamg_geometry.Edges,\
     308                                                                        np.array([[count,count+1,2]]),\
     309                                                                        np.hstack((np.arange(count+1,count+nods).reshape(-1,),np.arange(count+2,count+nods+1).reshape(-1,),(1+i)*np.ones((nods-1,1))))))
    209310                                                                count+=nods
    210311
     
    213314                                else:
    214315                                        nods=rifti['nods']-1
    215                                         bamg_geometry.Vertices=numpy.vstack(bamg_geometry.Vertices, numpy.hstack(rifti['x'][:],rifti['y'][:],numpy.ones((nods+1,1))))
    216                                         bamg_geometry.Edges   =numpy.vstack(bamg_geometry.Edges, numpy.hstack(numpy.arange(count+1,count+nods).reshape(-1,1),numpy.arange(count+2,count+nods+1).reshape(-1,1),i*numpy.ones((nods,1))))
     316                                        bamg_geometry.Vertices=np.vstack(bamg_geometry.Vertices, np.hstack(rifti['x'][:],rifti['y'][:],np.ones((nods+1,1))))
     317                                        bamg_geometry.Edges   =np.vstack(bamg_geometry.Edges, np.hstack(np.arange(count+1,count+nods).reshape(-1,),np.arange(count+2,count+nods+1).reshape(-1,),i*np.ones((nods,1))))
    217318                                        count=+nods+1
    218319
     
    224325                        if all(isinstance(track,str)):
    225326                                A=expread(track)
    226                                 track=numpy.hstack((A.x.reshape(-1,1),A.y.reshape(-1,1)))
     327                                track=np.hstack((A.x.reshape(-1,),A.y.reshape(-1,)))
    227328                        else:
    228329                                track=float(track)    #for some reason, it is of class "single"
    229                         if numpy.size(track,axis=1)==2:
    230                                 track=numpy.hstack((track,3.*numpy.ones((size(track,axis=0),1))))
     330                        if np.size(track,axis=1)==2:
     331                                track=np.hstack((track,3.*np.ones((size(track,axis=0),1))))
    231332
    232333                        #only keep those inside
    233                         flags=ContourToNodes(track[:,0],track[:,1],domainfile,0)
    234                         track=track[numpy.nonzero(flags),:]
     334                        flags=ContourToNodes(track[:,0],track[:,1],domainfile,0)[0]
     335                        track=track[np.nonzero(flags),:]
    235336
    236337                        #Add all points to bamg_geometry
    237                         nods=numpy.size(track,axis=0)
    238                         bamg_geometry.Vertices=numpy.vstack((bamg_geometry.Vertices,track))
    239                         bamg_geometry.Edges   =numpy.vstack((bamg_geometry.Edges,numpy.hstack((numpy.arange(count+1,count+nods).reshape(-1,1),numpy.arange(count+2,count+nods+1).reshape(-1,1),3.*numpy.ones((nods-1,1))))))
     338                        nods=np.size(track,axis=0)
     339                        bamg_geometry.Vertices=np.vstack((bamg_geometry.Vertices,track))
     340                        bamg_geometry.Edges   =np.vstack((bamg_geometry.Edges,np.hstack((np.arange(count+1,count+nods).reshape(-1,),np.arange(count+2,count+nods+1).reshape(-1,),3.*np.ones((nods-1,1))))))
    240341
    241342                        #update counter
     
    247348                        #recover RequiredVertices
    248349                        requiredvertices=options.getfieldvalue('RequiredVertices')    #for some reason, it is of class "single"
    249                         if numpy.size(requiredvertices,axis=1)==2:
    250                                 requiredvertices=numpy.hstack((requiredvertices,4.*numpy.ones((numpy.size(requiredvertices,axis=0),1))))
    251                        
     350                        if np.size(requiredvertices,axis=1)==2:
     351                                requiredvertices=np.hstack((requiredvertices,4.*np.ones((np.size(requiredvertices,axis=0),1))))
    252352
    253353                        #only keep those inside
    254354                        flags=ContourToNodes(requiredvertices[:,0],requiredvertices[:,1],domainfile,0)[0]
    255                         requiredvertices=requiredvertices[numpy.nonzero(flags)[0],:]
    256 
     355                        requiredvertices=requiredvertices[np.nonzero(flags)[0],:]
    257356                        #Add all points to bamg_geometry
    258                         nods=numpy.size(requiredvertices,axis=0)
    259                         bamg_geometry.Vertices=numpy.vstack((bamg_geometry.Vertices,requiredvertices))
     357                        nods=np.size(requiredvertices,axis=0)
     358                        bamg_geometry.Vertices=np.vstack((bamg_geometry.Vertices,requiredvertices))
    260359
    261360                        #update counter
     
    277376                        bamg_mesh=bamgmesh(md.private.bamg['mesh'].__dict__)
    278377                else:
    279                         bamg_mesh.Vertices=numpy.hstack((md.mesh.x.reshape(-1,1),md.mesh.y.reshape(-1,1),numpy.ones((md.mesh.numberofvertices,1))))
    280                         bamg_mesh.Triangles=numpy.hstack((md.mesh.elements,numpy.ones((md.mesh.numberofelements,1))))
     378                        bamg_mesh.Vertices=np.vstack((md.mesh.x,md.mesh.y,np.ones((md.mesh.numberofvertices)))).T
     379                        #bamg_mesh.Vertices=np.hstack((md.mesh.x.reshape(-1,),md.mesh.y.reshape(-1,),np.ones((md.mesh.numberofvertices,1))))
     380                        bamg_mesh.Triangles=np.hstack((md.mesh.elements,np.ones((md.mesh.numberofelements,1))))
    281381
    282382                if isinstance(md.rifts.riftstruct,dict):
     
    288388        bamg_options['coeff']=options.getfieldvalue('coeff',1.)
    289389        bamg_options['cutoff']=options.getfieldvalue('cutoff',10.**-5)
    290         bamg_options['err']=options.getfieldvalue('err',numpy.array([[0.01]]))
     390        bamg_options['err']=options.getfieldvalue('err',np.array([[0.01]]))
    291391        bamg_options['errg']=options.getfieldvalue('errg',0.1)
    292         bamg_options['field']=options.getfieldvalue('field',numpy.empty((0,1)))
     392        bamg_options['field']=options.getfieldvalue('field',np.empty((0,1)))
    293393        bamg_options['gradation']=options.getfieldvalue('gradation',1.5)
    294394        bamg_options['Hessiantype']=options.getfieldvalue('Hessiantype',0)
    295395        bamg_options['hmin']=options.getfieldvalue('hmin',10.**-100)
    296396        bamg_options['hmax']=options.getfieldvalue('hmax',10.**100)
    297         bamg_options['hminVertices']=options.getfieldvalue('hminVertices',numpy.empty((0,1)))
    298         bamg_options['hmaxVertices']=options.getfieldvalue('hmaxVertices',numpy.empty((0,1)))
    299         bamg_options['hVertices']=options.getfieldvalue('hVertices',numpy.empty((0,1)))
     397        bamg_options['hminVertices']=options.getfieldvalue('hminVertices',np.empty((0,1)))
     398        bamg_options['hmaxVertices']=options.getfieldvalue('hmaxVertices',np.empty((0,1)))
     399        bamg_options['hVertices']=options.getfieldvalue('hVertices',np.empty((0,1)))
    300400        bamg_options['KeepVertices']=options.getfieldvalue('KeepVertices',1)
    301         bamg_options['MaxCornerAngle']=options.getfieldvalue('MaxCornerAngle',10.)
    302401        bamg_options['maxnbv']=options.getfieldvalue('maxnbv',10**6)
    303402        bamg_options['maxsubdiv']=options.getfieldvalue('maxsubdiv',10.)
    304         bamg_options['metric']=options.getfieldvalue('metric',numpy.empty((0,1)))
     403        bamg_options['metric']=options.getfieldvalue('metric',np.empty((0,1)))
    305404        bamg_options['Metrictype']=options.getfieldvalue('Metrictype',0)
    306405        bamg_options['nbjacobi']=options.getfieldvalue('nbjacobi',1)
     
    309408        bamg_options['power']=options.getfieldvalue('power',1.)
    310409        bamg_options['splitcorners']=options.getfieldvalue('splitcorners',1)
    311         bamg_options['geometricalmetric']=options.getfieldvalue('geometricalmetric',0)
    312         bamg_options['random']=options.getfieldvalue('rand',True)
    313410        bamg_options['verbose']=options.getfieldvalue('verbose',1)
    314411        #}}}
    315412
    316413        #call Bamg
    317         [bamgmesh_out,bamggeom_out]=BamgMesher(bamg_mesh.__dict__,bamg_geometry.__dict__,bamg_options)
     414        bamgmesh_out,bamggeom_out=BamgMesher(bamg_mesh.__dict__,bamg_geometry.__dict__,bamg_options)
    318415
    319416        # plug results onto model
     417        if options.getfieldvalue('vertical',0):
     418                md.mesh=mesh2dvertical()
     419                md.mesh.x=bamgmesh_out['Vertices'][:,0].copy()
     420                md.mesh.y=bamgmesh_out['Vertices'][:,1].copy()
     421                md.mesh.elements=bamgmesh_out['Triangles'][:,0:3].astype(int)
     422                md.mesh.edges=bamgmesh_out['IssmEdges'].astype(int)
     423                md.mesh.segments=bamgmesh_out['IssmSegments'][:,0:3].astype(int)
     424                md.mesh.segmentmarkers=bamgmesh_out['IssmSegments'][:,3].astype(int)
     425
     426                #Fill in rest of fields:
     427                md.mesh.numberofelements=np.size(md.mesh.elements,axis=0)
     428                md.mesh.numberofvertices=np.size(md.mesh.x)
     429                md.mesh.numberofedges=np.size(md.mesh.edges,axis=0)
     430                md.mesh.vertexonboundary=np.zeros(md.mesh.numberofvertices,bool)
     431                md.mesh.vertexonboundary[md.mesh.segments[:,0:2]-1]=True
     432
     433                #Now, build the connectivity tables for this mesh. Doubled in matlab for some reason
     434                md.mesh.vertexonboundary=np.zeros(md.mesh.numberofvertices,)
     435                md.mesh.vertexonboundary[md.mesh.segments[:,0:2]-1]=1
     436
     437        elif options.getfieldvalue('3dsurface',0):
     438                md.mesh=mesh3dsurface()
     439                md.mesh.x=bamgmesh_out['Vertices'][:,0].copy()
     440                md.mesh.y=bamgmesh_out['Vertices'][:,1].copy()
     441                md.mesh.z=md.mesh.x
     442                md.mesh.z[:]=0
     443                md.mesh.elements=bamgmesh_out['Triangles'][:,0:3].astype(int)
     444                md.mesh.edges=bamgmesh_out['IssmEdges'].astype(int)
     445                md.mesh.segments=bamgmesh_out['IssmSegments'][:,0:3].astype(int)
     446                md.mesh.segmentmarkers=bamgmesh_out['IssmSegments'][:,3].astype(int)
     447
     448                #Fill in rest of fields:
     449                md.mesh.numberofelements=np.size(md.mesh.elements,axis=0)
     450                md.mesh.numberofvertices=np.size(md.mesh.x)
     451                md.mesh.numberofedges=np.size(md.mesh.edges,axis=0)
     452                md.mesh.vertexonboundary=np.zeros(md.mesh.numberofvertices,bool)
     453                md.mesh.vertexonboundary[md.mesh.segments[:,0:2]-1]=True
     454
     455        else:
     456                md.mesh=mesh2d()
     457                md.mesh.x=bamgmesh_out['Vertices'][:,0].copy()
     458                md.mesh.y=bamgmesh_out['Vertices'][:,1].copy()
     459                md.mesh.elements=bamgmesh_out['Triangles'][:,0:3].astype(int)
     460                md.mesh.edges=bamgmesh_out['IssmEdges'].astype(int)
     461                md.mesh.segments=bamgmesh_out['IssmSegments'][:,0:3].astype(int)
     462                md.mesh.segmentmarkers=bamgmesh_out['IssmSegments'][:,3].astype(int)
     463
     464                #Fill in rest of fields:
     465                md.mesh.numberofelements=np.size(md.mesh.elements,axis=0)
     466                md.mesh.numberofvertices=np.size(md.mesh.x)
     467                md.mesh.numberofedges=np.size(md.mesh.edges,axis=0)
     468                md.mesh.vertexonboundary=np.zeros(md.mesh.numberofvertices,bool)
     469                md.mesh.vertexonboundary[md.mesh.segments[:,0:2]-1]=True
     470
     471        #Bamg private fields
    320472        md.private.bamg=OrderedDict()
    321473        md.private.bamg['mesh']=bamgmesh(bamgmesh_out)
    322474        md.private.bamg['geometry']=bamggeom(bamggeom_out)
    323         md.mesh = mesh2d()
    324         md.mesh.x=bamgmesh_out['Vertices'][:,0].copy()
    325         md.mesh.y=bamgmesh_out['Vertices'][:,1].copy()
    326         md.mesh.elements=bamgmesh_out['Triangles'][:,0:3].astype(int)
    327         md.mesh.edges=bamgmesh_out['IssmEdges'].astype(int)
    328         md.mesh.segments=bamgmesh_out['IssmSegments'][:,0:3].astype(int)
    329         md.mesh.segmentmarkers=bamgmesh_out['IssmSegments'][:,3].astype(int)
    330 
    331         #Fill in rest of fields:
    332         md.mesh.numberofelements=numpy.size(md.mesh.elements,axis=0)
    333         md.mesh.numberofvertices=numpy.size(md.mesh.x)
    334         md.mesh.numberofedges=numpy.size(md.mesh.edges,axis=0)
    335         md.mesh.vertexonboundary=numpy.zeros(md.mesh.numberofvertices,bool)
    336         md.mesh.vertexonboundary[md.mesh.segments[:,0:2]-1]=True
    337475        md.mesh.elementconnectivity=md.private.bamg['mesh'].ElementConnectivity
    338         md.mesh.elementconnectivity[numpy.nonzero(numpy.isnan(md.mesh.elementconnectivity))]=0
     476        md.mesh.elementconnectivity[np.nonzero(np.isnan(md.mesh.elementconnectivity))]=0
    339477        md.mesh.elementconnectivity=md.mesh.elementconnectivity.astype(int)
    340478
    341479        #Check for orphan
    342         if numpy.any(numpy.logical_not(numpy.in1d(numpy.arange(1,md.mesh.numberofvertices+1),md.mesh.elements.flat))):
    343                 raise RuntimeError("Output mesh has orphans. Decrease MaxCornerAngle to prevent outside points (ex: 0.01)")
     480        if np.any(np.logical_not(np.in1d(np.arange(1,md.mesh.numberofvertices+1),md.mesh.elements.flat))):
     481                raise RuntimeError("Output mesh has orphans. Check your Domain and/or RequiredVertices")
    344482
    345483        return md
     
    351489        print("Checking Edge crossing...")
    352490        i=0
    353         while (i<numpy.size(geom.Edges,axis=0)):
     491        while (i<np.size(geom.Edges,axis=0)):
    354492
    355493                #edge counter
     
    364502
    365503                j=i    #test edges located AFTER i only
    366                 while (j<numpy.size(geom.Edges,axis=0)):
     504                while (j<np.size(geom.Edges,axis=0)):
    367505
    368506                        #edge counter
     
    381519
    382520                        #Check if the two edges are crossing one another
    383                         if SegIntersect(numpy.array([[x1,y1],[x2,y2]]),numpy.array([[x3,y3],[x4,y4]])):
     521                        if SegIntersect(np.array([[x1,y1],[x2,y2]]),np.array([[x3,y3],[x4,y4]])):
    384522
    385523                                #Get coordinate of intersection point (http://mathworld.wolfram.com/Line-LineIntersection.html)
    386                                 x=numpy.linalg.det(numpy.array([numpy.linalg.det(numpy.array([[x1,y1],[x2,y2]])),x1-x2],[numpy.linalg.det(numpy.array([[x3,y3],[x4,y4]])),x3-x4])/numpy.linalg.det(numpy.array([[x1-x2,y1-y2],[x3-x4,y3-y4]])))
    387                                 y=numpy.linalg.det(numpy.array([numpy.linalg.det(numpy.array([[x1,y1],[x2,y2]])),y1-y2],[numpy.linalg.det(numpy.array([[x3,y3],[x4,y4]])),y3-y4])/numpy.linalg.det(numpy.array([[x1-x2,y1-y2],[x3-x4,y3-y4]])))
     524                                x=np.linalg.det(np.array([np.linalg.det(np.array([[x1,y1],[x2,y2]])),x1-x2],[np.linalg.det(np.array([[x3,y3],[x4,y4]])),x3-x4])/np.linalg.det(np.array([[x1-x2,y1-y2],[x3-x4,y3-y4]])))
     525                                y=np.linalg.det(np.array([np.linalg.det(np.array([[x1,y1],[x2,y2]])),y1-y2],[np.linalg.det(np.array([[x3,y3],[x4,y4]])),y3-y4])/np.linalg.det(np.array([[x1-x2,y1-y2],[x3-x4,y3-y4]])))
    388526
    389527                                #Add vertex to the list of vertices
    390                                 geom.Vertices=numpy.vstack((geom.Vertices,[x,y,min(color1,color2)]))
    391                                 id=numpy.size(geom.Vertices,axis=0)
     528                                geom.Vertices=np.vstack((geom.Vertices,[x,y,min(color1,color2)]))
     529                                id=np.size(geom.Vertices,axis=0)
    392530
    393531                                #Update edges i and j
     
    395533                                edgej=geom.Edges[j,:].copy()
    396534                                geom.Edges[i,:]    =[edgei(0),id      ,edgei(2)]
    397                                 geom.Edges=numpy.vstack((geom.Edges,[id      ,edgei(1),edgei(2)]))
     535                                geom.Edges=np.vstack((geom.Edges,[id      ,edgei(1),edgei(2)]))
    398536                                geom.Edges[j,:]    =[edgej(0),id      ,edgej(2)]
    399                                 geom.Edges=numpy.vstack((geom.Edges,[id      ,edgej(1),edgej(2)]))
     537                                geom.Edges=np.vstack((geom.Edges,[id      ,edgej(1),edgej(2)]))
    400538
    401539                                #update current edge second tip
     
    407545        i=0
    408546        num=0
    409         while (i<numpy.size(geom.Vertices,axis=0)):
     547        while (i<np.size(geom.Vertices,axis=0)):
    410548
    411549                #vertex counter
     
    425563
    426564                        #update edges
    427                         posedges=numpy.nonzero(geom.Edges==i)
     565                        posedges=np.nonzero(geom.Edges==i)
    428566                        geom.Edges[posedges[0],:]=[]
    429                         posedges=numpy.nonzero(geom.Edges>i)
     567                        posedges=np.nonzero(geom.Edges>i)
    430568                        geom.Edges[posedges]=geom.Edges[posedges]-1
    431569
  • issm/trunk-jpl/src/py3/mesh/meshconvert.py

    r19895 r23670  
    1 import numpy
     1import numpy as np
    22from collections import OrderedDict
    33from BamgConvertMesh import BamgConvertMesh
     
    4343
    4444        #Fill in rest of fields:
    45         md.mesh.numberofelements   = numpy.size(md.mesh.elements,axis=0)
    46         md.mesh.numberofvertices   = numpy.size(md.mesh.x)
    47         md.mesh.numberofedges      = numpy.size(md.mesh.edges,axis=0)
    48         md.mesh.vertexonboundary   = numpy.zeros(md.mesh.numberofvertices,bool)
     45        md.mesh.numberofelements   = np.size(md.mesh.elements,axis=0)
     46        md.mesh.numberofvertices   = np.size(md.mesh.x)
     47        md.mesh.numberofedges      = np.size(md.mesh.edges,axis=0)
     48        md.mesh.vertexonboundary   = np.zeros(md.mesh.numberofvertices,bool)
    4949        md.mesh.vertexonboundary[md.mesh.segments[:,0:2]-1] = True
    5050
  • issm/trunk-jpl/src/py3/mesh/rifts/meshprocessoutsiderifts.py

    r19895 r23670  
    1 import numpy
     1import numpy as np
    22from ElementsFromEdge import ElementsFromEdge
    33import MatlabFuncs as m
     
    1919
    2020                tips=rift.tips
    21                 outsidetips=tips[numpy.nonzero(flags[rift.tips-1])[0]]
     21                outsidetips=tips[np.nonzero(flags[rift.tips-1])[0]]
    2222
    2323                #we have found outsidetips, tips that touch the domain outline. go through them
     
    2626                        #find tip in the segments, take first segment (there should be 2) that holds tip,
    2727                        #and node_connected_to_tip is the other node on this segment:
    28                         tipindex=numpy.nonzero(rift.segments[:,0]==tip)[0]
     28                        tipindex=np.nonzero(rift.segments[:,0]==tip)[0]
    2929                        if tipindex:
    3030                                tipindex=tipindex[0]
    3131                                node_connected_to_tip=rift.segments[tipindex,1]
    3232                        else:
    33                                 tipindex=numpy.nonzero(rift.segments[:,1]==tip)[0]
     33                                tipindex=np.nonzero(rift.segments[:,1]==tip)[0]
    3434                                tipindex=tipindex[0]
    3535                                node_connected_to_tip=rift.segments[tipindex,1]
     
    4141                        B=node_connected_to_tip
    4242
    43                         elements=numpy.empty(0,int)
     43                        elements=np.empty(0,int)
    4444
    4545                        while flags(B):    #as long as B does not belong to the domain outline, keep looking.
     
    4848                                #rule out those we already detected
    4949                                already_detected=m.ismember(edgeelements,elements)
    50                                 nextelement=edgeelements(numpy.nonzero(numpy.logical_not(already_detected))[0])
     50                                nextelement=edgeelements(np.nonzero(np.logical_not(already_detected))[0])
    5151                                #add new detected element to the list of elements we are looking for.
    52                                 elements=numpy.concatenate((elements,nextelement))
     52                                elements=np.concatenate((elements,nextelement))
    5353                                #new B:
    54                                 B=md.mesh.elements[nextelement-1,numpy.nonzero(numpy.logical_not(m.ismember(md.mesh.elements[nextelement-1,:],numpy.array([A,B]))))]
     54                                B=md.mesh.elements[nextelement-1,np.nonzero(np.logical_not(m.ismember(md.mesh.elements[nextelement-1,:],np.array([A,B]))))]
    5555               
    5656                        #take the list of elements on one side of the rift that connect to the tip,
    5757                        #and duplicate the tip on them, so as to open the rift to the outside.
    58                         num=numpy.size(md.mesh.x)+1
    59                         md.mesh.x=numpy.concatenate((md.mesh.x,md.mesh.x[tip]))
    60                         md.mesh.y=numpy.concatenate((md.mesh.y,md.mesh.y[tip]))
     58                        num=np.size(md.mesh.x)+1
     59                        md.mesh.x=np.concatenate((md.mesh.x,md.mesh.x[tip]))
     60                        md.mesh.y=np.concatenate((md.mesh.y,md.mesh.y[tip]))
    6161                        md.mesh.numberofvertices=num
    6262               
    6363                        #replace tip in elements
    6464                        newelements=md.mesh.elements[elements-1,:]
    65                         pos=numpy.nonzero(newelements==tip)
     65                        pos=np.nonzero(newelements==tip)
    6666                        newelements[pos]=num
    6767                        md.mesh.elements[elements-1,:]=newelements
    68                         rift.tips=numpy.concatenate((rift.tips,num))
     68                        rift.tips=np.concatenate((rift.tips,num))
    6969
    7070                        #deal with segments
    71                         tipsegments=numpy.nonzero(numpy.logical_or(md.mesh.segments[:,0]==tip,md.mesh.segments[:,1]==tip))[0]
     71                        tipsegments=np.nonzero(np.logical_or(md.mesh.segments[:,0]==tip,md.mesh.segments[:,1]==tip))[0]
    7272                        for segment_index in tipsegments:
    73                                 pos=numpy.nonzero(md.mesh.segments[segment_index,0:2]!=tip)[0]
     73                                pos=np.nonzero(md.mesh.segments[segment_index,0:2]!=tip)[0]
    7474                                other_node=md.mesh.segments[segment_index,pos]
    7575                                if not isconnected(md.mesh.elements,other_node,tip):
    76                                         pos=numpy.nonzero(md.mesh.segments[segment_index,0:2]==tip)[0]
     76                                        pos=np.nonzero(md.mesh.segments[segment_index,0:2]==tip)[0]
    7777                                        md.mesh.segments[segment_index,pos]=num
    7878
    7979        #Fill in rest of fields:
    80         md.mesh.numberofelements=numpy.size(md.mesh.elements,axis=0)
    81         md.mesh.numberofvertices=numpy.size(md.mesh.x)
    82         md.mesh.vertexonboundary=numpy.zeros(numpy.size(md.mesh.x),bool)
     80        md.mesh.numberofelements=np.size(md.mesh.elements,axis=0)
     81        md.mesh.numberofvertices=np.size(md.mesh.x)
     82        md.mesh.vertexonboundary=np.zeros(np.size(md.mesh.x),bool)
    8383        md.mesh.vertexonboundary[md.mesh.segments[:,0:2]-1]=True
    8484        md.rifts.numrifts=length(md.rifts.riftstruct)
  • issm/trunk-jpl/src/py3/mesh/rifts/meshprocessrifts.py

    r19895 r23670  
    1 import numpy
    2 from TriMeshProcessRifts import TriMeshProcessRifts
     1import numpy as np
     2from ProcessRifts import ProcessRifts
    33from ContourToMesh import ContourToMesh
    44from meshprocessoutsiderifts import meshprocessoutsiderifts
     
    2222
    2323        #Call MEX file
    24         [md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.segments,md.mesh.segmentmarkers,md.rifts.riftstruct]=TriMeshProcessRifts(md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.segments,md.mesh.segmentmarkers)
     24        md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.segments,md.mesh.segmentmarkers,md.rifts.riftstruct=ProcessRifts(md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.segments,md.mesh.segmentmarkers)
    2525        md.mesh.elements=md.mesh.elements.astype(int)
    2626        md.mesh.x=md.mesh.x.reshape(-1)
     
    2929        md.mesh.segmentmarkers=md.mesh.segmentmarkers.astype(int)
    3030        if not isinstance(md.rifts.riftstruct,list) or not md.rifts.riftstruct:
    31                 raise RuntimeError("TriMeshProcessRifts did not find any rift")
     31                raise RuntimeError("ProcessRifts did not find any rift")
    3232
    3333        #Fill in rest of fields:
    3434        numrifts=len(md.rifts.riftstruct)
    35         md.mesh.numberofelements=numpy.size(md.mesh.elements,axis=0)
    36         md.mesh.numberofvertices=numpy.size(md.mesh.x)
    37         md.mesh.vertexonboundary=numpy.zeros(numpy.size(md.mesh.x),bool)
     35        md.mesh.numberofelements=np.size(md.mesh.elements,axis=0)
     36        md.mesh.numberofvertices=np.size(md.mesh.x)
     37        md.mesh.vertexonboundary=np.zeros(np.size(md.mesh.x),bool)
    3838        md.mesh.vertexonboundary[md.mesh.segments[:,0:2]-1]=True
    3939
    4040        #get coordinates of rift tips
    4141        for rift in md.rifts.riftstruct:
    42                 rift['tip1coordinates']=numpy.hstack((md.mesh.x[rift['tips'][0,0].astype(int)-1].reshape(-1,1),md.mesh.y[rift['tips'][0,0].astype(int)-1].reshape(-1,1)))
    43                 rift['tip2coordinates']=numpy.hstack((md.mesh.x[rift['tips'][0,1].astype(int)-1].reshape(-1,1),md.mesh.y[rift['tips'][0,1].astype(int)-1].reshape(-1,1)))
     42                rift['tip1coordinates']=np.hstack((md.mesh.x[rift['tips'][0,0].astype(int)-1].reshape(-1,),md.mesh.y[rift['tips'][0,0].astype(int)-1].reshape(-1,)))
     43                rift['tip2coordinates']=np.hstack((md.mesh.x[rift['tips'][0,1].astype(int)-1].reshape(-1,),md.mesh.y[rift['tips'][0,1].astype(int)-1].reshape(-1,)))
    4444
    4545        #In case we have rifts that open up the domain outline, we need to open them:
    46         [flags,dum]=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,domainoutline,'node',0)
     46        flags=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,domainoutline,'node',0)
    4747        found=0
    4848        for rift in md.rifts.riftstruct:
     
    5858        #get elements that are not correctly oriented in the correct direction:
    5959        aires=GetAreas(md.mesh.elements,md.mesh.x,md.mesh.y)
    60         pos=numpy.nonzero(aires<0)[0]
    61         md.mesh.elements[pos,:]=numpy.hstack((md.mesh.elements[pos,1].reshape(-1,1),md.mesh.elements[pos,0].reshape(-1,1),md.mesh.elements[pos,2].reshape(-1,1)))
     60        pos=np.nonzero(aires<0)[0]
     61        md.mesh.elements[pos,:]=np.vstack((md.mesh.elements[pos,1],md.mesh.elements[pos,0],md.mesh.elements[pos,2])).T
    6262
    6363        return md
  • issm/trunk-jpl/src/py3/mesh/roundmesh.py

    r19895 r23670  
    1 import numpy
     1import numpy as np
    22import os
    33from collections import OrderedDict
     
    2020
    2121        #Get number of points on the circle
    22         pointsonedge=numpy.floor((2.*numpy.pi*radius) / resolution)
     22        pointsonedge=np.floor((2.*np.pi*radius) / resolution)+1 #+1 to close the outline
    2323
    2424        #Calculate the cartesians coordinates of the points
    25         x_list=numpy.ones(pointsonedge)
    26         y_list=numpy.ones(pointsonedge)
    27         theta=numpy.linspace(0.,2.*numpy.pi,num=pointsonedge,endpoint=False)
    28         x_list=roundsigfig(radius*x_list*numpy.cos(theta),12)
    29         y_list=roundsigfig(radius*y_list*numpy.sin(theta),12)
     25        theta=np.linspace(0.,2.*np.pi,pointsonedge)
     26        x_list=roundsigfig(radius*np.cos(theta),12)
     27        y_list=roundsigfig(radius*np.sin(theta),12)
    3028        A=OrderedDict()
    3129        A['x']=[x_list]
     
    3937
    4038        #move the closest node to the center
    41         pos=numpy.argmin(md.mesh.x**2+md.mesh.y**2)
     39        pos=np.argmin(md.mesh.x**2+md.mesh.y**2)
    4240        md.mesh.x[pos]=0.
    4341        md.mesh.y[pos]=0.
     
    5048def roundsigfig(x,n):
    5149
    52         digits=numpy.ceil(numpy.log10(numpy.abs(x)))
     50        digits=np.ceil(np.log10(np.abs(x)))
    5351        x=x/10.**digits
    54         x=numpy.round(x,decimals=n)
     52        x=np.round(x,decimals=n)
    5553        x=x*10.**digits
    5654
    57         pos=numpy.nonzero(numpy.isnan(x))
     55        pos=np.nonzero(np.isnan(x))
    5856        x[pos]=0.
    5957
  • issm/trunk-jpl/src/py3/mesh/squaremesh.py

    r19895 r23670  
    1 import numpy
     1import numpy as np
    22from NodeConnectivity import NodeConnectivity
    33from ElementConnectivity import ElementConnectivity
     
    2222
    2323        #initialization
    24         index=numpy.zeros((nel,3),int)
    25         x=numpy.zeros((nx*ny))
    26         y=numpy.zeros((nx*ny))
     24        index=np.zeros((nel,3),int)
     25        x=np.zeros((nx*ny))
     26        y=np.zeros((nx*ny))
    2727
    2828        #create coordinates
     
    4343
    4444        #Scale  x and y
    45         x=x/numpy.max(x)*Lx
    46         y=y/numpy.max(y)*Ly
     45        x=x/np.max(x)*Lx
     46        y=y/np.max(y)*Ly
    4747
    4848        #create segments
    49         segments=numpy.zeros((2*(nx-1)+2*(ny-1),3),int)
     49        segments=np.zeros((2*(nx-1)+2*(ny-1),3),int)
    5050        #left edge:
    51         segments[0:ny-1,:]=numpy.hstack((numpy.arange(2,ny+1).reshape(-1,1),numpy.arange(1,ny).reshape(-1,1),(2*numpy.arange(1,ny)-1).reshape(-1,1)))
     51        segments[0:ny-1,:]=np.vstack((np.arange(2,ny+1),np.arange(1,ny),(2*np.arange(1,ny)-1))).T
    5252        #right edge:
    53         segments[ny-1:2*(ny-1),:]=numpy.hstack((numpy.arange(ny*(nx-1)+1,nx*ny).reshape(-1,1),numpy.arange(ny*(nx-1)+2,nx*ny+1).reshape(-1,1),2*numpy.arange((ny-1)*(nx-2)+1,(nx-1)*(ny-1)+1).reshape(-1,1)))
     53        segments[ny-1:2*(ny-1),:]=np.vstack((np.arange(ny*(nx-1)+1,nx*ny),np.arange(ny*(nx-1)+2,nx*ny+1),2*np.arange((ny-1)*(nx-2)+1,(nx-1)*(ny-1)+1))).T
    5454        #front edge:
    55         segments[2*(ny-1):2*(ny-1)+(nx-1),:]=numpy.hstack((numpy.arange(2*ny,ny*nx+1,ny).reshape(-1,1),numpy.arange(ny,ny*(nx-1)+1,ny).reshape(-1,1),numpy.arange(2*(ny-1),2*(nx-1)*(ny-1)+1,2*(ny-1)).reshape(-1,1)))
     55        segments[2*(ny-1):2*(ny-1)+(nx-1),:]=np.vstack((np.arange(2*ny,ny*nx+1,ny),np.arange(ny,ny*(nx-1)+1,ny),np.arange(2*(ny-1),2*(nx-1)*(ny-1)+1,2*(ny-1)))).T
    5656        #back edge
    57         segments[2*(ny-1)+(nx-1):2*(nx-1)+2*(ny-1),:]=numpy.hstack((numpy.arange(1,(nx-2)*ny+2,ny).reshape(-1,1),numpy.arange(ny+1,ny*(nx-1)+2,ny).reshape(-1,1),numpy.arange(1,2*(nx-2)*(ny-1)+2,2*(ny-1)).reshape(-1,1)))
     57        segments[2*(ny-1)+(nx-1):2*(nx-1)+2*(ny-1),:]=np.vstack((np.arange(1,(nx-2)*ny+2,ny),np.arange(ny+1,ny*(nx-1)+2,ny),np.arange(1,2*(nx-2)*(ny-1)+2,2*(ny-1)))).T
    5858
    5959        #plug coordinates and nodes
     
    6262        md.mesh.y=y
    6363        md.mesh.numberofvertices=nods
    64         md.mesh.vertexonboundary=numpy.zeros((nods),bool)
     64        md.mesh.vertexonboundary=np.zeros((nods),bool)
    6565        md.mesh.vertexonboundary[segments[:,0:2]-1]=True
    6666
     
    7171
    7272        #Now, build the connectivity tables for this mesh.
    73         [md.mesh.vertexconnectivity]=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices)
    74         [md.mesh.elementconnectivity]=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity)
     73        md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices)[0]
     74        md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity)[0]
    7575
    7676        return md
  • issm/trunk-jpl/src/py3/mesh/triangle.py

    r19895 r23670  
    1 import numpy
     1import os.path
     2import numpy as np
    23from mesh2d import mesh2d
    3 from TriMesh import TriMesh
    44from NodeConnectivity import NodeConnectivity
    55from ElementConnectivity import ElementConnectivity
     6from Triangle_python import Triangle_python
    67import MatlabFuncs as m
    78
     
    1011        TRIANGLE - create model mesh using the triangle package
    1112
    12            This routine creates a model mesh using TriMesh and a domain outline, to within a certain resolution
     13           This routine creates a model mesh using Triangle and a domain outline, to within a certain resolution
    1314           where md is a @model object, domainname is the name of an Argus domain outline file,
    1415           and resolution is a characteristic length for the mesh (same unit as the domain outline
     
    4344        area = resolution**2
    4445
    45         #Mesh using TriMesh
     46        #Check that file exist (this is a very very common mistake)
     47        if not os.path.exists(domainname):
     48                raise IOError("file '%s' not found" % domainname)
     49
     50        #Mesh using Triangle
    4651        md.mesh=mesh2d()
    47         [md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.segments,md.mesh.segmentmarkers]=TriMesh(domainname,riftname,area)
     52        md.mesh.elements,md.mesh.x,md.mesh.y,md.mesh.segments,md.mesh.segmentmarkers=Triangle_python(domainname,riftname,area)
    4853        md.mesh.elements=md.mesh.elements.astype(int)
    4954        md.mesh.segments=md.mesh.segments.astype(int)
     
    5156
    5257        #Fill in rest of fields:
    53         md.mesh.numberofelements = numpy.size(md.mesh.elements,axis=0)
    54         md.mesh.numberofvertices = numpy.size(md.mesh.x)
    55         md.mesh.vertexonboundary = numpy.zeros(md.mesh.numberofvertices,bool)
     58        md.mesh.numberofelements = np.size(md.mesh.elements,axis=0)
     59        md.mesh.numberofvertices = np.size(md.mesh.x)
     60        md.mesh.vertexonboundary = np.zeros(md.mesh.numberofvertices,bool)
    5661        md.mesh.vertexonboundary[md.mesh.segments[:,0:2]-1] = True
    5762
    5863        #Now, build the connectivity tables for this mesh.
    59         [md.mesh.vertexconnectivity] = NodeConnectivity(md.mesh.elements, md.mesh.numberofvertices)
    60         [md.mesh.elementconnectivity] = ElementConnectivity(md.mesh.elements, md.mesh.vertexconnectivity)
     64        md.mesh.vertexconnectivity = NodeConnectivity(md.mesh.elements, md.mesh.numberofvertices)[0]
     65        md.mesh.elementconnectivity = ElementConnectivity(md.mesh.elements, md.mesh.vertexconnectivity)[0]
    6166
    6267        return md
  • issm/trunk-jpl/src/py3/miscellaneous/MatlabFuncs.py

    r19895 r23670  
    4949
    5050def ismember(a,s):
    51         import numpy
     51        import numpy as np
    5252
    53         if not isinstance(s,(tuple,list,dict,numpy.ndarray)):
     53        if not isinstance(s,(tuple,list,dict,np.ndarray)):
    5454                s=[s]
    5555
    56         if not isinstance(a,(tuple,list,dict,numpy.ndarray)):
     56        if not isinstance(a,(tuple,list,dict,np.ndarray)):
    5757                a=[a]
    5858
    59         if not isinstance(a,numpy.ndarray):
     59        if not isinstance(a,np.ndarray):
    6060                b=[item in s for item in a]
    6161
    6262        else:
    63                 if not isinstance(s,numpy.ndarray):
    64                         b=numpy.empty_like(a)
     63                if not isinstance(s,np.ndarray):
     64                        b=np.empty_like(a)
    6565                        for i,item in enumerate(a.flat):
    6666                                b.flat[i]=item in s
    6767                else:
    68                         b=numpy.in1d(a.flat,s.flat).reshape(a.shape)
     68                        b=np.in1d(a.flat,s.flat).reshape(a.shape)
    6969
    7070        return b
    7171
    7272def det(a):
    73         import numpy
     73        import numpy as np
    7474
    7575        if   a.shape==(1,):
     
    8383
    8484def sparse(ivec,jvec,svec,m=0,n=0,nzmax=0):
    85         import numpy
     85        import numpy as np
    8686
    8787        if not m:
    88                 m=numpy.max(ivec)
     88                m=np.max(ivec)
    8989        if not n:
    90                 n=numpy.max(jvec)
     90                n=np.max(jvec)
    9191
    92         a=numpy.zeros((m,n))
     92        a=np.zeros((m,n))
    9393
    9494        for i,j,s in zip(ivec.reshape(-1,order='F'),jvec.reshape(-1,order='F'),svec.reshape(-1,order='F')):
     
    9898
    9999def heaviside(x):
    100         import numpy
     100        import numpy as np
    101101
    102         y=numpy.zeros_like(x)
    103         y[numpy.nonzero(x> 0.)]=1.
    104         y[numpy.nonzero(x==0.)]=0.5
     102        y=np.zeros_like(x)
     103        y[np.nonzero(x> 0.)]=1.
     104        y[np.nonzero(x==0.)]=0.5
    105105
    106106        return y
    107 
  • issm/trunk-jpl/src/py3/miscellaneous/PythonFuncs.py

    r19895 r23670  
     1import numpy as np
     2
    13def logical_and_n(*arg):
    2         from numpy import logical_and
    3 
     4       
    45        if len(arg):
    56                result=arg[0]
     
    1213
    1314def logical_or_n(*arg):
    14         from numpy import logical_or
    15 
     15       
    1616        if len(arg):
    1717                result=arg[0]
  • issm/trunk-jpl/src/py3/miscellaneous/fielddisplay.py

    r19895 r23670  
    11#Module import
    2 import numpy
     2import numpy as np
    33from math import isnan
    44import MatlabFuncs as m
     
    3333
    3434        #matrix
    35         elif isinstance(field,numpy.ndarray):
     35        elif isinstance(field,np.ndarray):
    3636                string=displayunit(offset,name,str(field.shape),comment)
    3737
  • issm/trunk-jpl/src/py3/miscellaneous/isnans.py

    r19895 r23670  
    1 import numpy
     1import numpy as np
    22
    33def isnans(array):
     
    1313                returnvalue=0
    1414        else:
    15                 returnvalue=numpy.isnan(array)
     15                returnvalue=np.isnan(array)
    1616
    1717        return returnvalue
  • issm/trunk-jpl/src/py3/os/issmssh.py

    r19895 r23670  
    11from socket import gethostname
     2from sys import platform as _platform
    23import subprocess
    34import os
     
    4546        # (from http://code.google.com/p/robotframework/issues/detail?id=995)
    4647
    47         # Make FreeBSD use blocking I/O like other platforms
    48         import sys
    49         import fcntl
    50         from os import O_NONBLOCK
     48        if _platform == "darwin":
     49                # Make FreeBSD use blocking I/O like other platforms
     50                import sys
     51                import fcntl
     52                from os import O_NONBLOCK
     53               
     54                fd = sys.stdin.fileno()
     55                flags = fcntl.fcntl(fd, fcntl.F_GETFL)
     56                fcntl.fcntl(fd, fcntl.F_SETFL, flags & ~O_NONBLOCK)
     57               
     58                fd = sys.stdout.fileno()
     59                flags = fcntl.fcntl(fd, fcntl.F_GETFL)
     60                fcntl.fcntl(fd, fcntl.F_SETFL, flags & ~O_NONBLOCK)
    5161
    52         fd = sys.stdin.fileno()
    53         flags = fcntl.fcntl(fd, fcntl.F_GETFL)
    54         fcntl.fcntl(fd, fcntl.F_SETFL, flags & ~O_NONBLOCK)
    55 
    56         fd = sys.stdout.fileno()
    57         flags = fcntl.fcntl(fd, fcntl.F_GETFL)
    58         fcntl.fcntl(fd, fcntl.F_SETFL, flags & ~O_NONBLOCK)
    59 
  • issm/trunk-jpl/src/py3/parameterization/contourenvelope.py

    r19895 r23670  
    11import os.path
    2 import numpy
     2import numpy as np
    33import copy
    44from NodeConnectivity import NodeConnectivity
     
    4040        #Now, build the connectivity tables for this mesh.
    4141        #Computing connectivity
    42         if numpy.size(md.mesh.vertexconnectivity,axis=0)!=md.mesh.numberofvertices and numpy.size(md.mesh.vertexconnectivity,axis=0)!=md.mesh.numberofvertices2d:
    43                 [md.mesh.vertexconnectivity]=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices)
    44         if numpy.size(md.mesh.elementconnectivity,axis=0)!=md.mesh.numberofelements and numpy.size(md.mesh.elementconnectivity,axis=0)!=md.mesh.numberofelements2d:
    45                 [md.mesh.elementconnectivity]=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity)
     42        if np.size(md.mesh.vertexconnectivity,axis=0)!=md.mesh.numberofvertices and np.size(md.mesh.vertexconnectivity,axis=0)!=md.mesh.numberofvertices2d:
     43                md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices)[0]
     44        if np.size(md.mesh.elementconnectivity,axis=0)!=md.mesh.numberofelements and np.size(md.mesh.elementconnectivity,axis=0)!=md.mesh.numberofelements2d:
     45                md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity)[0]
    4646
    4747        #get nodes inside profile
     
    6565                        #get flag list of elements and nodes inside the contour
    6666                        nodein=ContourToMesh(elements,x,y,file,'node',1)
    67                         elemin=(numpy.sum(nodein(elements),axis=1)==numpy.size(elements,axis=1))
     67                        elemin=(np.sum(nodein(elements),axis=1)==np.size(elements,axis=1))
    6868                        #modify element connectivity
    69                         elemout=numpy.nonzero(numpy.logical_not(elemin))[0]
     69                        elemout=np.nonzero(np.logical_not(elemin))[0]
    7070                        elementconnectivity[elemout,:]=0
    71                         elementconnectivity[numpy.nonzero(m.ismember(elementconnectivity,elemout+1))]=0
     71                        elementconnectivity[np.nonzero(m.ismember(elementconnectivity,elemout+1))]=0
    7272                else:
    7373                        #get flag list of elements and nodes inside the contour
    74                         nodein=numpy.zeros(numberofvertices)
    75                         elemin=numpy.zeros(numberofelements)
     74                        nodein=np.zeros(numberofvertices)
     75                        elemin=np.zeros(numberofelements)
    7676
    77                         pos=numpy.nonzero(flags)
     77                        pos=np.nonzero(flags)
    7878                        elemin[pos]=1
    7979                        nodein[elements[pos,:]-1]=1
    8080
    8181                        #modify element connectivity
    82                         elemout=numpy.nonzero(numpy.logical_not(elemin))[0]
     82                        elemout=np.nonzero(np.logical_not(elemin))[0]
    8383                        elementconnectivity[elemout,:]=0
    84                         elementconnectivity[numpy.nonzero(m.ismember(elementconnectivity,elemout+1))]=0
     84                        elementconnectivity[np.nonzero(m.ismember(elementconnectivity,elemout+1))]=0
    8585
    8686        #Find element on boundary
     
    8888        flag=copy.deepcopy(elementconnectivity)
    8989        if len(args)==1:
    90                 flag[numpy.nonzero(flag)]=elemin[flag[numpy.nonzero(flag)]]
    91         elementonboundary=numpy.logical_and(numpy.prod(flag,axis=1)==0,numpy.sum(flag,axis=1)>0)
     90                flag[np.nonzero(flag)]=elemin[flag[np.nonzero(flag)]]
     91        elementonboundary=np.logical_and(np.prod(flag,axis=1)==0,np.sum(flag,axis=1)>0)
    9292
    9393        #Find segments on boundary
    94         pos=numpy.nonzero(elementonboundary)[0]
    95         num_segments=numpy.size(pos)
    96         segments=numpy.zeros((num_segments*3,3),int)
     94        pos=np.nonzero(elementonboundary)[0]
     95        num_segments=np.size(pos)
     96        segments=np.zeros((num_segments*3,3),int)
    9797        count=0
    9898
    9999        for el1 in pos:
    100                 els2=elementconnectivity[el1,numpy.nonzero(elementconnectivity[el1,:])[0]]-1
    101                 if numpy.size(els2)>1:
    102                         flag=numpy.intersect1d(numpy.intersect1d(elements[els2[0],:],elements[els2[1],:]),elements[el1,:])
     100                els2=elementconnectivity[el1,np.nonzero(elementconnectivity[el1,:])[0]]-1
     101                if np.size(els2)>1:
     102                        flag=np.intersect1d(np.intersect1d(elements[els2[0],:],elements[els2[1],:]),elements[el1,:])
    103103                        nods1=elements[el1,:]
    104                         nods1=numpy.delete(nods1,numpy.nonzero(nods1==flag))
     104                        nods1=np.delete(nods1,np.nonzero(nods1==flag))
    105105                        segments[count,:]=[nods1[0],nods1[1],el1+1]
    106106
    107                         ord1=numpy.nonzero(nods1[0]==elements[el1,:])[0][0]
    108                         ord2=numpy.nonzero(nods1[1]==elements[el1,:])[0][0]
     107                        ord1=np.nonzero(nods1[0]==elements[el1,:])[0][0]
     108                        ord2=np.nonzero(nods1[1]==elements[el1,:])[0][0]
    109109
    110110                        #swap segment nodes if necessary
     
    113113                                segments[count,0]=segments[count,1]
    114114                                segments[count,1]=temp
    115                         segments[count,0:2]=numpy.flipud(segments[count,0:2])
     115                        segments[count,0:2]=np.flipud(segments[count,0:2])
    116116                        count+=1
    117117                else:
    118118                        nods1=elements[el1,:]
    119                         flag=numpy.setdiff1d(nods1,elements[els2,:])
     119                        flag=np.setdiff1d(nods1,elements[els2,:])
    120120                        for j in range(0,3):
    121                                 nods=numpy.delete(nods1,j)
    122                                 if numpy.any(m.ismember(flag,nods)):
     121                                nods=np.delete(nods1,j)
     122                                if np.any(m.ismember(flag,nods)):
    123123                                        segments[count,:]=[nods[0],nods[1],el1+1]
    124                                         ord1=numpy.nonzero(nods[0]==elements[el1,:])[0][0]
    125                                         ord2=numpy.nonzero(nods[1]==elements[el1,:])[0][0]
     124                                        ord1=np.nonzero(nods[0]==elements[el1,:])[0][0]
     125                                        ord2=np.nonzero(nods[1]==elements[el1,:])[0][0]
    126126                                        if ( (ord1==0 and ord2==1) or (ord1==1 and ord2==2) or (ord1==2 and ord2==0) ):
    127127                                                temp=segments[count,0]
    128128                                                segments[count,0]=segments[count,1]
    129129                                                segments[count,1]=temp
    130                                         segments[count,0:2]=numpy.flipud(segments[count,0:2])
     130                                        segments[count,0:2]=np.flipud(segments[count,0:2])
    131131                                        count+=1
    132132        segments=segments[0:count,:]
  • issm/trunk-jpl/src/py3/parameterization/setflowequation.py

    r19895 r23670  
    1 import numpy
     1import numpy as np
    22from model import model
    33from pairoptions import pairoptions
    4 import MatlabFuncs as m
    5 import PythonFuncs as p
    64from FlagElements import FlagElements
    75
    8 def setflowequation(md,**kwargs):
     6def setflowequation(md,*args):
    97        """
    108        SETFLOWEQUATION - associate a solution type to each element
     
    2826
    2927        #some checks on list of arguments
    30         if not isinstance(md,model) or not len(kwargs):
     28        if not isinstance(md,model) or not len(args):
    3129                raise TypeError("setflowequation error message")
    3230
    3331        #process options
    34         options=pairoptions(**kwargs)
    35         print(options)
    36 #       options=deleteduplicates(options,1);
     32        options=pairoptions(*args)
     33        #       options=deleteduplicates(options,1);
    3734
    3835        #Find_out what kind of coupling to use
    3936        coupling_method=options.getfieldvalue('coupling','tiling')
    40         if coupling_method is not 'tiling' or not 'penalties':
     37        if not coupling_method in ['tiling','penalties']:
    4138                raise TypeError("coupling type can only be: tiling or penalties")
    4239
     
    4845        FSflag   = FlagElements(md,options.getfieldvalue('FS',''))
    4946        filltype     = options.getfieldvalue('fill','none')
    50 
    5147        #Flag the elements that have not been flagged as filltype
    52         if filltype is 'SIA':
    53                 SIAflag[numpy.nonzero(numpy.logical_not(p.logical_or_n(SSAflag,HOflag)))]=True
    54         elif filltype is 'SSA':
    55                 SSAflag[numpy.nonzero(numpy.logical_not(p.logical_or_n(SIAflag,HOflag,FSflag)))]=True
    56         elif filltype is 'HO':
    57                 HOflag[numpy.nonzero(numpy.logical_not(p.logical_or_n(SIAflag,SSAflag,FSflag)))]=True
    58 
     48        if 'SIA' in filltype:
     49                SIAflag= ~SSAflag & ~HOflag
     50        elif 'SSA' in filltype:
     51                SSAflag=~SIAflag & ~HOflag & ~FSflag
     52        elif 'HO' in filltype:
     53                HOflag=~SIAflag & ~SSAflag & ~FSflag
    5954        #check that each element has at least one flag
    6055        if not any(SIAflag+SSAflag+L1L2flag+HOflag+FSflag):
     
    6459        if any(SIAflag+SSAflag+L1L2flag+HOflag+FSflag>1):
    6560                print("setflowequation warning message: some elements have several types, higher order type is used for them")
    66                 SIAflag[numpy.nonzero(numpy.logical_and(SIAflag,SSAflag))]=False
    67                 SIAflag[numpy.nonzero(numpy.logical_and(SIAflag,HOflag))]=False
    68                 SSAflag[numpy.nonzero(numpy.logical_and(SSAflag,HOflag))]=False
     61                SIAflag[np.where(np.logical_and(SIAflag,SSAflag))]=False
     62                SIAflag[np.where(np.logical_and(SIAflag,HOflag))]=False
     63                SSAflag[np.where(np.logical_and(SSAflag,HOflag))]=False
     64
     65                #check that L1L2 is not coupled to any other model for now
     66                if any(L1L2flag) and any(SIAflag+SSAflag+HOflag+FSflag):
     67                        raise TypeError('L1L2 cannot be coupled to any other model')
     68
     69                #Check that no HO or FS for 2d mesh
     70                if domaintype(md.mesh)=='2Dhorizontal':
     71                        if any(FSflag+HOflag):
     72                                raise TypeError('FS and HO elements not allowed in 2d mesh, extrude it first')
    6973
    7074        #FS can only be used alone for now:
     
    7377
    7478        #Initialize node fields
    75         nodeonSIA=numpy.zeros(md.mesh.numberofvertices,bool)
    76         nodeonSIA[md.mesh.elements[numpy.nonzero(SIAflag),:]-1]=True
    77         nodeonSSA=numpy.zeros(md.mesh.numberofvertices,bool)
    78         nodeonSSA[md.mesh.elements[numpy.nonzero(SSAflag),:]-1]=True
    79         nodeonL1L2=numpy.zeros(md.mesh.numberofvertices,bool)
    80         nodeonL1L2[md.mesh.elements[numpy.nonzero(L1L2flag),:]-1]=True
    81         nodeonHO=numpy.zeros(md.mesh.numberofvertices,bool)
    82         nodeonHO[md.mesh.elements[numpy.nonzero(HOflag),:]-1]=True
    83         nodeonFS=numpy.zeros(md.mesh.numberofvertices,bool)
    84         noneflag=numpy.zeros(md.mesh.numberofelements,bool)
     79        nodeonSIA=np.zeros(md.mesh.numberofvertices,bool)
     80        nodeonSIA[md.mesh.elements[np.where(SIAflag),:]-1]=True
     81        nodeonSSA=np.zeros(md.mesh.numberofvertices,bool)
     82        nodeonSSA[md.mesh.elements[np.where(SSAflag),:]-1]=True
     83        nodeonL1L2=np.zeros(md.mesh.numberofvertices,bool)
     84        nodeonL1L2[md.mesh.elements[np.where(L1L2flag),:]-1]=True
     85        nodeonHO=np.zeros(md.mesh.numberofvertices,bool)
     86        nodeonHO[md.mesh.elements[np.where(HOflag),:]-1]=True
     87        nodeonFS=np.zeros(md.mesh.numberofvertices,bool)
     88        noneflag=np.zeros(md.mesh.numberofelements,bool)
    8589
    8690        #First modify FSflag to get rid of elements contrained everywhere (spc + border with HO or SSA)
    8791        if any(FSflag):
    88 #               fullspcnodes=double((~isnan(md.stressbalance.spcvx)+~isnan(md.stressbalance.spcvy)+~isnan(md.stressbalance.spcvz))==3 | (nodeonHO & nodeonFS));         %find all the nodes on the boundary of the domain without icefront
    89                 fullspcnodes=numpy.logical_or(numpy.logical_not(numpy.isnan(md.stressbalance.spcvx)).astype(int)+ \
    90                                               numpy.logical_not(numpy.isnan(md.stressbalance.spcvy)).astype(int)+ \
    91                                               numpy.logical_not(numpy.isnan(md.stressbalance.spcvz)).astype(int)==3, \
    92                                               numpy.logical_and(nodeonHO,nodeonFS)).astype(int)    #find all the nodes on the boundary of the domain without icefront
    93 #               fullspcelems=double(sum(fullspcnodes(md.mesh.elements),2)==6);         %find all the nodes on the boundary of the domain without icefront
    94                 fullspcelems=(numpy.sum(fullspcnodes[md.mesh.elements-1],axis=1)==6).astype(int)    #find all the nodes on the boundary of the domain without icefront
    95                 FSflag[numpy.nonzero(fullspcelems.reshape(-1))]=False
    96                 nodeonFS[md.mesh.elements[numpy.nonzero(FSflag),:]-1]=True
     92                fullspcnodes=np.logical_or(~np.isnan(md.stressbalance.spcvx)+~np.isnan(md.stressbalance.spcvy)+~np.isnan(md.stressbalance.spcvz),np.logical_and(nodeonHO,nodeonFS))    #find all the nodes on the boundary of the domain without icefront
     93                fullspcelems=np.sum(fullspcnodes[md.mesh.elements-1],axis=1)==6    #find all the nodes on the boundary of the domain without icefront
     94                FSflag[np.where(fullspcelems.reshape(-1))]=False
     95                nodeonFS[md.mesh.elements[np.where(FSflag),:]-1]=True
    9796
    9897        #Then complete with NoneApproximation or the other model used if there is no FS
    9998        if any(FSflag):
    10099                if   any(HOflag):    #fill with HO
    101                         HOflag[numpy.logical_not(FSflag)]=True
    102                         nodeonHO[md.mesh.elements[numpy.nonzero(HOflag),:]-1]=True
     100                        HOflag[~FSflag]=True
     101                        nodeonHO[md.mesh.elements[np.where(HOflag),:]-1]=True
    103102                elif any(SSAflag):    #fill with SSA
    104                         SSAflag[numpy.logical_not(FSflag)]=True
    105                         nodeonSSA[md.mesh.elements[numpy.nonzero(SSAflag),:]-1]=True
     103                        SSAflag[~FSflag]=True
     104                        nodeonSSA[md.mesh.elements[np.where(SSAflag),:]-1]=True
    106105                else:    #fill with none
    107                         noneflag[numpy.nonzero(numpy.logical_not(FSflag))]=True
     106                        noneflag[np.where(~FSflag)]=True
    108107
    109108        #Now take care of the coupling between SSA and HO
    110         md.stressbalance.vertex_pairing=numpy.array([])
    111         nodeonSSAHO=numpy.zeros(md.mesh.numberofvertices,bool)
    112         nodeonHOFS=numpy.zeros(md.mesh.numberofvertices,bool)
    113         nodeonSSAFS=numpy.zeros(md.mesh.numberofvertices,bool)
    114         SSAHOflag=numpy.zeros(md.mesh.numberofelements,bool)
    115         SSAFSflag=numpy.zeros(md.mesh.numberofelements,bool)
    116         HOFSflag=numpy.zeros(md.mesh.numberofelements,bool)
    117         if coupling_method is 'penalties':
     109        md.stressbalance.vertex_pairing=np.array([])
     110        nodeonSSAHO=np.zeros(md.mesh.numberofvertices,bool)
     111        nodeonHOFS=np.zeros(md.mesh.numberofvertices,bool)
     112        nodeonSSAFS=np.zeros(md.mesh.numberofvertices,bool)
     113        SSAHOflag=np.zeros(md.mesh.numberofelements,bool)
     114        SSAFSflag=np.zeros(md.mesh.numberofelements,bool)
     115        HOFSflag=np.zeros(md.mesh.numberofelements,bool)
     116        if coupling_method=='penalties':
    118117                #Create the border nodes between HO and SSA and extrude them
    119118                numnodes2d=md.mesh.numberofvertices2d
    120119                numlayers=md.mesh.numberoflayers
    121                 bordernodes2d=numpy.nonzero(numpy.logical_and(nodeonHO[0:numnodes2d],nodeonSSA[0:numnodes2d]))[0]+1    #Nodes connected to two different types of elements
     120                bordernodes2d=np.where(np.logical_and(nodeonHO[0:numnodes2d],nodeonSSA[0:numnodes2d]))[0]+1    #Nodes connected to two different types of elements
    122121
    123122                #initialize and fill in penalties structure
    124                 if numpy.all(numpy.logical_not(numpy.isnan(bordernodes2d))):
    125                         penalties=numpy.zeros((0,2))
     123                if np.all(np.logical_not(np.isnan(bordernodes2d))):
     124                        penalties=np.zeros((0,2))
    126125                        for     i in range(1,numlayers):
    127                                 penalties=numpy.vstack((penalties,numpy.hstack((bordernodes2d.reshape(-1,1),bordernodes2d.reshape(-1,1)+md.mesh.numberofvertices2d*(i)))))
     126                                penalties=np.vstack((penalties,np.vstack((bordernodes2d,bordernodes2d+md.mesh.numberofvertices2d*(i))).T))
    128127                        md.stressbalance.vertex_pairing=penalties
    129128
    130         elif coupling_method is 'tiling':
    131                 if   any(SSAflag) and any(HOflag):    #coupling SSA HO
     129        elif coupling_method=='tiling':
     130                if any(SSAflag) and any(HOflag):    #coupling SSA HO
    132131                        #Find node at the border
    133                         nodeonSSAHO[numpy.nonzero(numpy.logical_and(nodeonSSA,nodeonHO))]=True
     132                        nodeonSSAHO[np.where(np.logical_and(nodeonSSA,nodeonHO))]=True
    134133                        #SSA elements in contact with this layer become SSAHO elements
    135                         matrixelements=m.ismember(md.mesh.elements-1,numpy.nonzero(nodeonSSAHO)[0])
    136                         commonelements=numpy.sum(matrixelements,axis=1)!=0
    137                         commonelements[numpy.nonzero(HOflag)]=False    #only one layer: the elements previously in SSA
    138                         SSAflag[numpy.nonzero(commonelements)]=False    #these elements are now SSAHOelements
    139                         SSAHOflag[numpy.nonzero(commonelements)]=True
     134                        matrixelements=nodeonSSAHO[md.mesh.elements-1]
     135                        commonelements=np.sum(matrixelements,axis=1)!=0
     136                        commonelements[np.where(HOflag)]=False    #only one layer: the elements previously in SSA
     137                        SSAflag[np.where(commonelements)]=False    #these elements are now SSAHOelements
     138                        SSAHOflag[np.where(commonelements)]=True
    140139                        nodeonSSA[:]=False
    141                         nodeonSSA[md.mesh.elements[numpy.nonzero(SSAflag),:]-1]=True
     140                        nodeonSSA[md.mesh.elements[np.where(SSAflag),:]-1]=True
    142141
    143142                        #rule out elements that don't touch the 2 boundaries
    144                         pos=numpy.nonzero(SSAHOflag)[0]
    145                         elist=numpy.zeros(numpy.size(pos),dtype=int)
    146                         elist = elist + numpy.sum(nodeonSSA[md.mesh.elements[pos,:]-1],axis=1).astype(bool)
    147                         elist = elist - numpy.sum(nodeonHO[md.mesh.elements[pos,:]-1]  ,axis=1).astype(bool)
    148                         pos1=numpy.nonzero(elist==1)[0]
     143                        pos=np.where(SSAHOflag)[0]
     144                        elist=np.zeros(np.size(pos),dtype=int)
     145                        elist = elist + np.sum(nodeonSSA[md.mesh.elements[pos,:]-1],axis=1).astype(bool)
     146                        elist = elist - np.sum(nodeonHO[md.mesh.elements[pos,:]-1]  ,axis=1).astype(bool)
     147                        pos1=np.where(elist==1)[0]
    149148                        SSAflag[pos[pos1]]=True
    150149                        SSAHOflag[pos[pos1]]=False
    151                         pos2=numpy.nonzero(elist==-1)[0]
     150                        pos2=np.where(elist==-1)[0]
    152151                        HOflag[pos[pos2]]=True
    153152                        SSAHOflag[pos[pos2]]=False
     
    155154                        #Recompute nodes associated to these elements
    156155                        nodeonSSA[:]=False
    157                         nodeonSSA[md.mesh.elements[numpy.nonzero(SSAflag),:]-1]=True
     156                        nodeonSSA[md.mesh.elements[np.where(SSAflag),:]-1]=True
    158157                        nodeonHO[:]=False
    159                         nodeonHO[md.mesh.elements[numpy.nonzero(HOflag),:]-1]=True
     158                        nodeonHO[md.mesh.elements[np.where(HOflag),:]-1]=True
    160159                        nodeonSSAHO[:]=False
    161                         nodeonSSAHO[md.mesh.elements[numpy.nonzero(SSAHOflag),:]-1]=True
     160                        nodeonSSAHO[md.mesh.elements[np.where(SSAHOflag),:]-1]=True
    162161
    163162                elif any(HOflag) and any(FSflag):    #coupling HO FS
    164163                        #Find node at the border
    165                         nodeonHOFS[numpy.nonzero(numpy.logical_and(nodeonHO,nodeonFS))]=True
     164                        nodeonHOFS[np.where(np.logical_and(nodeonHO,nodeonFS))]=True
    166165                        #FS elements in contact with this layer become HOFS elements
    167                         matrixelements=m.ismember(md.mesh.elements-1,numpy.nonzero(nodeonHOFS)[0])
    168                         commonelements=numpy.sum(matrixelements,axis=1)!=0
    169                         commonelements[numpy.nonzero(HOflag)]=False    #only one layer: the elements previously in SSA
    170                         FSflag[numpy.nonzero(commonelements)]=False    #these elements are now SSAHOelements
    171                         HOFSflag[numpy.nonzero(commonelements)]=True
    172                         nodeonFS=numpy.zeros(md.mesh.numberofvertices,bool)
    173                         nodeonFS[md.mesh.elements[numpy.nonzero(FSflag),:]-1]=True
     166                        matrixelements=nodeonHOFS[md.mesh.elements-1]
     167                        commonelements=np.sum(matrixelements,axis=1)!=0
     168                        commonelements[np.where(HOflag)]=False    #only one layer: the elements previously in SSA
     169                        FSflag[np.where(commonelements)]=False    #these elements are now SSAHOelements
     170                        HOFSflag[np.where(commonelements)]=True
     171                        nodeonFS=np.zeros(md.mesh.numberofvertices,bool)
     172                        nodeonFS[md.mesh.elements[np.where(FSflag),:]-1]=True
    174173
    175174                        #rule out elements that don't touch the 2 boundaries
    176                         pos=numpy.nonzero(HOFSflag)[0]
    177                         elist=numpy.zeros(numpy.size(pos),dtype=int)
    178                         elist = elist + numpy.sum(nodeonFS[md.mesh.elements[pos,:]-1],axis=1).astype(bool)
    179                         elist = elist - numpy.sum(nodeonHO[md.mesh.elements[pos,:]-1],axis=1).astype(bool)
    180                         pos1=numpy.nonzero(elist==1)[0]
     175                        pos=np.where(HOFSflag)[0]
     176                        elist=np.zeros(np.size(pos),dtype=int)
     177                        elist = elist + np.sum(nodeonFS[md.mesh.elements[pos,:]-1],axis=1).astype(bool)
     178                        elist = elist - np.sum(nodeonHO[md.mesh.elements[pos,:]-1],axis=1).astype(bool)
     179                        pos1=np.where(elist==1)[0]
    181180                        FSflag[pos[pos1]]=True
    182181                        HOFSflag[pos[pos1]]=False
    183                         pos2=numpy.nonzero(elist==-1)[0]
     182                        pos2=np.where(elist==-1)[0]
    184183                        HOflag[pos[pos2]]=True
    185184                        HOFSflag[pos[pos2]]=False
     
    187186                        #Recompute nodes associated to these elements
    188187                        nodeonFS[:]=False
    189                         nodeonFS[md.mesh.elements[numpy.nonzero(FSflag),:]-1]=True
     188                        nodeonFS[md.mesh.elements[np.where(FSflag),:]-1]=True
    190189                        nodeonHO[:]=False
    191                         nodeonHO[md.mesh.elements[numpy.nonzero(HOflag),:]-1]=True
     190                        nodeonHO[md.mesh.elements[np.where(HOflag),:]-1]=True
    192191                        nodeonHOFS[:]=False
    193                         nodeonHOFS[md.mesh.elements[numpy.nonzero(HOFSflag),:]-1]=True
    194 
     192                        nodeonHOFS[md.mesh.elements[np.where(HOFSflag),:]-1]=True
    195193                elif any(FSflag) and any(SSAflag):
    196194                        #Find node at the border
    197                         nodeonSSAFS[numpy.nonzero(numpy.logical_and(nodeonSSA,nodeonFS))]=True
     195                        nodeonSSAFS[np.where(np.logical_and(nodeonSSA,nodeonFS))]=True
    198196                        #FS elements in contact with this layer become SSAFS elements
    199                         matrixelements=m.ismember(md.mesh.elements-1,numpy.nonzero(nodeonSSAFS)[0])
    200                         commonelements=numpy.sum(matrixelements,axis=1)!=0
    201                         commonelements[numpy.nonzero(SSAflag)]=False    #only one layer: the elements previously in SSA
    202                         FSflag[numpy.nonzero(commonelements)]=False    #these elements are now SSASSAelements
    203                         SSAFSflag[numpy.nonzero(commonelements)]=True
    204                         nodeonFS=numpy.zeros(md.mesh.numberofvertices,bool)
    205                         nodeonFS[md.mesh.elements[numpy.nonzero(FSflag),:]-1]=True
     197                        matrixelements=nodeonSSAFS[md.mesh.elements-1]
     198                        commonelements=np.sum(matrixelements,axis=1)!=0
     199                        commonelements[np.where(SSAflag)]=False    #only one layer: the elements previously in SSA
     200                        FSflag[np.where(commonelements)]=False    #these elements are now SSASSAelements
     201                        SSAFSflag[np.where(commonelements)]=True
     202                        nodeonFS=np.zeros(md.mesh.numberofvertices,bool)
     203                        nodeonFS[md.mesh.elements[np.where(FSflag),:]-1]=True
    206204
    207205                        #rule out elements that don't touch the 2 boundaries
    208                         pos=numpy.nonzero(SSAFSflag)[0]
    209                         elist=numpy.zeros(numpy.size(pos),dtype=int)
    210                         elist = elist + numpy.sum(nodeonSSA[md.mesh.elements[pos,:]-1],axis=1).astype(bool)
    211                         elist = elist - numpy.sum(nodeonFS[md.mesh.elements[pos,:]-1]  ,axis=1).astype(bool)
    212                         pos1=numpy.nonzero(elist==1)[0]
     206                        pos=np.where(SSAFSflag)[0]
     207                        elist=np.zeros(np.size(pos),dtype=int)
     208                        elist = elist + np.sum(nodeonSSA[md.mesh.elements[pos,:]-1],axis=1).astype(bool)
     209                        elist = elist - np.sum(nodeonFS[md.mesh.elements[pos,:]-1],axis=1).astype(bool)
     210                        pos1=np.where(elist==1)[0]
    213211                        SSAflag[pos[pos1]]=True
    214212                        SSAFSflag[pos[pos1]]=False
    215                         pos2=numpy.nonzero(elist==-1)[0]
     213                        pos2=np.where(elist==-1)[0]
    216214                        FSflag[pos[pos2]]=True
    217215                        SSAFSflag[pos[pos2]]=False
     
    219217                        #Recompute nodes associated to these elements
    220218                        nodeonSSA[:]=False
    221                         nodeonSSA[md.mesh.elements[numpy.nonzero(SSAflag),:]-1]=True
     219                        nodeonSSA[md.mesh.elements[np.where(SSAflag),:]-1]=True
    222220                        nodeonFS[:]=False
    223                         nodeonFS[md.mesh.elements[numpy.nonzero(FSflag),:]-1]=True
     221                        nodeonFS[md.mesh.elements[np.where(FSflag),:]-1]=True
    224222                        nodeonSSAFS[:]=False
    225                         nodeonSSAFS[md.mesh.elements[numpy.nonzero(SSAFSflag),:]-1]=True
     223                        nodeonSSAFS[md.mesh.elements[np.where(SSAFSflag),:]-1]=True
    226224
    227225                elif any(FSflag) and any(SIAflag):
     
    229227
    230228        #Create SSAHOApproximation where needed
    231         md.flowequation.element_equation=numpy.zeros(md.mesh.numberofelements,int)
    232         md.flowequation.element_equation[numpy.nonzero(noneflag)]=0
    233         md.flowequation.element_equation[numpy.nonzero(SIAflag)]=1
    234         md.flowequation.element_equation[numpy.nonzero(SSAflag)]=2
    235         md.flowequation.element_equation[numpy.nonzero(L1L2flag)]=3
    236         md.flowequation.element_equation[numpy.nonzero(HOflag)]=4
    237         md.flowequation.element_equation[numpy.nonzero(FSflag)]=5
    238         md.flowequation.element_equation[numpy.nonzero(SSAHOflag)]=6
    239         md.flowequation.element_equation[numpy.nonzero(SSAFSflag)]=7
    240         md.flowequation.element_equation[numpy.nonzero(HOFSflag)]=8
     229        md.flowequation.element_equation=np.zeros(md.mesh.numberofelements,int)
     230        md.flowequation.element_equation[np.where(noneflag)]=0
     231        md.flowequation.element_equation[np.where(SIAflag)]=1
     232        md.flowequation.element_equation[np.where(SSAflag)]=2
     233        md.flowequation.element_equation[np.where(L1L2flag)]=3
     234        md.flowequation.element_equation[np.where(HOflag)]=4
     235        md.flowequation.element_equation[np.where(FSflag)]=5
     236        md.flowequation.element_equation[np.where(SSAHOflag)]=6
     237        md.flowequation.element_equation[np.where(SSAFSflag)]=7
     238        md.flowequation.element_equation[np.where(HOFSflag)]=8
    241239
    242240        #border
     
    246244
    247245        #Create vertices_type
    248         md.flowequation.vertex_equation=numpy.zeros(md.mesh.numberofvertices,int)
    249         pos=numpy.nonzero(nodeonSSA)
     246        md.flowequation.vertex_equation=np.zeros(md.mesh.numberofvertices,int)
     247        pos=np.where(nodeonSSA)
    250248        md.flowequation.vertex_equation[pos]=2
    251         pos=numpy.nonzero(nodeonL1L2)
     249        pos=np.where(nodeonL1L2)
    252250        md.flowequation.vertex_equation[pos]=3
    253         pos=numpy.nonzero(nodeonHO)
     251        pos=np.where(nodeonHO)
    254252        md.flowequation.vertex_equation[pos]=4
    255         pos=numpy.nonzero(nodeonFS)
     253        pos=np.where(nodeonFS)
    256254        md.flowequation.vertex_equation[pos]=5
    257255        #DO SIA LAST! Otherwise spcs might not be set up correctly (SIA should have priority)
    258         pos=numpy.nonzero(nodeonSIA)
     256        pos=np.where(nodeonSIA)
    259257        md.flowequation.vertex_equation[pos]=1
    260258        if any(FSflag):
    261                 pos=numpy.nonzero(numpy.logical_not(nodeonFS))
     259                pos=np.where(np.logical_not(nodeonFS))
    262260                if not (any(HOflag) or any(SSAflag)):
    263261                        md.flowequation.vertex_equation[pos]=0
    264         pos=numpy.nonzero(nodeonSSAHO)
     262        pos=np.where(nodeonSSAHO)
    265263        md.flowequation.vertex_equation[pos]=6
    266         pos=numpy.nonzero(nodeonHOFS)
     264        pos=np.where(nodeonHOFS)
    267265        md.flowequation.vertex_equation[pos]=7
    268         pos=numpy.nonzero(nodeonSSAFS)
     266        pos=np.where(nodeonSSAFS)
    269267        md.flowequation.vertex_equation[pos]=8
    270268
  • issm/trunk-jpl/src/py3/parameterization/sethydrostaticmask.py

    r19895 r23670  
    1 import numpy
     1import numpy as np
    22import os
    33from model import model
    44from FlagElements import FlagElements
     5import pairoptions
    56from ContourToMesh import ContourToMesh
    67
     
    1920   """
    2021
    21         if numpy.size(md.geometry.bed,axis=0)!=md.mesh.numberofvertices or numpy.size(md.geometry.base,axis=0)!=md.mesh.numberofvertices or numpy.size(md.geometry.thickness,axis=0)!=md.mesh.numberofvertices:
     22        if np.size(md.geometry.bed,axis=0)!=md.mesh.numberofvertices or np.size(md.geometry.base,axis=0)!=md.mesh.numberofvertices or np.size(md.geometry.thickness,axis=0)!=md.mesh.numberofvertices:
    2223                raise IOError("hydrostaticmask error message: fields in md.geometry do not have the right size.")
    2324
     
    2627
    2728   #Check consistency of geometry
    28         if any(md.geometry.base[numpy.nonzero(md.mask.groundedice_levelset>0.)]!=md.geometry.bed[numpy.nonzero(md.mask.groundedice_levelset>0.)]):
     29        if any(md.geometry.base[np.nonzero(md.mask.groundedice_levelset>0.)]!=md.geometry.bed[np.nonzero(md.mask.groundedice_levelset>0.)]):
    2930           print "WARNING: md.geometry.bed and md.geometry.base not equal on grounded ice"
    3031
    31         if any(md.geometry.base[numpy.nonzero(md.mask.groundedice_levelset<=0.)]<md.geometry.bed[numpy.nonzero(md.mask.groundedice_levelset<=0.)]):
     32        if any(md.geometry.base[np.nonzero(md.mask.groundedice_levelset<=0.)]<md.geometry.bed[np.nonzero(md.mask.groundedice_levelset<=0.)]):
    3233                print "WARNING: md.geometry.base < md.geometry.bed on floating ice"
    3334
  • issm/trunk-jpl/src/py3/parameterization/setmask.py

    r19895 r23670  
    1 import numpy
     1import numpy as np
    22import os
    33from model import model
    44from FlagElements import FlagElements
    5 from pairoptions import pairoptions
     5import pairoptions
    66from ContourToMesh import ContourToMesh
    77
    8 def setmask(md, floatingicename, groundedicename, **kwargs):
     8def setmask(md, floatingicename, groundedicename, *args):
    99        """
    1010        SETMASK - establish boundaries between grounded and floating ice.
     
    2626                raise TypeError("setmask error message")
    2727
     28        if len(args)%2:
     29                raise TypeError("odd number of arguments provided in setmask")
     30
    2831        #process options
    29         options=pairoptions(**kwargs)
     32        options=pairoptions.pairoptions(*args)
    3033
    3134        #Get assigned fields
     
    4144        #arrays come from domain outlines that can intersect one another:
    4245
    43         elementonfloatingice = numpy.logical_and(elementonfloatingice,numpy.logical_not(elementongroundedice))
    44         elementongroundedice = numpy.logical_not(elementonfloatingice)
     46        elementonfloatingice = np.logical_and(elementonfloatingice,np.logical_not(elementongroundedice))
     47        elementongroundedice = np.logical_not(elementonfloatingice)
    4548
    4649        #the order here is important. we choose vertexongroundedice as default on the grounding line.
    47         vertexonfloatingice = numpy.zeros(md.mesh.numberofvertices,'bool')
    48         vertexongroundedice = numpy.zeros(md.mesh.numberofvertices,'bool')
    49         vertexongroundedice[md.mesh.elements[numpy.nonzero(elementongroundedice),:]-1]=True
    50         vertexonfloatingice[numpy.nonzero(numpy.logical_not(vertexongroundedice))]=True
     50        vertexonfloatingice = np.zeros(md.mesh.numberofvertices,'bool')
     51        vertexongroundedice = np.zeros(md.mesh.numberofvertices,'bool')
     52        vertexongroundedice[md.mesh.elements[np.nonzero(elementongroundedice),:]-1]=True
     53        vertexonfloatingice[np.nonzero(np.logical_not(vertexongroundedice))]=True
    5154        #}}}
    5255
    5356        #level sets
    54         md.mask.groundedice_levelset = -1.*numpy.ones(md.mesh.numberofvertices)
    55         md.mask.groundedice_levelset[md.mesh.elements[numpy.nonzero(elementongroundedice),:]-1]=1.
     57        md.mask.groundedice_levelset = -1.*np.ones(md.mesh.numberofvertices)
     58        md.mask.groundedice_levelset[md.mesh.elements[np.nonzero(elementongroundedice),:]-1]=1.
    5659
    57         if(len(kwargs)):
    58                 md.mask.ice_levelset = 1.*numpy.ones(md.mesh.numberofvertices)
     60        if(len(args)):
     61                md.mask.ice_levelset = 1.*np.ones(md.mesh.numberofvertices)
    5962                icedomainfile = options.getfieldvalue('icedomain','none')
    6063                if not os.path.exists(icedomainfile):
    6164                        raise IOError("setmask error message: ice domain file '%s' not found." % icedomainfile)
    6265                #use contourtomesh to set ice values inside ice domain
    63                 [vertexinsideicedomain,elementinsideicedomain]=ContourToMesh(elements,x,y,icedomainfile,'node',1)
    64                 md.mask.ice_levelset[numpy.nonzero(vertexinsideicedomain)[0]] = -1.
     66                vertexinsideicedomain,elementinsideicedomain=ContourToMesh(elements,x,y,icedomainfile,'node',1)
     67                md.mask.ice_levelset[np.nonzero(vertexinsideicedomain)[0]] = -1.
    6568        else:
    66                 md.mask.ice_levelset = -1.*numpy.ones(md.mesh.numberofvertices)
     69                md.mask.ice_levelset = -1.*np.ones(md.mesh.numberofvertices)
    6770
    6871        return md
  • issm/trunk-jpl/src/py3/plot/applyoptions.py

    r21255 r23670  
    1 import numpy as np
     1import numpy as  np
    22from cmaptools import truncate_colormap
    33from plot_contour import plot_contour
     
    1010        from mpl_toolkits.mplot3d import Axes3D
    1111        import matplotlib as mpl
    12         import pylab as p
    1312        import matplotlib.pyplot as plt
    1413except ImportError:
    1514        print("could not import pylab, matplotlib has not been installed, no plotting capabilities enabled")
    1615
    17 def applyoptions(md,data,options,fig,ax):
     16def applyoptions(md,data,options,fig,axgrid,gridindex):
    1817        '''
    1918        APPLYOPTIONS - apply options to current plot
     
    3029        # get handle to current figure and axes instance
    3130        #fig = p.gcf()
    32         #ax=p.gca()
    33 
    34         #font {{{
     31        ax=     axgrid[gridindex]
     32
     33        # {{{ font
    3534        fontsize=options.getfieldvalue('fontsize',8)
    3635        fontweight=options.getfieldvalue('fontweight','normal')
     
    3938                                'fontweight'    :fontweight,
    4039                                'family'                        :fontfamily}
    41         #}}}
    42 
    43         #title {{{
     40        # }}}
     41        # {{{ title
    4442        if options.exist('title'):
    4543                title=options.getfieldvalue('title')
    4644                if options.exist('titlefontsize'):
    4745                        titlefontsize=options.getfieldvalue('titlefontsize')
    48 else:
    49         titlefontsize=fontsize
    50         if options.exist('titlefontweight'):
    51                 titlefontweight=options.getfieldvalue('titlefontweight')
    52 else:
    53         titlefontweight=fontweight
    54         #title font
    55         titlefont=font.copy()
    56         titlefont['size']=titlefontsize
    57         titlefont['weight']=titlefontweight
    58         ax.set_title(title,**titlefont)
    59         #}}}
    60                
    61         #xlabel, ylabel, zlabel {{{
     46                else:
     47                        titlefontsize=fontsize
     48                if options.exist('titlefontweight'):
     49                        titlefontweight=options.getfieldvalue('titlefontweight')
     50                else:
     51                        titlefontweight=fontweight
     52                #title font
     53                titlefont=font.copy()
     54                titlefont['size']=titlefontsize
     55                titlefont['weight']=titlefontweight
     56                ax.set_title(title,**titlefont)
     57        # }}}
     58        # {{{ xlabel, ylabel, zlabel
    6259        if options.exist('labelfontsize'):
    6360                labelfontsize=options.getfieldvalue('labelfontsize')
    64 else:
    65         labelfontsize=fontsize
     61        else:
     62                labelfontsize=fontsize
    6663        if options.exist('labelfontweight'):
    6764                labelfontweight=options.getfieldvalue('labelfontweight')
    68 else:
    69         labelfontweight=fontweight
     65        else:
     66                labelfontweight=fontweight
    7067
    7168        #font dict for labels
     
    7673        if options.exist('xlabel'):
    7774                ax.set_xlabel(options.getfieldvalue('xlabel'),**labelfont)
    78                 if options.exist('ylabel'):
    79                         ax.set_ylabel(options.getfieldvalue('ylabel'),**labelfont)
    80                         if options.exist('zlabel'):
    81                                 ax.set_zlabel(options.getfieldvalue('zlabel'),**labelfont)
    82                                 #}}}
    83 
    84         #xticks, yticks, zticks (tick locations) {{{
     75        if options.exist('ylabel'):
     76                ax.set_ylabel(options.getfieldvalue('ylabel'),**labelfont)
     77        if options.exist('zlabel'):
     78                ax.set_zlabel(options.getfieldvalue('zlabel'),**labelfont)
     79        # }}}
     80        # {{{ xticks, yticks, zticks (tick locations)
    8581        if options.exist('xticks'):
    8682                if options.exist('xticklabels'):
    8783                        xticklabels=options.getfieldvalue('xticklabels')
    8884                        ax.set_xticks(options.getfieldvalue('xticks'),xticklabels)
    89 else:
    90         ax.set_xticks(options.getfieldvalue('xticks'))
     85                else:
     86                        ax.set_xticks(options.getfieldvalue('xticks'))
    9187        if options.exist('yticks'):
    9288                if options.exist('yticklabels'):
    9389                        yticklabels=options.getfieldvalue('yticklabels')
    9490                        ax.set_yticks(options.getfieldvalue('yticks'),yticklabels)
    95 else:
    96         ax.set_yticks(options.getfieldvalue('yticks'))
     91                else:
     92                        ax.set_yticks(options.getfieldvalue('yticks'))
    9793        if options.exist('zticks'):
    9894                if options.exist('zticklabels'):
    9995                        zticklabels=options.getfieldvalue('zticklabels')
    10096                        ax.set_zticks(options.getfieldvalue('zticks'),zticklabels)
    101 else:
    102         ax.set_zticks(options.getfieldvalue('zticks'))
    103         #}}}
    104 
    105         #xticklabels,yticklabels,zticklabels {{{
     97                else:
     98                        ax.set_zticks(options.getfieldvalue('zticks'))
     99        # }}}
     100        # {{{ xticklabels,yticklabels,zticklabels
    106101        if options.getfieldvalue('ticklabels','off')=='off' or options.getfieldvalue('ticklabels',0)==0:
    107102                options.addfielddefault('xticklabels',[])
    108103                options.addfielddefault('yticklabels',[])
    109104                # TODO check if ax has a z-axis (e.g. is 3D)
    110                 if options.exist('xticklabels'):
    111                         xticklabels=options.getfieldvalue('xticklabels')
    112                         ax.set_xticklabels(xticklabels)
    113                         if options.exist('yticklabels'):
    114                                 yticklabels=options.getfieldvalue('yticklabels')
    115                                 ax.set_yticklabels(yticklabels)
    116                                 if options.exist('zticklabels'):
    117                                         zticklabels=options.getfieldvalue('zticklabels')
    118                                         ax.set_zticklabels(zticklabels)
    119                                         #}}}
    120 
    121         #ticklabel notation {{{
     105        if options.exist('xticklabels'):
     106                xticklabels=options.getfieldvalue('xticklabels')
     107                ax.set_xticklabels(xticklabels)
     108        if options.exist('yticklabels'):
     109                yticklabels=options.getfieldvalue('yticklabels')
     110                ax.set_yticklabels(yticklabels)
     111        if options.exist('zticklabels'):
     112                zticklabels=options.getfieldvalue('zticklabels')
     113                ax.set_zticklabels(zticklabels)
     114        # }}}
     115        # {{{ ticklabel notation
    122116        #ax.ticklabel_format(style='sci',scilimits=(0,0))
    123         #}}}
    124 
    125         #ticklabelfontsize {{{
     117        # }}}
     118        # {{{ ticklabelfontsize
    126119        if options.exist('ticklabelfontsize'):
    127120                for label in ax.get_xticklabels() + ax.get_yticklabels():
    128121                        label.set_fontsize(options.getfieldvalue('ticklabelfontsize'))
    129                         if int(md.mesh.dimension)==3:
    130                                 for label in ax.get_zticklabels():
    131                                         label.set_fontsize(options.getfieldvalue('ticklabelfontsize'))
    132                                         #}}}
    133 
    134         #view
     122                if int(md.mesh.dimension)==3:
     123                        for label in ax.get_zticklabels():
     124                                label.set_fontsize(options.getfieldvalue('ticklabelfontsize'))
     125        # }}}
     126        # {{{ view TOFIX
    135127        #if int(md.mesh.dimension) == 3 and options.exist('layer'):
    136128        #       #options.getfieldvalue('view') ?
    137129        #       ax=fig.gca(projection='3d')
    138130        #plt.show()
    139 
    140         #axis {{{
     131        # }}}
     132        # {{{ axis
    141133        if options.exist('axis'):
    142134                if options.getfieldvalue('axis',True)=='off':
     
    144136                        p.setp(ax.get_xticklabels(), visible=False)
    145137                        p.setp(ax.get_yticklabels(), visible=False)
    146                         # }}}
    147 
    148         #box
     138        # }}}
     139        # {{{ box
    149140        if options.exist('box'):
    150141                eval(options.getfieldvalue('box'))
    151 
    152         #xlim, ylim, zlim {{{
    153         if options.exist('xlim'):
     142        # }}}
     143        # {{{ xlim, ylim, zlim
     144        if options.exist('xlim'):
    154145                ax.set_xlim(options.getfieldvalue('xlim'))
    155                 if options.exist('ylim'):
    156                         ax.set_ylim(options.getfieldvalue('ylim'))
    157                         if options.exist('zlim'):
    158                                 ax.set_zlim(options.getfieldvalue('zlim'))
    159                                 #}}}
    160 
    161         #latlon
    162 
    163         #Basinzoom
    164 
    165         #ShowBasins
    166 
    167         #clim {{{
     146        if options.exist('ylim'):
     147                ax.set_ylim(options.getfieldvalue('ylim'))
     148        if options.exist('zlim'):
     149                ax.set_zlim(options.getfieldvalue('zlim'))
     150        # }}}
     151        # {{{ latlon TODO
     152        # }}}
     153        # {{{ Basinzoom TODO
     154        # }}}
     155        # {{{ ShowBasins TODO
     156        # }}}
     157        # {{{ clim
    168158        if options.exist('clim'):
    169159                lims=options.getfieldvalue('clim')
    170160                assert len(lims)==2, 'error, clim should be passed as a list of length 2'
    171 elif options.exist('caxis'):
    172         lims=options.getfieldvalue('caxis')
    173         assert len(lims)==2, 'error, caxis should be passed as a list of length 2'
    174         options.addfielddefault('clim',lims)
    175 else:
    176         if len(data)>0: lims=[data.min(),data.max()]
    177 else: lims=[0,1]
    178 #}}}
    179 
    180         #shading
     161        elif options.exist('caxis'):
     162                lims=options.getfieldvalue('caxis')
     163                assert len(lims)==2, 'error, caxis should be passed as a list of length 2'
     164                options.addfielddefault('clim',lims)
     165        else:
     166                if len(data)>0:
     167                        lims=[data.min(),data.max()]
     168                else:
     169                        lims=[0,1]
     170        # }}}
     171        # {{{ shading TODO
    181172        #if options.exist('shading'):
    182 
    183         #grid {{{
     173        # }}}
     174        # {{{ grid
    184175        if options.exist('grid'):
    185176                if 'on' in options.getfieldvalue('grid','on'):
    186177                        ax.grid()
    187                         #}}}
    188 
    189         #colormap {{{
    190         # default sequential colormap
    191         defaultmap=truncate_colormap(mpl.cm.gnuplot2,0.1,0.9,128)
    192         cmap=options.getfieldvalue('colormap',defaultmap)
    193         norm = mpl.colors.Normalize(vmin=lims[0], vmax=lims[1])
    194         options.addfield('colornorm',norm)
     178        # }}}
     179        # {{{ colormap
     180        if options.exist('colornorm'):
     181                norm=options.getfieldvalue('colornorm')
     182        if options.exist('colormap'):
     183                cmap=options.getfieldvalue('colormap')
    195184        cbar_extend=0
    196185        if options.exist('cmap_set_over'):
    197                 over=options.getfieldvalue('cmap_set_over','0.5')
    198                 cmap.set_over(over)
    199186                cbar_extend+=1
    200                 if options.exist('cmap_set_under'):
    201                         under=options.getfieldvalue('cmap_set_under','0.5')
    202                         cmap.set_under(under)
    203                         cbar_extend+=2
    204                         options.addfield('colormap',cmap)
    205                         #}}}
    206 
    207         #contours {{{
     187        if options.exist('cmap_set_under'):
     188                cbar_extend+=2
     189        # }}}
     190        # {{{ contours
    208191        if options.exist('contourlevels'):
    209192                plot_contour(md,data,options,ax)
    210                 #}}}
    211 
    212         #wrapping
    213 
    214         #colorbar {{{
     193        # }}}
     194        # {{{ wrapping TODO
     195        # }}}
     196        # {{{ colorbar
    215197        if options.getfieldvalue('colorbar',1)==1:
    216198                if cbar_extend==0:
    217199                        extend='neither'
    218 elif cbar_extend==1:
    219         extend='max'
    220 elif cbar_extend==2:
    221         extend='min'
    222 elif cbar_extend==3:
    223         extend='both'
    224         cb = mpl.colorbar.ColorbarBase(ax.cax, cmap=cmap, norm=norm, extend=extend)
    225         if options.exist('alpha'):
    226                 cb.set_alpha(options.getfieldvalue('alpha'))
     200                elif cbar_extend==1:
     201                        extend='max'
     202                elif cbar_extend==2:
     203                        extend='min'
     204                elif cbar_extend==3:
     205                        extend='both'
     206                cb = mpl.colorbar.ColorbarBase(ax.cax,cmap=cmap, norm=norm, extend=extend)
     207                if options.exist('alpha'):
     208                        cb.set_alpha(options.getfieldvalue('alpha'))
    227209                if options.exist('colorbarnumticks'):
    228210                        cb.locator=MaxNLocator(nbins=options.getfieldvalue('colorbarnumticks',5))
    229 else:
    230         cb.locator=MaxNLocator(nbins=5) # default 5 ticks
    231         if options.exist('colorbartickspacing'):
    232                 locs=np.arange(lims[0],lims[1]+1,options.getfieldvalue('colorbartickspacing'))
    233                 cb.set_ticks(locs)
     211                else:
     212                        cb.locator=MaxNLocator(nbins=5) # default 5 ticks
     213                if options.exist('colorbartickspacing'):
     214                        locs=np.arange(lims[0],lims[1]+1,options.getfieldvalue('colorbartickspacing'))
     215                        cb.set_ticks(locs)
    234216                if options.exist('colorbarlines'):
    235217                        locs=np.arange(lims[0],lims[1]+1,options.getfieldvalue('colorbarlines'))
    236218                        cb.add_lines(locs,['k' for i in range(len(locs))],np.ones_like(locs))
    237                         if options.exist('colorbarlineatvalue'):
    238                                 locs=options.getfieldvalue('colorbarlineatvalue')
    239                                 colors=options.getfieldvalue('colorbarlineatvaluecolor',['k' for i in range (len(locs))])
    240                                 widths=options.getfieldvalue('colorbarlineatvaluewidth',np.ones_like(locs))
    241                                 cb.add_lines(locs,colors,widths)
    242                                 if options.exist('colorbartitle'):
    243                                         if options.exist('colorbartitlepad'):
    244                                                 cb.set_label(options.getfieldvalue('colorbartitle'),labelpad=options.getfieldvalue('colorbartitlepad'),fontsize=fontsize)
    245 else:
    246         cb.set_label(options.getfieldvalue('colorbartitle'),fontsize=fontsize)
    247         cb.ax.tick_params(labelsize=fontsize)
    248         cb.solids.set_rasterized(True)
    249         cb.update_ticks()
    250         cb.set_alpha(1)
    251         cb.draw_all()
    252         plt.sca(ax) # return to original axes control
    253         #}}}
    254 
    255         #expdisp {{{
    256                                 if options.exist('expdisp'):
    257                                         filename=options.getfieldvalue('expdisp')
    258                                         style=options.getfieldvalue('expstyle','k')
    259                                         linewidth=options.getfieldvalue('explinewidth',1)
    260                                         for i in range(len(filename)):
    261                                                 filenamei=filename[i]
    262                                                 stylei=style[i]
    263                                                 if type(linewidth)==list:
    264                                                         linewidthi=linewidth[i]
    265 else:
    266         linewidthi=linewidth
    267         expdisp(filenamei,ax,linestyle=stylei,linewidth=linewidthi,unitmultiplier=options.getfieldvalue('unit',1))
    268         #}}}
    269 
    270         #area
    271 
    272         #text {{{
     219                if options.exist('colorbarlineatvalue'):
     220                        locs=options.getfieldvalue('colorbarlineatvalue')
     221                        colors=options.getfieldvalue('colorbarlineatvaluecolor',['k' for i in range (len(locs))])
     222                        widths=options.getfieldvalue('colorbarlineatvaluewidth',np.ones_like(locs))
     223                        cb.add_lines(locs,colors,widths)
     224                if options.exist('colorbartitle'):
     225                        if options.exist('colorbartitlepad'):
     226                                cb.set_label(options.getfieldvalue('colorbartitle'),
     227                                                                                 labelpad=options.getfieldvalue('colorbartitlepad'),fontsize=fontsize)
     228                        else:
     229                                cb.set_label(options.getfieldvalue('colorbartitle'),fontsize=fontsize)
     230                cb.ax.tick_params(labelsize=fontsize)
     231                cb.solids.set_rasterized(True)
     232                cb.update_ticks()
     233                cb.draw_all()
     234                if options.exist('colorbarfontsize'):
     235                        colorbarfontsize=options.getfieldvalue('colorbarfontsize')
     236                        cb.ax.tick_params(labelsize=colorbarfontsize)
     237                        # cb.set_ticks([0,-10])
     238                        # cb.set_ticklabels([-10,0,10])
     239                if options.exist('colorbarticks'):
     240                        colorbarticks=options.getfieldvalue('colorbarticks')
     241                        cb.set_ticks(colorbarticks)
     242                plt.sca(ax) # return to original axes control
     243        # }}}
     244        # {{{ expdisp
     245        if options.exist('expdisp'):
     246                expdisp(ax,options)
     247        # }}}
     248        # {{{ area TODO
     249        # }}}
     250        # {{{ text
    273251        if options.exist('text'):
    274252                text=options.getfieldvalue('text')
     
    281259                for label,x,y,size,color,weight,rotation in zip(text,textx,texty,textfontsize,textcolor,textweight,textrotation):
    282260                        ax.text(x,y,label,transform=ax.transAxes,fontsize=size,color=color,weight=weight,rotation=rotation)
    283                         #}}}
    284 
    285         #north arrow
    286 
    287         #scale ruler
    288 
    289         #streamlines
     261        # }}}
     262        # {{{ north arrow TODO
     263        # }}}
     264        # {{{ scale ruler TODO
     265        # }}}
     266        # {{{ streamlines TOFIX
    290267        if options.exist('streamlines'):
    291268                plot_streamlines(md,options,ax)
    292 
    293 
    294         #axis positions
    295 
    296         #figure position
    297 
    298         #axes position
    299 
    300         #showregion
    301 
    302         #flat edges of a partition
    303 
    304         #scatter
    305 
    306         #backgroundcolor
    307 
    308         #figurebackgroundcolor
    309 
    310         #lighting
    311 
    312         #point cloud
    313 
    314         #inset
    315        
     269        # }}}
     270        # {{{ axis positions TODO
     271        # }}}
     272        # {{{ figure position TODO
     273        # }}}
     274        # {{{ axes position TODO
     275        # }}}
     276        # {{{ showregion TODO
     277        # }}}
     278        # {{{ flat edges of a partition TODO
     279        # }}}
     280        # {{{ scatter TODO
     281        # }}}
     282        # {{{ backgroundcolor TODO
     283        # }}}
     284        # {{{ figurebackgroundcolor TODO
     285        # }}}
     286        # {{{ lighting TODO
     287        # }}}
     288        # {{{ point cloud TODO
     289        # }}}
     290        # {{{ inset TODO
     291        # }}}
  • issm/trunk-jpl/src/py3/plot/checkplotoptions.py

    r21255 r23670  
    1 import numpy as np
     1import numpy as  np
    22
    33def checkplotoptions(md,options):
     
    1313        '''
    1414
    15 
    16         #units
     15        # {{{ units
    1716        if options.exist('unit'):
    1817                if 'km' in options.getfieldvalue('unit','km'):
     
    2019                elif '100km' in options.getfieldvalue('unit','100km'):
    2120                        options.changefieldvalue('unit',10**-5)
    22        
    23         #density
     21        # }}}
     22        # {{{ density
    2423        if options.exist('density'):
    2524                density=options.getfieldvalue('density')
    2625                options.changefieldvalue('density',abs(ceil(density)))
    27                
    28         #show section
     26        # }}}
     27        # {{{ show section
    2928        if options.exist('showsection'):
    3029                if 'on' in options.getfieldvalue('showsection','on'):
    3130                        options.changefieldvalue('showsection',4)
    32                        
    33         #smooth values
     31        # }}}   
     32        # {{{ smooth values
    3433        if options.exist('smooth'):
    3534                if 'on' in options.getfieldvalue('smooth','on'):
    3635                        options.changefieldvalue('smooth',0)
    37 
    38         #contouronly values
     36        # }}}
     37        # {{{ contouronly values
    3938        if options.exist('contouronly'):
    4039                if 'on' in options.getfieldvalue('contouronly','on'):
    4140                        options.changefieldvalue('contouronly',1)
    42 
    43         #colorbar
     41        # }}}
     42        # {{{ colorbar
    4443        if options.exist('colorbar'):
    4544                if 'on' in options.getfieldvalue('colorbar','on'):
     
    4746                elif 'off' in options.getfieldvalue('colorbar','off'):
    4847                        options.changefieldvalue('colorbar',0)
    49 
    50         #text
     48        # }}}
     49        # {{{ text
    5150        if options.exist('text'):
    52 
    5351                # text values (coerce to list for consistent functionality)
    5452                textlist=[]
     
    5654                textlist.extend([text] if isinstance(text,str) else text)
    5755                numtext=len(textlist)
    58 
    5956                # text position
    6057                textpos=options.getfieldvalue('textposition',[0.5,0.5])
    6158                if not isinstance(textpos,list):
    6259                        raise Exception('textposition should be passed as a list')
    63                         if any(isinstance(i,list) for i in textpos):
    64                                 textx=[item[0] for item in textpos]
    65                                 texty=[item[1] for item in textpos]
    66                         else:
    67                                 textx=[textpos[0]]
    68                                 texty=[textpos[1]]
     60                if any(isinstance(i,list) for i in textpos):
     61                    textx=[item[0] for item in textpos]
     62                    texty=[item[1] for item in textpos]
     63                else:
     64                    textx=[textpos[0]]
     65                    texty=[textpos[1]]
    6966                if len(textx)!=numtext or len(texty)!=numtext:
    7067                        raise Exception('textposition should contain one list of x,y vertices for every text instance')
    7168
    7269                # font size
    73         if options.exist('textfontsize'):
    74                 textfontsize=options.getfieldvalue('textfontsize',12)
    75                 sizelist=[]
    76                 sizelist.extend(textsize if isinstance(textfontsize,list) else [textfontsize])
    77         else:
    78                 sizelist=[12]
    79         if len(sizelist)==1:
    80                 sizelist=np.tile(sizelist,numtext)
     70                if options.exist('textfontsize'):
     71                        textfontsize=options.getfieldvalue('textfontsize',12)
     72                        sizelist=[]
     73                        sizelist.extend(textsize if isinstance(textfontsize,list) else [textfontsize])
     74                else:
     75                        sizelist=[12]
     76                if len(sizelist)==1:
     77                        sizelist=np.tile(sizelist,numtext)
    8178
    8279                # font color
     
    108105                        rotationlist=[0]
    109106                if len(rotationlist)==1:
    110                         rotationlist=np.tile(rotationlist,numtext)
     107                                rotationlist=np.tile(rotationlist,numtext)
    111108
    112109                options.changefieldvalue('text',textlist)
     
    117114                options.changefieldvalue('textweight',weightlist)
    118115                options.changefieldvalue('textrotation',rotationlist)
    119 
    120         #expdisp
     116        # }}}
     117        # {{{ expdisp
    121118        expdispvaluesarray=[]
    122119        expstylevaluesarray=[]
     
    136133                        else:
    137134                                expstylevaluesarray.append('-k')
    138 
    139135        options.changefieldvalue('expstyle',expstylevaluesarray)
    140136        options.changefieldvalue('expdisp',expdispvaluesarray)
    141 
    142         #latlonnumbering
     137        # }}}
     138        # {{{ latlonnumbering
    143139        if options.exist('latlonclick'):
    144140                if 'on' in options.getfieldvalue('latlonclick','on'):
    145141                        options.changefieldvalue('latlonclick',1)
    146 
    147         #northarrow
     142        # }}}
     143        # {{{ northarrow
    148144        if options.exist('northarrow'):
    149145                if 'on' in options.getfieldvalue('northarrow','on'):
     
    152148                        Ly=max(md.mesh.y)-min(md.mesh.y)
    153149                        options.changefieldvalue('northarrow',[min(md.mesh.x)+1./6.*Lx, min(md.mesh.y)+5./6.*Ly, 1./15.*Ly, 0.25, 1./250.*Ly])
    154 
    155         #scale ruler
     150        # }}}
     151        # {{{ scale ruler
    156152        if options.exist('scaleruler'):
    157                 if 'on' in options.exist('scaleruler','on'):
     153                if 'on' in options.getfieldvalue('scaleruler','off'):
    158154                        Lx=max(md.mesh.x)-min(md.mesh.x)
    159155                        Ly=max(md.mesh.y)-min(md.mesh.y)
    160                         options.changefieldvalue('scaleruler',[min(md.mesh.x)+6./8.*Lx, min(md.mesh.y)+1./10.*Ly, 10**(ceil(log10(Lx)))/5, floor(Lx/100), 5])
    161 
    162         #log scale
     156                        options.changefieldvalue('scaleruler',[min(md.mesh.x)+6./8.*Lx, min(md.mesh.y)+1./10.*Ly, 10**(np.ceil(np.log10(Lx)))/5, np.floor(Lx/100), 5])
     157        # }}}
     158        # {{{ log scale
    163159        if options.exist('log'):
    164                 if options.exist('clim'):
    165                         options.changefieldvalue('clim',log(options.getfieldvalue('clim'))/log(options.getfieldvalue('log')))
    166                         options.changefieldvalue('cutoff',log(options.getfieldvalue('cutoff',1.5))/log(options.getfieldvalue('log')))
    167 
     160                options.changefieldvalue('cutoff',np.log10(options.getfieldvalue('cutoff',1.5))/np.log10(options.getfieldvalue('log')))
     161        # }}}
    168162        return options
  • issm/trunk-jpl/src/py3/plot/colormaps/cmaptools.py

    r21255 r23670  
    1 import numpy as np
     1import numpy as  np
    22
    33try:
  • issm/trunk-jpl/src/py3/plot/export_gl.py

    r19895 r23670  
    22from checkplotoptions import checkplotoptions
    33from model import model
    4 import numpy as np
     4import numpy as  np
    55import math
    66from writejsfile import writejsfile
  • issm/trunk-jpl/src/py3/plot/plot_contour.py

    r21255 r23670  
    11from averaging import averaging
    2 import matplotlib.pyplot as plt
    32from processmesh import processmesh
    43from processdata import processdata
     4try:
     5        import matplotlib.pyplot as plt
     6except ImportError:
     7        print("could not import pylab, matplotlib has not been installed, no plotting capabilities enabled")
    58
    69def plot_contour(md,datain,options,ax):
     
    3134        # retrieve necessary options
    3235        levels=options.getfieldvalue('contourlevels')
    33         colors=options.getfieldvalue('contourcolors')
    3436        norm=options.getfieldvalue('colornorm')
    35         linestyles=options.getfieldvalue('contourlinestyles')
    36         linewidths=options.getfieldvalue('contourlinewidths')
     37        colors=options.getfieldvalue('contourcolors','y')
     38        linestyles=options.getfieldvalue('contourlinestyles','-')
     39        linewidths=options.getfieldvalue('contourlinewidths',1)
    3740
    3841        ax.tricontour(x,y,elements,data,levels,colors=colors,norm=norm,linestyles=linestyles,linewidths=linewidths)
  • issm/trunk-jpl/src/py3/plot/plot_manager.py

    r19895 r23670  
    77from checkplotoptions import checkplotoptions
    88from plot_mesh import plot_mesh
     9from plot_BC import plot_BC
     10from plot_elementnumbering import plot_elementnumbering
     11from plot_vertexnumbering import plot_vertexnumbering
    912from processmesh import processmesh
    1013from processdata import processdata
     
    2225        from plot_overlay import plot_overlay
    2326
    24 def plot_manager(md,options,fig,ax):
     27def plot_manager(md,options,fig,axgrid,gridindex):
    2528        '''
    2629        PLOT_MANAGER - distribute the plots called by plotmodel
     
    3942        #parse options and get a structure of options
    4043        options=checkplotoptions(md,options)
     44        #get data to be plotted
     45        data=options.getfieldvalue('data')
     46        #add ticklabel has a default option
     47        options.addfielddefault('ticklabels','on')
    4148
    42         #get data to be plotted
    43         data=options.getfieldvalue('data');
     49        ax=axgrid[gridindex]
     50        # {{{ basemap plot TOFIX
     51        #if options.exist('basemap'):
     52        #       plot_basemap(md,data,options,nrows,ncols,i)
     53        # }}}
     54        # {{{ overlay plot
     55        if options.exist('overlay') and overlaysupport:
     56                plot_overlay(md,data,options,ax)
     57                options.addfielddefault('alpha',0.5)
     58                options.addfielddefault('xlim',[min(md.mesh.x),max(md.mesh.x)])
     59                options.addfielddefault('ylim',[min(md.mesh.y),max(md.mesh.y)])
     60        # }}}
     61        # {{{ dealing with special plot
     62        if isinstance(data,str):
     63                if data=='mesh':
     64                        plot_mesh(md,options,fig,axgrid,gridindex)
    4465
     66                        #fig.delaxes(fig.axes[1]) # hack to remove colorbar after the fact
     67                        return
     68                elif data=='BC':
     69                        plot_BC(md,options,fig,axgrid,gridindex)
     70                        return
     71                elif data=='elementnumbering':
     72                        plot_elementnumbering(md,options,fig,axgrid,gridindex)
     73                        return
     74                elif data=='vertexnumbering':
     75                        plot_vertexnumbering(md,options,fig,axgrid,gridindex)
     76                        return
     77                elif data=='none':
     78                        print('no data provided to plot (TODO: write plot_none.py)')
     79                        applyoptions(md,[],options,fig,axgrid,gridindex)
     80                        return
     81                else:
     82                        print("WARNING: '%s' is not implemented or is not a valid string for option 'data'" % data)
     83        # }}}
     84        # {{{ Gridded plot TODO
     85        # }}}
     86        # {{{ Section plot TODO
     87        # }}}
     88        # {{{ Profile plot TODO
     89        # }}}
     90
     91        #process data and model
     92        x,y,z,elements,is2d,isplanet=processmesh(md,data,options)
     93        data2,datatype=processdata(md,data,options)
     94        #plot unit
     95        plot_unit(x,y,z,elements,data2,is2d,isplanet,datatype,options,fig,axgrid,gridindex)
     96        #apply all options
     97        applyoptions(md,data2,options,fig,axgrid,gridindex)
     98
     99        #ground overlay on kml plot_unit
     100
     101        # Bits and pieces
    45102        #initialize plot handle variable
    46103        #handle=None
     
    49106        #p.subplot(nrows,ncols,i,aspect='equal')
    50107
    51         ##basemap plot
    52         #if options.exist('basemap'):
    53         #       plot_basemap(md,data,options,nrows,ncols,i)
    54 
    55         #overlay plot
    56         if options.exist('overlay') and overlaysupport:
    57                 plot_overlay(md,data,options,ax)
    58                 options.addfielddefault('alpha',0.5)
    59                 options.addfielddefault('xlim',[min(md.mesh.x),max(md.mesh.x)])
    60                 options.addfielddefault('ylim',[min(md.mesh.y),max(md.mesh.y)])
    61 
    62         #figure out if this is a special plot
    63         if isinstance(data,str):
    64 
    65                 # convert string to lower case for a case-insensitive comparison
    66                 if data.lower()=='mesh':
    67                         plot_mesh(md,options,ax)
    68                         applyoptions(md,[],options,fig,ax)
    69                         fig.delaxes(fig.axes[1]) # hack to remove colorbar after the fact
    70                         return
    71                 elif data.lower()=='none':
    72                         print('no data provided to plot (TODO: write plot_none.py)')
    73                         applyoptions(md,[],options,fig,ax)
    74                         return
    75                 else:
    76                         print(("WARNING: '%s' is not implemented or is not a valid string for option 'data'" % data))
     108        #standard plot
     109        #if not handle:
     110        #       p.subplot(nrows,ncols,i,aspect='equal')
    77111
    78112        #elif data in vars(md):
    79113        #else:
    80114                #print "'data' not a string, plotting model properties yet to be implemented..."
    81 
    82         #Gridded plot
    83 
    84         #Section plot
    85 
    86         #Profile plot
    87 
    88         #process data and model
    89         x,y,z,elements,is2d,isplanet=processmesh(md,data,options)
    90         data2,datatype=processdata(md,data,options)
    91 
    92         #standard plot
    93         #if not handle:
    94         #       p.subplot(nrows,ncols,i,aspect='equal')
    95 
    96         #plot unit
    97         plot_unit(x,y,z,elements,data2,is2d,isplanet,datatype,options,ax)
    98 
    99         #apply all options
    100         applyoptions(md,data2,options,fig,ax)
    101        
    102         #ground overlay on kml plot_unit
  • issm/trunk-jpl/src/py3/plot/plot_mesh.py

    r19895 r23670  
    44        print("could not import pylab, matplotlib has not been installed, no plotting capabilities enabled")
    55
     6import numpy as np
    67from processmesh import processmesh
    78from applyoptions import applyoptions
    8 
    9 def plot_mesh(md,options,ax):
     9from mpl_toolkits.mplot3d.art3d import Line3DCollection
     10from mpl_toolkits.axes_grid1 import inset_locator
     11from mpl_toolkits.mplot3d import Axes3D
     12def plot_mesh(md,options,fig,axgrid,gridindex):
    1013        '''
    1114        PLOT_MESH - plot model mesh
     
    1619                See also: PLOTMODEL
    1720        '''
     21        x,y,z,elements,is2d,isplanet=processmesh(md,'mesh',options)
    1822
    19         x,y,z,elements,is2d,isplanet=processmesh(md,[],options)
    20 
     23        ax=axgrid[gridindex]
     24        fig.delaxes(axgrid.cbar_axes[gridindex])
     25       
    2126        if is2d:
    2227                ax.triplot(x,y,elements)
    2328        else:
    24                 print('WARNING: only 2D mesh plot is currently implemented')
    25        
     29                ax=inset_locator.inset_axes(axgrid[gridindex],width='100%',height='100%',loc=3,borderpad=0,axes_class=Axes3D)
     30               
     31                AB=elements[:,0:2]
     32                BC=elements[:,1:3]
     33                CA=np.vstack((elements[:,2],elements[:,0])).T
     34                DE=elements[:,3:5]
     35                EF=elements[:,4:]
     36                FD=np.vstack((elements[:,5],elements[:,3])).T
     37                AD=np.vstack((elements[:,0],elements[:,3])).T
     38                BE=np.vstack((elements[:,1],elements[:,4])).T
     39                CF=np.vstack((elements[:,2],elements[:,5])).T
     40               
     41                tmpa=np.vstack((AB,BC,CA,DE,EF,FD,AD,BE,CF))
     42                #deleting segments that appear multiple times
     43                tmpb = np.ascontiguousarray(tmpa).view(np.dtype((np.void, tmpa.dtype.itemsize * tmpa.shape[1])))
     44                _, idx = np.unique(tmpb, return_index=True)
     45                triel= tmpa[idx]
     46               
     47                for triangle in triel:
     48                        tri=list(zip(x[triangle],y[triangle],z[triangle]))
     49                        pl3=Line3DCollection([tri],edgecolor='r')
     50                        ax.add_collection3d(pl3)
     51                       
     52                ax.set_xlim([min(x),max(x)])
     53                ax.set_ylim([min(y),max(y)])
     54                ax.set_zlim([min(z),max(z)])
    2655        #apply options
    2756        options.addfielddefault('title','Mesh')
    2857        options.addfielddefault('colorbar','off')
    2958        options.addfielddefault('ticklabels','on')
     59        applyoptions(md,[],options,fig,axgrid,gridindex)
  • issm/trunk-jpl/src/py3/plot/plot_overlay.py

    r21255 r23670  
    1 import numpy as np
     1import numpy as  np
    22from processmesh import processmesh
    33from processdata import processdata
     
    55import matplotlib.pyplot as plt
    66import matplotlib as mpl
     7import os
    78try:
    8     from mpl_toolkits.basemap import Basemap
     9        from mpl_toolkits.basemap import Basemap
    910except ImportError:
    10     print('Basemap toolkit not installed')
    11 
    12 import os
    13 
     11        print('Basemap toolkit not installed')
    1412try:
    15         from osgeo import gdal
     13        from osgeo import gdal
    1614except ImportError:
    1715        print('osgeo/gdal for python not installed, plot_overlay is disabled')
     
    2523
    2624        x,y,z,elements,is2d,isplanet=processmesh(md,[],options)
    27 
    28         if data=='none' or data==None:
     25        try:
     26                data,datatype=processdata(md,data,options)
     27                imageonly=0
     28        except (TypeError,ValueError):#that should catch None and 'none' but may also catch unwanted errors
    2929                imageonly=1
    3030                data=np.float('nan')*np.ones((md.mesh.numberofvertices,))
    3131                datatype=1
    32         else:
    33                 imageonly=0
    34                 data,datatype=processdata(md,data,options)
    3532
    3633        if not is2d:
    3734                raise Exception('overlay plot not supported for 3D meshes, project on a 2D layer first')
    3835
    39         if not options.exist('geotiff_name'):
    40                 raise Exception('overlay error: provide geotiff_name with path to geotiff file')
    41         geotiff=options.getfieldvalue('geotiff_name')
     36        if not options.exist('overlay_image'):
     37                raise Exception('overlay error: provide overlay_image with path to geotiff file')
     38        image=options.getfieldvalue('overlay_image')
    4239
    4340        xlim=options.getfieldvalue('xlim',[min(md.mesh.x),max(md.mesh.x)])
    4441        ylim=options.getfieldvalue('ylim',[min(md.mesh.y),max(md.mesh.y)])
    4542
    46         gtif=gdal.Open(geotiff)
     43        gtif=gdal.Open(image)
    4744        trans=gtif.GetGeoTransform()
    4845        xmin=trans[0]
     
    5047        ymin=trans[3]+gtif.RasterYSize*trans[5]
    5148        ymax=trans[3]
    52        
    53         # allow supplied geotiff to have limits smaller than basemap or model limits
     49        # allow supplied image to have limits smaller than basemap or model limits
    5450        x0=max(min(xlim),xmin)
    5551        x1=min(max(xlim),xmax)
     
    5753        y1=min(max(ylim),ymax)
    5854        inputname='temp.tif'
    59         os.system('gdal_translate -quiet -projwin ' + str(x0) + ' ' + str(y1) + ' ' + str(x1) + ' ' + str(y0) + ' ' + geotiff + ' ' + inputname)
    60        
     55        os.system('gdal_translate -quiet -projwin ' + str(x0) + ' ' + str(y1) + ' ' + str(x1) + ' ' + str(y0) + ' ' + image+ ' ' + inputname)
     56
    6157        gtif=gdal.Open(inputname)
    6258        arr=gtif.ReadAsArray()
    6359        #os.system('rm -rf ./temp.tif')
    64        
     60
    6561        if gtif.RasterCount>=3:  # RGB array
    6662                r=gtif.GetRasterBand(1).ReadAsArray()
     
    8480                plt.hist(arr.flatten(),bins=256,range=(0.,1.))
    8581                plt.title('histogram of overlay image, use for setting overlaylims')
    86                 plt.show()
     82                plt.show()
    8783                plt.sca(ax) # return to original axes/figure
    88                
     84
    8985        # get parameters from cropped geotiff
    9086        trans=gtif.GetGeoTransform()
     
    9490        ymax=trans[3]
    9591        dx=trans[1]
    96         dy=trans[5]     
    97        
     92        dy=trans[5]
     93
    9894        xarr=np.arange(xmin,xmax,dx)
    9995        yarr=np.arange(ymin,ymax,-dy) # -dy since origin='upper' (not sure how robust this is)
     
    10298        norm=mpl.colors.Normalize(vmin=overlaylims[0],vmax=overlaylims[1])
    10399
     100        pc=ax.pcolormesh(xg, yg, np.flipud(arr), cmap=mpl.cm.Greys, norm=norm)
     101
    104102        if options.exist('basemap'):
    105103                # create coordinate grid in map projection units (for plotting)
    106                 lat,lon=xy2ll(xlim,ylim,-1,0,71)
    107                 #plt.sca(ax)
    108                 width=xmax-xmin
    109                 height=ymax-ymin
    110                 lat_0,lon_0=xy2ll(xmin+width/2.,ymin+height/2.,-1,0,71)
    111                 m=Basemap(projection='spstere',
    112                         llcrnrlon=lon[0],llcrnrlat=lat[0],urcrnrlon=lon[1],urcrnrlat=lat[1],
    113                         epsg=3031,
    114                         resolution='c')
    115                         #width=width,height=height,lon_0=lon_0,lat_0=lat_0,
    116                         #lat_0=-90,lon_0=0,lat_ts=-71,
    117                         #llcrnrx=x0,llcrnry=y0,urcrnrx=x1,urcrnry=y1)
    118                 #test
    119                 #m.ax=ax
    120                 meridians=np.arange(-180.,181.,1.)
    121                 parallels=np.arange(-80.,80.,1.)
    122                 m.drawparallels(parallels,labels=[0,0,1,1]) # labels=[left,right,top,bottom]
    123                 m.drawmeridians(meridians,labels=[1,1,0,0])
    124                 m.drawcoastlines()
    125                 pc=m.pcolormesh(xg, yg, np.flipud(arr), cmap=mpl.cm.Greys, norm=norm, ax=ax)
     104                if md.mesh.epsg==3413:
     105                        hemisphere=1
     106                        st_lat=70
     107                        lon_0=45
     108                elif md.mesh.epsg==3031:
     109                        hemisphere=-1
     110                        st_lat=71
     111                        lon_0=0
     112                else:
     113                        hemisphere=input('epsg code {} is not supported chose your hemisphere (1 for North, -1 for south)'.format(mesh.epsg))
    126114
    127         else:
    128                 pc=ax.pcolormesh(xg, yg, np.flipud(arr), cmap=mpl.cm.Greys, norm=norm)
    129        
    130         #rasterization?
     115                lat,lon=xy2ll(xlim,ylim,hemisphere,lon_0,st_lat)
     116                extent=[np.diff(xlim)[0],np.diff(ylim)[0]]
     117                center=[lon[0]+np.diff(lon)[0]*0.5,lat[0]+np.diff(lat)[0]*0.5]
     118                m=Basemap(llcrnrlon=lon[0],llcrnrlat=lat[0],urcrnrlon=lon[1],urcrnrlat=lat[1],
     119                                                        lon_0=center[0],lat_0=center[1],#width=extent[0],height=extent[1],#
     120                                                        epsg=md.mesh.epsg,anchor='NW',
     121                                                        resolution='i',ax=ax)
     122
     123                meridians=np.arange(np.floor(lon[0]),np.ceil(lon[1]),1.)
     124                parallels=np.arange(np.floor(lat[0]),np.ceil(lat[1]),1.)
     125                m.drawparallels(parallels,labels=[1,0,0,0],ax=ax) # labels=[left,right,top,bottom]
     126                m.drawmeridians(meridians,labels=[0,0,1,0],ax=ax)
     127                m.drawcoastlines(ax=ax)
     128                m.drawmapboundary(ax=ax)
     129
     130        #rasterization?
    131131        if options.getfieldvalue('rasterized',0):
    132132                pc.set_rasterized(True)
  • issm/trunk-jpl/src/py3/plot/plot_streamlines.py

    r21255 r23670  
    1 import numpy as np
    2 import matplotlib.pyplot as plt
    3 import matplotlib.tri as tri
     1import numpy as  np
    42from processmesh import processmesh
    53from processdata import processdata
    6 from scipy.interpolate import griddata
    74from ContourToMesh import ContourToMesh
     5try:
     6        import matplotlib.pyplot as plt
     7        import matplotlib.tri as tri
     8        from scipy.interpolate import griddata
     9except ImportError:
     10        print("could not import pylab, matplotlib has not been installed, no plotting capabilities enabled")
    811
    912def plot_streamlines(md,options,ax):
    1013    '''
    11     plot streamlines on a figure, using by default vx and vy components in md.initialization. 
     14    plot streamlines on a figure, using by default vx and vy components in md.initialization.
    1215
    1316    Usage:
     
    2225        streamlineswidthscale: scaling multiplier for linewidth scaled by velocity
    2326        streamlinesarrowsize: size of arrows on lines (default 1)
    24        
     27
    2528    '''
    2629
     
    3336    arrowsize=options.getfieldvalue('streamlinesarrowsize',1)
    3437
    35     #process mesh and data 
     38    #process mesh and data
    3639    x,y,z,elements,is2d,isplanet=processmesh(md,vx,options)
    3740    u,datatype=processdata(md,vx,options)
  • issm/trunk-jpl/src/py3/plot/plot_unit.py

    r21255 r23670  
    11from cmaptools import truncate_colormap
     2from plot_quiver import plot_quiver
     3from scipy.interpolate import griddata
     4import numpy as  np
    25try:
    3     import pylab as p
    4     import matplotlib as mpl
    5     import matplotlib.pyplot as plt
    6     import numpy as np
     6        import matplotlib as mpl
     7        import matplotlib.pyplot as plt
     8        from mpl_toolkits.axes_grid1 import inset_locator
     9        from mpl_toolkits.mplot3d import Axes3D
     10        from mpl_toolkits.mplot3d.art3d import Poly3DCollection
    711except ImportError:
    8     print("could not import pylab, matplotlib has not been installed, no plotting capabilities enabled")
    9 
    10 def plot_unit(x,y,z,elements,data,is2d,isplanet,datatype,options,ax):
    11     """
    12     PLOT_UNIT - unit plot, display data
    13    
    14         Usage:
    15                 plot_unit(x,y,z,elements,data,is2d,isplanet,datatype,options)
    16    
    17         See also: PLOTMODEL, PLOT_MANAGER
    18     """
    19    
    20     #edgecolor
    21     edgecolor=options.getfieldvalue('edgecolor','None')
    22    
    23     #number of colorlevels for plots
    24     colorlevels=options.getfieldvalue('colorlevels',128)
    25    
    26     alpha=options.getfieldvalue('alpha',1)
    27    
    28     #colormap
    29     # default sequential colormap
    30     defaultmap=truncate_colormap(mpl.cm.gnuplot2,0.1,0.9,128)
    31     cmap=options.getfieldvalue('colormap',defaultmap)
    32     if options.exist('cmap_set_over'):
    33         over=options.getfieldvalue('cmap_set_over','0.5')
    34         cmap.set_over(over)
    35     if options.exist('cmap_set_under'):
    36         under=options.getfieldvalue('cmap_set_under','0.5')
    37         cmap.set_under(under)
    38    
    39     #normalize colormap if clim/caxis specified
    40     if options.exist('clim'):
    41         lims=options.getfieldvalue('clim',[np.amin(data),np.amax(data)])
    42     elif options.exist('caxis'):
    43         lims=options.getfieldvalue('caxis',[np.amin(data),np.amax(data)])
    44     else:
    45         if np.amin(data)==np.amax(data):
    46             lims=[np.amin(data)-0.5,np.amax(data)+0.5]
    47         else:
    48             lims=[np.amin(data),np.amax(data)]
    49     norm = mpl.colors.Normalize(vmin=lims[0], vmax=lims[1])
    50     if datatype==1:
    51        #element plot
    52         if is2d:
    53             tri=ax.tripcolor(x,y,elements,data,colorlevels,cmap=cmap,norm=norm,alpha=alpha,edgecolors=edgecolor)
    54         else:
    55             raise ValueError('plot_unit error: 3D element plot not supported yet')
    56         return
    57    
    58     elif datatype==2:
    59         #node plot
    60         if is2d:
    61             tri=ax.tricontourf(x,y,elements,data,colorlevels,cmap=cmap,norm=norm,alpha=alpha,extend='both')
    62             if edgecolor != 'None':
    63                 ax.triplot(x,y,elements,color=edgecolor)
    64         else:
    65             raise ValueError('plot_unit error: 3D node plot not supported yet')
    66         return
    67    
    68     elif datatype==3:
    69         vx=data[:,0]
    70         vy=data[:,1]
    71         #TODO write plot_quiver.py to handle this here
    72         color=np.sqrt(vx**2+vy**2)
    73         scale=options.getfieldvalue('scale',1000)
    74         width=options.getfieldvalue('width',0.005*(np.amax(x)-np.amin(y)))
    75         headwidth=options.getfieldvalue('headwidth',3)
    76         headlength=options.getfieldvalue('headlength',5)
    77         Q=ax.quiver(x,y,vx,vy,color,cmap=cmap,norm=norm,scale=scale,
    78                 width=width,headwidth=headwidth,headlength=headlength)
    79         return
    80    
    81     elif datatype==4:
    82         #P1 patch plot
    83         print('plot_unit message: P1 patch plot not implemented yet')
    84         return
    85    
    86     elif datatype==5:
    87         print('plot_unit message: P0 patch plot not implemented yet')
    88         return
    89    
    90     else:
    91         raise ValueError('datatype=%d not supported' % datatype)
    92    
     12        print("could not import pylab, matplotlib has not been installed, no plotting capabilities enabled")
     13
     14def plot_unit(x,y,z,elements,data,is2d,isplanet,datatype,options,fig,axgrid,gridindex):
     15        """
     16        PLOT_UNIT - unit plot, display data
     17
     18        Usage:
     19        plot_unit(x,y,z,elements,data,is2d,isplanet,datatype,options)
     20
     21        See also: PLOTMODEL, PLOT_MANAGER
     22        """
     23        #if we are plotting 3d replace the current axis
     24        if not is2d:
     25                axgrid[gridindex].axis('off')
     26                ax=inset_locator.inset_axes(axgrid[gridindex],width='100%',height='100%',loc=3,borderpad=0,axes_class=Axes3D)
     27                ax.set_axis_bgcolor((0.7,0.7,0.7))
     28        else:
     29                ax=axgrid[gridindex]
     30
     31        #edgecolor
     32        edgecolor=options.getfieldvalue('edgecolor','None')
     33
     34        # colormap
     35        # {{{ give number of colorlevels and transparency
     36        colorlevels=options.getfieldvalue('colorlevels',128)
     37        alpha=options.getfieldvalue('alpha',1)
     38        if alpha<1:
     39                antialiased=True
     40        else:
     41                antialiased=False
     42        # }}}
     43        # {{{ define wich colormap to use
     44        try:
     45                defaultmap=plt.cm.get_cmap('viridis',colorlevels)
     46        except AttributeError:
     47                print("Viridis can't be found (probably too old Matplotlib) reverting to gnuplot colormap")
     48                defaultmap=truncate_colormap('gnuplot2',0.1,0.9,colorlevels)
     49        cmap=options.getfieldvalue('colormap',defaultmap)
     50        if options.exist('cmap_set_over'):
     51                over=options.getfieldvalue('cmap_set_over','0.5')
     52                cmap.set_over(over)
     53        if options.exist('cmap_set_under'):
     54                under=options.getfieldvalue('cmap_set_under','0.5')
     55                cmap.set_under(under)
     56        options.addfield('colormap',cmap)
     57        # }}}
     58        # {{{ if plotting only one of several layers reduce dataset, same for surface
     59        if options.getfieldvalue('layer',0)>=1:
     60                plotlayer=options.getfieldvalue('layer',0)
     61                if datatype==1:
     62                        slicesize=np.shape(elements)[0]
     63                elif datatype in [2,3]:
     64                        slicesize=len(x)
     65                data=data[(plotlayer-1)*slicesize:plotlayer*slicesize]
     66        # }}}
     67        # {{{ Get the colormap limits
     68        if options.exist('clim'):
     69                lims=options.getfieldvalue('clim',[np.amin(data),np.amax(data)])
     70        elif options.exist('caxis'):
     71                lims=options.getfieldvalue('caxis',[np.amin(data),np.amax(data)])
     72        else:
     73                if np.amin(data)==np.amax(data):
     74                        lims=[np.amin(data)-0.5,np.amax(data)+0.5]
     75                else:
     76                        lims=[np.amin(data),np.amax(data)]
     77        # }}}
     78        # {{{ Set the spread of the colormap (default is normal
     79        if options.exist('log'):
     80                norm = mpl.colors.LogNorm(vmin=lims[0], vmax=lims[1])
     81        else:
     82                norm = mpl.colors.Normalize(vmin=lims[0], vmax=lims[1])
     83        if options.exist('log'):
     84                norm = mpl.colors.LogNorm(vmin=lims[0], vmax=lims[1])
     85        else:
     86                norm = mpl.colors.Normalize(vmin=lims[0], vmax=lims[1])
     87        options.addfield('colornorm',norm)
     88        # }}}
     89
     90        # Plot depending on the datatype
     91        # {{{ data are on elements
     92
     93        if datatype==1:
     94                if is2d:
     95                        if options.exist('mask'):
     96                                triangles=mpl.tri.Triangulation(x,y,elements,data.mask)
     97                        else:
     98                                triangles=mpl.tri.Triangulation(x,y,elements)
     99                        tri=ax.tripcolor(triangles,data,colorlevels,cmap=cmap,norm=norm,alpha=alpha,edgecolors=edgecolor)
     100                else:
     101                        #first deal with colormap
     102                        loccmap = plt.cm.ScalarMappable(cmap=cmap)
     103                        loccmap.set_array([min(data),max(data)])
     104                        loccmap.set_clim(vmin=min(data),vmax=max(data))
     105
     106                        #dealing with prism sides
     107                        recface=np.vstack((elements[:,0],elements[:,1],elements[:,4],elements[:,3])).T
     108                        eltind=np.arange(0,np.shape(elements)[0])
     109                        recface=np.vstack((recface,np.vstack((elements[:,1],elements[:,2],elements[:,5],elements[:,4])).T))
     110                        eltind=np.hstack((eltind,np.arange(0,np.shape(elements)[0])))
     111                        recface=np.vstack((recface,np.vstack((elements[:,2],elements[:,0],elements[:,3],elements[:,5])).T))
     112                        eltind=np.hstack((eltind,np.arange(0,np.shape(elements)[0])))
     113                        tmp = np.ascontiguousarray(np.sort(recface)).view(np.dtype((np.void, recface.dtype.itemsize * recface.shape[1])))
     114                        _, idx, recur = np.unique(tmp, return_index=True, return_counts=True)
     115                        recel= recface[idx[np.where(recur==1)]]
     116                        recindex=eltind[idx[np.where(recur==1)]]
     117                        for i,rectangle in enumerate(recel):
     118                                rec=list(zip(x[rectangle],y[rectangle],z[rectangle]))
     119                                pl3=Poly3DCollection([rec])
     120                                color=loccmap.to_rgba(data[recindex[i]])
     121                                pl3.set_edgecolor(color)
     122                                pl3.set_color(color)
     123                                ax.add_collection3d(pl3)
     124
     125                        #dealing with prism bases
     126                        triface=np.vstack((elements[:,0:3],elements[:,3:6]))
     127                        eltind=np.arange(0,np.shape(elements)[0])
     128                        eltind=np.hstack((eltind,np.arange(0,np.shape(elements)[0])))
     129                        tmp = np.ascontiguousarray(triface).view(np.dtype((np.void, triface.dtype.itemsize * triface.shape[1])))
     130                        _, idx,recur = np.unique(tmp, return_index=True,return_counts=True)
     131                        #we keep only top and bottom elements
     132                        triel= triface[idx[np.where(recur==1)]]
     133                        triindex=eltind[idx[np.where(recur==1)]]
     134                        for i,triangle in enumerate(triel):
     135                                tri=list(zip(x[triangle],y[triangle],z[triangle]))
     136                                pl3=Poly3DCollection([tri])
     137                                color=loccmap.to_rgba(data[triindex[i]])
     138                                pl3.set_edgecolor(color)
     139                                pl3.set_color(color)
     140                                ax.add_collection3d(pl3)
     141       
     142                        ax.set_xlim([min(x),max(x)])
     143                        ax.set_ylim([min(y),max(y)])
     144                        ax.set_zlim([min(z),max(z)])
     145
     146                        #raise ValueError('plot_unit error: 3D element plot not supported yet')
     147                return
     148
     149        # }}}
     150        # {{{ data are on nodes
     151
     152        elif datatype==2:
     153                if is2d:
     154                        if np.ma.is_masked(data):
     155                                EltMask=np.asarray([np.any(np.in1d(index,np.where(data.mask))) for index in elements])
     156                                triangles=mpl.tri.Triangulation(x,y,elements,EltMask)
     157                        else:
     158                                triangles=mpl.tri.Triangulation(x,y,elements)
     159                                #tri=ax.tricontourf(triangles,data,colorlevels,cmap=cmap,norm=norm,alpha=alpha)
     160                        if options.exist('log'):
     161                                if alpha<1:#help with antialiasing
     162                                        tri=ax.tricontour(triangles,data,colorlevels,cmap=cmap,norm=norm,alpha=0.1,antialiased=antialiased)
     163                                tri=ax.tricontourf(triangles,data,colorlevels,cmap=cmap,norm=norm,alpha=alpha,antialiased=antialiased)
     164                        else:
     165                                if alpha<1:#help with antialiasing
     166                                        tri=ax.tricontour(triangles,data,colorlevels,cmap=cmap,norm=norm,alpha=0.1,antialiased=antialiased)
     167                                tri=ax.tricontourf(triangles,data,colorlevels,cmap=cmap,norm=norm,alpha=alpha,extend='both',antialiased=antialiased)
     168                        if edgecolor != 'None':
     169                                ax.triplot(x,y,elements,color=edgecolor)
     170                else:
     171                        #first deal with the colormap
     172                        loccmap = plt.cm.ScalarMappable(cmap=cmap)
     173                        loccmap.set_array([min(data),max(data)])
     174                        loccmap.set_clim(vmin=min(data),vmax=max(data))
     175
     176                        #deal with prism sides
     177                        recface=np.vstack((elements[:,0],elements[:,1],elements[:,4],elements[:,3])).T
     178                        recface=np.vstack((recface,np.vstack((elements[:,1],elements[:,2],elements[:,5],elements[:,4])).T))
     179                        recface=np.vstack((recface,np.vstack((elements[:,2],elements[:,0],elements[:,3],elements[:,5])).T))
     180                        tmp = np.ascontiguousarray(np.sort(recface)).view(np.dtype((np.void, recface.dtype.itemsize * recface.shape[1])))
     181                        _, idx, recur = np.unique(tmp, return_index=True, return_counts=True)
     182                        recel= recface[idx[np.where(recur==1)]]
     183                        for rectangle in recel:
     184                                rec=list(zip(x[rectangle],y[rectangle],z[rectangle]))
     185                                pl3=Poly3DCollection([rec])
     186                                color=loccmap.to_rgba(np.mean(data[rectangle]))
     187                                pl3.set_edgecolor(color)
     188                                pl3.set_color(color)
     189                                ax.add_collection3d(pl3)
     190
     191                        #deal with prism faces
     192                        triface=np.vstack((elements[:,0:3],elements[:,3:6]))
     193                        tmp = np.ascontiguousarray(triface).view(np.dtype((np.void, triface.dtype.itemsize * triface.shape[1])))
     194                        _, idx,recur = np.unique(tmp, return_index=True,return_counts=True)
     195                        #we keep only top and bottom elements
     196                        triel= triface[idx[np.where(recur==1)]]
     197                        for triangle in triel:
     198                                tri=list(zip(x[triangle],y[triangle],z[triangle]))
     199                                pl3=Poly3DCollection([tri])
     200                                color=loccmap.to_rgba(np.mean(data[triangle]))
     201                                pl3.set_edgecolor(color)
     202                                pl3.set_color(color)
     203                                ax.add_collection3d(pl3)
     204
     205                        ax.set_xlim([min(x),max(x)])
     206                        ax.set_ylim([min(y),max(y)])
     207                        ax.set_zlim([min(z),max(z)])
     208                        #raise ValueError('plot_unit error: 3D element plot not supported yet')
     209                return
     210
     211        # }}}
     212        # {{{ plotting quiver
     213        elif datatype==3:
     214                if is2d:
     215                        Q=plot_quiver(x,y,data,options,ax)
     216                else:
     217                        raise ValueError('plot_unit error: 3D node plot not supported yet')
     218                return
     219       
     220        # }}}
     221        # {{{ plotting P1 Patch (TODO)
     222
     223        elif datatype==4:
     224                print('plot_unit message: P1 patch plot not implemented yet')
     225                return
     226
     227        # }}}
     228        # {{{ plotting P0 Patch (TODO)
     229
     230        elif datatype==5:
     231                print('plot_unit message: P0 patch plot not implemented yet')
     232                return
     233
     234        # }}}
     235        else:
     236                raise ValueError('datatype=%d not supported' % datatype)
  • issm/trunk-jpl/src/py3/plot/plotmodel.py

    r21255 r23670  
    1 import numpy as np
     1import numpy as  np
    22from plotoptions import plotoptions
     3from plotdoc import plotdoc
     4from plot_manager import plot_manager
     5from math import ceil, sqrt
    36
    47try:
     
    69        import matplotlib.pyplot as plt
    710        from mpl_toolkits.axes_grid1 import ImageGrid, AxesGrid
     11        from mpl_toolkits.mplot3d import Axes3D
    812except ImportError:
    913        print("could not import pylab, matplotlib has not been installed, no plotting capabilities enabled")
    1014
    11 from plot_manager import plot_manager
    12 from math import ceil, sqrt
    13 
    1415def plotmodel(md,*args):
    15         '''
    16         at command prompt, type 'plotdoc' for additional documentation
     16        '''     at command prompt, type 'plotdoc()' for additional documentation
    1717        '''
    1818
    19         #First process options 
     19        #First process options
    2020        options=plotoptions(*args)
    2121
    2222        #get number of subplots
    2323        subplotwidth=ceil(sqrt(options.numberofplots))
    24        
    2524        #Get figure number and number of plots
    2625        figurenumber=options.figurenumber
     
    3736                nrows=np.ceil(numberofplots/subplotwidth)
    3837                nr=False
    39        
     38
    4039        if options.list[0].exist('ncols'):
    4140                ncols=options.list[0].getfieldvalue('ncols')
     
    4645        ncols=int(ncols)
    4746        nrows=int(nrows)
    48        
     47
    4948        #check that nrows and ncols were given at the same time!
    5049        if not nr==nc:
    5150                raise Exception('error: nrows and ncols need to be specified together, or not at all')
    52        
     51
    5352        #Go through plots
    5453        if numberofplots:
    55                
    5654                #if plt.fignum_exists(figurenumber):
    5755                #       plt.cla()
     
    6058                if options.list[0].exist('figsize'):
    6159                        figsize=options.list[0].getfieldvalue('figsize')
    62                         fig=plt.figure(figurenumber,figsize=(figsize[0],figsize[1]),tight_layout=True)
     60                        fig=plt.figure(figurenumber,figsize=(figsize[0],figsize[1]))#,tight_layout=True)
    6361                else:
    64                         fig=plt.figure(figurenumber,tight_layout=True)
     62                        fig=plt.figure(figurenumber)#,tight_layout=True)
    6563                fig.clf()
    6664
     65                backgroundcolor=options.list[0].getfieldvalue('backgroundcolor',(0.7,0.7,0.7))
     66                fig.set_facecolor(backgroundcolor)
     67
     68
     69                translator={'on':'each',
     70                                                                'off':'None',
     71                                                                'one':'single'}
    6772                # options needed to define plot grid
     73                plotnum=options.numberofplots
    6874                direction=options.list[0].getfieldvalue('direction','row') # row,column
    6975                axes_pad=options.list[0].getfieldvalue('axes_pad',0.25)
    7076                add_all=options.list[0].getfieldvalue('add_all',True) # True,False
    7177                share_all=options.list[0].getfieldvalue('share_all',True) # True,False
    72                 label_mode=options.list[0].getfieldvalue('label_mode','1') # 1,L,all
    73                 cbar_mode=options.list[0].getfieldvalue('cbar_mode','each') # none,single,each
    74                 cbar_location=options.list[0].getfieldvalue('cbar_location','right') # right,top
    75                 cbar_size=options.list[0].getfieldvalue('cbar_size','5%')
    76                 cbar_pad=options.list[0].getfieldvalue('cbar_pad','2.5%') # None or %
    77                
    78                 axgrid=ImageGrid(fig, 111,
     78                label_mode=options.list[0].getfieldvalue('label_mode','L') # 1,L,all
     79                colorbar=options.list[0].getfieldvalue('colorbar','on') # on, off (single)
     80                cbar_mode=translator[colorbar]
     81                cbar_location=options.list[0].getfieldvalue('colorbarpos','right') # right,top
     82                cbar_size=options.list[0].getfieldvalue('colorbarsize','5%')
     83                cbar_pad=options.list[0].getfieldvalue('colorbarpad','2.5%') # None or %
     84
     85                axgrid=ImageGrid(fig,111,
    7986                                nrows_ncols=(nrows,ncols),
     87                                ngrids=plotnum,
    8088                                direction=direction,
    8189                                axes_pad=axes_pad,
     
    8694                                cbar_location=cbar_location,
    8795                                cbar_size=cbar_size,
    88                                 cbar_pad=cbar_pad
    89                                 )
     96                                cbar_pad=cbar_pad)
    9097
    91                 if cbar_mode=='none':
    92                         for ax in axgrid.cbar_axes: fig._axstack.remove(ax)
     98                if cbar_mode=='None':
     99                        for ax in axgrid.cbar_axes:
     100                                fig._axstack.remove(ax)
    93101
    94                 for i in range(numberofplots):
    95                         plot_manager(options.list[i].getfieldvalue('model',md),options.list[i],fig,axgrid[i])
    96 
     102                for i,ax in enumerate(axgrid.axes_all):
     103                        plot_manager(options.list[i].getfieldvalue('model',md),options.list[i],fig,axgrid,i)
    97104                fig.show()
    98105        else:
  • issm/trunk-jpl/src/py3/plot/processdata.py

    r21255 r23670  
    1 from math import isnan
    2 import numpy as np
     1import numpy as  np
    32
    43def processdata(md,data,options):
    5     """
    6     PROCESSDATA - process data to be plotted
     4        """
     5        PROCESSDATA - process data to be plotted
     6       
     7        datatype = 1 -> elements
     8        datatype = 2 -> nodes
     9        datatype = 3 -> node quivers
     10        datatype = 4 -> patch
     11       
     12        Usage:
     13        data,datatype=processdata(md,data,options);
     14       
     15        See also: PLOTMODEL, PROCESSMESH
     16        """
     17        # {{{ Initialisation and grabbing auxiliaries
     18        # check format
     19        if (len(data)==0 or (len(data)==1 and not isinstance(data,dict) and np.isnan(data).all())):
     20                raise ValueError("processdata error message: 'data' provided is empty")
     21        # get the shape
     22        if 'numberofvertices2d' in dir(md.mesh):
     23                numberofvertices2d=md.mesh.numberofvertices2d
     24                numberofelements2d=md.mesh.numberofelements2d
     25        else:
     26                numberofvertices2d=np.nan
     27                numberofelements2d=np.nan
     28        procdata=np.copy(data)
     29        #initialize datatype
     30        datatype=0
     31        # get datasize
     32        if np.ndim(procdata)==1:
     33                datasize=(np.shape(procdata)[0],1)
     34        elif np.ndim(procdata)==2:
     35                datasize=np.shape(procdata)
     36        elif np.ndim(procdata)==3:
     37                if np.shape(procdata)[0]==2:
     38                        #treating a dim two list that needs to be stacked
     39                        procdata=np.hstack((procdata[0,:,:],procdata[1,:,:]))
     40                        datasize=np.shape(procdata)
     41                else:
     42                        raise ValueError('data list contains more than two vectore, we can not cope with that')
     43        else:
     44                raise ValueError('data passed to plotmodel has bad dimensions; check that column vectors are rank-1')
     45  # }}}     
     46        # {{{ process NaN's if any
     47        nanfill=options.getfieldvalue('nan',-9999)
     48        if np.any(np.isnan(procdata)):
     49                lb=np.nanmin(procdata)
     50                ub=np.nanmax(procdata)
     51                if lb==ub:
     52                        lb=lb-0.5
     53                        ub=ub+0.5
     54                        nanfill=lb-1
     55                        #procdata[np.isnan(procdata)]=nanfill
     56                procdata=np.ma.array(procdata,mask=np.isnan(procdata))
     57                options.addfielddefault('clim',[lb,ub])
     58                options.addfielddefault('cmap_set_under','1')
     59                print("WARNING: nan's treated as", nanfill, "by default.  Change using pairoption 'nan',nan_fill_value in plotmodel call")
     60  # }}} 
     61        # {{{ log
     62        if options.exist('log'):
     63                cutoff=options.getfieldvalue('log',1)
     64                procdata[np.where(procdata<cutoff)]=cutoff
     65        # }}}
     66        # {{{ quiver plot
     67        if datasize[1]>1 and datasize[0]!= md.mesh.numberofvertices+1:
     68                if datasize[0]==md.mesh.numberofvertices and datasize[1]==2:
     69                        datatype=3
     70                else:
     71                        raise ValueError('plotmodel error message: data should have two columns of length md.mesh.numberofvertices for a quiver plot')
     72        # }}} 
     73        # {{{ element data
     74
     75        if datasize[0]==md.mesh.numberofelements and datasize[1]==1:
     76                #initialize datatype if non patch
     77                if datatype!=4 and datatype!=5:
     78                        datatype=1
     79                # {{{mask
     80                if options.exist('mask'):
     81                        flags=options.getfieldvalue('mask')
     82                        hide=np.invert(flags)
     83                        if np.size(flags)==md.mesh.numberofvertices:
     84                                EltMask=np.asarray([np.any(np.in1d(index,np.where(hide))) for index in md.mesh.elements-1])
     85                                procdata=np.ma.array(procdata,mask=EltMask)
     86                                options.addfielddefault('cmap_set_bad','w')
     87                        elif np.size(flags)==md.mesh.numberofelements:
     88                                procdata=np.ma.array(procdata,mask=hide)
     89                                options.addfielddefault('cmap_set_bad','w')
     90                        else:
     91                                print('plotmodel warning: mask length not supported yet (supported length are md.mesh.numberofvertices and md.mesh.numberofelements')
     92                # }}} 
     93
     94        # }}} 
     95        # {{{ node data
     96        if datasize[0]==md.mesh.numberofvertices and datasize[1]==1:
     97                datatype=2
     98                # {{{ Mask
     99                if options.exist('mask'):
     100                        flags=options.getfieldvalue('mask')
     101                        hide=np.invert(flags)
     102                        if np.size(flags)==md.mesh.numberofvertices:
     103                                procdata=np.ma.array(procdata,mask=hide)
     104                                options.addfielddefault('cmap_set_bad','w')
     105                        elif np.size(flags)==md.mesh.numberofelements:
     106                                NodeMask=np.zeros(np.shape(md.mesh.x),dtype=bool)
     107                                HideElt=md.mesh.elements[np.where(hide)[0]]-1
     108                                NodeMask[HideElt]=True
     109                                procdata=np.ma.array(procdata,mask=NodeMask)
     110                                options.addfielddefault('cmap_set_bad','w')
     111                        else:
     112                                print('plotmodel warning: mask length not supported yet (supported length are md.mesh.numberofvertices and md.mesh.numberofelements')
     113          # }}} 
     114        # }}} 
     115        # {{{ spc time series
     116        if datasize[0]==md.mesh.numberofvertices+1:
     117                datatype=2
     118                spccol=options.getfieldvalue('spccol',0)
     119                print('multiple-column spc field; specify column to plot using option "spccol"')
     120                print('column ', spccol, ' plotted for time: ', procdata[-1,spccol])
     121                procdata=procdata[0:-1,spccol]
    7122   
    8         datatype = 1 -> elements
    9         datatype = 2 -> nodes
    10         datatype = 3 -> node quivers
    11         datatype = 4 -> patch
    12    
    13         Usage:
    14                 data,datatype=processdata(md,data,options);
    15    
    16         See also: PLOTMODEL, PROCESSMESH
    17     """
    18    
    19     #check format
    20     if (len(data)==0 or (len(data)==1 and not isinstance(data,dict) and isnan(data).all())):
    21         raise ValueError("processdata error message: 'data' provided is empty")
    22    
    23     #needed later on
    24     if 'numberofvertices2d' in dir(md.mesh):
    25         numberofvertices2d=md.mesh.numberofvertices2d
    26         numberofelements2d=md.mesh.numberofelements2d
    27     else:
    28         numberofvertices2d=np.nan
    29         numberofelements2d=np.nan
    30    
    31     procdata=np.copy(data)
    32    
    33     #process patch
    34    
    35     #initialize datatype
    36     datatype=0
    37    
    38     #get datasize
    39     if np.ndim(procdata)==1:
    40         datasize=np.array([len(procdata),1])
    41     else:
    42         datasize=np.shape(procdata)
    43         if len(datasize)>2:
    44             raise ValueError('data passed to plotmodel has more than 2 dimensions; check that column vectors are rank-1')
    45    
    46     #process NaN's if any
    47     nanfill=options.getfieldvalue('nan',-9999)
    48     if np.any(np.isnan(procdata)):
    49         lb=np.min(data[~np.isnan(data)])
    50         ub=np.max(data[~np.isnan(data)])
    51         if lb==ub:
    52             lb=lb-0.5
    53             ub=ub+0.5
    54             nanfill=lb-1
    55         procdata[np.isnan(procdata)]=nanfill
    56         options.addfielddefault('clim',[lb,ub])
    57         options.addfielddefault('cmap_set_under','1')
    58         print(("WARNING: nan's treated as", nanfill, "by default.  Change using pairoption 'nan',nan_fill_value in plotmodel call"))
    59    
    60     #quiver plot
    61     if datasize[1]>1 and datasize[0]!= md.mesh.numberofvertices+1:
    62         if datasize[0]==md.mesh.numberofvertices and datasize[1]==2:
    63             datatype=3
    64         else:
    65             raise ValueError('plotmodel error message: data should have two columns of length md.mesh.numberofvertices for a quiver plot')
    66    
    67     #non-patch processing
    68    
    69     #element data
    70     if datasize[0]==md.mesh.numberofelements and datasize[1]==1:
    71        
    72         #initialize datatype if non patch
    73         if datatype!=4 and datatype!=5:
    74             datatype=1
    75    
    76         #mask?
    77    
    78         #log?
    79    
    80     #node data
    81     if datasize[0]==md.mesh.numberofvertices and datasize[1]==1:
    82         datatype=2
    83    
    84     #spc time series?
    85     if datasize[0]==md.mesh.numberofvertices+1:
    86         datatype=2
    87         spccol=options.getfieldvalue('spccol',0)
    88         print('multiple-column spc field; specify column to plot using option "spccol"')
    89         print(('column ', spccol, ' plotted for time: ', procdata[-1,spccol]))
    90         procdata=procdata[0:-1,spccol]
    91    
    92         #mask?
    93    
    94         #log?
     123                #mask?
    95124   
    96125    #layer projection?
    97126   
    98127    #control arrow density if quiver plot
    99    
    100     #convert rank-2 array to rank-1
    101     if np.ndim(procdata)==2 and np.shape(procdata)[1]==1:
    102         procdata=procdata.reshape(-1,)
    103    
    104     #if datatype is still zero, error out
    105     if datatype==0:
    106         raise ValueError("processdata error: data provided not recognized or not supported")
    107     else:
    108         return procdata, datatype
     128        # }}} 
     129        # {{{ convert rank-2 array to rank-1
     130        if np.ndim(procdata)==2 and np.shape(procdata)[1]==1:
     131                procdata=procdata.reshape(-1,)
     132        # }}} 
     133        # {{{ if datatype is still zero, error out
     134        if datatype==0:
     135                raise ValueError("processdata error: data provided not recognized or not supported")
     136        else:
     137                return procdata, datatype
     138  # }}} 
  • issm/trunk-jpl/src/py3/plot/processmesh.py

    r21255 r23670  
    11from math import isnan
    2 import MatlabFuncs as m
    3 import numpy as np
     2import numpy as  np
    43
    54def processmesh(md,data,options):
    65        """
    76        PROCESSMESH - process the mesh for plotting
    8 
     7       
    98        Usage:
    10                 x,y,z,elements,is2d=processmech(md,data,options)
    11 
     9        x,y,z,elements,is2d=processmech(md,data,options)
     10       
    1211        See also: PLOTMODEL, PROCESSDATA
    1312        """
    14 
    15         #some checks
     13       
     14        # {{{ check mesh size parameters
    1615        if md.mesh.numberofvertices==0:
    1716                raise ValueError('processmesh error: mesh is empty')
    1817        if md.mesh.numberofvertices==md.mesh.numberofelements:
    1918                raise ValueError('processmesh error: the number of elements is the same as the number of nodes')
     19        # }}}
     20  # {{{ treating coordinates
    2021
    21         if len(data)==0 or not isinstance(data,dict):
     22        try:
     23                z=md.mesh.z
     24        except AttributeError:
     25                z=np.zeros(np.shape(md.mesh.x))
     26        elements=md.mesh.elements-1
     27       
     28        if options.getfieldvalue('layer',0)>=1:
     29                x=md.mesh.x2d
     30                y=md.mesh.y2d
     31                z=np.zeros(np.shape(x))
     32                elements=md.mesh.elements2d-1
     33        elif 'latlon' in options.getfieldvalue('coord','xy'):
     34                x=md.mesh.long
     35                y=md.mesh.lat
     36        else:
     37                x=md.mesh.x
     38                y=md.mesh.y
     39
     40        #is it a 2D plot?
     41        if md.mesh.dimension()==2 or options.getfieldvalue('layer',0)>=1:
     42                is2d=1
     43        else:
     44                is2d=0
    2245               
    23                 if 'latlon' not in options.getfieldvalue('coord','xy').lower(): #convert to lower case for comparison
    24                         x=md.mesh.x
    25                         if 'x2d' in dir(md.mesh): x2d=md.mesh.x2d
    26                         y=md.mesh.y
    27                         if 'y2d' in dir(md.mesh): y2d=md.mesh.x2d
    28                 else:
    29                         x=md.mesh.long
    30                         y=md.mesh.lat
    31 
    32                 if 'z' in dir(md.mesh):
    33                         z=md.mesh.z
    34                 else:
    35                         z=np.zeros_like(md.mesh.x)
    36                
    37                 if 'elements2d' in dir(md.mesh):
    38                         elements2d=md.mesh.elements2d
    39                         elements2d=elements2d-1  # subtract one since python indexes from zero
    40                 elements=md.mesh.elements
    41                 elements=elements-1
    42 
    43                 #is it a 2D plot?
    44                 if md.mesh.dimension()==2:
    45                         is2d=1
    46                 else:
    47                         if options.getfieldvalue('layer',0)>=1:
    48                                 is2d=1
    49                         else:
    50                                 is2d=0
    51 
    52                 #layer projection?
    53                 if options.getfieldvalue('layer',0)>=1:
    54                          if 'latlon' in options.getfieldvalue('coord','xy').lower():
    55                                  raise ValueError('processmesh error: cannot work with 3D mesh in lat-lon coords')
    56                         #we modify the mesh temporarily to a 2D mesh from which the 3D mesh was extruded
    57                          x=x2d
    58                          y=y2d
    59                          z=zeros(size(x2d))
    60                          elements=elements2d
    61        
    62         else:
    63                 #Process mesh for plotting
    64                 if md.mesh.dimension()==2:
    65                         is2d=1
    66                 else:
    67                         # process polycollection here for 3D plot
    68                         is2d=0
    69        
    7046        #units
    7147        if options.exist('unit'):
  • issm/trunk-jpl/src/py3/plot/writejsfield.py

    r19895 r23670  
    1 import numpy
     1import numpy as np
    22def writejsfield(fid,name,variable,nods):
    33#WRITEJSFIELD - write variable to javascript file
     
    88        #write array:
    99        #if not isinstance(variable, list):
    10         if type(variable[0])==numpy.float64:
     10        if type(variable[0])==np.float64:
    1111                fid.write('<!-- {0}{{{{{{-->\n'.format(name))
    1212                fid.write('{0}=['.format(name))
  • issm/trunk-jpl/src/py3/plot/writejsfile.py

    r19895 r23670  
    1 import numpy
     1import numpy as np
    22from writejsfield import writejsfield
    33def writejsfile(filename,model,keyname):
     
    4848                fid.write('result["shortlabel"]="{0}";\n'.format(results[i].shortlabel))
    4949                fid.write('result["unit"]="{0}";\n'.format(results[i].unit))
    50                 if type(results[i].data)==numpy.float64:
     50                if type(results[i].data)==np.float64:
    5151                        fid.write('result["time_range"]=[{0},{1}];\n'.format(results[i].time_range[0],results[i].time_range[1]))
    5252                fid.write('results["{0}"]=result;\n'.format(i))
  • issm/trunk-jpl/src/py3/shp/shp2exp.py

    r21349 r23670  
    3333                geom=shp.shapes()[i].shapeType
    3434                if geom==5: # polygon
    35          expdict['closed']=1
     35                        expdict['closed']=1
    3636                        tmpx=[p[0] for p in shp.shapes()[i].points]
    3737                        tmpy=[q[1] for q in shp.shapes()[i].points]
     
    3939                        y.append(tmpy)
    4040                elif geom==3: # line
    41          expdict['closed']=0
     41                        expdict['closed']=0
    4242                        tmpx=[p[0] for p in shp.shapes()[i].points]
    4343                        tmpy=[q[1] for q in shp.shapes()[i].points]
     
    4545                        y.append(tmpy)
    4646                elif geom==1: # point
    47          expdict['closed']=0
     47                        expdict['closed']=0
    4848                        x.append(shp.shapes()[i].points[0][0])
    4949                        y.append(shp.shapes()[i].points[0][1])
  • issm/trunk-jpl/src/py3/solve/WriteData.py

    r19895 r23670  
    1 import numpy
    2 import math
     1import numpy as np
    32import struct
    43import pairoptions
    54import MatlabFuncs as m
    6 from EnumDefinitions import *
    7 from EnumToString import EnumToString
    8 
    9 def WriteData(fid,**kwargs):
     5
     6def WriteData(fid,prefix,*args):
    107        """
    118        WRITEDATA - write model field in binary file
    12  
     9
    1310           Usage:
    1411              WriteData(fid,varargin)
     
    1613
    1714        #process options
    18         options=pairoptions.pairoptions(**kwargs)
     15        options=pairoptions.pairoptions(*args)
    1916
    2017        #Get data properties
     
    2421                fieldname = options.getfieldvalue('fieldname')
    2522                classname = options.getfieldvalue('class',str(type(obj)).rsplit('.')[-1].split("'")[0])
    26                 if options.exist('enum'):
    27                         enum = options.getfieldvalue('enum')
    28                 else:
    29                         enum = BuildEnum(classname+'_'+fieldname)
    30                 data      = getattr(obj,fieldname)
     23                name      = options.getfieldvalue('name',prefix+'.'+fieldname);
     24                if options.exist('data'):
     25                        data = options.getfieldvalue('data')
     26                else:
     27                        data      = getattr(obj,fieldname)
    3128        else:
    3229                #No processing required
    3330                data = options.getfieldvalue('data')
    34                 enum = options.getfieldvalue('enum')
     31                name = options.getfieldvalue('name')
     32
    3533        format  = options.getfieldvalue('format')
    3634        mattype = options.getfieldvalue('mattype',0)    #only required for matrices
     
    4442        #Scale data if necesarry
    4543        if options.exist('scale'):
     44                data=np.array(data)
    4645                scale = options.getfieldvalue('scale')
    47                 if numpy.size(data) > 1 :
    48                         if numpy.size(data,0)==timeserieslength:
    49                                 data=numpy.array(data)
    50                                 data[0:-1,:] = scale*data[0:-1,:]
    51                         else:
    52                                 data  = scale*data
     46                if np.size(data) > 1 and np.ndim(data) > 1 and np.size(data,0)==timeserieslength:
     47                        data[0:-1,:] = scale*data[0:-1,:]
    5348                else:
    5449                        data  = scale*data
    55         if numpy.size(data) > 1 :
    56                 if numpy.size(data,0)==timeserieslength:
    57                         yts=365.0*24.0*3600.0
     50        if np.size(data) > 1 and np.size(data,0)==timeserieslength:
     51                yts = options.getfieldvalue('yts')
     52                if np.ndim(data) > 1:
    5853                        data[-1,:] = yts*data[-1,:]
     54                else:
     55                        data[-1] = yts*data[-1]
    5956
    6057        #Step 1: write the enum to identify this record uniquely
    61         fid.write(struct.pack('i',enum))
     58        fid.write(struct.pack('i',len(name)))
     59        fid.write(struct.pack('%ds' % len(name),name))
    6260
    6361        #Step 2: write the data itself.
    6462        if   m.strcmpi(format,'Boolean'):    # {{{
    6563#               if len(data) !=1:
    66 #                       raise ValueError('field %s cannot be marshalled as it has more than one element!' % EnumToString(enum)[0])
     64#                       raise ValueError('field %s cannot be marshalled as it has more than one element!' % name[0])
    6765
    6866                #first write length of record
    6967                fid.write(struct.pack('i',4+4))  #1 bool (disguised as an int)+code
    7068
    71                 #write data code: 
    72                 fid.write(struct.pack('i',FormatToCode(format))) 
     69                #write data code:
     70                fid.write(struct.pack('i',FormatToCode(format)))
    7371
    7472                #now write integer
     
    7876        elif m.strcmpi(format,'Integer'):    # {{{
    7977#               if len(data) !=1:
    80 #                       raise ValueError('field %s cannot be marshalled as it has more than one element!' % EnumToString(enum)[0])
     78#                       raise ValueError('field %s cannot be marshalled as it has more than one element!' % name[0])
    8179
    8280                #first write length of record
    8381                fid.write(struct.pack('i',4+4))  #1 integer + code
    8482
    85                 #write data code: 
    86                 fid.write(struct.pack('i',FormatToCode(format))) 
     83                #write data code:
     84                fid.write(struct.pack('i',FormatToCode(format)))
    8785
    8886                #now write integer
    89                 fid.write(struct.pack('i',data)) 
     87                fid.write(struct.pack('i',data))
    9088                # }}}
    9189
    9290        elif m.strcmpi(format,'Double'):    # {{{
    9391#               if len(data) !=1:
    94 #                       raise ValueError('field %s cannot be marshalled as it has more than one element!' % EnumToString(enum)[0])
     92#                       raise ValueError('field %s cannot be marshalled as it has more than one element!' % name[0])
    9593
    9694                #first write length of record
    9795                fid.write(struct.pack('i',8+4))  #1 double+code
    9896
    99                 #write data code: 
    100                 fid.write(struct.pack('i',FormatToCode(format))) 
     97                #write data code:
     98                fid.write(struct.pack('i',FormatToCode(format)))
    10199
    102100                #now write double
    103                 fid.write(struct.pack('d',data)) 
     101                fid.write(struct.pack('d',data))
    104102                # }}}
    105103
     
    108106                fid.write(struct.pack('i',len(data)+4+4))  #string + string size + code
    109107
    110                 #write data code: 
    111                 fid.write(struct.pack('i',FormatToCode(format))) 
     108                #write data code:
     109                fid.write(struct.pack('i',FormatToCode(format)))
    112110
    113111                #now write string
    114                 fid.write(struct.pack('i',len(data))) 
    115                 fid.write(struct.pack('%ds' % len(data),data)) 
     112                fid.write(struct.pack('i',len(data)))
     113                fid.write(struct.pack('%ds' % len(data),data))
    116114                # }}}
    117115
     
    119117
    120118                if   isinstance(data,bool):
    121                         data=numpy.array([data])
     119                        data=np.array([data])
    122120                elif isinstance(data,(list,tuple)):
    123                         data=numpy.array(data).reshape(-1,1)
    124                 if numpy.ndim(data) == 1:
    125                         if numpy.size(data):
    126                                 data=data.reshape(numpy.size(data),1)
     121                        data=np.array(data).reshape(-1,)
     122                if np.ndim(data) == 1:
     123                        if np.size(data):
     124                                data=data.reshape(np.size(data),)
    127125                        else:
    128126                                data=data.reshape(0,0)
     
    131129                s=data.shape
    132130                #if matrix = NaN, then do not write anything
    133                 if s[0]==1 and s[1]==1 and math.isnan(data[0][0]):
     131                if np.ndim(data)==2 and np.product(s)==1 and np.all(np.isnan(data)):
    134132                        s=(0,0)
    135133
    136134                #first write length of record
    137                 fid.write(struct.pack('i',4+4+8*s[0]*s[1]+4+4))    #2 integers (32 bits) + the double matrix + code + matrix type
    138 
    139                 #write data code and matrix type: 
    140                 fid.write(struct.pack('i',FormatToCode(format))) 
     135                fid.write(struct.pack('i',4+4+8*np.product(s)+4+4))    #2 integers (32 bits) + the double matrix + code + matrix type
     136
     137                #write data code and matrix type:
     138                fid.write(struct.pack('i',FormatToCode(format)))
    141139                fid.write(struct.pack('i',mattype))
    142140
    143141                #now write matrix
    144                 fid.write(struct.pack('i',s[0]))
    145                 fid.write(struct.pack('i',s[1]))
    146                 for i in range(s[0]):
    147                         for j in range(s[1]):
    148                                 fid.write(struct.pack('d',float(data[i][j])))    #get to the "c" convention, hence the transpose
     142                if np.ndim(data)==1:
     143                        fid.write(struct.pack('i',s[0]))
     144                        fid.write(struct.pack('i',1))
     145                        for i in range(s[0]):
     146                                fid.write(struct.pack('d',float(data[i])))    #get to the "c" convention, hence the transpose
     147                else:
     148                        fid.write(struct.pack('i',s[0]))
     149                        fid.write(struct.pack('i',s[1]))
     150                        for i in range(s[0]):
     151                                for j in range(s[1]):
     152                                        fid.write(struct.pack('d',float(data[i][j])))    #get to the "c" convention, hence the transpose
    149153                # }}}
    150154
     
    152156
    153157                if   isinstance(data,int):
    154                         data=numpy.array([data])
     158                        data=np.array([data])
    155159                elif isinstance(data,(list,tuple)):
    156                         data=numpy.array(data).reshape(-1,1)
    157                 if numpy.ndim(data) == 1:
    158                         if numpy.size(data):
    159                                 data=data.reshape(numpy.size(data),1)
     160                        data=np.array(data).reshape(-1,)
     161                if np.ndim(data) == 1:
     162                        if np.size(data):
     163                                data=data.reshape(np.size(data),)
    160164                        else:
    161165                                data=data.reshape(0,0)
     
    164168                s=data.shape
    165169                #if matrix = NaN, then do not write anything
    166                 if s[0]==1 and s[1]==1 and math.isnan(data[0][0]):
     170                if np.ndim(data)==2 and np.product(s)==1 and np.all(np.isnan(data)):
    167171                        s=(0,0)
    168172
    169173                #first write length of record
    170                 fid.write(struct.pack('i',4+4+8*s[0]*s[1]+4+4))    #2 integers (32 bits) + the double matrix + code + matrix type
    171 
    172                 #write data code and matrix type: 
    173                 fid.write(struct.pack('i',FormatToCode(format))) 
     174                fid.write(struct.pack('i',4+4+8*np.product(s)+4+4))    #2 integers (32 bits) + the double matrix + code + matrix type
     175
     176                #write data code and matrix type:
     177                fid.write(struct.pack('i',FormatToCode(format)))
    174178                fid.write(struct.pack('i',mattype))
    175179
    176180                #now write matrix
    177                 fid.write(struct.pack('i',s[0]))
    178                 fid.write(struct.pack('i',s[1]))
    179                 for i in range(s[0]):
    180                         for j in range(s[1]):
    181                                 fid.write(struct.pack('d',float(data[i][j])))    #get to the "c" convention, hence the transpose
     181                if np.ndim(data) == 1:
     182                        fid.write(struct.pack('i',s[0]))
     183                        fid.write(struct.pack('i',1))
     184                        for i in range(s[0]):
     185                                fid.write(struct.pack('d',float(data[i])))    #get to the "c" convention, hence the transpose
     186                else:
     187                        fid.write(struct.pack('i',s[0]))
     188                        fid.write(struct.pack('i',s[1]))
     189                        for i in range(s[0]):
     190                                for j in range(s[1]):
     191                                        fid.write(struct.pack('d',float(data[i][j])))    #get to the "c" convention, hence the transpose
    182192                # }}}
    183193
     
    185195
    186196                if   isinstance(data,(bool,int,float)):
    187                         data=numpy.array([data])
     197                        data=np.array([data])
    188198                elif isinstance(data,(list,tuple)):
    189                         data=numpy.array(data).reshape(-1,1)
    190                 if numpy.ndim(data) == 1:
    191                         if numpy.size(data):
    192                                 data=data.reshape(numpy.size(data),1)
     199                        data=np.array(data).reshape(-1,)
     200                if np.ndim(data) == 1:
     201                        if np.size(data):
     202                                data=data.reshape(np.size(data),)
    193203                        else:
    194204                                data=data.reshape(0,0)
     
    197207                s=data.shape
    198208                #if matrix = NaN, then do not write anything
    199                 if s[0]==1 and s[1]==1 and math.isnan(data[0][0]):
     209                if np.ndim(data)==1 and np.product(s)==1 and np.all(np.isnan(data)):
    200210                        s=(0,0)
    201211
    202212                #first write length of record
    203                 recordlength=4+4+8*s[0]*s[1]+4+4; #2 integers (32 bits) + the double matrix + code + matrix type
    204                 if recordlength > 2**31 :
    205                         raise ValueError('field %s cannot be marshalled because it is larger than 4^31 bytes!' % EnumToString(enum)[0])
     213                recordlength=4+4+8*np.product(s)+4+4; #2 integers (32 bits) + the double matrix + code + matrix type
     214                if recordlength > 4**31 :
     215                        raise ValueError('field %s cannot be marshalled because it is larger than 4^31 bytes!' % enum)
    206216
    207217                fid.write(struct.pack('i',recordlength))  #2 integers (32 bits) + the double matrix + code + matrix type
    208218
    209                 #write data code and matrix type: 
    210                 fid.write(struct.pack('i',FormatToCode(format))) 
     219                #write data code and matrix type:
     220                fid.write(struct.pack('i',FormatToCode(format)))
    211221                fid.write(struct.pack('i',mattype))
    212222
    213223                #now write matrix
    214                 fid.write(struct.pack('i',s[0]))
    215                 fid.write(struct.pack('i',s[1]))
    216                 for i in range(s[0]):
     224                if np.ndim(data) == 1:
     225                        fid.write(struct.pack('i',s[0]))
     226                        fid.write(struct.pack('i',1))
     227                        for i in range(s[0]):
     228                                fid.write(struct.pack('d',float(data[i])))    #get to the "c" convention, hence the transpose
     229                else:
     230                        fid.write(struct.pack('i',s[0]))
     231                        fid.write(struct.pack('i',s[1]))
     232                        for i in range(s[0]):
     233                                for j in range(s[1]):
     234                                        fid.write(struct.pack('d',float(data[i][j])))    #get to the "c" convention, hence the transpose
     235                # }}}
     236
     237        elif m.strcmpi(format,'CompressedMat'):    # {{{
     238
     239                if   isinstance(data,(bool,int,float)):
     240                        data=np.array([data])
     241                elif isinstance(data,(list,tuple)):
     242                        data=np.array(data).reshape(-1,)
     243                if np.ndim(data) == 1:
     244                        if np.size(data):
     245                                data=data.reshape(np.size(data),)
     246                        else:
     247                                data=data.reshape(0,0)
     248
     249                #Get size
     250                s=data.shape
     251                if np.ndim(data) == 1:
     252                   n2=1
     253                else:
     254                        n2=s[1]
     255
     256                #if matrix = NaN, then do not write anything
     257                if np.ndim(data)==1 and np.product(s)==1 and np.all(np.isnan(data)):
     258                        s=(0,0)
     259                        n2=0
     260
     261                #first write length of record
     262                recordlength=4+4+8+8+1*(s[0]-1)*n2+8*n2+4+4 #2 integers (32 bits) + the matrix + code + matrix type
     263                if recordlength > 4**31 :
     264                        raise ValueError('field %s cannot be marshalled because it is larger than 4^31 bytes!' % enum)
     265
     266                fid.write(struct.pack('i',recordlength))  #2 integers (32 bits) + the matrix + code + matrix type
     267
     268                #write data code and matrix type:
     269                fid.write(struct.pack('i',FormatToCode(format)))
     270                fid.write(struct.pack('i',mattype))
     271
     272                #Write offset and range
     273                A = data[0:s[0]-1]
     274                offsetA = A.min()
     275                rangeA = A.max() - offsetA
     276
     277                if rangeA == 0:
     278                        A = A*0
     279                else:
     280                        A = (A-offsetA)/rangeA*255.
     281
     282                #now write matrix
     283                if np.ndim(data) == 1:
     284                        fid.write(struct.pack('i',s[0]))
     285                        fid.write(struct.pack('i',1))
     286                        fid.write(struct.pack('d',float(offsetA)))
     287                        fid.write(struct.pack('d',float(rangeA)))
     288                        for i in range(s[0]-1):
     289                                fid.write(struct.pack('B',int(A[i])))
     290
     291                        fid.write(struct.pack('d',float(data[s[0]-1])))    #get to the "c" convention, hence the transpose
     292
     293                elif np.product(s) > 0:
     294                        fid.write(struct.pack('i',s[0]))
     295                        fid.write(struct.pack('i',s[1]))
     296                        fid.write(struct.pack('d',float(offsetA)))
     297                        fid.write(struct.pack('d',float(rangeA)))
     298                        for i in range(s[0]-1):
     299                                for j in range(s[1]):
     300                                        fid.write(struct.pack('B',int(A[i][j])))    #get to the "c" convention, hence the transpose
     301
    217302                        for j in range(s[1]):
    218                                 fid.write(struct.pack('d',float(data[i][j])))    #get to the "c" convention, hence the transpose
     303                                fid.write(struct.pack('d',float(data[s[0]-1][j])))
     304
    219305                # }}}
    220306
     
    225311                for matrix in data:
    226312                        if   isinstance(matrix,(bool,int,float)):
    227                                 matrix=numpy.array([matrix])
     313                                matrix=np.array([matrix])
    228314                        elif isinstance(matrix,(list,tuple)):
    229                                 matrix=numpy.array(matrix).reshape(-1,1)
    230                         if numpy.ndim(matrix) == 1:
    231                                 if numpy.size(matrix):
    232                                         matrix=matrix.reshape(numpy.size(matrix),1)
     315                                matrix=np.array(matrix).reshape(-1,)
     316                        if np.ndim(matrix) == 1:
     317                                if np.size(matrix):
     318                                        matrix=matrix.reshape(np.size(matrix),)
    233319                                else:
    234320                                        matrix=matrix.reshape(0,0)
    235321
    236322                        s=matrix.shape
    237                         recordlength+=4*2+s[0]*s[1]*8    #row and col of matrix + matrix of doubles
     323                        recordlength+=4*2+np.product(s)*8    #row and col of matrix + matrix of doubles
    238324
    239325                #write length of record
    240                 fid.write(struct.pack('i',recordlength)) 
    241 
    242                 #write data code: 
    243                 fid.write(struct.pack('i',FormatToCode(format))) 
     326                fid.write(struct.pack('i',recordlength))
     327
     328                #write data code:
     329                fid.write(struct.pack('i',FormatToCode(format)))
    244330
    245331                #write data, first number of records
    246                 fid.write(struct.pack('i',len(data)))
    247 
    248                 #write each matrix:
     332                fid.write(struct.pack('i',len(data)))
     333
    249334                for matrix in data:
    250335                        if   isinstance(matrix,(bool,int,float)):
    251                                 matrix=numpy.array([matrix])
     336                                matrix=np.array([matrix])
    252337                        elif isinstance(matrix,(list,tuple)):
    253                                 matrix=numpy.array(matrix).reshape(-1,1)
    254                         if numpy.ndim(matrix) == 1:
    255                                 matrix=matrix.reshape(numpy.size(matrix),1)
     338                                matrix=np.array(matrix).reshape(-1,)
     339                        if np.ndim(matrix) == 1:
     340                                matrix=matrix.reshape(np.size(matrix),)
    256341
    257342                        s=matrix.shape
    258                         fid.write(struct.pack('i',s[0]))
    259                         fid.write(struct.pack('i',s[1]))
    260                         for i in range(s[0]):
    261                                 for j in range(s[1]):
    262                                         fid.write(struct.pack('d',float(matrix[i][j])))
     343
     344                        if np.ndim(matrix) == 1:
     345                                fid.write(struct.pack('i',s[0]))
     346                                fid.write(struct.pack('i',1))
     347                                for i in range(s[0]):
     348                                        fid.write(struct.pack('d',float(matrix[i])))    #get to the "c" convention, hence the transpose
     349                        else:
     350                                fid.write(struct.pack('i',s[0]))
     351                                fid.write(struct.pack('i',s[1]))
     352                                for i in range(s[0]):
     353                                        for j in range(s[1]):
     354                                                fid.write(struct.pack('d',float(matrix[i][j])))
    263355                # }}}
    264356
     
    271363
    272364                #write length of record
    273                 fid.write(struct.pack('i',recordlength)) 
    274 
    275                 #write data code: 
    276                 fid.write(struct.pack('i',FormatToCode(format))) 
     365                fid.write(struct.pack('i',recordlength))
     366
     367                #write data code:
     368                fid.write(struct.pack('i',FormatToCode(format)))
    277369
    278370                #now write length of string array
    279                 fid.write(struct.pack('i',len(data))) 
     371                fid.write(struct.pack('i',len(data)))
    280372
    281373                #now write the strings
    282374                for string in data:
    283                         fid.write(struct.pack('i',len(string))) 
    284                         fid.write(struct.pack('%ds' % len(string),string)) 
     375                        fid.write(struct.pack('i',len(string)))
     376                        fid.write(struct.pack('%ds' % len(string),string))
    285377                # }}}
    286378
    287379        else:    # {{{
    288                 raise TypeError('WriteData error message: data type: %d not supported yet! (%s)' % (format,EnumToString(enum)[0]))
     380                raise TypeError('WriteData error message: data type: %d not supported yet! (%s)' % (format,enum))
    289381        # }}}
    290 
    291 def BuildEnum(string): # {{{
    292         """
    293         BUILDENUM - build enum out of string
    294  
    295     Usage:
    296        enum=BuildEnum(string)
    297         """
    298 
    299         if '_' in string:
    300                 substrs=string.split('_')
    301                 string=''
    302                 for substr in substrs:
    303                         string+=substr[0].upper()+substr[1:]
    304         else:
    305                 #take first letter of string and make it uppercase:
    306                 string=string[0].upper()+string[1:]
    307 
    308         #Get Enum
    309         enum=StringToEnum(string)[0]
    310 
    311         return enum
    312 # }}}
    313382
    314383def FormatToCode(format): # {{{
    315384        """
    316         This routine takes the format string, and hardcodes it into an integer, which 
    317         is passed along the record, in order to identify the nature of the dataset being 
     385        This routine takes the format string, and hardcodes it into an integer, which
     386        is passed along the record, in order to identify the nature of the dataset being
    318387        sent.
    319388        """
     
    337406        elif m.strcmpi(format,'StringArray'):
    338407                code=9
     408        elif m.strcmpi(format,'CompressedMat'):
     409                code=10
    339410        else:
    340411                raise InputError('FormatToCode error message: data type not supported yet!')
     
    342413        return code
    343414# }}}
    344 
  • issm/trunk-jpl/src/py3/solve/loadresultsfromcluster.py

    r19895 r23670  
    33import platform
    44from loadresultsfromdisk import loadresultsfromdisk
     5
     6from helpers import *
    57
    68def loadresultsfromcluster(md,runtimename=False):
     
    2325                filelist.append(md.miscellaneous.name+'.qmu.err')
    2426                filelist.append(md.miscellaneous.name+'.qmu.out')
    25                 if 'tabular_graphics_data' in md.qmu.params:
    26                         if md.qmu.params['tabular_graphics_data']:
     27                if 'tabular_graphics_data' in fieldnames(md.qmu.params):
     28                        if md.qmu.params.tabular_graphics_data:
    2729                                filelist.append('dakota_tabular.dat')
    2830        else:
     
    3133
    3234        #If we are here, no errors in the solution sequence, call loadresultsfromdisk.
    33         md=loadresultsfromdisk(md,md.miscellaneous.name+'.outbin')
    34 
     35        if os.path.exists(md.miscellaneous.name+'.outbin'):
     36                if os.path.getsize(md.miscellaneous.name+'.outbin')>0:
     37                        md=loadresultsfromdisk(md,md.miscellaneous.name+'.outbin')
     38                else:
     39                        print('WARNING, outbin file is empty for run '+md.miscellaneous.name)
     40        elif not md.qmu.isdakota:
     41                print('WARNING, outbin file does not exist '+md.miscellaneous.name)
     42               
    3543        #erase the log and output files
    3644        if md.qmu.isdakota:
    37                 filename=os.path.join('qmu'+str(os.getpid()),md.miscellaneous.name)
     45                #filename=os.path.join('qmu'+str(os.getpid()),md.miscellaneous.name)
     46                filename = md.miscellaneous.name
     47
     48                # this will not work like normal as dakota doesn't generate outbin files,
     49                #   instead calls postqmu to store results directly in the model
     50                #   at md.results.dakota via dakota_out_parse
     51                md=loadresultsfromdisk(md,md.miscellaneous.name+'.outbin')
    3852        else:
    3953                filename=md.miscellaneous.name
     
    4963        if hostname==cluster.name:
    5064                if md.qmu.isdakota:
    51                         filename=os.path.join('qmu'+str(os.getpid()),md.miscellaneous.name)
     65                        #filename=os.path.join('qmu'+str(os.getpid()),md.miscellaneous.name)
     66                        filename = md.miscellaneous.name
    5267                        TryRem('.queue',filename)
    5368                else:
     
    5974                                TryRem('.bat',filename)
    6075
     76                # remove this for bin file debugging
    6177                TryRem('.bin',filename)
     78
     79        #cwd = os.getcwd().split('/')[-1]
     80        if md.qmu.isdakota:
     81                os.chdir('..')
     82                #TryRem('',cwd)
    6283
    6384        return md
    6485
    6586def TryRem(extension,filename):
    66         try:   
     87        try:
    6788                os.remove(filename+extension)
    6889        except OSError:
  • issm/trunk-jpl/src/py3/solve/loadresultsfromdisk.py

    r19895 r23670  
    22from results import results
    33from parseresultsfromdisk import parseresultsfromdisk
    4 from EnumToString import EnumToString
    54import MatlabFuncs as m
     5from postqmu import postqmu
    66
    77def loadresultsfromdisk(md,filename):
     
    2828
    2929                #load results onto model
    30                 structure=parseresultsfromdisk(filename,not md.settings.io_gather)
     30                structure=parseresultsfromdisk(md,filename,not md.settings.io_gather)
    3131                if not len(structure):
    3232                        raise RuntimeError("No result found in binary file '%s'. Check for solution crash." % filename)
     
    5858        #post processes qmu results if necessary
    5959        else:
    60 
    61                 if not isinstance(md.private.solution,str):
    62                         [md.private.solution]=EnumToString(md.private.solution)
    63                 md=postqmu(md)
    64                 os.chdir('..')
     60                md=postqmu(md,filename)
    6561
    6662        return md
    67 
  • issm/trunk-jpl/src/py3/solve/marshall.py

    r19895 r23670  
    11from WriteData import WriteData
    2 from EnumDefinitions import *
    32
    43def marshall(md):
     
    1211              marshall(md)
    1312        """
    14 
    15         print("marshalling file '%s.bin'." % md.miscellaneous.name)
     13        if md.verbose.solution:
     14                print("marshalling file '%s.bin'." % md.miscellaneous.name)
    1615
    1716        #open file for binary writing
     
    2120                raise IOError("marshall error message: could not open '%s.bin' file for binary writing." % md.miscellaneous.name)
    2221
    23         #First, write MaximumNumberOfEnum to make sure that the Enums are synchronized
    24         WriteData(fid,'enum',MaximumNumberOfDefinitionsEnum(),'data',True,'format','Boolean')
    25 
    26         #Go through all model fields: check that it is a class and call checkconsistency
    27         fields=vars(md)
    28 
    29 #       for field in fields.iterkeys():
    3022        for field in md.properties():
    3123
    3224                #Some properties do not need to be marshalled
    33                 if field in ['results','radaroverlay','toolkits','cluster','flaim','private']:
     25                if field in ['results','radaroverlay','toolkits','cluster','private']:
    3426                        continue
    3527
     
    4032                #Marshall current object
    4133                #print "marshalling %s ..." % field
    42                 exec("md.%s.marshall(md,fid)" % field)
     34                exec("md.{}.marshall('md.{}',md,fid)".format(field,field))
    4335
    44         #Last, write MaximumNumberOfEnum+1 to make sure that the binary file is not corrupt
    45         WriteData(fid,'enum',MaximumNumberOfDefinitionsEnum()+1,'data',True,'format','Boolean');
     36        #Last, write "md.EOF" to make sure that the binary file is not corrupt
     37        WriteData(fid,'XXX','name','md.EOF','data',True,'format','Boolean');
    4638
    4739        #close file
  • issm/trunk-jpl/src/py3/solve/parseresultsfromdisk.py

    r19895 r23670  
    11import struct
    2 import numpy
     2import numpy as np
    33from collections import OrderedDict
    44import results as resultsclass
    5 import MatlabFuncs as m
    6 
    7 def parseresultsfromdisk(filename,iosplit):
    8         """
    9         PARSERESULTSFROMDISK - ...
    10 
    11            Usage:
    12               results=parseresultsfromdisk(filename,iosplit)
    13         """
    14 
     5
     6def parseresultsfromdisk(md,filename,iosplit):
    157        if iosplit:
    16                 results=parseresultsfromdiskiosplit(filename)
     8                saveres=parseresultsfromdiskiosplit(md,filename)
    179        else:
    18                 results=parseresultsfromdiskioserial(filename)
    19 
    20         return results
    21 
    22 def parseresultsfromdiskioserial(filename):    # {{{
    23         """
    24         PARSERESULTSFROMDISK - ...
    25          
    26             Usage:
    27                results=parseresultsfromdiskioserial(filename)
    28         """
    29 
     10                saveres=parseresultsfromdiskioserial(md,filename)
     11
     12        return saveres
     13
     14def parseresultsfromdiskioserial(md,filename):    # {{{
    3015        #Open file
    3116        try:
     
    3520
    3621        #initialize results:
    37         results=[]
    38         results.append(None)
     22        saveres=[]
    3923
    4024        #Read fields until the end of the file.
    41         result=ReadData(fid)
     25        loadres=ReadData(fid,md)
    4226
    4327        counter=0
    4428        check_nomoresteps=0
    45         step=result['step']
    46 
    47         while result:
    48 
     29        step=loadres['step']
     30
     31        while loadres:
     32                #check that the new result does not add a step, which would be an error:
    4933                if check_nomoresteps:
    50                         #check that the new result does not add a step, which would be an error:
    51                         if result['step']>=1:
     34                        if loadres['step']>=1:
    5235                                raise TypeError("parsing results for a steady-state core, which incorporates transient results!")
    5336
    5437                #Check step, increase counter if this is a new step
    55                 if(step!=result['step'] and result['step']>1):
     38                if(step!=loadres['step'] and loadres['step']>1):
    5639                        counter = counter + 1
    57                         step    = result['step']
    58 
    59                 #Add result
    60                 if result['step']==0:
     40                        step    = loadres['step']
     41
     42                #Add result
     43                if loadres['step']==0:
    6144                        #if we have a step = 0, this is a steady state solution, don't expect more steps.
    6245                        index = 0;
    6346                        check_nomoresteps=1
    64        
    65                 elif result['step']==1:
     47                elif loadres['step']==1:
    6648                        index = 0
    6749                else:
    6850                        index = counter;
    69        
    70                 if index > len(results)-1:
    71                         for i in range(len(results)-1,index-1):
    72                                 results.append(None)
    73                         results.append(resultsclass.results())
    7451               
    75                 elif results[index] is None:
    76                         results[index]=resultsclass.results()
    77 
     52                if index > len(saveres)-1:
     53                        for i in range(len(saveres)-1,index-1):
     54                                saveres.append(None)
     55                        saveres.append(resultsclass.results())
     56                elif saveres[index] is None:
     57                        saveres[index]=resultsclass.results()
    7858                       
    7959                #Get time and step
    80                 if result['step'] != -9999.:
    81                         setattr(results[index],'step',result['step'])
    82                 if result['time'] != -9999.:
    83                         setattr(results[index],'time',result['time'])
    84        
    85                 #Add result
    86                 if hasattr(results[index],result['fieldname']) and not m.strcmp(result['fieldname'],'SolutionType'):
    87                         setattr(results[index],result['fieldname'],numpy.vstack((getattr(results[index],result['fieldname']),result['field'])))
    88                 else:
    89                         setattr(results[index],result['fieldname'],result['field'])
    90 
    91                 #read next result
    92                 result=ReadData(fid)
     60                if loadres['step'] != -9999.:
     61                        saveres[index].__dict__['step']=loadres['step']
     62                if loadres['time'] != -9999.:
     63                        saveres[index].__dict__['time']=loadres['time']
     64
     65                #Add result
     66                saveres[index].__dict__[loadres['fieldname']]=loadres['field']
     67
     68                #read next result
     69                loadres=ReadData(fid,md)
    9370
    9471        fid.close()
    9572
    96         return results
    97         # }}}
    98 def parseresultsfromdiskiosplit(filename):    # {{{
    99         """
    100         PARSERESULTSFROMDISKIOSPLIT - ...
    101          
    102             Usage:
    103                results=parseresultsfromdiskiosplit(filename)
    104         """
     73        return saveres
     74        # }}}
     75def parseresultsfromdiskiosplit(md,filename):    # {{{
    10576
    10677        #Open file
     
    11081                raise IOError("loadresultsfromdisk error message: could not open '%s' for binary reading." % filename)
    11182
    112         results=[]
     83        saveres=[]
    11384
    11485        #if we have done split I/O, ie, we have results that are fragmented across patches,
    11586        #do a first pass, and figure out the structure of results
    116         result=ReadDataDimensions(fid)
    117         while result:
     87        loadres=ReadDataDimensions(fid)
     88        while loadres:
    11889
    11990                #Get time and step
    120                 if result['step'] > len(results):
    121                         for i in range(len(results),result['step']-1):
    122                                 results.append(None)
    123                         results.append(resultsclass.results())
    124                 setattr(results[result['step']-1],'step',result['step'])
    125                 setattr(results[result['step']-1],'time',result['time'])
    126 
    127                 #Add result
    128                 setattr(results[result['step']-1],result['fieldname'],float('NaN'))
    129 
    130                 #read next result
    131                 result=ReadDataDimensions(fid)
     91                if loadres['step'] > len(saveres):
     92                        for i in range(len(saveres),loadres['step']-1):
     93                                saveres.append(None)
     94                        saveres.append(resultsclass.results())
     95                setattr(saveres[loadres['step']-1],'step',loadres['step'])
     96                setattr(saveres[loadres['step']-1],'time',loadres['time'])
     97
     98                #Add result
     99                setattr(saveres[loadres['step']-1],loadres['fieldname'],float('NaN'))
     100
     101                #read next result
     102                loadres=ReadDataDimensions(fid)
    132103
    133104        #do a second pass, and figure out the size of the patches
    134105        fid.seek(0)    #rewind
    135         result=ReadDataDimensions(fid)
    136         while result:
    137 
    138                 #read next result
    139                 result=ReadDataDimensions(fid)
     106        loadres=ReadDataDimensions(fid)
     107        while loadres:
     108
     109                #read next result
     110                loadres=ReadDataDimensions(fid)
    140111
    141112        #third pass, this time to read the real information
    142113        fid.seek(0)    #rewind
    143         result=ReadData(fid)
    144         while result:
     114        loadres=ReadData(fid,md)
     115        while loadres:
    145116
    146117                #Get time and step
    147                 if result['step']> len(results):
    148                         for i in range(len(results),result['step']-1):
    149                                 results.append(None)
    150                         results.append(resultsclass.results())
    151                 setattr(results[result['step']-1],'step',result['step'])
    152                 setattr(results[result['step']-1],'time',result['time'])
    153 
    154                 #Add result
    155                 setattr(results[result['step']-1],result['fieldname'],result['field'])
    156 
    157                 #read next result
    158                 result=ReadData(fid)
     118                if loadres['step']> len(saveres):
     119                        for i in range(len(saveres),loadres['step']-1):
     120                                saveres.append(None)
     121                        saveres.append(saveresclass.saveres())
     122                setattr(saveres[loadres['step']-1],'step',loadres['step'])
     123                setattr(saveres[loadres['step']-1],'time',loadres['time'])
     124
     125                #Add result
     126                setattr(saveres[loadres['step']-1],loadres['fieldname'],loadres['field'])
     127
     128                #read next result
     129                loadres=ReadData(fid,md)
    159130
    160131        #close file
    161132        fid.close()
    162133
    163         return results
    164         # }}}
    165 def ReadData(fid):    # {{{
     134        return saveres
     135        # }}}
     136def ReadData(fid,md):    # {{{
    166137        """
    167138        READDATA - ...
    168139         
    169140            Usage:
    170                field=ReadData(fid)
     141               field=ReadData(fid,md)
    171142        """
    172143
     
    182153                M=struct.unpack('i',fid.read(struct.calcsize('i')))[0]
    183154                if   type==1:
    184                         field=numpy.array(struct.unpack('%dd' % M,fid.read(M*struct.calcsize('d'))),dtype=float)
     155                        field=np.array(struct.unpack('%dd' % M,fid.read(M*struct.calcsize('d'))),dtype=float)
    185156                elif type==2:
    186157                        field=struct.unpack('%ds' % M,fid.read(M))[0][:-1]
     
    188159                        N=struct.unpack('i',fid.read(struct.calcsize('i')))[0]
    189160#                       field=transpose(fread(fid,[N M],'double'));
    190                         field=numpy.zeros(shape=(M,N),dtype=float)
     161                        field=np.zeros(shape=(M,N),dtype=float)
    191162                        for i in range(M):
    192163                                field[i,:]=struct.unpack('%dd' % N,fid.read(N*struct.calcsize('d')))
     164                elif type==4:
     165                        N=struct.unpack('i',fid.read(struct.calcsize('i')))[0]
     166#                       field=transpose(fread(fid,[N M],'int'));
     167                        field=np.zeros(shape=(M,N),dtype=int)
     168                        for i in range(M):
     169                                field[i,:]=struct.unpack('%ii' % N,fid.read(N*struct.calcsize('i')))
    193170                else:
    194171                        raise TypeError("cannot read data of type %d" % type)
    195172
    196173                #Process units here FIXME: this should not be done here!
    197                 yts=365.0*24.0*3600.0
    198                 if m.strcmp(fieldname,'BalancethicknessThickeningRate'):
    199                         field = field*yts
    200                 elif m.strcmp(fieldname,'Time'):
    201                         field = field/yts
    202                 elif m.strcmp(fieldname,'HydrologyWaterVx'):
    203                         field = field*yts
    204                 elif m.strcmp(fieldname,'HydrologyWaterVy'):
    205                         field = field*yts
    206                 elif m.strcmp(fieldname,'Vx'):
    207                         field = field*yts
    208                 elif m.strcmp(fieldname,'Vy'):
    209                         field = field*yts
    210                 elif m.strcmp(fieldname,'Vz'):
    211                         field = field*yts
    212                 elif m.strcmp(fieldname,'Vel'):
    213                         field = field*yts
    214                 elif m.strcmp(fieldname,'BasalforcingsGroundediceMeltingRate'):
    215                         field = field*yts
    216                 elif m.strcmp(fieldname,'TotalSmb'):
    217                         field = field/10.**12.*yts #(GigaTon/year)
    218                 elif m.strcmp(fieldname,'SmbMassBalance'):
    219                         field = field*yts
    220                 elif m.strcmp(fieldname,'CalvingCalvingrate'):
    221                         field = field*yts
    222 
    223 
    224                 result=OrderedDict()
    225                 result['fieldname']=fieldname
    226                 result['time']=time
    227                 result['step']=step
    228                 result['field']=field
     174                yts=md.constants.yts
     175                if fieldname=='BalancethicknessThickeningRate':
     176                        field = field*yts
     177                elif fieldname=='HydrologyWaterVx':
     178                        field = field*yts
     179                elif fieldname=='HydrologyWaterVy':
     180                        field = field*yts
     181                elif fieldname=='Vx':
     182                        field = field*yts
     183                elif fieldname=='Vy':
     184                        field = field*yts
     185                elif fieldname=='Vz':
     186                        field = field*yts
     187                elif fieldname=='Vel':
     188                        field = field*yts
     189                elif fieldname=='BasalforcingsGroundediceMeltingRate':
     190                        field = field*yts
     191                elif fieldname=='BasalforcingsFloatingiceMeltingRate':
     192                        field = field*yts
     193                elif fieldname=='TotalFloatingBmb':
     194                        field = field/10.**12*yts #(GigaTon/year)
     195                elif fieldname=='TotalFloatingBmbScaled':
     196                        field = field/10.**12*yts #(GigaTon/year)
     197                elif fieldname=='TotalGroundedBmb':
     198                        field = field/10.**12*yts #(GigaTon/year)
     199                elif fieldname=='TotalGroundedBmbScaled':
     200                        field = field/10.**12*yts #(GigaTon/year)
     201                elif fieldname=='TotalSmb':
     202                        field = field/10.**12*yts #(GigaTon/year)
     203                elif fieldname=='TotalSmbScaled':
     204                        field = field/10.**12*yts #(GigaTon/year)
     205                elif fieldname=='SmbMassBalance':
     206                        field = field*yts
     207                elif fieldname=='SmbPrecipitation':
     208                        field = field*yts
     209                elif fieldname=='SmbRunoff':
     210                        field = field*yts
     211                elif fieldname=='SmbEvaporation':
     212                        field = field*yts;
     213                elif fieldname=='SmbRefreeze':
     214                        field = field*yts;
     215                elif fieldname=='SmbEC':
     216                        field = field*yts
     217                elif fieldname=='SmbAccumulation':
     218                        field = field*yts
     219                elif fieldname=='SmbMelt':
     220                        field = field*yts
     221                elif fieldname=='SmbMAdd':
     222                        field = field*yts
     223                elif fieldname=='CalvingCalvingrate':
     224                        field = field*yts
     225                elif fieldname=='LoveKernelsReal' or fieldname=='LoveKernelsImag':
     226                        nlayer = md.materials.numlayers
     227                        degmax = md.love.sh_nmax
     228                        nfreq  = md.love.nfreq
     229                        #for numpy 1.8+ only
     230                        #temp_field = np.full((degmax+1,nfreq,nlayer+1,6),0.0)
     231                        temp_field = np.empty((degmax+1,nfreq,nlayer+1,6))
     232                        temp_field.fill(0.0)
     233                        for ii in range(degmax+1):
     234                                for jj in range(nfreq):
     235                                        for kk in range(nlayer+1):
     236                                                ll = ii*(nlayer+1)*6 + (kk*6+1)
     237                                                for mm in range(6):
     238                                                        temp_field[ii,jj,kk,mm] = field[ll+mm-1,jj]
     239                        field=temp_field
     240
     241                if time !=-9999:
     242                        time = time/yts
     243
     244                saveres=OrderedDict()
     245                saveres['fieldname']=fieldname
     246                saveres['time']=time
     247                saveres['step']=step
     248                saveres['field']=field
    229249
    230250        except struct.error as e:
    231                 result=None
    232 
    233         return result
     251                saveres=None
     252
     253        return saveres
    234254        # }}}
    235255def ReadDataDimensions(fid):    # {{{
     
    262282                        raise TypeError("cannot read data of type %d" % type)
    263283
    264                 result=OrderedDict()
    265                 result['fieldname']=fieldname
    266                 result['time']=time
    267                 result['step']=step
    268                 result['M']=M
    269                 result['N']=N
     284                saveres=OrderedDict()
     285                saveres['fieldname']=fieldname
     286                saveres['time']=time
     287                saveres['step']=step
     288                saveres['M']=M
     289                saveres['N']=N
    270290
    271291        except struct.error as e:
    272                 result=None
    273 
    274         return result
    275         # }}}
     292                saveres=None
     293
     294        return saveres
     295        # }}}
  • issm/trunk-jpl/src/py3/solve/solve.py

    r19895 r23670  
    33import shutil
    44from pairoptions import pairoptions
    5 from EnumDefinitions import *
    6 from EnumToString import EnumToString
    75from ismodelselfconsistent import ismodelselfconsistent
    86from marshall import marshall
    97from waitonlock import waitonlock
    108from loadresultsfromcluster import loadresultsfromcluster
    11 import MatlabFuncs as m
     9from preqmu import *
     10#from MatlabFuncs import *
    1211
    13 def solve(md,solutionenum,**kwargs):
     12def solve(md,solutionstring,*args):
    1413        """
    1514        SOLVE - apply solution sequence for this model
    1615 
    1716           Usage:
    18               md=solve(md,solutionenum,varargin)
     17              md=solve(md,solutionstring,varargin)
    1918              where varargin is a list of paired arguments of string OR enums
    2019 
    21            solution types available comprise:
    22               - StressbalanceSolutionEnum
    23               - MasstransportSolutionEnum
    24               - ThermalSolutionEnum
    25               - SteadystateSolutionEnum
    26               - TransientSolutionEnum
    27               - BalancethicknessSolutionEnum
    28               - BedSlopeSolutionEnum
    29               - SurfaceSlopeSolutionEnum
    30               - HydrologySolutionEnum
    31               - FlaimSolutionEnum
    32  
     20                solution types available comprise:
     21                 - 'Stressbalance'    or 'sb'
     22                 - 'Masstransport'    or 'mt'
     23                 - 'Thermal'          or 'th'
     24                 - 'Steadystate'      or 'ss'
     25                 - 'Transient'        or 'tr'
     26                 - 'Balancethickness' or 'mc'
     27                 - 'Balancevelocity'  or 'bv'
     28                 - 'BedSlope'         or 'bsl'
     29                 - 'SurfaceSlope'     or 'ssl'
     30                 - 'Hydrology'        or 'hy'
     31                 - 'DamageEvolution'  or 'da'
     32                 - 'Gia'              or 'gia'
     33                 - 'Esa'              or 'esa'
     34                 - 'Sealevelrise'     or 'slr'
     35                 - 'Love'             or 'lv'
     36
    3337           extra options:
    34               - loadonly : does not solve. only load results
     38        - loadonly : does not solve. only load results
    3539                  - checkconsistency : 'yes' or 'no' (default is 'yes'), ensures checks on consistency of model
    3640                  - restart: 'directory name (relative to the execution directory) where the restart file is located.
    3741 
    3842           Examples:
    39               md=solve(md,StressbalanceSolutionEnum);
     43              md=solve(md,'Stressbalance');
     44         md=solve(md,'sb');
    4045        """
    4146
    4247        #recover and process solve options
    43         if EnumToString(solutionenum)[0][-8:] != 'Solution':
    44                 raise ValueError("solutionenum '%s' not supported!" % EnumToString(solutionenum)[0])
    45         options=pairoptions(solutionenum=solutionenum,**kwargs)
     48        if solutionstring.lower() == 'sb' or solutionstring.lower() == 'stressbalance':
     49                solutionstring = 'StressbalanceSolution';
     50        elif solutionstring.lower() == 'mt' or solutionstring.lower() == 'masstransport':
     51                solutionstring = 'MasstransportSolution';       
     52        elif solutionstring.lower() == 'th' or solutionstring.lower() == 'thermal':
     53                solutionstring = 'ThermalSolution';
     54        elif solutionstring.lower() == 'st' or solutionstring.lower() == 'steadystate':
     55                solutionstring = 'SteadystateSolution';
     56        elif solutionstring.lower() == 'tr' or solutionstring.lower() == 'transient':
     57                solutionstring = 'TransientSolution';
     58        elif solutionstring.lower() == 'mc' or solutionstring.lower() == 'balancethickness':
     59                solutionstring = 'BalancethicknessSolution';
     60        elif solutionstring.lower() == 'bv' or solutionstring.lower() == 'balancevelocity':
     61                solutionstring = 'BalancevelocitySolution';
     62        elif solutionstring.lower() == 'bsl' or solutionstring.lower() == 'bedslope':
     63                solutionstring = 'BedSlopeSolution';
     64        elif solutionstring.lower() == 'ssl' or solutionstring.lower() == 'surfaceslope':
     65                solutionstring = 'SurfaceSlopeSolution';
     66        elif solutionstring.lower() == 'hy' or solutionstring.lower() == 'hydrology':
     67                solutionstring = 'HydrologySolution';
     68        elif solutionstring.lower() == 'da' or solutionstring.lower() == 'damageevolution':
     69                solutionstring = 'DamageEvolutionSolution';
     70        elif solutionstring.lower() == 'gia' or solutionstring.lower() == 'gia':
     71                solutionstring = 'GiaSolution';
     72        elif solutionstring.lower() == 'lv' or solutionstring.lower() == 'love':
     73                solutionstring = 'LoveSolution';
     74        elif solutionstring.lower() == 'esa':
     75                solutionstring = 'EsaSolution';
     76        elif solutionstring.lower() == 'slr' or solutionstring.lower() == 'sealevelrise':
     77                solutionstring = 'SealevelriseSolution';
     78        else:   
     79                raise ValueError("solutionstring '%s' not supported!" % solutionstring)
     80        options=pairoptions('solutionstring',solutionstring,*args)
    4681
    4782        #recover some fields
    48         md.private.solution=solutionenum
    49         cluster=md.cluster
     83        md.private.solution=solutionstring
     84        cluster=md.cluster
     85        if options.getfieldvalue('batch','no')=='yes':
     86                batch=1
     87        else:
     88                batch=0;
    5089
    5190        #check model consistency
    52         if m.strcmpi(options.getfieldvalue('checkconsistency','yes'),'yes'):
    53                 print("checking model consistency")
    54                 if solutionenum == FlaimSolutionEnum():
    55                         md.private.isconsistent=True
    56                         md.mesh.checkconsistency(md,solutionenum)
    57                         md.flaim.checkconsistency(md,solutionenum)
    58                         if not md.private.isconsistent:
    59                                 raise RuntimeError("Model not consistent, see messages above.")
    60                 else:
    61                         ismodelselfconsistent(md)
     91        if options.getfieldvalue('checkconsistency','yes')=='yes':
     92                if md.verbose.solution:
     93                        print("checking model consistency")
     94                ismodelselfconsistent(md)
    6295
    6396        #First, build a runtime name that is unique
     
    80113                md=preqmu(md,options)
    81114
    82         #flaim analysis
    83         if solutionenum == FlaimSolutionEnum():
    84                 md=flaim_sol(md,options)
    85                 [md.private.solution]=EnumToString(solutionenum)
    86                 return md
    87 
    88115        #Do we load results only?
    89116        if options.getfieldvalue('loadonly',False):
     
    95122        marshall(md)                                           # bin file
    96123        md.toolkits.ToolkitsFile(md.miscellaneous.name+'.toolkits')    # toolkits file
    97         cluster.BuildQueueScript(md.private.runtimename,md.miscellaneous.name,md.private.solution,md.settings.io_gather,md.debug.valgrind,md.debug.gprof,md.qmu.isdakota)    # queue file
     124        cluster.BuildQueueScript(md.private.runtimename,md.miscellaneous.name,md.private.solution,md.settings.io_gather,md.debug.valgrind,md.debug.gprof,md.qmu.isdakota,md.transient.isoceancoupling)    # queue file
    98125
    99126        #Stop here if batch mode
    100         if m.strcmpi(options.getfieldvalue('batch','no'),'yes'):
     127        if options.getfieldvalue('batch','no')=='yes':
    101128                print('batch mode requested: not launching job interactively')
    102129                print('launch solution sequence on remote cluster by hand')
     
    113140       
    114141        #Launch job
    115         cluster.LaunchQueueJob(md.miscellaneous.name,md.private.runtimename,filelist,restart)
     142        cluster.LaunchQueueJob(md.miscellaneous.name,md.private.runtimename,filelist,restart,batch)
    116143
    117144        #wait on lock
     
    122149                        print('The results must be loaded manually with md=loadresultsfromcluster(md).')
    123150                else:            #load results
    124                         print('loading results from cluster')
     151                        if md.verbose.solution:
     152                                print('loading results from cluster')
    125153                        md=loadresultsfromcluster(md)
    126154
    127155        #post processes qmu results if necessary
    128156        if md.qmu.isdakota:
    129                 if not strncmpi(options['keep'],'y',1):
     157                if not strncmpi(options.getfieldvalue('keep','y'),'y',1):
    130158                        shutil.rmtree('qmu'+str(os.getpid()))
    131159
  • issm/trunk-jpl/src/py3/solve/waitonlock.py

    r19895 r23670  
    4848                #loop till file .lock exist or time is up
    4949                while ispresent==0 and etime<timelimit:
    50                         ispresent=os.path.exist(filename)
     50                        ispresent=os.path.exists(filename)
    5151                        time.sleep(1)
    5252                        etime+=1/60
  • issm/trunk-jpl/src/py3/solvers/asmoptions.py

    r19895 r23670  
    88       
    99        #retrieve options provided in varargin
    10         arguments=pairoptions.pairoptions(**kwargs)
     10        arguments=pairoptions.pairoptions(*args)
    1111       
    12         options=[['toolkit','petsc'],['mat_type','aij'],['ksp_type','gmres'],['pc_type','asm'],['sub_pc_type','lu'],['pc_asm_overlap',3],['ksp_max_it',100],['ksp_rtol',1e-30]];
     12        options=[['toolkit','petsc'],['mat_type','mpiaij'],['ksp_type','gmres'],['pc_type','asm'],['sub_pc_type','lu'],['pc_asm_overlap',3],['ksp_max_it',100],['ksp_rtol',1e-30]];
    1313
    1414        #now, go through our arguments, and write over default options.
  • issm/trunk-jpl/src/py3/solvers/iluasmoptions.py

    r19895 r23670  
    1111                         
    1212        #retrieve options provided in varargin
    13         options=pairoptions.pairoptions(**kwargs)
     13        options=pairoptions.pairoptions(*args)
    1414        iluasm=OrderedDict()
    1515
  • issm/trunk-jpl/src/py3/solvers/issmgslsolver.py

    r19895 r23670  
     1from collections import OrderedDict
    12import pairoptions
    23
    3 def issmgslsolver(**kwargs):
     4def issmgslsolver(*args):
    45        #ISSMSOLVE - return issm solver options
    56        #
     
    89       
    910        #retrieve options provided in varargin
    10         arguments=pairoptions.pairoptions(**kwargs)
     11        arguments=pairoptions.pairoptions(*args)
    1112       
    12         options=[['toolkit','issm'],['mat_type','dense'],['vec_type','seq'],['solver_type','gsl']];
     13        options=OrderedDict()
     14        options['toolkit'] = 'issm'
     15        options['mat_type'] = 'dense'
     16        options['vec_type'] = 'seq'
     17        options['solver_type'] = 'gsl'
    1318
    1419        #now, go through our arguments, and write over default options.
  • issm/trunk-jpl/src/py3/solvers/issmmumpssolver.py

    r19895 r23670  
     1from collections import OrderedDict
    12import pairoptions
    23
    3 def issmmumpssolver(**kwargs):
     4def issmmumpssolver(*args):
    45        #ISSMSOLVE - return issm solver options
    56        #
     
    89       
    910        #retrieve options provided in varargin
    10         arguments=pairoptions.pairoptions(**kwargs)
     11        arguments=pairoptions.pairoptions(*args)
    1112       
    12         options=[['toolkit','issm'],['mat_type','mpidense'],['vec_type','mpi'],['solver_type','mumps']];
     13        options=OrderedDict()
     14        options['toolkit'] = 'issm'
     15        options['mat_type'] = 'mpidense'
     16        options['vec_type'] = 'mpi'
     17        options['solver_type'] = 'mumps'
    1318
    1419        #now, go through our arguments, and write over default options.
  • issm/trunk-jpl/src/py3/solvers/jacobiasmoptions.py

    r19895 r23670  
    11import pairoptions
    22
    3 def jacobiasmoptions(**kwargs):
     3def jacobiasmoptions(*args):
    44        #ASMOPTIONS - return Additive Shwartz Method with Jacobi preconditioner petsc options
    55        #
     
    88       
    99        #retrieve options provided in varargin
    10         arguments=pairoptions.pairoptions(**kwargs)
     10        arguments=pairoptions.pairoptions(*args)
    1111       
    12         options=[['toolkit','petsc'],['mat_type','aij'],['ksp_type','gmres'],['pc_type','asm'],['sub_pc_type','jacobi'],['pc_asm_overlap',3],['ksp_max_it',100],['ksp_rtol',1e-15]];
     12        options=[['toolkit','petsc'],['mat_type','mpiaij'],['ksp_type','gmres'],['pc_type','asm'],['sub_pc_type','jacobi'],['pc_asm_overlap',3],['ksp_max_it',100],['ksp_rtol',1e-15]];
    1313
    1414        #now, go through our arguments, and write over default options.
  • issm/trunk-jpl/src/py3/solvers/jacobicgoptions.py

    r19895 r23670  
    88       
    99        #retrieve options provided in varargin
    10         arguments=pairoptions.pairoptions(**kwargs)
     10        arguments=pairoptions.pairoptions(*args)
    1111       
    12         options=[['toolkit','petsc'],['mat_type','aij'],['ksp_type','cg'],['ksp_max_it',100],['ksp_rtol',1e-15]];
     12        options=[['toolkit','petsc'],['mat_type','mpiaij'],['ksp_type','cg'],['ksp_max_it',100],['ksp_rtol',1e-15]];
    1313
    1414        #now, go through our arguments, and write over default options.
  • issm/trunk-jpl/src/py3/solvers/matlaboptions.py

    r19895 r23670  
    11import pairoptions
    22
    3 def matlaboptions(**kwargs):
     3def matlaboptions(*args):
    44        #MATLABOPTIONS - return Matlab petsc options
    55        #
     
    88       
    99        #retrieve options provided in varargin
    10         arguments=pairoptions.pairoptions(**kwargs)
     10        arguments=pairoptions.pairoptions(*args)
    1111       
    1212        options=[['toolkit','petsc'],['ksp_type','matlab']];
  • issm/trunk-jpl/src/py3/solvers/mumpsoptions.py

    r19895 r23670  
    33from IssmConfig import IssmConfig
    44
    5 def mumpsoptions(**kwargs):
     5def mumpsoptions(*args):
    66        """
    77        MUMPSOPTIONS - return MUMPS direct solver  petsc options
     
    1212
    1313        #retrieve options provided in varargin
    14         options=pairoptions.pairoptions(**kwargs)
     14        options=pairoptions.pairoptions(*args)
    1515        mumps=OrderedDict()
    1616
    1717        #default mumps options
    18         PETSC_VERSION=IssmConfig('_PETSC_MAJOR_')[0]
    19         if PETSC_VERSION==2.:
     18        PETSC_MAJOR=IssmConfig('_PETSC_MAJOR_')[0]
     19        PETSC_MINOR=IssmConfig('_PETSC_MINOR_')[0]
     20        if PETSC_MAJOR==2.:
    2021                mumps['toolkit']='petsc'
    2122                mumps['mat_type']=options.getfieldvalue('mat_type','aijmumps')
     
    2324                mumps['pc_type']=options.getfieldvalue('pc_type','lu')
    2425                mumps['mat_mumps_icntl_14']=options.getfieldvalue('mat_mumps_icntl_14',120)
    25                 mumps['pc_factor_shift_positive_definite']=options.getfieldvalue('pc_factor_shift_positive_definite','true')
    26         if PETSC_VERSION==3.:
     26        if PETSC_MAJOR==3.:
    2727                mumps['toolkit']='petsc'
    2828                mumps['mat_type']=options.getfieldvalue('mat_type','mpiaij')
    2929                mumps['ksp_type']=options.getfieldvalue('ksp_type','preonly')
    3030                mumps['pc_type']=options.getfieldvalue('pc_type','lu')
    31                 mumps['pc_factor_mat_solver_package']=options.getfieldvalue('pc_factor_mat_solver_package','mumps')
     31                if PETSC_MINOR>8.:
     32                        mumps['pc_factor_mat_solver_type']=options.getfieldvalue('pc_factor_mat_solver_type','mumps')
     33                else:
     34                        mumps['pc_factor_mat_solver_package']=options.getfieldvalue('pc_factor_mat_solver_package','mumps')
    3235                mumps['mat_mumps_icntl_14']=options.getfieldvalue('mat_mumps_icntl_14',120)
    33                 mumps['pc_factor_shift_positive_definite']=options.getfieldvalue('pc_factor_shift_positive_definite','true')
    3436
    3537        return mumps
    36 
  • issm/trunk-jpl/src/py3/solvers/soroptions.py

    r19895 r23670  
    11import pairoptions
    22
    3 def soroptions(**kwargs):
     3def soroptions(*args):
    44        #SOROPTIONS - return Relaxation Solver petsc options
    55        #
     
    88       
    99        #retrieve options provided in varargin
    10         arguments=pairoptions.pairoptions(**kwargs)
     10        arguments=pairoptions.pairoptions(*args)
    1111       
    12         options=[['toolkit','petsc'],['mat_type','aij'],['ksp_type','cg'],['pc_type','sor'],['pc_sor_omega',1.1],['pc_sor_its',2]];
     12        options=[['toolkit','petsc'],['mat_type','mpiaij'],['ksp_type','cg'],['pc_type','sor'],['pc_sor_omega',1.1],['pc_sor_its',2]];
    1313
    1414        #now, go through our arguments, and write over default options.
  • issm/trunk-jpl/src/py3/solvers/stokesoptions.py

    r19895 r23670  
    22from IssmConfig import IssmConfig
    33
    4 def stokesoptions(**kwargs):
     4def stokesoptions(*args):
    55        #STOKESOPTIONS - return STOKES multi-physics solver petsc options
    66        #
     
    99       
    1010        #retrieve options provided in varargin
    11         arguments=pairoptions.pairoptions(**kwargs)
     11        arguments=pairoptions.pairoptions(*args)
    1212
    1313
Note: See TracChangeset for help on using the changeset viewer.