Changeset 21303


Ignore:
Timestamp:
10/21/16 08:49:08 (8 years ago)
Author:
bdef
Message:

CHG: major cosmetic clean up we now ask shape (N,) rather than (N,1) also uniformised numpy imports

Location:
issm/trunk-jpl/src/m
Files:
118 edited

Legend:

Unmodified
Added
Removed
  • issm/trunk-jpl/src/m/archive/arch.py

    r21170 r21303  
    1 import numpy
     1import numpy as np
    22import math
    33import struct
     
    150150def write_vector(fid,data): # {{{
    151151        """
    152         Procedure to write a numpy array to an arch file
     152        Procedure to write a np.array to an arch file
    153153        """
    154154        # Make sure our vector is the correct shape.
    155155        # Reshape it into a row vector if it is not correct.
    156156        if isinstance(data,(bool,int,long,float)):
    157                 data=numpy.array([data])
     157                data=np.array([data])
    158158        elif isinstance(data,(list,tuple)):
    159                 data=numpy.array(data).reshape(-1,1)
    160        
    161         if numpy.ndim(data) == 1:
    162                 if numpy.size(data):
    163                         data=data.reshape(numpy.size(data),1)
     159                data=np.array(data).reshape(-1,)
     160       
     161        if np.ndim(data) == 1:
     162                if np.size(data):
     163                        data=data.reshape(np.size(data),)
    164164                else:
    165165                        data=data.reshape(0,0)
     
    216216                        rows=struct.unpack('>i',fid.read(struct.calcsize('>i')))[0]
    217217                        cols=struct.unpack('>i',fid.read(struct.calcsize('>i')))[0]
    218                         raw_data=numpy.zeros(shape=(rows,cols),dtype=float)
     218                        raw_data=np.zeros(shape=(rows,cols),dtype=float)
    219219                        for i in xrange(rows):
    220220                                raw_data[i,:]=struct.unpack('>%dd' % cols,fid.read(cols*struct.calcsize('>d')))
     
    259259        elif format.shape[0] == 1 and format.shape[1] == 1:
    260260                code=2
    261         elif isinstance(format,(list,tuple,numpy.ndarray)):
     261        elif isinstance(format,(list,tuple,np.ndarray)):
    262262                code=3
    263263        else:
  • issm/trunk-jpl/src/m/boundaryconditions/PattynSMB.py

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

    r19527 r21303  
    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/m/boundaryconditions/SetIceShelfBC.py

    r20910 r21303  
    11import os
    2 import numpy
     2import numpy as np
    33from ContourToMesh import ContourToMesh
    44import MatlabFuncs as m
     
    2727                        raise IOError("SetIceShelfBC error message: ice front file '%s' not found." % icefrontfile)
    2828                nodeinsideicefront=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,icefrontfile,'node',2)
    29                 nodeonicefront=numpy.logical_and(md.mesh.vertexonboundary,nodeinsideicefront.reshape(-1))
     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/m/boundaryconditions/SetMarineIceSheetBC.py

    r20910 r21303  
    11import os
    2 import numpy
     2import numpy as np
    33from ContourToMesh import ContourToMesh
    44import MatlabFuncs as m
     
    2929                        raise IOError("SetMarineIceSheetBC error message: ice front file '%s' not found." % icefrontfile)
    3030                incontour=ContourToMesh(md.mesh.elements,md.mesh.x,md.mesh.y,icefrontfile,'node',2)
    31                 vertexonicefront=numpy.logical_and(md.mesh.vertexonboundary,incontour.reshape(-1))
     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/m/boundaryconditions/love_numbers.py

    r21069 r21303  
    11from MatlabFuncs import *
    22from model import *
    3 from numpy import *
     3from np.import *
    44
    55def love_numbers(value,*varargin):
  • issm/trunk-jpl/src/m/classes/SMBcomponents.py

    r21049 r21303  
    3838        def initialize(self,md): # {{{
    3939
    40                 if numpy.all(numpy.isnan(self.accumulation)):
    41                         self.accumulation=numpy.zeros((md.mesh.numberofvertices,1))
     40                if np.all(np.isnan(self.accumulation)):
     41                        self.accumulation=np.zeros((md.mesh.numberofvertices))
    4242                        print "      no SMB.accumulation specified: values set as zero"
    4343
    44                 if numpy.all(numpy.isnan(self.runoff)):
    45                         self.runoff=numpy.zeros((md.mesh.numberofvertices,1))
     44                if np.all(np.isnan(self.runoff)):
     45                        self.runoff=np.zeros((md.mesh.numberofvertices))
    4646                        print "      no SMB.runoff specified: values set as zero"
    4747
    48                 if numpy.all(numpy.isnan(self.evaporation)):
    49                         self.evaporation=numpy.zeros((md.mesh.numberofvertices,1))
     48                if np.all(np.isnan(self.evaporation)):
     49                        self.evaporation=np.zeros((md.mesh.numberofvertices))
    5050                        print "      no SMB.evaporation specified: values set as zero"
    5151
  • issm/trunk-jpl/src/m/classes/SMBd18opdd.py

    r21049 r21303  
    1 import numpy
     1import numpy as np
    22from fielddisplay import fielddisplay
    33from checkfield import checkfield
     
    6464        def initialize(self,md): # {{{
    6565
    66                 if numpy.all(numpy.isnan(self.s0p)):
    67                         self.s0p=numpy.zeros((md.mesh.numberofvertices,1))
     66                if np.all(np.isnan(self.s0p)):
     67                        self.s0p=np.zeros((md.mesh.numberofvertices))
    6868                        print "      no SMBd18opdd.s0p specified: values set as zero"
    6969
    70                 if numpy.all(numpy.isnan(self.s0t)):
    71                         self.s0t=numpy.zeros((md.mesh.numberofvertices,1))
     70                if np.all(np.isnan(self.s0t)):
     71                        self.s0t=np.zeros((md.mesh.numberofvertices))
    7272                        print "      no SMBd18opdd.s0t specified: values set as zero"
    7373                       
     
    9090                if 'MasstransportAnalysis' in analyses:
    9191                        md = checkfield(md,'fieldname','smb.desfac','<=',1,'numel',[1])
    92                         md = checkfield(md,'fieldname','smb.s0p','>=',0,'NaN',1,'Inf',1,'size',[md.mesh.numberofvertices,1])
    93                         md = checkfield(md,'fieldname','smb.s0t','>=',0,'NaN',1,'Inf',1,'size',[md.mesh.numberofvertices,1])
     92                        md = checkfield(md,'fieldname','smb.s0p','>=',0,'NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
     93                        md = checkfield(md,'fieldname','smb.s0t','>=',0,'NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
    9494                        md = checkfield(md,'fieldname','smb.rlaps','>=',0,'numel',[1])
    9595                        md = checkfield(md,'fieldname','smb.rlapslgm','>=',0,'numel',[1])
     
    9898                                md = checkfield(md,'fieldname','smb.temperatures_presentday','size',[md.mesh.numberofvertices+1,12],'NaN',1,'Inf',1,'timeseries',1)
    9999                                md = checkfield(md,'fieldname','smb.precipitations_presentday','size',[md.mesh.numberofvertices+1,12],'NaN',1,'Inf',1,'timeseries',1)
    100                                 md = checkfield(md,'fieldname','smb.delta18o','NaN',1,'Inf',1,'size',[2,numpy.nan],'singletimeseries',1)
     100                                md = checkfield(md,'fieldname','smb.delta18o','NaN',1,'Inf',1,'size',[2,np.nan],'singletimeseries',1)
    101101                                md = checkfield(md,'fieldname','smb.dpermil','>=',0,'numel',[1])
    102102               
  • issm/trunk-jpl/src/m/classes/SMBforcing.py

    r21049 r21303  
    1 import numpy
     1import numpy as np
    22from fielddisplay import fielddisplay
    33from checkfield import checkfield
     
    3333        def initialize(self,md): # {{{
    3434
    35                 if numpy.all(numpy.isnan(self.mass_balance)):
    36                         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))
    3737                        print "      no SMBforcing.mass_balance specified: values set as zero"
    3838
  • issm/trunk-jpl/src/m/classes/SMBmeltcomponents.py

    r21049 r21303  
    4040        def initialize(self,md): # {{{
    4141
    42                 if numpy.all(numpy.isnan(self.accumulation)):
    43                         self.accumulation=numpy.zeros((md.mesh.numberofvertices,1))
     42                if np.all(np.isnan(self.accumulation)):
     43                        self.accumulation=np.zeros((md.mesh.numberofvertices))
    4444                        print "      no SMB.accumulation specified: values set as zero"
    4545
    46                 if numpy.all(numpy.isnan(self.evaporation)):
    47                         self.evaporation=numpy.zeros((md.mesh.numberofvertices,1))
     46                if np.all(np.isnan(self.evaporation)):
     47                        self.evaporation=np.zeros((md.mesh.numberofvertices))
    4848                        print "      no SMB.evaporation specified: values set as zero"
    4949
    50                 if numpy.all(numpy.isnan(self.melt)):
    51                         self.melt=numpy.zeros((md.mesh.numberofvertices,1))
     50                if np.all(np.isnan(self.melt)):
     51                        self.melt=np.zeros((md.mesh.numberofvertices))
    5252                        print "      no SMB.melt specified: values set as zero"
    5353
    54                 if numpy.all(numpy.isnan(self.refreeze)):
    55                         self.refreeze=numpy.zeros((md.mesh.numberofvertices,1))
     54                if np.all(np.isnan(self.refreeze)):
     55                        self.refreeze=np.zeros((md.mesh.numberofvertices))
    5656                        print "      no SMB.refreeze specified: values set as zero"
    5757
  • issm/trunk-jpl/src/m/classes/SMBpdd.py

    r21049 r21303  
    1 import numpy
     1import numpy as np
    22from fielddisplay import fielddisplay
    33from checkfield import checkfield
     
    9494        def initialize(self,md): # {{{
    9595
    96                 if numpy.all(numpy.isnan(self.s0p)):
    97                         self.s0p=numpy.zeros((md.mesh.numberofvertices,1))
     96                if np.all(np.isnan(self.s0p)):
     97                        self.s0p=np.zeros((md.mesh.numberofvertices))
    9898                        print "      no SMBpdd.s0p specified: values set as zero"
    9999
    100                 if numpy.all(numpy.isnan(self.s0t)):
    101                         self.s0t=numpy.zeros((md.mesh.numberofvertices,1))
     100                if np.all(np.isnan(self.s0t)):
     101                        self.s0t=np.zeros((md.mesh.numberofvertices))
    102102                        print "      no SMBpdd.s0t specified: values set as zero"
    103103
     
    119119                if 'MasstransportAnalysis' in analyses:
    120120                        md = checkfield(md,'fieldname','smb.desfac','<=',1,'numel',[1])
    121                         md = checkfield(md,'fieldname','smb.s0p','>=',0,'NaN',1,'Inf',1,'size',[md.mesh.numberofvertices,1])
    122                         md = checkfield(md,'fieldname','smb.s0t','>=',0,'NaN',1,'Inf',1,'size',[md.mesh.numberofvertices,1])
     121                        md = checkfield(md,'fieldname','smb.s0p','>=',0,'NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
     122                        md = checkfield(md,'fieldname','smb.s0t','>=',0,'NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
    123123                        md = checkfield(md,'fieldname','smb.rlaps','>=',0,'numel',[1])
    124124                        md = checkfield(md,'fieldname','smb.rlapslgm','>=',0,'numel',[1])
     
    128128                                md = checkfield(md,'fieldname','smb.precipitation','NaN',1,'Inf',1,'timeseries',1)
    129129                        elif self.isdelta18o:
    130                                 md = checkfield(md,'fieldname','smb.delta18o','NaN',1,'Inf',1,'size',[2,numpy.nan],'singletimeseries',1)
    131                                 md = checkfield(md,'fieldname','smb.delta18o_surface','NaN',1,'Inf',1,'size',[2,numpy.nan],'singletimeseries',1)
     130                                md = checkfield(md,'fieldname','smb.delta18o','NaN',1,'Inf',1,'size',[2,np.nan],'singletimeseries',1)
     131                                md = checkfield(md,'fieldname','smb.delta18o_surface','NaN',1,'Inf',1,'size',[2,np.nan],'singletimeseries',1)
    132132                                md = checkfield(md,'fieldname','smb.temperatures_presentday','size',[md.mesh.numberofvertices+1,12],'NaN',1,'Inf',1,'timeseries',1)
    133133                                md = checkfield(md,'fieldname','smb.temperatures_lgm','size',[md.mesh.numberofvertices+1,12],'NaN',1,'Inf',1,'timeseries',1)
    134134                                md = checkfield(md,'fieldname','smb.precipitations_presentday','size',[md.mesh.numberofvertices+1,12],'NaN',1,'Inf',1,'timeseries',1)
    135135                                md = checkfield(md,'fieldname','smb.precipitations_lgm','size',[md.mesh.numberofvertices+1,12],'NaN',1,'Inf',1,'timeseries',1)                                       
    136                                 md = checkfield(md,'fieldname','smb.Tdiff','NaN',1,'Inf',1,'size',[2,numpy.nan],'singletimeseries',1)
    137                                 md = checkfield(md,'fieldname','smb.sealev','NaN',1,'Inf',1,'size',[2,numpy.nan],'singletimeseries',1)
     136                                md = checkfield(md,'fieldname','smb.Tdiff','NaN',1,'Inf',1,'size',[2,np.nan],'singletimeseries',1)
     137                                md = checkfield(md,'fieldname','smb.sealev','NaN',1,'Inf',1,'size',[2,np.nan],'singletimeseries',1)
    138138                        elif self.ismungsm:
    139139                                md = checkfield(md,'fieldname','smb.temperatures_presentday','size',[md.mesh.numberofvertices+1,12],'NaN',1,'Inf',1,'timeseries',1)
     
    141141                                md = checkfield(md,'fieldname','smb.precipitations_presentday','size',[md.mesh.numberofvertices+1,12],'NaN',1,'Inf',1,'timeseries',1)
    142142                                md = checkfield(md,'fieldname','smb.precipitations_lgm','size',[md.mesh.numberofvertices+1,12],'NaN',1,'Inf',1,'timeseries',1)                                       
    143                                 md = checkfield(md,'fieldname','smb.Pfac','NaN',1,'Inf',1,'size',[2,numpy.nan],'singletimeseries',1)
    144                                 md = checkfield(md,'fieldname','smb.Tdiff','NaN',1,'Inf',1,'size',[2,numpy.nan],'singletimeseries',1)
    145                                 md = checkfield(md,'fieldname','smb.sealev','NaN',1,'Inf',1,'size',[2,numpy.nan],'singletimeseries',1)
     143                                md = checkfield(md,'fieldname','smb.Pfac','NaN',1,'Inf',1,'size',[2,np.nan],'singletimeseries',1)
     144                                md = checkfield(md,'fieldname','smb.Tdiff','NaN',1,'Inf',1,'size',[2,np.nan],'singletimeseries',1)
     145                                md = checkfield(md,'fieldname','smb.sealev','NaN',1,'Inf',1,'size',[2,np.nan],'singletimeseries',1)
    146146
    147147                md = checkfield(md,'fieldname','masstransport.requested_outputs','stringrow',1)
  • issm/trunk-jpl/src/m/classes/adinversion.py

    r21049 r21303  
    1212
    1313from MatlabFuncs import *
    14 from numpy import *
     14from np.import *
    1515
    1616# ADINVERSION class definition
    17 
    1817#
    19 
    2018#    Usage:
    21 
    2219#       adinversion=adinversion();
    23 
    24 
    2520
    2621class adinversion:
     
    7570
    7671
    77                 num_controls=numpy.numel(md.inversion.control_parameters)
    78                 num_costfunc=numpy.size(md.inversion.cost_functions,2)
     72                num_controls=np.numel(md.inversion.control_parameters)
     73                num_costfunc=np.size(md.inversion.cost_functions,2)
    7974
    8075
     
    9590
    9691                if solution=='BalancethicknessSolution':
    97                         md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices, 1],float('Nan'),1)
    98                         md = checkfield(md,'fieldname','inversion.surface_obs','size',[md.mesh.numberofvertices, 1], float('Nan'),1)
     92                        md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices],float('Nan'),1)
     93                        md = checkfield(md,'fieldname','inversion.surface_obs','size',[md.mesh.numberofvertices], float('Nan'),1)
    9994                elif solution=='BalancethicknessSoftSolution':
    100                         md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices, 1],float('Nan'),1)
     95                        md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices],float('Nan'),1)
    10196                else:
    102                         md = checkfield(md,'fieldname','inversion.vx_obs','size',[md.mesh.numberofvertices, 1],float('Nan'),1)
    103                         if not numpy.strcmp(domaintype(md.mesh),'2Dvertical'):
    104                                 md = checkfield(md,'fieldname','inversion.vy_obs','size',[md.mesh.numberofvertices, 1],float('Nan'),1)
     97                        md = checkfield(md,'fieldname','inversion.vx_obs','size',[md.mesh.numberofvertices],float('Nan'),1)
     98                        if not np.strcmp(domaintype(md.mesh),'2Dvertical'):
     99                                md = checkfield(md,'fieldname','inversion.vy_obs','size',[md.mesh.numberofvertices],float('Nan'),1)
    105100                return md
    106101
     
    164159
    165160                #process control parameters
    166                 num_control_parameters = numpy.numel(self.control_parameters);
     161                num_control_parameters = np.numel(self.control_parameters);
    167162                WriteData(fid,prefix,'object',self,'fieldname','control_parameters','format','StringArray');
    168163                WriteData(fid,prefix,'data',num_control_parameters,'name','md.inversion.num_control_parameters','format','Integer');
    169164
    170165                #process cost functions
    171                 num_cost_functions=numpy.size(self.cost_functions,2);
     166                num_cost_functions=np.size(self.cost_functions,2);
    172167                data=copy.deepcopy(self.cost_functions)
    173                 data[numpy.nonzero(self.cost_functions==101)] =['SurfaceAbsVelMisfit'];
    174                 data[numpy.nonzero(self.cost_functions==102)]=['SurfaceRelVelMisfit'];
    175                 data[numpy.nonzero(self.cost_functions==103)]=['SurfaceLogVelMisfit'];
    176                 data[numpy.nonzero(self.cost_functions==104)]=['SurfaceLogVxVyMisfit'];
    177                 data[numpy.nonzero(self.cost_functions==105)]=['SurfaceAverageVelMisfit'];
    178                 data[numpy.nonzero(self.cost_functions==201)]=['ThicknessAbsMisfit'];
    179                 data[numpy.nonzero(self.cost_functions==501)]=['DragCoefficientAbsGradient'];
    180                 data[numpy.nonzero(self.cost_functions==502)]=['RheologyBbarAbsGradient'];
    181                 data[numpy.nonzero(self.cost_functions==503)]=['ThicknessAbsGradient'];
    182                 data[numpy.nonzero(self.cost_functions==504)]=['ThicknessAlongGradient'];
    183                 data[numpy.nonzero(self.cost_functions==505)]=['ThicknessAcrossGradient'];
    184                 data[numpy.nonzero(self.cost_functions==506)]=['BalancethicknessMisfit'];
    185                 data[numpy.nonzero(self.cost_functions==601)]=['SurfaceAbsMisfit'];
    186                 data[numpy.nonzero(self.cost_functions==1001)]=['Outputdefinition1'];
    187                 data[numpy.nonzero(self.cost_functions==1002)]=['Outputdefinition2'];
    188                 data[numpy.nonzero(self.cost_functions==1003)]=['Outputdefinition3'];
    189                 data[numpy.nonzero(self.cost_functions==1004)]=['Outputdefinition4'];
    190                 data[numpy.nonzero(self.cost_functions==1005)]=['Outputdefinition5'];
    191                 data[numpy.nonzero(self.cost_functions==1006)]=['Outputdefinition6'];
    192                 data[numpy.nonzero(self.cost_functions==1007)]=['Outputdefinition7'];
    193                 data[numpy.nonzero(self.cost_functions==1008)]=['Outputdefinition8'];
    194                 data[numpy.nonzero(self.cost_functions==1009)]=['Outputdefinition8'];
    195                 data[numpy.nonzero(self.cost_functions==1010)]=['Outputdefinition10'];
     168                data[np.nonzero(self.cost_functions==101)] =['SurfaceAbsVelMisfit'];
     169                data[np.nonzero(self.cost_functions==102)]=['SurfaceRelVelMisfit'];
     170                data[np.nonzero(self.cost_functions==103)]=['SurfaceLogVelMisfit'];
     171                data[np.nonzero(self.cost_functions==104)]=['SurfaceLogVxVyMisfit'];
     172                data[np.nonzero(self.cost_functions==105)]=['SurfaceAverageVelMisfit'];
     173                data[np.nonzero(self.cost_functions==201)]=['ThicknessAbsMisfit'];
     174                data[np.nonzero(self.cost_functions==501)]=['DragCoefficientAbsGradient'];
     175                data[np.nonzero(self.cost_functions==502)]=['RheologyBbarAbsGradient'];
     176                data[np.nonzero(self.cost_functions==503)]=['ThicknessAbsGradient'];
     177                data[np.nonzero(self.cost_functions==504)]=['ThicknessAlongGradient'];
     178                data[np.nonzero(self.cost_functions==505)]=['ThicknessAcrossGradient'];
     179                data[np.nonzero(self.cost_functions==506)]=['BalancethicknessMisfit'];
     180                data[np.nonzero(self.cost_functions==601)]=['SurfaceAbsMisfit'];
     181                data[np.nonzero(self.cost_functions==1001)]=['Outputdefinition1'];
     182                data[np.nonzero(self.cost_functions==1002)]=['Outputdefinition2'];
     183                data[np.nonzero(self.cost_functions==1003)]=['Outputdefinition3'];
     184                data[np.nonzero(self.cost_functions==1004)]=['Outputdefinition4'];
     185                data[np.nonzero(self.cost_functions==1005)]=['Outputdefinition5'];
     186                data[np.nonzero(self.cost_functions==1006)]=['Outputdefinition6'];
     187                data[np.nonzero(self.cost_functions==1007)]=['Outputdefinition7'];
     188                data[np.nonzero(self.cost_functions==1008)]=['Outputdefinition8'];
     189                data[np.nonzero(self.cost_functions==1009)]=['Outputdefinition8'];
     190                data[np.nonzero(self.cost_functions==1010)]=['Outputdefinition10'];
    196191                WriteData(fid,prefix,'data',data,'name','md.inversion.cost_functions','format','StringArray');
    197192                WriteData(fid,prefix,'data',num_cost_functions,'name','md.inversion.num_cost_functions','format','Integer');
  • issm/trunk-jpl/src/m/classes/autodiff.py

    r21049 r21303  
    1 import numpy
     1import numpy as np
    22from dependent import dependent
    33from independent import independent
     
    104104                if num_dependent_objects:
    105105                        names=[]
    106                         types=numpy.zeros(num_dependent_objects)
    107                         indices=numpy.zeros(num_dependent_objects)
     106                        types=np.zeros(num_dependent_objects)
     107                        indices=np.zeros(num_dependent_objects)
    108108
    109109                        for i,dep in enumerate(self.dependents):
     
    122122                if num_independent_objects:
    123123                        names=[None] * num_independent_objects
    124                         types=numpy.zeros(num_independent_objects)
     124                        types=np.zeros(num_independent_objects)
    125125
    126126                        for i,indep in enumerate(self.independents):
     
    136136
    137137                        for indep in self.independents:
    138                                 if not numpy.isnan(indep.fos_forward_index):
     138                                if not np.isnan(indep.fos_forward_index):
    139139                                        index+=indep.fos_forward_index
    140140                                        break
     
    153153
    154154                        for dep in self.dependents:
    155                                 if not numpy.isnan(dep.fos_reverse_index):
     155                                if not np.isnan(dep.fos_reverse_index):
    156156                                        index+=dep.fos_reverse_index
    157157                                        break
  • issm/trunk-jpl/src/m/classes/bamggeom.py

    r14640 r21303  
    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):
  • issm/trunk-jpl/src/m/classes/bamgmesh.py

    r14640 r21303  
    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.Quadrilaterals=np.empty((0,0))
     16                self.IssmEdges=np.empty((0,0))
     17                self.IssmSegments=np.empty((0,0))
     18                self.VerticesOnGeomVertex=np.empty((0,0))
     19                self.VerticesOnGeomEdge=np.empty((0,0))
     20                self.EdgesOnGeomEdge=np.empty((0,0))
     21                self.SubDomains=np.empty((0,4))
     22                self.SubDomainsFromGeom=np.empty((0,0))
     23                self.ElementConnectivity=np.empty((0,0))
     24                self.NodalConnectivity=np.empty((0,0))
     25                self.NodalElementConnectivity=np.empty((0,0))
     26                self.CrackedVertices=np.empty((0,0))
     27                self.CrackedEdges=np.empty((0,0))
    2828
    2929                if not len(args):
  • issm/trunk-jpl/src/m/classes/basalforcings.py

    r21049 r21303  
    33from checkfield import checkfield
    44from WriteData import WriteData
    5 import numpy
     5import numpy as np
    66
    77class basalforcings(object):
     
    3838        def initialize(self,md): # {{{
    3939
    40                 if numpy.all(numpy.isnan(self.groundedice_melting_rate)):
    41                         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))
    4242                        print "      no basalforcings.groundedice_melting_rate specified: values set as zero"
    4343
    44                 if numpy.all(numpy.isnan(self.floatingice_melting_rate)):
    45                         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))
    4646                        print "      no basalforcings.floatingice_melting_rate specified: values set as zero"
    4747
  • issm/trunk-jpl/src/m/classes/clusters/vilje.py

    r21234 r21303  
    107107                fid.write('#PBS -e %s/%s/%s.errlog \n\n' % (self.executionpath,dirname,modelname))
    108108                fid.write('export ISSM_DIR="%s/../"\n' % self.codepath)
    109                 fid.write('module load intelcomp/13.0.1\n')
    110                 fid.write('module load mpt/2.06\n')
    111                 fid.write('module load petsc/3.4.1d\n')
    112                 fid.write('module load parmetis/4.0.2\n')
    113                 fid.write('module load mumps/4.10.0\n')
     109                fid.write('module load intelcomp/17.0.0\n')
     110                fid.write('module load mpt/2.14\n')
     111                fid.write('module load petsc/3.7.4d\n')
     112                fid.write('module load parmetis/4.0.3\n')
     113                fid.write('module load mumps/5.0.2\n')
    114114                fid.write('cd %s/%s/\n\n' % (self.executionpath,dirname))
    115115                fid.write('mpiexec_mpt -np %i %s/%s %s %s/%s %s\n' % (self.np,self.codepath,executable,str(solution),self.executionpath,dirname,modelname))
  • issm/trunk-jpl/src/m/classes/dependent.py

    r21049 r21303  
    11import os.path
    2 import numpy
     2import numpy as np
    33from pairoptions import pairoptions
    44from fielddisplay import fielddisplay
     
    5151                s+="%s\n" % fielddisplay(self,'type',"type of variable ('vertex' or 'scalar')")
    5252
    53                 if not numpy.isnan(self.fos_reverse_index):
     53                if not np.isnan(self.fos_reverse_index):
    5454                        s+="%s\n" % fielddisplay(self,'fos_reverse_index',"index for fos_reverse driver of ADOLC")
    5555                if self.exp:
     
    7070                                raise RuntimeError("dependent checkconsistency error: index for segments should be >=0")
    7171
    72                 if not numpy.isnan(self.fos_reverse_index):
     72                if not np.isnan(self.fos_reverse_index):
    7373                        if not strcmpi(driver,'fos_reverse'):
    7474                                raise TypeError("cannot declare a dependent with a fos_reverse_index when the driver is not fos_reverse!")
  • issm/trunk-jpl/src/m/classes/esa.py

    r21260 r21303  
    22from MatlabFuncs import *
    33from model import *
    4 from numpy import *
     4from np.import *
    55from checkfield import checkfield
    66from WriteData import WriteData
  • issm/trunk-jpl/src/m/classes/flowequation.py

    r21049 r21303  
    1 import numpy
     1import numpy as np
    22import copy
    33from project3d import project3d
     
    105105                        md = checkfield(md,'fieldname','flowequation.element_equation','size',[md.mesh.numberofelements],'values',[1,2])
    106106                elif m.strcmp(md.mesh.domaintype(),'3D'):
    107                         md = checkfield(md,'fieldname','flowequation.vertex_equation','size',[md.mesh.numberofvertices],'values',numpy.arange(0,8+1))
    108                         md = checkfield(md,'fieldname','flowequation.element_equation','size',[md.mesh.numberofelements],'values',numpy.arange(0,8+1))
     107                        md = checkfield(md,'fieldname','flowequation.vertex_equation','size',[md.mesh.numberofvertices],'values',np.arange(0,8+1))
     108                        md = checkfield(md,'fieldname','flowequation.element_equation','size',[md.mesh.numberofelements],'values',np.arange(0,8+1))
    109109                else:
    110110                        raise RuntimeError('mesh type not supported yet')
     
    114114                if 'StressbalanceSIAAnalysis' in analyses:
    115115                        if any(self.element_equation==1):
    116                                 if numpy.any(numpy.logical_and(self.vertex_equation,md.mask.groundedice_levelset)):
     116                                if np.any(np.logical_and(self.vertex_equation,md.mask.groundedice_levelset)):
    117117                                        print "\n !!! Warning: SIA's model is not consistent on ice shelves !!!\n"
    118118
  • issm/trunk-jpl/src/m/classes/gia.py

    r21049 r21303  
    4747                        return md
    4848               
    49                 md = checkfield(md,'fieldname','gia.mantle_viscosity','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices,1],'>',0)
    50                 md = checkfield(md,'fieldname','gia.lithosphere_thickness','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices,1],'>',0)
     49                md = checkfield(md,'fieldname','gia.mantle_viscosity','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices],'>',0)
     50                md = checkfield(md,'fieldname','gia.lithosphere_thickness','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices],'>',0)
    5151                md = checkfield(md,'fieldname','gia.cross_section_shape','numel',[1],'values',[1,2])
    5252
  • issm/trunk-jpl/src/m/classes/groundingline.py

    r21049 r21303  
    1 import numpy
     1import numpy as np
    22from fielddisplay import fielddisplay
    33from checkfield import checkfield
     
    3838
    3939                if not m.strcmp(self.migration,'None'):
    40                         if numpy.any(numpy.isnan(md.geometry.bed)):
     40                        if np.any(np.isnan(md.geometry.bed)):
    4141                                md.checkmessage("requesting grounding line migration, but bathymetry is absent!")
    42                         pos=numpy.nonzero(md.mask.groundedice_levelset>0.)[0]
    43                         if any(numpy.abs(md.geometry.base[pos]-md.geometry.bed[pos])>10**-10):
     42                        pos=np.nonzero(md.mask.groundedice_levelset>0.)[0]
     43                        if any(np.abs(md.geometry.base[pos]-md.geometry.bed[pos])>10**-10):
    4444                                md.checkmessage("base not equal to bed on grounded ice!")
    4545                        if any(md.geometry.bed - md.geometry.base > 10**-9):
  • issm/trunk-jpl/src/m/classes/hydrologydc.py

    r21280 r21303  
    1 import numpy
     1import numpy as np
    22from project3d import project3d
    33from fielddisplay import fielddisplay
     
    134134        # }}}
    135135        def initialize(self,md): # {{{
    136                 if numpy.all(numpy.isnan(self.basal_moulin_input)):
    137                         self.basal_moulin_input=numpy.zeros((md.mesh.numberofvertices,1))
     136                if np.all(np.isnan(self.basal_moulin_input)):
     137                        self.basal_moulin_input=np.zeros((md.mesh.numberofvertices))
    138138                        print"      no hydrology.basal_moulin_input specified: values set as zero"
    139139
     
    166166                md = checkfield(md,'fieldname','hydrology.sediment_porosity','>',0.,'numel',[1])
    167167                md = checkfield(md,'fieldname','hydrology.sediment_thickness','>',0.,'numel',[1])
    168                 md = checkfield(md,'fieldname','hydrology.sediment_transmitivity','>=',0,'size',[md.mesh.numberofvertices,1])
     168                md = checkfield(md,'fieldname','hydrology.sediment_transmitivity','>=',0,'size',[md.mesh.numberofvertices])
    169169                if self.isefficientlayer==1:
    170170                        md = checkfield(md,'fieldname','hydrology.spcepl_head','Inf',1,'timeseries',1)
    171                         md = checkfield(md,'fieldname','hydrology.mask_eplactive_node','size',[md.mesh.numberofvertices,1],'values',[0,1])
     171                        md = checkfield(md,'fieldname','hydrology.mask_eplactive_node','size',[md.mesh.numberofvertices],'values',[0,1])
    172172                        md = checkfield(md,'fieldname','hydrology.epl_compressibility','>',0.,'numel',[1])
    173173                        md = checkfield(md,'fieldname','hydrology.epl_porosity','>',0.,'numel',[1])
  • issm/trunk-jpl/src/m/classes/independent.py

    r21049 r21303  
    1 import numpy
     1import numpy as np
    22from pairoptions import pairoptions
    33from fielddisplay import fielddisplay
     
    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
     
    3434                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!")
  • issm/trunk-jpl/src/m/classes/initialization.py

    r21049 r21303  
    1 import numpy
     1import numpy as np
    22from project3d import project3d
    33from fielddisplay import fielddisplay
     
    6161
    6262                #Lithostatic pressure by default
    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,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        #}}}
     
    7077        def checkconsistency(self,md,solution,analyses):    # {{{
    7178                if 'StressbalanceAnalysis' in analyses:
    72                         if not numpy.any(numpy.logical_or(numpy.isnan(md.initialization.vx),numpy.isnan(md.initialization.vy))):
     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])
     
    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")
    8592                if 'ThermalAnalysis' in analyses:
     
    98105                if 'HydrologyDCInefficientAnalysis' in analyses:
    99106                        if hasattr(md.hydrology,'hydrologydc'):
    100                                 md = checkfield(md,'fieldname','initialization.sediment_head','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices,1])
     107                                md = checkfield(md,'fieldname','initialization.sediment_head','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
    101108                if 'HydrologyDCEfficientAnalysis' in analyses:
    102109                        if hasattr(md.hydrology,'hydrologydc'):
    103110                                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])
     111                                        md = checkfield(md,'fieldname','initialization.epl_head','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
     112                                        md = checkfield(md,'fieldname','initialization.epl_thickness','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
    106113
    107114                return md
     
    124131                if md.thermal.isenthalpy:
    125132                        tpmp = md.materials.meltingpoint - md.materials.beta*md.initialization.pressure;
    126                         pos  = numpy.nonzero(md.initialization.temperature > tpmp)[0]
     133                        pos  = np.nonzero(md.initialization.temperature > tpmp)[0]
    127134                        enthalpy      = md.materials.heatcapacity*(md.initialization.temperature-md.constants.referencetemperature);
    128                         enthalpy[pos] = md.materials.heatcapacity*tpmp[pos].reshape(-1,1) - md.constants.referencetemperature + md.materials.latentheat*md.initialization.waterfraction[pos].reshape(-1,1)
     135                        enthalpy[pos] = md.materials.heatcapacity*tpmp[pos].reshape(-1,) - md.constants.referencetemperature + md.materials.latentheat*md.initialization.waterfraction[pos].reshape(-1,)
    129136                        WriteData(fid,prefix,'data',enthalpy,'format','DoubleMat','mattype',1,'name','md.initialization.enthalpy');
    130137
  • issm/trunk-jpl/src/m/classes/inversion.py

    r21244 r21303  
    1 import numpy
     1import numpy as np
    22from project3d import project3d
    33from fielddisplay import fielddisplay
     
    7676                self.vel_obs=project3d(md,'vector',self.vel_obs,'type','node')
    7777                self.thickness_obs=project3d(md,'vector',self.thickness_obs,'type','node')
    78                 if not numpy.any(numpy.isnan(self.cost_functions_coefficients)):
     78                if not np.any(np.isnan(self.cost_functions_coefficients)):
    7979                        self.cost_functions_coefficients=project3d(md,'vector',self.cost_functions_coefficients,'type','node')
    80                 if not numpy.any(numpy.isnan(self.min_parameters)):
     80                if not np.any(np.isnan(self.min_parameters)):
    8181                        self.min_parameters=project3d(md,'vector',self.min_parameters,'type','node')
    82                 if not numpy.any(numpy.isnan(self.max_parameters)):
     82                if not np.any(np.isnan(self.max_parameters)):
    8383                        self.max_parameters=project3d(md,'vector',self.max_parameters,'type','node')
    8484                return self
     
    9898                #maximum number of iteration in the optimization algorithm for
    9999                #each step
    100                 self.maxiter_per_step=20*numpy.ones(self.nsteps)
     100                self.maxiter_per_step=20*np.ones(self.nsteps)
    101101
    102102                #the inversed parameter is updated as follows:
     
    105105                #inversed parameter (10^8 for B, 50 for drag) and can be decreased
    106106                #after the first iterations
    107                 self.gradient_scaling=50*numpy.ones((self.nsteps,1))
     107                self.gradient_scaling=50*np.ones((self.nsteps,1))
    108108
    109109                #several responses can be used:
     
    113113                #misfit(1)/misfit(0) < self.step_threshold, we go directly to
    114114                #the next step
    115                 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
    116116
    117117                #cost_function_threshold is a criteria to stop the control methods.
     
    128128                        return md
    129129
    130                 num_controls=numpy.size(md.inversion.control_parameters)
    131                 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)
    132132
    133133                md = checkfield(md,'fieldname','inversion.iscontrol','values',[0,1])
     
    185185
    186186                #process cost functions
    187                 num_cost_functions=numpy.size(self.cost_functions)
     187                num_cost_functions=np.size(self.cost_functions)
    188188                data=marshallcostfunctions(self.cost_functions)
    189189                WriteData(fid,prefix,'data',data,'name','md.inversion.cost_functions','format','StringArray')
  • issm/trunk-jpl/src/m/classes/linearbasalforcings.py

    r21049 r21303  
    22from checkfield import checkfield
    33from WriteData import WriteData
    4 import numpy
     4import numpy as np
    55
    66class linearbasalforcings(object):
     
    5151        def initialize(self,md): # {{{
    5252
    53                 if numpy.all(numpy.isnan(self.groundedice_melting_rate)):
    54                         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))
    5555                        print "      no basalforcings.groundedice_melting_rate specified: values set as zero"
    5656
     
    9292                yts=md.constants.yts
    9393
    94                 floatingice_melting_rate = numpy.zeros((md.mesh.numberofvertices,1))
    95                 pos=numpy.nonzero(md.geometry.base<=md.basalforcings.deepwater_elevation)
     94                floatingice_melting_rate = np.zeros((md.mesh.numberofvertices))
     95                pos=np.nonzero(md.geometry.base<=md.basalforcings.deepwater_elevation)
    9696                floatingice_melting_rate[pos]=md.basalforcings.deepwater_melting_rate
    97                 pos=numpy.nonzero(numpy.logical_and(md.geometry.base>md.basalforcings.deepwater_elevation,md.geometry.base<md.basalforcings.upperwater_elevation))
     97                pos=np.nonzero(np.logical_and(md.geometry.base>md.basalforcings.deepwater_elevation,md.geometry.base<md.basalforcings.upperwater_elevation))
    9898                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)
    9999
  • issm/trunk-jpl/src/m/classes/m1qn3inversion.py

    r21049 r21303  
    1 import numpy
     1import numpy as np
    22from project3d import project3d
    33from fielddisplay import fielddisplay
     
    9898                self.vel_obs=project3d(md,'vector',self.vel_obs,'type','node')
    9999                self.thickness_obs=project3d(md,'vector',self.thickness_obs,'type','node')
    100                 if not numpy.any(numpy.isnan(self.cost_functions_coefficients)):
     100                if not np.any(np.isnan(self.cost_functions_coefficients)):
    101101                        self.cost_functions_coefficients=project3d(md,'vector',self.cost_functions_coefficients,'type','node')
    102                 if not numpy.any(numpy.isnan(self.min_parameters)):
     102                if not np.any(np.isnan(self.min_parameters)):
    103103                        self.min_parameters=project3d(md,'vector',self.min_parameters,'type','node')
    104                 if not numpy.any(numpy.isnan(self.max_parameters)):
     104                if not np.any(np.isnan(self.max_parameters)):
    105105                        self.max_parameters=project3d(md,'vector',self.max_parameters,'type','node')
    106106                return self
     
    137137                        return md
    138138
    139                 num_controls=numpy.size(md.inversion.control_parameters)
    140                 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)
    141141
    142142                md = checkfield(md,'fieldname','inversion.iscontrol','values',[0,1])
     
    189189
    190190                #process cost functions
    191                 num_cost_functions=numpy.size(self.cost_functions)
     191                num_cost_functions=np.size(self.cost_functions)
    192192                data=marshallcostfunctions(self.cost_functions)
    193193                WriteData(fid,prefix,'data',data,'name','md.inversion.cost_functions','format','StringArray')
  • issm/trunk-jpl/src/m/classes/mask.py

    r21155 r21303  
    1 import numpy
     1import numpy as np
    22from fielddisplay import fielddisplay
    33from project3d import project3d
     
    4040
    4141                md = checkfield(md,'fieldname','mask.ice_levelset'        ,'size',[md.mesh.numberofvertices])
    42                 isice=numpy.array(md.mask.ice_levelset<=0,int)
    43                 if numpy.sum(isice)==0:
     42                isice=np.array(md.mask.ice_levelset<=0,int)
     43                if np.sum(isice)==0:
    4444                        raise TypeError("no ice present in the domain")
    4545
  • issm/trunk-jpl/src/m/classes/maskpsl.py

    r21049 r21303  
    1 import numpy
     1import numpy as np
    22import MatlabFuncs as m
    33from model import *
     
    1111#   Usage:
    1212#      maskpsl=maskpsl();
     13
    1314        def __init__(self,*args): # {{{
    1415                self.groundedice_levelset = float('NaN')
     
    1617                self.ocean_levelset = float('NaN')
    1718                self.land_levelset = float('NaN')
    18                
     19
    1920                if not len(args):
    2021                        self.setdefaultparameters()
     
    2425        def __repr__(self): # {{{
    2526                string='   masks:'
    26                
    2727                string="%s\n%s"%(string,fielddisplay(self,'groundedice_levelset','is ice grounded ? grounded ice if > 0, grounding line position if = 0, floating ice if < 0'))
    2828                string="%s\n%s"%(string,fielddisplay(self,'ice_levelset','presence of ice if < 0, icefront position if = 0, no ice if > 0'))
    2929                string="%s\n%s"%(string,fielddisplay(self,'ocean_levelset','is the vertex on the ocean ? yes if = 1, no if = 0'))
    3030                string="%s\n%s"%(string,fielddisplay(self,'land_levelset','is the vertex on the land ? yes if = 1, no if = 0'))
    31        
    3231                return string
     32
    3333        # }}}   
    3434        def loadobj(self): # {{{
    3535                # This def is directly called by matlab when a model object is
    3636                # loaded. Update old properties here
    37 
    3837                #2014 February 5th
    3938                if numel(self.ice_levelset)>1 and all(self.ice_levelset>=0):
     
    4140                return self
    4241        # }}}
     42
    4343        def setdefaultparameters(self): # {{{
    4444                return self
     45
    4546        # }}}
     47
    4648        def checkconsistency(self,md,solution,analyses): # {{{
    47 
    48                 md = checkfield(md,'fieldname','mask.groundedice_levelset','size',[md.mesh.numberofvertices, 1])
    49                 md = checkfield(md,'fieldname','mask.ice_levelset'        ,'size',[md.mesh.numberofvertices, 1])
    50                 md = checkfield(md,'fieldname','mask.ocean_levelset','size',[md.mesh.numberofvertices, 1])
    51                 md = checkfield(md,'fieldname','mask.land_levelset','size',[md.mesh.numberofvertices, 1])
     49                md = checkfield(md,'fieldname','mask.groundedice_levelset','size',[md.mesh.numberofvertices])
     50                md = checkfield(md,'fieldname','mask.ice_levelset'        ,'size',[md.mesh.numberofvertices])
     51                md = checkfield(md,'fieldname','mask.ocean_levelset','size',[md.mesh.numberofvertices])
     52                md = checkfield(md,'fieldname','mask.land_levelset','size',[md.mesh.numberofvertices])
    5253                isice=(md.mask.ice_levelset<=0)
    5354                if sum(isice)==0:
     
    5657                if max(md.mask.ice_levelset)<0:
    5758                        print('no ice front provided')
    58                
    59                 elements=md.mesh.elements-1; elements=elements.astype(numpy.int32, copy=False);
    60                 icefront=numpy.sum(md.mask.ice_levelset[elements]==0,axis=1)
     59
     60                elements=md.mesh.elements-1; elements=elements.astype(np.int32, copy=False);
     61                icefront=np.sum(md.mask.ice_levelset[elements]==0,axis=1)
    6162                if (max(icefront)==3 & m.strcmp(md.mesh.elementtype(),'Tria')) or (max(icefront==6) & m.strcmp(md.mesh.elementtype(),'Penta')):
    6263                        raise RuntimeError('At least one element has all nodes on ice front, change md.mask.ice_levelset to fix it')
    63                
     64
    6465                return md
     66
    6567        # }}}
     68
    6669        def extrude(self,md): # {{{
    6770                self.groundedice_levelset=project3d(md,'vector',self.groundedice_levelset,'type','node')
     
    7174                return self
    7275        # }}}
     76
    7377        def mask(*args): # {{{
    7478                if not len(args):
     
    7781                        raise RuntimeError('constructor not supported')
    7882                return self
     83
    7984        # }}}
     85
    8086        def marshall(self,prefix,md,fid): # {{{
    8187                WriteData(fid,prefix,'object',self,'class','mask','fieldname','groundedice_levelset','format','DoubleMat','mattype',1)
     
    8591        # }}}
    8692        def savemodeljs(self,fid,modelname): # {{{
    87 
    8893                writejs1Darray(fid,[modelname, '.mask.groundedice_levelset'],self.groundedice_levelset)
    8994                writejs1Darray(fid,[modelname, '.mask.ice_levelset'],self.ice_levelset)
    9095                writejs1Darray(fid,[modelname, '.mask.ocean_levelset'],self.ocean_levelset)
    9196                writejs1Darray(fid,[modelname, '.mask.land_levelset'],self.land_levelset)
     97        # }}}
    9298
    93         # }}}
  • issm/trunk-jpl/src/m/classes/mesh2d.py

    r21049 r21303  
    1 import numpy
     1import numpy as np
    22from fielddisplay import fielddisplay
    33from checkfield import checkfield
     
    8585                md = checkfield(md,'fieldname','mesh.x','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
    8686                md = checkfield(md,'fieldname','mesh.y','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
    87                 md = checkfield(md,'fieldname','mesh.elements','NaN',1,'Inf',1,'>',0,'values',numpy.arange(1,md.mesh.numberofvertices+1))
     87                md = checkfield(md,'fieldname','mesh.elements','NaN',1,'Inf',1,'>',0,'values',np.arange(1,md.mesh.numberofvertices+1))
    8888                md = checkfield(md,'fieldname','mesh.elements','size',[md.mesh.numberofelements,3])
    89                 if numpy.any(numpy.logical_not(m.ismember(numpy.arange(1,md.mesh.numberofvertices+1),md.mesh.elements))):
     89                if np.any(np.logical_not(m.ismember(np.arange(1,md.mesh.numberofvertices+1),md.mesh.elements))):
    9090                        md.checkmessage("orphan nodes have been found. Check the mesh outline")
    9191                md = checkfield(md,'fieldname','mesh.numberofelements','>',0)
     
    112112                WriteData(fid,prefix,'object',self,'class','mesh','fieldname','x','format','DoubleMat','mattype',1)
    113113                WriteData(fid,prefix,'object',self,'class','mesh','fieldname','y','format','DoubleMat','mattype',1)
    114                 WriteData(fid,prefix,'name','md.mesh.z','data',numpy.zeros(self.numberofvertices),'format','DoubleMat','mattype',1);
     114                WriteData(fid,prefix,'name','md.mesh.z','data',np.zeros(self.numberofvertices),'format','DoubleMat','mattype',1);
    115115                WriteData(fid,prefix,'object',self,'class','mesh','fieldname','elements','format','DoubleMat','mattype',2)
    116116                WriteData(fid,prefix,'object',self,'class','mesh','fieldname','numberofelements','format','Integer')
  • issm/trunk-jpl/src/m/classes/mesh3dprisms.py

    r21049 r21303  
    1 import numpy
     1import numpy as np
    22from fielddisplay import fielddisplay
    33from checkfield import *
     
    108108                md = checkfield(md,'fieldname','mesh.y','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
    109109                md = checkfield(md,'fieldname','mesh.z','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
    110                 md = checkfield(md,'fieldname','mesh.elements','NaN',1,'Inf',1,'>',0,'values',numpy.arange(1,md.mesh.numberofvertices+1))
     110                md = checkfield(md,'fieldname','mesh.elements','NaN',1,'Inf',1,'>',0,'values',np.arange(1,md.mesh.numberofvertices+1))
    111111                md = checkfield(md,'fieldname','mesh.elements','size',[md.mesh.numberofelements,6])
    112                 if numpy.any(numpy.logical_not(m.ismember(numpy.arange(1,md.mesh.numberofvertices+1),md.mesh.elements))):
     112                if np.any(np.logical_not(m.ismember(np.arange(1,md.mesh.numberofvertices+1),md.mesh.elements))):
    113113                        md.checkmessage("orphan nodes have been found. Check the mesh3dprisms outline")
    114114                md = checkfield(md,'fieldname','mesh.numberoflayers','>=',0)
  • issm/trunk-jpl/src/m/classes/mesh3dsurface.py

    r21049 r21303  
    11from MatlabFuncs import *
    22from model import *
    3 from numpy import *
     3from np.import *
    44from fielddisplay import fielddisplay
    55from checkfield import checkfield
  • issm/trunk-jpl/src/m/classes/mismipbasalforcings.py

    r21271 r21303  
    33from checkfield import checkfield
    44from WriteData import WriteData
    5 import numpy
     5import numpy as np
    66
    77class mismipbasalforcings(object):
     
    2121        self.geothermalflux = float('NaN')
    2222
    23         if numpy.all(numpy.isnan(self.groundedice_melting_rate)):
    24             self.groundedice_melting_rate=numpy.zeros(md.mesh.numberofvertices)
     23        if np.all(np.isnan(self.groundedice_melting_rate)):
     24            self.groundedice_melting_rate=np.zeros(md.mesh.numberofvertices)
    2525            print ' no basalforcings.groundedice_melting_rate specified: values set as zero'
    2626
     
    8181            print 'WARNING: value of yts for MISMIP+ runs different from ISSM default!'
    8282
    83         floatingice_melting_rate = numpy.zeros((md.mesh.numberofvertices,1))
    84         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)
     83        floatingice_melting_rate = np.zeros((md.mesh.numberofvertices))
     84        floatingice_melting_rate = md.basalforcings.meltrate_factor*np.tanh((md.geometry.base-md.geometry.bed)/md.basalforcings.threshold_thickness)*np.amax(md.basalforcings.upperdepth_melt-md.geometry.base,0)
    8585
    8686        WriteData(fid,prefix,'name','md.basalforcings.model','data',3,'format','Integer')
  • issm/trunk-jpl/src/m/classes/model.py

    r21097 r21303  
    11#module imports {{{
    2 import numpy
     2import numpy as np
    33import copy
    44import sys
     
    231231                #get elements that are inside area
    232232                flag_elem=FlagElements(md1,area)
    233                 if not numpy.any(flag_elem):
     233                if not np.any(flag_elem):
    234234                        raise RuntimeError("extracted model is empty")
    235235
    236236                #kick out all elements with 3 dirichlets
    237                 spc_elem=numpy.nonzero(numpy.logical_not(flag_elem))[0]
    238                 spc_node=numpy.unique(md1.mesh.elements[spc_elem,:])-1
    239                 flag=numpy.ones(md1.mesh.numberofvertices)
     237                spc_elem=np.nonzero(np.logical_not(flag_elem))[0]
     238                spc_node=np.unique(md1.mesh.elements[spc_elem,:])-1
     239                flag=np.ones(md1.mesh.numberofvertices)
    240240                flag[spc_node]=0
    241                 pos=numpy.nonzero(numpy.logical_not(numpy.sum(flag[md1.mesh.elements-1],axis=1)))[0]
     241                pos=np.nonzero(np.logical_not(np.sum(flag[md1.mesh.elements-1],axis=1)))[0]
    242242                flag_elem[pos]=0
    243243
    244244                #extracted elements and nodes lists
    245                 pos_elem=numpy.nonzero(flag_elem)[0]
    246                 pos_node=numpy.unique(md1.mesh.elements[pos_elem,:])-1
     245                pos_elem=np.nonzero(flag_elem)[0]
     246                pos_node=np.unique(md1.mesh.elements[pos_elem,:])-1
    247247
    248248                #keep track of some fields
    249249                numberofvertices1=md1.mesh.numberofvertices
    250250                numberofelements1=md1.mesh.numberofelements
    251                 numberofvertices2=numpy.size(pos_node)
    252                 numberofelements2=numpy.size(pos_elem)
    253                 flag_node=numpy.zeros(numberofvertices1)
     251                numberofvertices2=np.size(pos_node)
     252                numberofelements2=np.size(pos_elem)
     253                flag_node=np.zeros(numberofvertices1)
    254254                flag_node[pos_node]=1
    255255
    256256                #Create Pelem and Pnode (transform old nodes in new nodes and same thing for the elements)
    257                 Pelem=numpy.zeros(numberofelements1,int)
    258                 Pelem[pos_elem]=numpy.arange(1,numberofelements2+1)
    259                 Pnode=numpy.zeros(numberofvertices1,int)
    260                 Pnode[pos_node]=numpy.arange(1,numberofvertices2+1)
     257                Pelem=np.zeros(numberofelements1,int)
     258                Pelem[pos_elem]=np.arange(1,numberofelements2+1)
     259                Pnode=np.zeros(numberofvertices1,int)
     260                Pnode[pos_node]=np.arange(1,numberofvertices2+1)
    261261
    262262                #renumber the elements (some node won't exist anymore)
     
    283283                        #get field
    284284                        field=getattr(md1,fieldi)
    285                         fieldsize=numpy.shape(field)
     285                        fieldsize=np.shape(field)
    286286                        if hasattr(field,'__dict__') and not m.ismember(fieldi,['results'])[0]:    #recursive call
    287287                                object_fields=vars(field)
     
    289289                                        #get field
    290290                                        field=getattr(getattr(md1,fieldi),fieldj)
    291                                         fieldsize=numpy.shape(field)
     291                                        fieldsize=np.shape(field)
    292292                                        if len(fieldsize):
    293293                                                #size = number of nodes * n
     
    295295                                                        setattr(getattr(md2,fieldi),fieldj,field[pos_node])
    296296                                                elif fieldsize[0]==numberofvertices1+1:
    297                                                         setattr(getattr(md2,fieldi),fieldj,numpy.vstack((field[pos_node],field[-1,:])))
     297                                                        setattr(getattr(md2,fieldi),fieldj,np.vstack((field[pos_node],field[-1,:])))
    298298                                                #size = number of elements * n
    299299                                                elif fieldsize[0]==numberofelements1:
     
    305305                                                setattr(md2,fieldi,field[pos_node])
    306306                                        elif fieldsize[0]==numberofvertices1+1:
    307                                                 setattr(md2,fieldi,numpy.hstack((field[pos_node],field[-1,:])))
     307                                                setattr(md2,fieldi,np.hstack((field[pos_node],field[-1,:])))
    308308                                        #size = number of elements * n
    309309                                        elif fieldsize[0]==numberofelements1:
     
    320320                if md1.mesh.__class__.__name__=='mesh3dprisms':
    321321                        md2.mesh.uppervertex=md1.mesh.uppervertex[pos_node]
    322                         pos=numpy.nonzero(numpy.logical_not(md2.mesh.uppervertex==-1))[0]
    323                         md2.mesh.uppervertex[pos]=Pnode[md2.mesh.uppervertex[pos]-1]
     322                        pos=np.where(~np.isnan(md2.mesh.uppervertex))[0]
     323                        md2.mesh.uppervertex[pos]=Pnode[md2.mesh.uppervertex[pos].astype(int)-1]
    324324
    325325                        md2.mesh.lowervertex=md1.mesh.lowervertex[pos_node]
    326                         pos=numpy.nonzero(numpy.logical_not(md2.mesh.lowervertex==-1))[0]
    327                         md2.mesh.lowervertex[pos]=Pnode[md2.mesh.lowervertex[pos]-1]
     326                        pos=np.where(~np.isnan(md2.mesh.lowervertex))[0]
     327                        md2.mesh.lowervertex[pos]=Pnode[md2.mesh.lowervertex[pos].astype(int)-1]
    328328
    329329                        md2.mesh.upperelements=md1.mesh.upperelements[pos_elem]
    330                         pos=numpy.nonzero(numpy.logical_not(md2.mesh.upperelements==-1))[0]
    331                         md2.mesh.upperelements[pos]=Pelem[md2.mesh.upperelements[pos]-1]
     330                        pos=np.where(~np.isnan(md2.mesh.upperelements))[0]
     331                        md2.mesh.upperelements[pos]=Pelem[md2.mesh.upperelements[pos].astype(int)-1]
    332332
    333333                        md2.mesh.lowerelements=md1.mesh.lowerelements[pos_elem]
    334                         pos=numpy.nonzero(numpy.logical_not(md2.mesh.lowerelements==-1))[0]
    335                         md2.mesh.lowerelements[pos]=Pelem[md2.mesh.lowerelements[pos]-1]
     334                        pos=np.where(~np.isnan(md2.mesh.lowerelements))[0]
     335                        md2.mesh.lowerelements[pos]=Pelem[md2.mesh.lowerelements[pos].astype(int)-1]
    336336
    337337                #Initial 2d mesh
    338338                if md1.mesh.__class__.__name__=='mesh3dprisms':
    339                         flag_elem_2d=flag_elem[numpy.arange(0,md1.mesh.numberofelements2d)]
    340                         pos_elem_2d=numpy.nonzero(flag_elem_2d)[0]
    341                         flag_node_2d=flag_node[numpy.arange(0,md1.mesh.numberofvertices2d)]
    342                         pos_node_2d=numpy.nonzero(flag_node_2d)[0]
    343 
    344                         md2.mesh.numberofelements2d=numpy.size(pos_elem_2d)
    345                         md2.mesh.numberofvertices2d=numpy.size(pos_node_2d)
     339                        flag_elem_2d=flag_elem[np.arange(0,md1.mesh.numberofelements2d)]
     340                        pos_elem_2d=np.nonzero(flag_elem_2d)[0]
     341                        flag_node_2d=flag_node[np.arange(0,md1.mesh.numberofvertices2d)]
     342                        pos_node_2d=np.nonzero(flag_node_2d)[0]
     343
     344                        md2.mesh.numberofelements2d=np.size(pos_elem_2d)
     345                        md2.mesh.numberofvertices2d=np.size(pos_node_2d)
    346346                        md2.mesh.elements2d=md1.mesh.elements2d[pos_elem_2d,:]
    347347                        md2.mesh.elements2d[:,0]=Pnode[md2.mesh.elements2d[:,0]-1]
     
    354354                #Edges
    355355                if m.strcmp(md.mesh.domaintype(),'2Dhorizontal'):
    356                         if numpy.ndim(md2.mesh.edges)>1 and numpy.size(md2.mesh.edges,axis=1)>1:    #do not use ~isnan because there are some numpy.nans...
     356                        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...
    357357                                #renumber first two columns
    358                                 pos=numpy.nonzero(md2.mesh.edges[:,3]!=-1)[0]
     358                                pos=np.nonzero(md2.mesh.edges[:,3]!=-1)[0]
    359359                                md2.mesh.edges[:  ,0]=Pnode[md2.mesh.edges[:,0]-1]
    360360                                md2.mesh.edges[:  ,1]=Pnode[md2.mesh.edges[:,1]-1]
     
    362362                                md2.mesh.edges[pos,3]=Pelem[md2.mesh.edges[pos,3]-1]
    363363                                #remove edges when the 2 vertices are not in the domain.
    364                                 md2.mesh.edges=md2.mesh.edges[numpy.nonzero(numpy.logical_and(md2.mesh.edges[:,0],md2.mesh.edges[:,1]))[0],:]
     364                                md2.mesh.edges=md2.mesh.edges[np.nonzero(np.logical_and(md2.mesh.edges[:,0],md2.mesh.edges[:,1]))[0],:]
    365365                                #Replace all zeros by -1 in the last two columns
    366                                 pos=numpy.nonzero(md2.mesh.edges[:,2]==0)[0]
     366                                pos=np.nonzero(md2.mesh.edges[:,2]==0)[0]
    367367                                md2.mesh.edges[pos,2]=-1
    368                                 pos=numpy.nonzero(md2.mesh.edges[:,3]==0)[0]
     368                                pos=np.nonzero(md2.mesh.edges[:,3]==0)[0]
    369369                                md2.mesh.edges[pos,3]=-1
    370370                                #Invert -1 on the third column with last column (Also invert first two columns!!)
    371                                 pos=numpy.nonzero(md2.mesh.edges[:,2]==-1)[0]
     371                                pos=np.nonzero(md2.mesh.edges[:,2]==-1)[0]
    372372                                md2.mesh.edges[pos,2]=md2.mesh.edges[pos,3]
    373373                                md2.mesh.edges[pos,3]=-1
     
    376376                                md2.mesh.edges[pos,0]=values
    377377                                #Finally remove edges that do not belong to any element
    378                                 pos=numpy.nonzero(numpy.logical_and(md2.mesh.edges[:,1]==-1,md2.mesh.edges[:,2]==-1))[0]
    379                                 md2.mesh.edges=numpy.delete(md2.mesh.edges,pos,axis=0)
     378                                pos=np.nonzero(np.logical_and(md2.mesh.edges[:,1]==-1,md2.mesh.edges[:,2]==-1))[0]
     379                                md2.mesh.edges=np.delete(md2.mesh.edges,pos,axis=0)
    380380
    381381                #Penalties
    382                 if numpy.any(numpy.logical_not(numpy.isnan(md2.stressbalance.vertex_pairing))):
    383                         for i in xrange(numpy.size(md1.stressbalance.vertex_pairing,axis=0)):
     382                if np.any(np.logical_not(np.isnan(md2.stressbalance.vertex_pairing))):
     383                        for i in xrange(np.size(md1.stressbalance.vertex_pairing,axis=0)):
    384384                                md2.stressbalance.vertex_pairing[i,:]=Pnode[md1.stressbalance.vertex_pairing[i,:]]
    385                         md2.stressbalance.vertex_pairing=md2.stressbalance.vertex_pairing[numpy.nonzero(md2.stressbalance.vertex_pairing[:,0])[0],:]
    386                 if numpy.any(numpy.logical_not(numpy.isnan(md2.masstransport.vertex_pairing))):
    387                         for i in xrange(numpy.size(md1.masstransport.vertex_pairing,axis=0)):
     385                        md2.stressbalance.vertex_pairing=md2.stressbalance.vertex_pairing[np.nonzero(md2.stressbalance.vertex_pairing[:,0])[0],:]
     386                if np.any(np.logical_not(np.isnan(md2.masstransport.vertex_pairing))):
     387                        for i in xrange(np.size(md1.masstransport.vertex_pairing,axis=0)):
    388388                                md2.masstransport.vertex_pairing[i,:]=Pnode[md1.masstransport.vertex_pairing[i,:]]
    389                         md2.masstransport.vertex_pairing=md2.masstransport.vertex_pairing[numpy.nonzero(md2.masstransport.vertex_pairing[:,0])[0],:]
     389                        md2.masstransport.vertex_pairing=md2.masstransport.vertex_pairing[np.nonzero(md2.masstransport.vertex_pairing[:,0])[0],:]
    390390
    391391                #recreate segments
     
    394394                        md2.mesh.elementconnectivity=ElementConnectivity(md2.mesh.elements,md2.mesh.vertexconnectivity)[0]
    395395                        md2.mesh.segments=contourenvelope(md2)
    396                         md2.mesh.vertexonboundary=numpy.zeros(numberofvertices2,bool)
     396                        md2.mesh.vertexonboundary=np.zeros(numberofvertices2,bool)
    397397                        md2.mesh.vertexonboundary[md2.mesh.segments[:,0:2]-1]=True
    398398                else:
     
    401401                        md2.mesh.elementconnectivity=ElementConnectivity(md2.mesh.elements2d,md2.mesh.vertexconnectivity)[0]
    402402                        segments=contourenvelope(md2)
    403                         md2.mesh.vertexonboundary=numpy.zeros(numberofvertices2/md2.mesh.numberoflayers,bool)
     403                        md2.mesh.vertexonboundary=np.zeros(numberofvertices2/md2.mesh.numberoflayers,bool)
    404404                        md2.mesh.vertexonboundary[segments[:,0:2]-1]=True
    405                         md2.mesh.vertexonboundary=numpy.tile(md2.mesh.vertexonboundary,md2.mesh.numberoflayers)
     405                        md2.mesh.vertexonboundary=np.tile(md2.mesh.vertexonboundary,md2.mesh.numberoflayers)
    406406                        #Then do it for 3d as usual
    407407                        md2.mesh.vertexconnectivity=NodeConnectivity(md2.mesh.elements,md2.mesh.numberofvertices)[0]
     
    410410                #Boundary conditions: Dirichlets on new boundary
    411411                #Catch the elements that have not been extracted
    412                 orphans_elem=numpy.nonzero(numpy.logical_not(flag_elem))[0]
    413                 orphans_node=numpy.unique(md1.mesh.elements[orphans_elem,:])-1
     412                orphans_elem=np.nonzero(np.logical_not(flag_elem))[0]
     413                orphans_node=np.unique(md1.mesh.elements[orphans_elem,:])-1
    414414                #Figure out which node are on the boundary between md2 and md1
    415                 nodestoflag1=numpy.intersect1d(orphans_node,pos_node)
     415                nodestoflag1=np.intersect1d(orphans_node,pos_node)
    416416                nodestoflag2=Pnode[nodestoflag1].astype(int)-1
    417                 if numpy.size(md1.stressbalance.spcvx)>1 and numpy.size(md1.stressbalance.spcvy)>2 and numpy.size(md1.stressbalance.spcvz)>2:
    418                         if numpy.size(md1.inversion.vx_obs)>1 and numpy.size(md1.inversion.vy_obs)>1:
     417                if np.size(md1.stressbalance.spcvx)>1 and np.size(md1.stressbalance.spcvy)>2 and np.size(md1.stressbalance.spcvz)>2:
     418                        if np.size(md1.inversion.vx_obs)>1 and np.size(md1.inversion.vy_obs)>1:
    419419                                md2.stressbalance.spcvx[nodestoflag2]=md2.inversion.vx_obs[nodestoflag2]
    420420                                md2.stressbalance.spcvy[nodestoflag2]=md2.inversion.vy_obs[nodestoflag2]
    421421                        else:
    422                                 md2.stressbalance.spcvx[nodestoflag2]=numpy.nan
    423                                 md2.stressbalance.spcvy[nodestoflag2]=numpy.nan
     422                                md2.stressbalance.spcvx[nodestoflag2]=np.nan
     423                                md2.stressbalance.spcvy[nodestoflag2]=np.nan
    424424                                print "\n!! extract warning: spc values should be checked !!\n\n"
    425425                        #put 0 for vz
    426426                        md2.stressbalance.spcvz[nodestoflag2]=0
    427                 if numpy.any(numpy.logical_not(numpy.isnan(md1.thermal.spctemperature))):
    428                         md2.thermal.spctemperature[nodestoflag2,0]=1
     427                if np.any(np.logical_not(np.isnan(md1.thermal.spctemperature))):
     428                        md2.thermal.spctemperature[nodestoflag2]=1
    429429
    430430                #Results fields
     
    441441                                                        #get subfields
    442442                                                        for solutionsubfield,subfield in fieldi.__dict__.iteritems():
    443                                                                 if   numpy.size(subfield)==numberofvertices1:
     443                                                                if   np.size(subfield)==numberofvertices1:
    444444                                                                        setattr(fieldr,solutionsubfield,subfield[pos_node])
    445                                                                 elif numpy.size(subfield)==numberofelements1:
     445                                                                elif np.size(subfield)==numberofelements1:
    446446                                                                        setattr(fieldr,solutionsubfield,subfield[pos_elem])
    447447                                                                else:
     
    455455                                                #get subfields
    456456                                                for solutionsubfield,subfield in field.__dict__.iteritems():
    457                                                         if   numpy.size(subfield)==numberofvertices1:
     457                                                        if   np.size(subfield)==numberofvertices1:
    458458                                                                setattr(fieldr,solutionsubfield,subfield[pos_node])
    459                                                         elif numpy.size(subfield)==numberofelements1:
     459                                                        elif np.size(subfield)==numberofelements1:
    460460                                                                setattr(fieldr,solutionsubfield,subfield[pos_elem])
    461461                                                        else:
     
    510510                                raise TypeError("extrusionexponent must be >=0")
    511511                        numlayers=args[0]
    512                         extrusionlist=(numpy.arange(0.,float(numlayers-1)+1.,1.)/float(numlayers-1))**args[1]
     512                        extrusionlist=(np.arange(0.,float(numlayers-1)+1.,1.)/float(numlayers-1))**args[1]
    513513
    514514                elif len(args)==3:    #two polynomial laws
     
    520520                                raise TypeError("lower and upper extrusionexponents must be >=0")
    521521
    522                         lowerextrusionlist=(numpy.arange(0.,1.+2./float(numlayers-1),2./float(numlayers-1)))**lowerexp/2.
    523                         upperextrusionlist=(numpy.arange(0.,1.+2./float(numlayers-1),2./float(numlayers-1)))**upperexp/2.
    524                         extrusionlist=numpy.unique(numpy.concatenate((lowerextrusionlist,1.-upperextrusionlist)))
     522                        lowerextrusionlist=(np.arange(0.,1.+2./float(numlayers-1),2./float(numlayers-1)))**lowerexp/2.
     523                        upperextrusionlist=(np.arange(0.,1.+2./float(numlayers-1),2./float(numlayers-1)))**upperexp/2.
     524                        extrusionlist=np.unique(np.concatenate((lowerextrusionlist,1.-upperextrusionlist)))
    525525
    526526                if numlayers<2:
     
    550550                md.mesh.extractedelements           = mesh2d.extractedelements
    551551
    552                 x3d=numpy.empty((0))
    553                 y3d=numpy.empty((0))
    554                 z3d=numpy.empty((0))    #the lower node is on the bed
     552                x3d=np.empty((0))
     553                y3d=np.empty((0))
     554                z3d=np.empty((0))    #the lower node is on the bed
    555555                thickness3d=md.geometry.thickness    #thickness and bed for these nodes
    556556                bed3d=md.geometry.base
     
    558558                #Create the new layers
    559559                for i in xrange(numlayers):
    560                         x3d=numpy.concatenate((x3d,md.mesh.x))
    561                         y3d=numpy.concatenate((y3d,md.mesh.y))
     560                        x3d=np.concatenate((x3d,md.mesh.x))
     561                        y3d=np.concatenate((y3d,md.mesh.y))
    562562                        #nodes are distributed between bed and surface accordingly to the given exponent
    563                         z3d=numpy.concatenate((z3d,(bed3d+thickness3d*extrusionlist[i]).reshape(-1)))
    564                 number_nodes3d=numpy.size(x3d)    #number of 3d nodes for the non extruded part of the mesh
     563                        z3d=np.concatenate((z3d,(bed3d+thickness3d*extrusionlist[i]).reshape(-1)))
     564                number_nodes3d=np.size(x3d)    #number of 3d nodes for the non extruded part of the mesh
    565565
    566566                #Extrude elements
    567                 elements3d=numpy.empty((0,6),int)
     567                elements3d=np.empty((0,6),int)
    568568                for i in xrange(numlayers-1):
    569                         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
    570                 number_el3d=numpy.size(elements3d,axis=0)    #number of 3d nodes for the non extruded part of the mesh
     569                        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
     570                number_el3d=np.size(elements3d,axis=0)    #number of 3d nodes for the non extruded part of the mesh
    571571
    572572                #Keep a trace of lower and upper nodes
    573                 lowervertex=-1*numpy.ones(number_nodes3d,int)
    574                 uppervertex=-1*numpy.ones(number_nodes3d,int)
    575                 lowervertex[md.mesh.numberofvertices:]=numpy.arange(1,(numlayers-1)*md.mesh.numberofvertices+1)
    576                 uppervertex[:(numlayers-1)*md.mesh.numberofvertices]=numpy.arange(md.mesh.numberofvertices+1,number_nodes3d+1)
     573                lowervertex=np.nan*np.ones(number_nodes3d,int)
     574                uppervertex=np.nan*np.ones(number_nodes3d,int)
     575                lowervertex[md.mesh.numberofvertices:]=np.arange(1,(numlayers-1)*md.mesh.numberofvertices+1)
     576                uppervertex[:(numlayers-1)*md.mesh.numberofvertices]=np.arange(md.mesh.numberofvertices+1,number_nodes3d+1)
    577577                md.mesh.lowervertex=lowervertex
    578578                md.mesh.uppervertex=uppervertex
    579579
    580580                #same for lower and upper elements
    581                 lowerelements=-1*numpy.ones(number_el3d,int)
    582                 upperelements=-1*numpy.ones(number_el3d,int)
    583                 lowerelements[md.mesh.numberofelements:]=numpy.arange(1,(numlayers-2)*md.mesh.numberofelements+1)
    584                 upperelements[:(numlayers-2)*md.mesh.numberofelements]=numpy.arange(md.mesh.numberofelements+1,(numlayers-1)*md.mesh.numberofelements+1)
     581                lowerelements=np.nan*np.ones(number_el3d,int)
     582                upperelements=np.nan*np.ones(number_el3d,int)
     583                lowerelements[md.mesh.numberofelements:]=np.arange(1,(numlayers-2)*md.mesh.numberofelements+1)
     584                upperelements[:(numlayers-2)*md.mesh.numberofelements]=np.arange(md.mesh.numberofelements+1,(numlayers-1)*md.mesh.numberofelements+1)
    585585                md.mesh.lowerelements=lowerelements
    586586                md.mesh.upperelements=upperelements
     
    605605
    606606                #bedinfo and surface info
    607                 md.mesh.vertexonbase=project3d(md,'vector',numpy.ones(md.mesh.numberofvertices2d,bool),'type','node','layer',1)
    608                 md.mesh.vertexonsurface=project3d(md,'vector',numpy.ones(md.mesh.numberofvertices2d,bool),'type','node','layer',md.mesh.numberoflayers)
     607                md.mesh.vertexonbase=project3d(md,'vector',np.ones(md.mesh.numberofvertices2d,bool),'type','node','layer',1)
     608                md.mesh.vertexonsurface=project3d(md,'vector',np.ones(md.mesh.numberofvertices2d,bool),'type','node','layer',md.mesh.numberoflayers)
    609609                md.mesh.vertexonboundary=project3d(md,'vector',md.mesh.vertexonboundary,'type','node')
    610610
     
    630630
    631631                #connectivity
    632                 md.mesh.elementconnectivity=numpy.tile(md.mesh.elementconnectivity,(numlayers-1,1))
    633                 md.mesh.elementconnectivity[numpy.nonzero(md.mesh.elementconnectivity==0)]=-sys.maxint-1
    634                 if not numpy.isnan(md.mesh.elementconnectivity).all():
     632                md.mesh.elementconnectivity=np.tile(md.mesh.elementconnectivity,(numlayers-1,1))
     633                md.mesh.elementconnectivity[np.nonzero(md.mesh.elementconnectivity==0)]=-sys.maxint-1
     634                if not np.isnan(md.mesh.elementconnectivity).all():
    635635                        for i in xrange(1,numlayers-1):
    636636                                md.mesh.elementconnectivity[i*md.mesh.numberofelements2d:(i+1)*md.mesh.numberofelements2d,:] \
    637637                                                =md.mesh.elementconnectivity[i*md.mesh.numberofelements2d:(i+1)*md.mesh.numberofelements2d,:]+md.mesh.numberofelements2d
    638                                 md.mesh.elementconnectivity[numpy.nonzero(md.mesh.elementconnectivity<0)]=0
     638                                md.mesh.elementconnectivity[np.nonzero(md.mesh.elementconnectivity<0)]=0
    639639
    640640                md.materials.extrude(md)
     
    674674
    675675                #observations
    676                 if not numpy.isnan(md.inversion.vx_obs).all(): md.inversion.vx_obs=project2d(md,md.inversion.vx_obs,md.mesh.numberoflayers)
    677                 if not numpy.isnan(md.inversion.vy_obs).all(): md.inversion.vy_obs=project2d(md,md.inversion.vy_obs,md.mesh.numberoflayers)
    678                 if not numpy.isnan(md.inversion.vel_obs).all(): md.inversion.vel_obs=project2d(md,md.inversion.vel_obs,md.mesh.numberoflayers)
    679                 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)
    680                 if isinstance(md.inversion.min_parameters,numpy.ndarray):
     676                if not np.isnan(md.inversion.vx_obs).all(): md.inversion.vx_obs=project2d(md,md.inversion.vx_obs,md.mesh.numberoflayers)
     677                if not np.isnan(md.inversion.vy_obs).all(): md.inversion.vy_obs=project2d(md,md.inversion.vy_obs,md.mesh.numberoflayers)
     678                if not np.isnan(md.inversion.vel_obs).all(): md.inversion.vel_obs=project2d(md,md.inversion.vel_obs,md.mesh.numberoflayers)
     679                if not np.isnan(md.inversion.cost_functions_coefficients).all(): md.inversion.cost_functions_coefficients=project2d(md,md.inversion.cost_functions_coefficients,md.mesh.numberoflayers)
     680                if isinstance(md.inversion.min_parameters,np.ndarray):
    681681                    if md.inversion.min_parameters.size>1: md.inversion.min_parameters=project2d(md,md.inversion.min_parameters,md.mesh.numberoflayers)
    682                 if isinstance(md.inversion.max_parameters,numpy.ndarray):
     682                if isinstance(md.inversion.max_parameters,np.ndarray):
    683683                    if md.inversion.max_parameters.size>1: md.inversion.max_parameters=project2d(md,md.inversion.max_parameters,md.mesh.numberoflayers)
    684                 if not numpy.isnan(md.smb.mass_balance).all():
     684                if not np.isnan(md.smb.mass_balance).all():
    685685                        md.smb.mass_balance=project2d(md,md.smb.mass_balance,md.mesh.numberoflayers)
    686686               
    687687                #results
    688                 if not numpy.isnan(md.initialization.vx).all(): md.initialization.vx=DepthAverage(md,md.initialization.vx)
    689                 if not numpy.isnan(md.initialization.vy).all(): md.initialization.vy=DepthAverage(md,md.initialization.vy)
    690                 if not numpy.isnan(md.initialization.vz).all(): md.initialization.vz=DepthAverage(md,md.initialization.vz)
    691                 if not numpy.isnan(md.initialization.vel).all(): md.initialization.vel=DepthAverage(md,md.initialization.vel)
    692                 if not numpy.isnan(md.initialization.temperature).all(): md.initialization.temperature=DepthAverage(md,md.initialization.temperature)
    693                 if not numpy.isnan(md.initialization.pressure).all(): md.initialization.pressure=project2d(md,md.initialization.pressure,1)
    694                 if not numpy.isnan(md.initialization.sediment_head).all(): md.initialization.sediment_head=project2d(md,md.initialization.sediment_head,1)
    695                 if not numpy.isnan(md.initialization.epl_head).all(): md.initialization.epl_head=project2d(md,md.initialization.epl_head,1)
    696                 if not numpy.isnan(md.initialization.epl_thickness).all(): md.initialization.epl_thickness=project2d(md,md.initialization.epl_thickness,1)
     688                if not np.isnan(md.initialization.vx).all(): md.initialization.vx=DepthAverage(md,md.initialization.vx)
     689                if not np.isnan(md.initialization.vy).all(): md.initialization.vy=DepthAverage(md,md.initialization.vy)
     690                if not np.isnan(md.initialization.vz).all(): md.initialization.vz=DepthAverage(md,md.initialization.vz)
     691                if not np.isnan(md.initialization.vel).all(): md.initialization.vel=DepthAverage(md,md.initialization.vel)
     692                if not np.isnan(md.initialization.temperature).all(): md.initialization.temperature=DepthAverage(md,md.initialization.temperature)
     693                if not np.isnan(md.initialization.pressure).all(): md.initialization.pressure=project2d(md,md.initialization.pressure,1)
     694                if not np.isnan(md.initialization.sediment_head).all(): md.initialization.sediment_head=project2d(md,md.initialization.sediment_head,1)
     695                if not np.isnan(md.initialization.epl_head).all(): md.initialization.epl_head=project2d(md,md.initialization.epl_head,1)
     696                if not np.isnan(md.initialization.epl_thickness).all(): md.initialization.epl_thickness=project2d(md,md.initialization.epl_thickness,1)
    697697
    698698                #gia
    699                 if not numpy.isnan(md.gia.mantle_viscosity).all(): md.gia.mantle_viscosity=project2d(md,md.gia.mantle_viscosity,1)
    700                 if not numpy.isnan(md.gia.lithosphere_thickness).all(): md.gia.lithosphere_thickness=project2d(md,md.gia.lithosphere_thickness,1)
     699                if not np.isnan(md.gia.mantle_viscosity).all(): md.gia.mantle_viscosity=project2d(md,md.gia.mantle_viscosity,1)
     700                if not np.isnan(md.gia.lithosphere_thickness).all(): md.gia.lithosphere_thickness=project2d(md,md.gia.lithosphere_thickness,1)
    701701
    702702                #elementstype
    703                 if not numpy.isnan(md.flowequation.element_equation).all():
     703                if not np.isnan(md.flowequation.element_equation).all():
    704704                        md.flowequation.element_equation=project2d(md,md.flowequation.element_equation,1)
    705705                        md.flowequation.vertex_equation=project2d(md,md.flowequation.vertex_equation,1)
     
    725725                md.stressbalance.loadingforce=project2d(md,md.stressbalance.loadingforce,md.mesh.numberoflayers)
    726726                md.masstransport.spcthickness=project2d(md,md.masstransport.spcthickness,md.mesh.numberoflayers)
    727                 if not numpy.isnan(md.damage.spcdamage).all(): md.damage.spcdamage=project2d(md,md.damage.spcdamage,md.mesh.numberoflayers-1)
     727                if not np.isnan(md.damage.spcdamage).all(): md.damage.spcdamage=project2d(md,md.damage.spcdamage,md.mesh.numberoflayers-1)
    728728                md.thermal.spctemperature=project2d(md,md.thermal.spctemperature,md.mesh.numberoflayers-1)
    729729
     
    752752                md.geometry.thickness=project2d(md,md.geometry.thickness,1)
    753753                md.geometry.base=project2d(md,md.geometry.base,1)
    754                 if isinstance(md.geometry.bed,numpy.ndarray):
     754                if isinstance(md.geometry.bed,np.ndarray):
    755755                    md.geometry.bed=project2d(md,md.geometry.bed,1)
    756756                md.mask.groundedice_levelset=project2d(md,md.mask.groundedice_levelset,1)
     
    758758
    759759                #lat long
    760                 if isinstance(md.mesh.lat,numpy.ndarray):
     760                if isinstance(md.mesh.lat,np.ndarray):
    761761                    if md.mesh.lat.size==md.mesh.numberofvertices:  md.mesh.lat=project2d(md,md.mesh.lat,1)
    762                 if isinstance(md.mesh.long,numpy.ndarray):
     762                if isinstance(md.mesh.long,np.ndarray):
    763763                    if md.mesh.long.size==md.mesh.numberofvertices: md.mesh.long=project2d(md,md.mesh.long,1)
    764764
     
    770770                mesh.numberofelements=md.mesh.numberofelements2d
    771771                mesh.elements=md.mesh.elements2d
    772                 if not numpy.isnan(md.mesh.vertexonboundary).all(): mesh.vertexonboundary=project2d(md,md.mesh.vertexonboundary,1)
    773                 if not numpy.isnan(md.mesh.elementconnectivity).all(): mesh.elementconnectivity=project2d(md,md.mesh.elementconnectivity,1)
     772                if not np.isnan(md.mesh.vertexonboundary).all(): mesh.vertexonboundary=project2d(md,md.mesh.vertexonboundary,1)
     773                if not np.isnan(md.mesh.elementconnectivity).all(): mesh.elementconnectivity=project2d(md,md.mesh.elementconnectivity,1)
    774774                md.mesh=mesh
    775775
  • issm/trunk-jpl/src/m/classes/outputdefinition.py

    r21254 r21303  
    22from checkfield import checkfield
    33from WriteData import WriteData
    4 import numpy as np
     4import numpy as  np
    55
    66class outputdefinition(object):
  • issm/trunk-jpl/src/m/classes/qmu.py

    r21254 r21303  
    1 import numpy
     1import numpy as np
    22from project3d import project3d
    33from collections import OrderedDict
     
    105105        # }}}
    106106        def extrude(self,md): # {{{
    107                 self.partition=project3d(md,'vector',numpy.transpose(self.partition),'type','node')
     107                self.partition=project3d(md,'vector',np.transpose(self.partition),'type','node')
    108108                return self
    109109        #}}}
     
    120120                        md.checkmessage("concurrency should be set to 1 when running dakota in library mode")
    121121                if md.qmu.partition:
    122                         if not numpy.size(md.qmu.partition)==md.mesh.numberofvertices:
     122                        if not np.size(md.qmu.partition)==md.mesh.numberofvertices:
    123123                                md.checkmessage("user supplied partition for qmu analysis should have size md.mesh.numberofvertices x 1")
    124124                        if not min(md.qmu.partition)==0:
  • issm/trunk-jpl/src/m/classes/results.py

    r21049 r21303  
    1 import numpy
     1import numpy as np
    22from pairoptions import pairoptions
    33from fielddisplay import fielddisplay
  • issm/trunk-jpl/src/m/classes/rifts.py

    r21245 r21303  
    1 import numpy
     1import numpy as np
    22from fielddisplay import fielddisplay
    33from checkfield import checkfield
     
    3333        #}}}
    3434        def checkconsistency(self,md,solution,analyses):    # {{{
    35                 if (not self.riftstruct) or numpy.any(isnans(self.riftstruct)):
     35                if (not self.riftstruct) or np.any(isnans(self.riftstruct)):
    3636                        numrifts=0
    3737                else:
     
    4343                        if not isinstance(self.riftstruct,list):
    4444                                md.checkmessage("rifts.riftstruct should be a structure!")
    45                         if numpy.any(md.mesh.segmentmarkers>=2):
     45                        if np.any(md.mesh.segmentmarkers>=2):
    4646                                #We have segments with rift markers, but no rift structure!
    4747                                md.checkmessage("model should be processed for rifts (run meshprocessrifts)!")
     
    4949                                md = checkfield(md,'fieldname',"rifts.riftstruct[%d]['fill']" % i,'values',['Water','Air','Ice','Melange',0,1,2,3])
    5050                else:
    51                         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))):
    5252                                md.checkmessage("riftstruct should be NaN since numrifts is 0!")
    5353
     
    5757
    5858                #Process rift info
    59                 if (not self.riftstruct) or numpy.any(isnans(self.riftstruct)):
     59                if (not self.riftstruct) or np.any(isnans(self.riftstruct)):
    6060                        numrifts=0
    6161                else:
     
    6464                numpairs=0
    6565                for rift in self.riftstruct:
    66                         numpairs+=numpy.size(rift['penaltypairs'],axis=0)
     66                        numpairs+=np.size(rift['penaltypairs'],axis=0)
    6767
    6868                # Convert strings in riftstruct to hard coded numbers
     
    7676
    7777                # 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.
    78                 data=numpy.zeros((numpairs,12))
     78                data=np.zeros((numpairs,12))
    7979                count=0
    8080                for rift in self.riftstruct:
    81                         numpairsforthisrift=numpy.size(rift['penaltypairs'],0)
     81                        numpairsforthisrift=np.size(rift['penaltypairs'],0)
    8282                        data[count:count+numpairsforthisrift,0:7]=rift['penaltypairs']
    8383                        data[count:count+numpairsforthisrift,7]=rift['fill']
  • issm/trunk-jpl/src/m/classes/slr.py

    r21295 r21303  
    22from MatlabFuncs import *
    33from model import *
    4 from numpy import *
     4import numpy as np
    55from checkfield import checkfield
    66from WriteData import WriteData
     
    1515       
    1616        def __init__(self): # {{{
    17                 self.deltathickness    = NaN
    18                 self.sealevel          = NaN
     17                self.deltathickness    = float('NaN')
     18                self.sealevel          = float('NaN')
    1919                self.maxiter           = 0
    2020                self.reltol            = 0
     
    6060               
    6161                #Convergence criterion: absolute, relative and residual
    62                 self.reltol=NaN #default
     62                self.reltol=float('NaN') #default
    6363                self.abstol=0.001 #1 mm of sea level rise
    6464
     
    9595                        return md
    9696
    97                 md = checkfield(md,'fieldname','slr.deltathickness','NaN',1,'Inf',1,'size',[md.mesh.numberofelements,1])
    98                 md = checkfield(md,'fieldname','slr.sealevel','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices,1])
     97                md = checkfield(md,'fieldname','slr.deltathickness','NaN',1,'Inf',1,'size',[md.mesh.numberofelements])
     98                md = checkfield(md,'fieldname','slr.sealevel','NaN',1,'Inf',1,'size',[md.mesh.numberofvertices])
    9999                md = checkfield(md,'fieldname','slr.love_h','NaN',1,'Inf',1)
    100100                md = checkfield(md,'fieldname','slr.love_k','NaN',1,'Inf',1)
  • issm/trunk-jpl/src/m/classes/steadystate.py

    r21049 r21303  
    1 import numpy
     1import numpy as np
    22from fielddisplay import fielddisplay
    33from checkfield import checkfield
     
    5454                        md.checkmessage("for a steadystate computation, timestepping.time_step must be zero.")
    5555
    56                 if numpy.isnan(md.stressbalance.reltol):
     56                if np.isnan(md.stressbalance.reltol):
    5757                        md.checkmessage("for a steadystate computation, stressbalance.reltol (relative convergence criterion) must be defined!")
    5858
  • issm/trunk-jpl/src/m/classes/stressbalance.py

    r21049 r21303  
    1 import numpy
     1import numpy as np
    22import sys
    33import copy
     
    149149                #singular solution
    150150#               if ~any((~isnan(md.stressbalance.spcvx)+~isnan(md.stressbalance.spcvy))==2),
    151                 if not numpy.any(numpy.logical_and(numpy.logical_not(numpy.isnan(md.stressbalance.spcvx)),numpy.logical_not(numpy.isnan(md.stressbalance.spcvy)))):
     151                if not np.any(np.logical_and(np.logical_not(np.isnan(md.stressbalance.spcvx)),np.logical_not(np.isnan(md.stressbalance.spcvy)))):
    152152                        print "\n !!! Warning: no spc applied, model might not be well posed if no basal friction is applied, check for solution crash\n"
    153153                #CHECK THAT EACH LINES CONTAINS ONLY NAN VALUES OR NO NAN VALUES
    154154#               if any(sum(isnan(md.stressbalance.referential),2)~=0 & sum(isnan(md.stressbalance.referential),2)~=6),
    155                 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)):
     155                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)):
    156156                        md.checkmessage("Each line of stressbalance.referential should contain either only NaN values or no NaN values")
    157157                #CHECK THAT THE TWO VECTORS PROVIDED ARE ORTHOGONAL
    158158#               if any(sum(isnan(md.stressbalance.referential),2)==0),
    159                 if numpy.any(numpy.sum(numpy.isnan(md.stressbalance.referential),axis=1)==0):
    160                         pos=[i for i,item in enumerate(numpy.sum(numpy.isnan(md.stressbalance.referential),axis=1)) if item==0]
    161 #                       numpy.inner (and numpy.dot) calculate all the dot product permutations, resulting in a full matrix multiply
    162 #                       if numpy.any(numpy.abs(numpy.inner(md.stressbalance.referential[pos,0:2],md.stressbalance.referential[pos,3:5]).diagonal())>sys.float_info.epsilon):
     159                if np.any(np.sum(np.isnan(md.stressbalance.referential),axis=1)==0):
     160                        pos=[i for i,item in enumerate(np.sum(np.isnan(md.stressbalance.referential),axis=1)) if item==0]
     161#                       np.inner (and np.dot) calculate all the dot product permutations, resulting in a full matrix multiply
     162#                       if np.any(np.abs(np.inner(md.stressbalance.referential[pos,0:2],md.stressbalance.referential[pos,3:5]).diagonal())>sys.float_info.epsilon):
    163163#                               md.checkmessage("Vectors in stressbalance.referential (columns 1 to 3 and 4 to 6) must be orthogonal")
    164164                        for item in md.stressbalance.referential[pos,:]:
    165                                 if numpy.abs(numpy.inner(item[0:2],item[3:5]))>sys.float_info.epsilon:
     165                                if np.abs(np.inner(item[0:2],item[3:5]))>sys.float_info.epsilon:
    166166                                        md.checkmessage("Vectors in stressbalance.referential (columns 1 to 3 and 4 to 6) must be orthogonal")
    167167                #CHECK THAT NO rotation specified for FS Grounded ice at base
    168168                if m.strcmp(md.mesh.domaintype(),'3D') and md.flowequation.isFS:
    169                         pos=numpy.nonzero(numpy.logical_and(md.mask.groundedice_levelset,md.mesh.vertexonbase))
    170                         if numpy.any(numpy.logical_not(numpy.isnan(md.stressbalance.referential[pos,:]))):
     169                        pos=np.nonzero(np.logical_and(md.mask.groundedice_levelset,md.mesh.vertexonbase))
     170                        if np.any(np.logical_not(np.isnan(md.stressbalance.referential[pos,:]))):
    171171                                md.checkmessage("no referential should be specified for basal vertices of grounded ice")
    172172
     
    195195                WriteData(fid,prefix,'object',self,'class','stressbalance','fieldname','referential','format','DoubleMat','mattype',1)
    196196               
    197                 if isinstance(self.loadingforce, (list, tuple, numpy.ndarray)):
     197                if isinstance(self.loadingforce, (list, tuple, np.ndarray)):
    198198                        lx=self.loadingforce[:,0];
    199199                        ly=self.loadingforce[:,1];
  • issm/trunk-jpl/src/m/classes/taoinversion.py

    r21049 r21303  
    1 import numpy
     1import numpy as np
    22from project3d import project3d
    33from WriteData import WriteData
     
    125125
    126126
    127                 num_controls= numpy.numel(md.inversion.control_parameters)
    128                 num_costfunc= numpy.size(md.inversion.cost_functions,2)
     127                num_controls= np.numel(md.inversion.control_parameters)
     128                num_costfunc= np.size(md.inversion.cost_functions,2)
    129129
    130130                md = checkfield(md,'fieldname','inversion.iscontrol','values',[0, 1])
     
    155155
    156156                if solution=='BalancethicknessSolution':
    157                         md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices, 1],'NaN',1,'Inf',1)
     157                        md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices],'NaN',1,'Inf',1)
    158158                elif solution=='BalancethicknessSoftSolution':
    159                         md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices, 1],'NaN',1,'Inf',1)
     159                        md = checkfield(md,'fieldname','inversion.thickness_obs','size',[md.mesh.numberofvertices],'NaN',1,'Inf',1)
    160160                else:
    161                         md = checkfield(md,'fieldname','inversion.vx_obs','size',[md.mesh.numberofvertices, 1],'NaN',1,'Inf',1)
    162                         md = checkfield(md,'fieldname','inversion.vy_obs','size',[md.mesh.numberofvertices, 1],'NaN',1,'Inf',1)
     161                        md = checkfield(md,'fieldname','inversion.vx_obs','size',[md.mesh.numberofvertices],'NaN',1,'Inf',1)
     162                        md = checkfield(md,'fieldname','inversion.vy_obs','size',[md.mesh.numberofvertices],'NaN',1,'Inf',1)
    163163
    164164                def marshall(self, md, fid):
     
    188188
    189189                        #process control parameters
    190                         num_control_parameters = numpy.numel(self.control_parameters)
     190                        num_control_parameters = np.numel(self.control_parameters)
    191191                        WriteData(fid,prefix,'object',self,'fieldname','control_parameters','format','StringArray')
    192192                        WriteData(fid,prefix,'data',num_control_parameters,'name','md.inversion.num_control_parameters','format','Integer')
    193193
    194194                        #process cost functions
    195                         num_cost_functions = numpy.size(self.cost_functions,2)
     195                        num_cost_functions = np.size(self.cost_functions,2)
    196196                        data= marshallcostfunctions(self.cost_functions)
    197197                        WriteData(fid,prefix,'data',data,'name','md.inversion.cost_functions','format','StringArray')
  • issm/trunk-jpl/src/m/classes/thermal.py

    r21049 r21303  
    1 import numpy
     1import numpy as  np
    22from project3d import project3d
    33from fielddisplay import fielddisplay
    44from checkfield import checkfield
    55from WriteData import WriteData
    6 import MatlabFuncs as m
    76
    87class thermal(object):
     
    4443                #}}}
    4544        def extrude(self,md): # {{{
    46                 self.spctemperature=project3d(md,'vector',self.spctemperature,'type','node','layer',md.mesh.numberoflayers,'padding',numpy.nan)
    47                 if isinstance(md.initialization.temperature,numpy.ndarray) and numpy.size(md.initialization.temperature,axis=0)==md.mesh.numberofvertices:
    48                         self.spctemperature=float('nan')*numpy.ones((md.mesh.numberofvertices,1))
    49                         pos=numpy.nonzero(md.mesh.vertexonsurface)[0]
     45                self.spctemperature=project3d(md,'vector',self.spctemperature,'type','node','layer',md.mesh.numberoflayers,'padding',np.nan)
     46                if isinstance(md.initialization.temperature,np.ndarray) and np.size(md.initialization.temperature,axis=0)==md.mesh.numberofvertices:
     47                        self.spctemperature=float('NaN')*np.ones((md.mesh.numberofvertices))
     48                        pos=np.where(md.mesh.vertexonsurface)[0]
    5049                        self.spctemperature[pos]=md.initialization.temperature[pos]    #impose observed temperature on surface
    5150                return self
     
    9594                md = checkfield(md,'fieldname','thermal.stabilization','numel',[1],'values',[0,1,2])
    9695                md = checkfield(md,'fieldname','thermal.spctemperature','Inf',1,'timeseries',1)
     96                md = checkfield(md,'fieldname','thermal.requested_outputs','stringrow',1)
     97
    9798                if 'EnthalpyAnalysis' in analyses and md.thermal.isenthalpy and md.mesh.dimension()==3:
    98                         pos=numpy.nonzero(numpy.logical_not(numpy.isnan(md.thermal.spctemperature[0:md.mesh.numberofvertices])))
    99                         replicate=numpy.tile(md.geometry.surface-md.mesh.z,(1,numpy.size(md.thermal.spctemperature,axis=1)))
    100                         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")
     99                        pos=np.where(~np.isnan(md.thermal.spctemperature[0:md.mesh.numberofvertices]))
     100                        try:
     101                                spccol=np.size(md.thermal.spctemperature,1)
     102                        except IndexError:
     103                                spccol=1
     104                        replicate=np.tile(md.geometry.surface-md.mesh.z,(spccol))
     105                        control=md.materials.meltingpoint-md.materials.beta*md.materials.rho_ice*md.constants.g*replicate
     106                        md = checkfield(md,'fieldname','thermal.spctemperature','field',md.thermal.spctemperature[pos],'<=',control[pos],'message',"spctemperature should be below the adjusted melting point")
    101107                        md = checkfield(md,'fieldname','thermal.isenthalpy','numel',[1],'values',[0,1])
    102108                        md = checkfield(md,'fieldname','thermal.isdynamicbasalspc','numel',[1],'values',[0,1]);
    103109                        if(md.thermal.isenthalpy):
    104                                 if numpy.isnan(md.stressbalance.reltol):
     110                                if np.isnan(md.stressbalance.reltol):
    105111                                        md.checkmessage("for a steadystate computation, thermal.reltol (relative convergence criterion) must be defined!")
    106112                                md = checkfield(md,'fieldname','thermal.reltol','>',0.,'message',"reltol must be larger than zero");
    107                 md = checkfield(md,'fieldname','thermal.requested_outputs','stringrow',1)
     113
    108114
    109115                return md
  • issm/trunk-jpl/src/m/consistency/checkfield.py

    r20913 r21303  
    1 import numpy
     1import numpy as np
    22import os
    33from pairoptions import pairoptions
     
    4444
    4545        if isinstance(field,(bool,int,long,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.{}=field[:,0]".format(fieldname))
     66                                         print('{} had a bad dimension, we fixed it but you should check it'.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]:
     70                        if   np.isnan(fieldsize[0]):
     71                                if not np.size(field,1)==fieldsize[1]:
    6672                                        md = md.checkmessage(options.getfieldvalue('message',\
    6773                                                "field '%s' should have %d columns" % (fieldname,fieldsize[1])))
    68                         elif numpy.isnan(fieldsize[1]):
    69                                 if not numpy.size(field,0)==fieldsize[0]:
     74                        elif np.isnan(fieldsize[1]):
     75                                if not np.size(field,0)==fieldsize[0]:
    7076                                        md = md.checkmessage(options.getfieldvalue('message',\
    7177                                                "field '%s' should have %d lines" % (fieldname,fieldsize[0])))
    7278                        else:
    73                                 if (not numpy.size(field,0)==fieldsize[0]) or (not numpy.size(field,1)==fieldsize[1]):
     79                                if (not np.size(field,0)==fieldsize[0]) or (not np.size(field,1)==fieldsize[1]):
    7480                                        md = md.checkmessage(options.getfieldvalue('message',\
    7581                                                "field '%s' size should be %d x %d" % (fieldname,fieldsize[0],fieldsize[1])))
     
    7884        if options.exist('numel'):
    7985                fieldnumel=options.getfieldvalue('numel')
    80                 if numpy.size(field) not in fieldnumel:
     86                if 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))
     
    97103        #check Inf
    98104        if options.getfieldvalue('Inf',0):
    99                 if numpy.any(numpy.isinf(field)):
     105                if np.any(np.isinf(field)):
    100106                        md = md.checkmessage(options.getfieldvalue('message',\
    101107                                "Inf values found in field '%s'" % fieldname))
     
    124130        if options.exist('>='):
    125131                lowerbound=options.getfieldvalue('>=')
    126                 if numpy.any(field<lowerbound):
     132                if np.any(field<lowerbound):
    127133                        md = md.checkmessage(options.getfieldvalue('message',\
    128134                                "field '%s' should have values above %d" % (fieldname,lowerbound)))
    129135        if options.exist('>'):
    130136                lowerbound=options.getfieldvalue('>')
    131                 if numpy.any(field<=lowerbound):
     137                if np.any(field<=lowerbound):
    132138                        md = md.checkmessage(options.getfieldvalue('message',\
    133139                                "field '%s' should have values above %d" % (fieldname,lowerbound)))
     
    136142        if options.exist('<='):
    137143                upperbound=options.getfieldvalue('<=')
    138                 if numpy.any(field>upperbound):
     144                if np.any(field>upperbound):
    139145                        md = md.checkmessage(options.getfieldvalue('message',\
    140146                                "field '%s' should have values below %d" % (fieldname,upperbound)))
    141147        if options.exist('<'):
    142148                upperbound=options.getfieldvalue('<')
    143                 if numpy.any(field>=upperbound):
     149                if np.any(field>=upperbound):
    144150                        md = md.checkmessage(options.getfieldvalue('message',\
    145151                                "field '%s' should have values below %d" % (fieldname,upperbound)))
     
    158164        #Check forcings (size and times)
    159165        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:
     166                if   np.size(field,0)==md.mesh.numberofvertices:
     167                        if np.ndim(field)>1 and not np.size(field,1)==1:
    162168                                md = md.checkmessage(options.getfieldvalue('message',\
    163169                                        "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,:])):
     170                elif np.size(field,0)==md.mesh.numberofvertices+1 or np.size(field,0)==2:
     171                        if not all(field[-1,:]==np.sort(field[-1,:])):
    166172                                md = md.checkmessage(options.getfieldvalue('message',\
    167173                                        "field '%s' columns should be sorted chronologically" % fieldname))
     
    175181        #Check single value forcings (size and times)
    176182        if options.getfieldvalue('singletimeseries',0):
    177                 if numpy.size(field,0)==2:
    178                         if not all(field[-1,:]==numpy.sort(field[-1,:])):
     183                if np.size(field,0)==2:
     184                        if not all(field[-1,:]==np.sort(field[-1,:])):
    179185                                md = md.checkmessage(options.getfieldvalue('message',\
    180186                                                "field '%s' columns should be sorted chronologically" % fieldname))
  • issm/trunk-jpl/src/m/contrib/defleurian/netCDF/export_netCDF.py

    r21268 r21303  
    11from netCDF4 import Dataset, stringtochar
    2 import numpy as np
     2import numpy as  np
    33import time
    44import collections
     
    4242        typelist=[bool,str,unicode,int,float,complex,
    4343                                                collections.OrderedDict,
    44                                                 numpy.int64,numpy.ndarray,numpy.float64]
     44                                                np.int64,np.ndarray,np.float64]
    4545        groups=dict.keys(md.__dict__)
    4646        for group in groups:
     
    121121        TypeDict = {float:'f8',
    122122                                                        'float64':'f8',
    123                                                         numpy.float64:'f8',
     123                                                        np.float64:'f8',
    124124                                                        int:'i8',
    125125                                                        'int64':'i8',
    126                                                         numpy.int64:'i8',
     126                                                        np.int64:'i8',
    127127                                                        str:str,
    128128                                                        dict:str}
  • issm/trunk-jpl/src/m/contrib/defleurian/paraview/enveloppeVTK.py

    r20786 r21303  
    1 import numpy
     1import numpy as np
    22import os
    33import model
     
    4040                os.mkdir(filename)
    4141
    42         IsEnveloppe=numpy.where(model.mesh.vertexonbase | model.mesh.vertexonsurface)
     42        IsEnveloppe=np.where(model.mesh.vertexonbase | model.mesh.vertexonsurface)
    4343        #get the element related variables
    4444        if 'z' in dict.keys(model.mesh.__dict__):
    45                 points=numpy.column_stack((model.mesh.x,model.mesh.y,model.mesh.z))
    46                 num_of_elt=numpy.size(numpy.isnan(model.mesh.lowerelements))+numpy.size(numpy.isnan(model.mesh.upperelements))
    47                 low_elt_num=numpy.size(numpy.isnan(model.mesh.lowerelements))
    48                 top_elt_num=numpy.size(numpy.isnan(model.mesh.upperelements))
     45                points=np.column_stack((model.mesh.x,model.mesh.y,model.mesh.z))
     46                num_of_elt=np.size(np.isnan(model.mesh.lowerelements))+np.size(np.isnan(model.mesh.upperelements))
     47                low_elt_num=np.size(np.isnan(model.mesh.lowerelements))
     48                top_elt_num=np.size(np.isnan(model.mesh.upperelements))
    4949        else:
    50                 points=numpy.column_stack((model.mesh.x,model.mesh.y,numpy.zeros(numpy.shape(model.mesh.x))))
    51                 num_of_elt=numpy.shape(model.mesh.elements)[0]
     50                points=np.column_stack((model.mesh.x,model.mesh.y,np.zeros(np.shape(model.mesh.x))))
     51                num_of_elt=np.shape(model.mesh.elements)[0]
    5252               
    53         num_of_points=numpy.size(points)[0]
    54         dim=numpy.size(points)[1]
    55         point_per_elt=numpy.shape(model.mesh.elements)[1]
     53        num_of_points=np.size(points)[0]
     54        dim=np.size(points)[1]
     55        point_per_elt=np.shape(model.mesh.elements)[1]
    5656               
    5757        celltype=5 #triangles
     
    6767                for solution in solnames:
    6868                        #looking for multiple time steps
    69                         if (numpy.size(res_struct.__dict__[solution])>num_of_timesteps):
    70                                 num_of_timesteps=numpy.size(res_struct.__dict__[solution])
     69                        if (np.size(res_struct.__dict__[solution])>num_of_timesteps):
     70                                num_of_timesteps=np.size(res_struct.__dict__[solution])
    7171                                num_of_timesteps=int(num_of_timesteps)+1
    7272        else:
     
    106106                        for sol in solnames:
    107107                                #dealing with results on different timesteps
    108                                 if(numpy.size(res_struct.__dict__[sol])>timestep):
     108                                if(np.size(res_struct.__dict__[sol])>timestep):
    109109                                        timestep = step
    110110                                else:
    111                                         timestep = numpy.size(res_struct.__dict__[sol])
     111                                        timestep = np.size(res_struct.__dict__[sol])
    112112                               
    113113                                #getting the  fields in the solution
    114                                 if(numpy.size(res_struct.__dict__[sol])>1):
     114                                if(np.size(res_struct.__dict__[sol])>1):
    115115                                        fieldnames=dict.keys(res_struct.__dict__[sol].__getitem__(timestep-1).__dict__)
    116116                                else:
     
    118118                                #check which field is a real result and print
    119119                                for field in fieldnames:
    120                                         if(numpy.size(res_struct.__dict__[sol])>1):
     120                                        if(np.size(res_struct.__dict__[sol])>1):
    121121                                                fieldstruct=res_struct.__dict__[sol].__getitem__(timestep-1).__dict__[field]
    122122                                        else:
    123123                                                fieldstruct=res_struct.__dict__[sol].__dict__[field]
    124124
    125                                         if ((numpy.size(fieldstruct))==num_of_points):
     125                                        if ((np.size(fieldstruct))==num_of_points):
    126126                                                fid.write('SCALARS %s float 1 \n' % field)
    127127                                                fid.write('LOOKUP_TABLE default\n')
    128128                                                for node in range(0,num_of_points):
    129129                                                        #paraview does not like NaN, replacing
    130                                                         if numpy.isnan(fieldstruct[node]):
     130                                                        if np.isnan(fieldstruct[node]):
    131131                                                                fid.write('%e\n' % -9999.9999)
    132132                                                        #also checking for verry small value that mess up
     
    143143                        for field in othernames:
    144144#                               fprintf(fid,s,res_struct.(fieldnames{k})(IsEnveloppe));
    145                                 if ((numpy.size(other_struct.__dict__[field]))==num_of_points):
     145                                if ((np.size(other_struct.__dict__[field]))==num_of_points):
    146146                                        fid.write('SCALARS %s float 1 \n' % field)
    147147                                        fid.write('LOOKUP_TABLE default\n')
    148148                                        for node in range(0,num_of_points):
    149149                                                #paraview does not like NaN, replacing
    150                                                 if numpy.isnan(other_struct.__dict__[field][node]):
     150                                                if np.isnan(other_struct.__dict__[field][node]):
    151151                                                        fid.write('%e\n' % -9999.9999)
    152152                                                #also checking for verry small value that mess up
  • issm/trunk-jpl/src/m/contrib/defleurian/paraview/exportVTK.py

    r21130 r21303  
    1 import numpy
     1import numpy as np
    22import os
    33import model
     
    4242        #get the element related variables
    4343        if 'z' in dict.keys(model.mesh.__dict__):
    44                 points=numpy.column_stack((model.mesh.x,model.mesh.y,model.mesh.z))
     44                points=np.column_stack((model.mesh.x,model.mesh.y,model.mesh.z))
    4545                dim=3
    4646        else:
    47                 points=numpy.column_stack((model.mesh.x,model.mesh.y,numpy.zeros(numpy.shape(model.mesh.x))))
     47                points=np.column_stack((model.mesh.x,model.mesh.y,np.zeros(np.shape(model.mesh.x))))
    4848                dim=2
    4949
    50         num_of_points=numpy.size(model.mesh.x)
    51         num_of_elt=numpy.shape(model.mesh.elements)[0]
    52         point_per_elt=numpy.shape(model.mesh.elements)[1]
     50        num_of_points=np.size(model.mesh.x)
     51        num_of_elt=np.shape(model.mesh.elements)[0]
     52        point_per_elt=np.shape(model.mesh.elements)[1]
    5353               
    5454        #Select the type of element function of the number of nodes per elements
     
    7070                for solution in solnames:
    7171                        #looking for multiple time steps
    72                         if (numpy.size(res_struct.__dict__[solution])>num_of_timesteps):
    73                                 num_of_timesteps=numpy.size(res_struct.__dict__[solution])
     72                        if (np.size(res_struct.__dict__[solution])>num_of_timesteps):
     73                                num_of_timesteps=np.size(res_struct.__dict__[solution])
    7474                                num_of_timesteps=int(num_of_timesteps)
    7575        else:
     
    112112                        for sol in solnames:
    113113                                #dealing with results on different timesteps
    114                                 if(numpy.size(res_struct.__dict__[sol])>timestep):
     114                                if(np.size(res_struct.__dict__[sol])>timestep):
    115115                                        timestep = step
    116116                                else:
    117                                         timestep = numpy.size(res_struct.__dict__[sol])
     117                                        timestep = np.size(res_struct.__dict__[sol])
    118118                               
    119119                                #getting the  fields in the solution
    120                                 if(numpy.size(res_struct.__dict__[sol])>1):
     120                                if(np.size(res_struct.__dict__[sol])>1):
    121121                                        fieldnames=dict.keys(res_struct.__dict__[sol].__getitem__(timestep).__dict__)
    122122                                else:
     
    124124                                #check which field is a real result and print
    125125                                for field in fieldnames:
    126                                         if(numpy.size(res_struct.__dict__[sol])>1):
     126                                        if(np.size(res_struct.__dict__[sol])>1):
    127127                                                fieldstruct=res_struct.__dict__[sol].__getitem__(timestep).__dict__[field]
    128128                                        else:
    129129                                                fieldstruct=res_struct.__dict__[sol].__dict__[field]
    130130
    131                                         if ((numpy.size(fieldstruct))==num_of_points):
     131                                        if ((np.size(fieldstruct))==num_of_points):
    132132                                                fid.write('SCALARS %s float 1 \n' % field)
    133133                                                fid.write('LOOKUP_TABLE default\n')
    134134                                                for node in range(0,num_of_points):
    135135                                                        #paraview does not like NaN, replacing
    136                                                         if numpy.isnan(fieldstruct[node]):
     136                                                        if np.isnan(fieldstruct[node]):
    137137                                                                fid.write('%e\n' % -9999.9999)
    138138                                                        #also checking for verry small value that mess up
     
    148148                        othernames=(dict.keys(other_struct.__dict__))
    149149                        for field in othernames:
    150                                 if ((numpy.size(other_struct.__dict__[field]))==num_of_points):
     150                                if ((np.size(other_struct.__dict__[field]))==num_of_points):
    151151                                        fid.write('SCALARS %s float 1 \n' % field)
    152152                                        fid.write('LOOKUP_TABLE default\n')
    153153                                        for node in range(0,num_of_points):
    154154                                                #paraview does not like NaN, replacing
    155                                                 if numpy.isnan(other_struct.__dict__[field][node]):
     155                                                if np.isnan(other_struct.__dict__[field][node]):
    156156                                                        fid.write('%e\n' % -9999.9999)
    157157                                                #also checking for verry small value that mess up
  • issm/trunk-jpl/src/m/contrib/morlighem/bamg/YamsCall.py

    r17480 r21303  
    1 import numpy
     1import numpy as np
    22import time
    33import subprocess
     
    3737        t1=time.time()
    3838        print "%s" % '      computing metric...'
    39         metric=ComputeMetric(hessian,scale,epsilon,hmin,hmax,numpy.empty(0,int))
     39        metric=ComputeMetric(hessian,scale,epsilon,hmin,hmax,np.empty(0,int))
    4040        t2=time.time()
    4141        print "%s%d%s\n" % (' done (',t2-t1,' seconds)')
     
    4444        t1=time.time()
    4545        print "%s" % '      writing initial mesh files...'
    46         numpy.savetxt('carre0.met',metric)
     46        np.savetxt('carre0.met',metric)
    4747
    4848        f=open('carre0.mesh','w')
     
    6666
    6767        #Deal with rifts
    68         if numpy.any(not numpy.isnan(md.rifts.riftstruct)):
     68        if np.any(not np.isnan(md.rifts.riftstruct)):
    6969
    7070                #we have the list of triangles that make up the rift. keep those triangles around during refinement.
    71                 triangles=numpy.empty(0,int)
     71                triangles=np.empty(0,int)
    7272                for riftstruct in md.rifts.riftstruct:
    73                         triangles=numpy.concatenate((triangles,riftstruct.segments[:,2]))
     73                        triangles=np.concatenate((triangles,riftstruct.segments[:,2]))
    7474
    75                 f.write("\n\n%s\n%i\n\n" % ('RequiredTriangles',numpy.size(triangles)))
     75                f.write("\n\n%s\n%i\n\n" % ('RequiredTriangles',np.size(triangles)))
    7676                for triangle in triangles:
    7777                        f.write("%i\n" % triangle)
     
    9797        t1=time.time()
    9898        print "\n%s" % '      reading final mesh files...'
    99         Tria=numpy.loadtxt('carre1.tria',int)
    100         Coor=numpy.loadtxt('carre1.coor',float)
     99        Tria=np.loadtxt('carre1.tria',int)
     100        Coor=np.loadtxt('carre1.coor',float)
    101101        md.mesh.x=Coor[:,0]
    102102        md.mesh.y=Coor[:,1]
    103         md.mesh.z=numpy.zeros((numpy.size(Coor,axis=0),1))
     103        md.mesh.z=np.zeros((np.size(Coor,axis=0),1))
    104104        md.mesh.elements=Tria
    105         md.mesh.numberofvertices=numpy.size(Coor,axis=0)
    106         md.mesh.numberofelements=numpy.size(Tria,axis=0)
     105        md.mesh.numberofvertices=np.size(Coor,axis=0)
     106        md.mesh.numberofelements=np.size(Tria,axis=0)
    107107        numberofelements2=md.mesh.numberofelements
    108108        t2=time.time()
  • issm/trunk-jpl/src/m/coordsystems/gmtmask.py

    r21069 r21303  
    11from MatlabFuncs import *
    22from model import *
    3 from numpy import *
     3from np.import *
    44from os import getenv, putenv
    55import subprocess
  • issm/trunk-jpl/src/m/coordsystems/ll2xy.py

    r21254 r21303  
    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/m/coordsystems/xy2ll.py

    r21254 r21303  
    1 import numpy as np
     1import numpy as  np
    22from math import pi
    33
     
    3737                raise StandardError('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
  • issm/trunk-jpl/src/m/exp/expcoarsen.py

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

    r21278 r21303  
    11from expread import expread
    2 import numpy as np
     2import numpy as  np
    33from matplotlib.path import Path
    44import matplotlib.patches as patches
  • issm/trunk-jpl/src/m/exp/expread.py

    r17731 r21303  
    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 xrange(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/m/exp/expwrite.py

    r19459 r21303  
    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/m/extrusion/DepthAverage.py

    r21254 r21303  
    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/m/extrusion/project2d.py

    r21254 r21303  
    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/m/extrusion/project3d.py

    r17725 r21303  
    1 import numpy
     1import numpy as np
    22from pairoptions import pairoptions
    33
     
    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,long,float)) or numpy.size(vector2d)==1:
     43        if isinstance(vector2d,(bool,int,long,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 xrange(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 xrange(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 xrange(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 xrange(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 xrange(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 xrange(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/m/geometry/FlagElements.py

    r20910 r21303  
    1 import numpy
     1import numpy as np
    22import os
    33#from basinzoom import basinzoon
     
    2424        if   isinstance(region,(str,unicode)):
    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
     
    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/m/geometry/GetAreas.py

    r13984 r21303  
    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/m/geometry/SegIntersect.py

    r13503 r21303  
    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/m/geometry/slope.py

    r21254 r21303  
    1 import numpy as np
     1import numpy as  np
    22from GetNodalFunctionsCoeff import  GetNodalFunctionsCoeff
    33
  • issm/trunk-jpl/src/m/interp/SectionValues.py

    r21254 r21303  
    11import os
    22from expread import expread
    3 import numpy as np
     3import numpy as  np
    44from project2d import project2d
    55#from InterpFromMesh2d import InterpFromMesh2d
  • issm/trunk-jpl/src/m/interp/averaging.py

    r21254 r21303  
    1 import numpy as np
     1import numpy as  np
    22from GetAreas import GetAreas
    33import MatlabFuncs as m
     
    8282                average_node = csc_matrix(average_node)
    8383        else:
    84                 average_node=csc_matrix(data.reshape(-1,1))
     84                average_node=csc_matrix(data.reshape(-1,))
    8585
    8686        #loop over iteration
  • issm/trunk-jpl/src/m/interp/holefiller.py

    r21254 r21303  
    1 import numpy as np
     1import numpy as  np
    22from scipy.spatial import cKDTree
    33
  • issm/trunk-jpl/src/m/interp/interp.py

    r21254 r21303  
    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/m/io/loadvars.py

    r21268 r21303  
    11import shelve
    22import os.path
    3 import numpy as np
     3import numpy as  np
    44from netCDF4 import Dataset
    55from netCDF4 import chartostring
     
    77from os import path
    88from whichdb import whichdb
     9from collections import OrderedDict
    910from model import *
    1011
     
    130131                                                                        Tree[t].__dict__[str(var)]=varval[0]
    131132                                                        else:
    132                                                                 if varval[0]==u'':
     133                                                                if str(varval[0])=='':
    133134                                                                        Tree.__dict__[str(var)]=[]
    134135                                                                elif varval[0]=='True':
     
    167168                                                        #dealling with dict
    168169                                                        if varval.dtype==str:
    169                                                                 Tree.__dict__[str(var)]=dict(zip(varval[:,0], varval[:,1]))
     170                                                                Tree.__dict__[str(var)]=OrderedDict(zip(varval[:,0], varval[:,1]))
    170171                                                        else:
    171172                                                                if type(Tree)==list:
     
    178179                                                                else:
    179180                                                                        Tree.__dict__[str(var)]=varval[:,:]
     181                                                        try:
     182                                                                print('treated {}.{} with type {}'.format(mod,var,type(Tree.__dict__[str(var)])))
     183                                                        except AttributeError:
     184                                                                print('treated {}.{} with type {}'.format(mod,var,type(Tree[0].__dict__[str(var)])))
    180185                                                elif vardim==3:
    181186                                                        if type(Tree)==list:
  • issm/trunk-jpl/src/m/materials/TMeltingPoint.py

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

    r20628 r21303  
    1 import numpy
     1import numpy as np
    22
    33def cuffey(temperature):
     
    1313        """
    1414       
    15         if numpy.any(temperature<0.):
     15        if np.any(temperature<0.):
    1616                raise RuntimeError("input temperature should be in Kelvin (positive)")
    1717       
    1818        T = temperature-273.15
    1919
    20         rigidity=numpy.zeros_like(T)
    21         pos=numpy.nonzero(T<=-45)
     20        rigidity=np.zeros_like(T)
     21        pos=np.nonzero(T<=-45)
    2222        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))
     23        pos=np.nonzero(np.logical_and(-45<=T,T<-40))
    2424        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))
     25        pos=np.nonzero(np.logical_and(-40<=T,T<-35))
    2626        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))
     27        pos=np.nonzero(np.logical_and(-35<=T,T<-30))
    2828        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))
     29        pos=np.nonzero(np.logical_and(-30<=T,T<-25))
    3030        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))
     31        pos=np.nonzero(np.logical_and(-25<=T,T<-20))
    3232        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))
     33        pos=np.nonzero(np.logical_and(-20<=T,T<-15))
    3434        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))
     35        pos=np.nonzero(np.logical_and(-15<=T,T<-10))
    3636        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))
     37        pos=np.nonzero(np.logical_and(-10<=T,T<-5))
    3838        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))
     39        pos=np.nonzero(np.logical_and(-5<=T,T<-2))
    4040        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)
     41        pos=np.nonzero(-2<=T)
    4242        rigidity[pos]=10**8*(-0.000132282004110*(T[pos]+2)**3 +0.003209542058346*(T[pos]+2)**2    -0.051381363322371*(T[pos]+2)+ 0.837883605537096)
    4343
    4444        #Now make sure that rigidity is positive
    45         pos=numpy.nonzero(rigidity<0)
     45        pos=np.nonzero(rigidity<0)
    4646        rigidity[pos]=1**6
    4747
  • issm/trunk-jpl/src/m/materials/cuffeytemperate.py

    r20628 r21303  
    1 import numpy
     1import numpy as np
    22import cuffey
    33
     
    1515        """
    1616
    17         if numpy.any(temperature<0.):
     17        if np.any(temperature<0.):
    1818                raise RuntimeError("input temperature should be in Kelvin (positive)")
    1919
    20         if (numpy.any(temperature.shape~=waterfraction.shape)),
     20        if (np.any(temperature.shape~=waterfraction.shape)),
    2121                error('input temperature and waterfraction should have same size!');
    2222        end
    23         if numpy.any(waterfraction<0 | waterfraction>1)
     23        if np.any(waterfraction<0 | waterfraction>1)
    2424                error('input waterfraction should be between 0 and 1');
    2525        end
    2626
    27         rigidity=numpy.multiply(cuffey(temperature), (1*numpy.ones(waterfraction.shape)+181.25*numpy.maximum(numpy.zeros(waterfraction.shape), numpy.minimum(0.01*numpy.ones(waterfraction.shape), waterfraction)))**(-1/stressexp));
     27        rigidity=np.multiply(cuffey(temperature), (1*np.ones(waterfraction.shape)+181.25*np.maximum(np.zeros(waterfraction.shape), np.minimum(0.01*np.ones(waterfraction.shape), waterfraction)))**(-1/stressexp));
    2828
    2929        return rigidity
  • issm/trunk-jpl/src/m/materials/paterson.py

    r17864 r21303  
    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/m/mech/analyticaldamage.py

    r21254 r21303  
    1 import numpy as np
     1import numpy as  np
    22from averaging import averaging
    33#from plotmodel import plotmodel
  • issm/trunk-jpl/src/m/mech/backstressfrominversion.py

    r21254 r21303  
    1 import numpy as np
     1import numpy as  np
    22from averaging import averaging
    33from thomasparams import thomasparams
  • issm/trunk-jpl/src/m/mech/calcbackstress.py

    r21254 r21303  
    1 import numpy as np
     1import numpy as  np
    22from averaging import averaging
    33from thomasparams import thomasparams
  • issm/trunk-jpl/src/m/mech/damagefrominversion.py

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

    r21275 r21303  
    1 import numpy as np
     1import numpy as  np
    22from GetNodalFunctionsCoeff import GetNodalFunctionsCoeff
    33from results import results
  • issm/trunk-jpl/src/m/mech/robintemperature.py

    r21254 r21303  
    1 import numpy as np
     1import numpy as  np
    22from scipy.special import erf
    33
  • issm/trunk-jpl/src/m/mech/steadystateiceshelftemp.py

    r21254 r21303  
    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/m/mech/thomasparams.py

    r21254 r21303  
    1 import numpy as np
     1import numpy as  np
    22from averaging import averaging
    33
  • issm/trunk-jpl/src/m/mesh/ComputeHessian.py

    r17488 r21303  
    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'):
     
    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)),np.tile(areas.reshape(-1,),(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)),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,0]*alpha,axis=1)
     48        grad_ely=np.sum(field[index-1,0]*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)),np.tile((areas*grad_elx).reshape(-1,),(3,1)),numberofnodes,1)
     52        grady=m.sparse(line,np.ones((linesize,1)),np.tile((areas*grad_ely).reshape(-1,),(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).reshape(-1,),np.sum(grady[index-1,0]*alpha,axis=1).reshape(-1,),np.sum(grady[index-1,0]*beta,axis=1).reshape(-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)),np.tile((areas*hessian[:,0]).reshape(-1,),(3,1)),numberofnodes,1)/weights,
     62                                                                                         m.sparse(line,np.ones((linesize,1)),np.tile((areas*hessian[:,1]).reshape(-1,),(3,1)),numberofnodes,1)/weights,
     63                                                                                         m.sparse(line,np.ones((linesize,1)),np.tile((areas*hessian[:,2]).reshape(-1,),(3,1)),numberofnodes,1)/weights ))
    6464
    6565        return hessian
  • issm/trunk-jpl/src/m/mesh/ComputeMetric.py

    r15749 r21303  
    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/m/mesh/ElementsFromEdge.py

    r17497 r21303  
    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/m/mesh/GetNodalFunctionsCoeff.py

    r13984 r21303  
    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/m/mesh/bamg.py

    r20910 r21303  
    11import os.path
    2 import numpy
     2import numpy as  np
    33from mesh2d import mesh2d
    44from collections import OrderedDict
     
    9494                        if i:
    9595                                flags=ContourToNodes(domaini['x'],domaini['y'],domainfile,0)[0]
    96                                 if numpy.any(numpy.logical_not(flags)):
     96                                if np.any(np.logical_not(flags)):
    9797                                        raise RuntimeError("bamg error message: All holes should be strictly inside the principal domain")
    9898
    9999                        #Add all points to bamg_geometry
    100100                        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))))))
     101                        bamg_geometry.Vertices=np.vstack((bamg_geometry.Vertices,np.vstack((domaini['x'][0:nods],domaini['y'][0:nods],np.ones((nods)))).T))
     102                        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))
    103103                        if i:
    104                                 bamg_geometry.SubDomains=numpy.vstack((bamg_geometry.SubDomains,[2,count+1,1,1]))
     104                                bamg_geometry.SubDomains=np.vstack((bamg_geometry.SubDomains,[2,count+1,1,1]))
     105
     106                        # bamg_geometry.Vertices=np.hstack((bamg_geometry.Vertices,np.vstack((domaini['x'][0:nods].reshape(-1),domaini['y'][0:nods].reshape(-1),np.ones((nods))))))
     107                        # bamg_geometry.Edges   =np.vstack((bamg_geometry.Edges,np.hstack((np.arange(count+1,count+nods+1).reshape(-1,),np.hstack((np.arange(count+2,count+nods+1),count+1)).reshape(-1,),1.*np.ones((nods,))))))
     108                        # if i:
     109                        #       bamg_geometry.SubDomains=np.vstack((bamg_geometry.SubDomains,[2,count+1,1,1]))
    105110
    106111                        #update counter
     
    120125                                #detect whether all points of the rift are inside the domain
    121126                                flags=ContourToNodes(rifti['x'],rifti['y'],domain[0],0)[0]
    122                                 if numpy.all(numpy.logical_not(flags)):
     127                                if np.all(np.logical_not(flags)):
    123128                                        raise RuntimeError("one rift has all its points outside of the domain outline")
    124129
    125                                 elif numpy.any(numpy.logical_not(flags)):
     130                                elif np.any(np.logical_not(flags)):
    126131                                        #We LOTS of work to do
    127132                                        print "Rift tip outside of or on the domain has been detected and is being processed..."
    128133
    129134                                        #check that only one point is outside (for now)
    130                                         if numpy.sum(numpy.logical_not(flags).astype(int))!=1:
     135                                        if np.sum(np.logical_not(flags).astype(int))!=1:
    131136                                                raise RuntimeError("bamg error message: only one point outside of the domain is supported yet")
    132137
     
    136141                                                pass
    137142                                        elif not flags[-1]:
    138                                                 rifti['x']=numpy.flipud(rifti['x'])
    139                                                 rifti['y']=numpy.flipud(rifti['y'])
     143                                                rifti['x']=np.flipud(rifti['x'])
     144                                                rifti['y']=np.flipud(rifti['y'])
    140145                                        else:
    141146                                                raise RuntimeError("bamg error message: only a rift tip can be outside of the domain")
     
    146151                                        x2=rifti['x'][1]
    147152                                        y2=rifti['y'][1]
    148                                         for j in xrange(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]]])):
     153                                        for j in xrange(0,np.size(domain[0]['x'])-1):
     154                                                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]]])):
    150155
    151156                                                        #Get position of the two nodes of the edge in domain
     
    161166#                                                       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]);
    162167#                                                       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]]))
     168                                                        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]]))
     169                                                        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]]))
    165170
    166171                                                        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):
     172                                                        tipdis=np.array([sqrt((x-x3)**2+(y-y3)**2),sqrt((x-x4)**2+(y-y4)**2)])
     173
     174                                                        if np.min(tipdis)/segdis < options.getfieldvalue('toltip',0):
    170175                                                                print "moving tip-domain intersection point"
    171176
     
    179184                                                                #OK, now we can add our own rift
    180185                                                                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))))))
     186                                                                bamg_geometry.Vertices=np.vstack((bamg_geometry.Vertices,np.hstack((rifti['x'][1:].reshape(-1,),rifti['y'][1:].reshape(-1,),np.ones((nods,1))))))
     187                                                                bamg_geometry.Edges=np.vstack((bamg_geometry.Edges,\
     188                                                                        np.array([[pos,count+1,(1+i)]]),\
     189                                                                        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))))))
    185190                                                                count+=nods
    186191
     
    189194                                                        else:
    190195                                                                #Add intersection point to Vertices
    191                                                                 bamg_geometry.Vertices=numpy.vstack((bamg_geometry.Vertices,numpy.array([[x,y,1]])))
     196                                                                bamg_geometry.Vertices=np.vstack((bamg_geometry.Vertices,np.array([[x,y,1]])))
    192197                                                                count+=1
    193198
    194199                                                                #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]
     200                                                                pos=np.nonzero(np.logical_and(bamg_geometry.Edges[:,0]==i1,bamg_geometry.Edges[:,1]==i2))[0]
    196201                                                                if not pos:
    197202                                                                        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]]]),\
     203                                                                bamg_geometry.Edges=np.vstack((bamg_geometry.Edges[0:pos-1,:],\
     204                                                                        np.array([[bamg_geometry.Edges[pos,0],count                     ,bamg_geometry.Edges[pos,2]]]),\
     205                                                                        np.array([[count                     ,bamg_geometry.Edges[pos,1],bamg_geometry.Edges[pos,2]]]),\
    201206                                                                        bamg_geometry.Edges[pos+1:,:]))
    202207
    203208                                                                #OK, now we can add our own rift
    204209                                                                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))))))
     210                                                                bamg_geometry.Vertices=np.vstack((bamg_geometry.Vertices,np.hstack((rifti['x'][1:].reshape(-1,),rifti['y'][1:].reshape(-1,),np.ones((nods,1))))))
     211                                                                bamg_geometry.Edges=np.vstack((bamg_geometry.Edges,\
     212                                                                        np.array([[count,count+1,2]]),\
     213                                                                        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))))))
    209214                                                                count+=nods
    210215
     
    213218                                else:
    214219                                        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))))
     220                                        bamg_geometry.Vertices=np.vstack(bamg_geometry.Vertices, np.hstack(rifti['x'][:],rifti['y'][:],np.ones((nods+1,1))))
     221                                        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))))
    217222                                        count=+nods+1
    218223
     
    224229                        if all(isinstance(track,(str,unicode))):
    225230                                A=expread(track)
    226                                 track=numpy.hstack((A.x.reshape(-1,1),A.y.reshape(-1,1)))
     231                                track=np.hstack((A.x.reshape(-1,),A.y.reshape(-1,)))
    227232                        else:
    228233                                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))))
     234                        if np.size(track,axis=1)==2:
     235                                track=np.hstack((track,3.*np.ones((size(track,axis=0),1))))
    231236
    232237                        #only keep those inside
    233238                        flags=ContourToNodes(track[:,0],track[:,1],domainfile,0)[0]
    234                         track=track[numpy.nonzero(flags),:]
     239                        track=track[np.nonzero(flags),:]
    235240
    236241                        #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))))))
     242                        nods=np.size(track,axis=0)
     243                        bamg_geometry.Vertices=np.vstack((bamg_geometry.Vertices,track))
     244                        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))))))
    240245
    241246                        #update counter
     
    247252                        #recover RequiredVertices
    248253                        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))))
     254                        if np.size(requiredvertices,axis=1)==2:
     255                                requiredvertices=np.hstack((requiredvertices,4.*np.ones((np.size(requiredvertices,axis=0),1))))
    251256
    252257                        #only keep those inside
    253258                        flags=ContourToNodes(requiredvertices[:,0],requiredvertices[:,1],domainfile,0)[0]
    254                         requiredvertices=requiredvertices[numpy.nonzero(flags)[0],:]
     259                        requiredvertices=requiredvertices[np.nonzero(flags)[0],:]
    255260                        #Add all points to bamg_geometry
    256                         nods=numpy.size(requiredvertices,axis=0)
    257                         bamg_geometry.Vertices=numpy.vstack((bamg_geometry.Vertices,requiredvertices))
     261                        nods=np.size(requiredvertices,axis=0)
     262                        bamg_geometry.Vertices=np.vstack((bamg_geometry.Vertices,requiredvertices))
    258263
    259264                        #update counter
     
    275280                        bamg_mesh=bamgmesh(md.private.bamg['mesh'].__dict__)
    276281                else:
    277                         bamg_mesh.Vertices=numpy.hstack((md.mesh.x.reshape(-1,1),md.mesh.y.reshape(-1,1),numpy.ones((md.mesh.numberofvertices,1))))
    278                         bamg_mesh.Triangles=numpy.hstack((md.mesh.elements,numpy.ones((md.mesh.numberofelements,1))))
     282                        bamg_mesh.Vertices=np.vstack((md.mesh.x,md.mesh.y,np.ones((md.mesh.numberofvertices)))).T
     283                        #bamg_mesh.Vertices=np.hstack((md.mesh.x.reshape(-1,),md.mesh.y.reshape(-1,),np.ones((md.mesh.numberofvertices,1))))
     284                        bamg_mesh.Triangles=np.hstack((md.mesh.elements,np.ones((md.mesh.numberofelements,1))))
    279285
    280286                if isinstance(md.rifts.riftstruct,dict):
     
    286292        bamg_options['coeff']=options.getfieldvalue('coeff',1.)
    287293        bamg_options['cutoff']=options.getfieldvalue('cutoff',10.**-5)
    288         bamg_options['err']=options.getfieldvalue('err',numpy.array([[0.01]]))
     294        bamg_options['err']=options.getfieldvalue('err',np.array([[0.01]]))
    289295        bamg_options['errg']=options.getfieldvalue('errg',0.1)
    290         bamg_options['field']=options.getfieldvalue('field',numpy.empty((0,1)))
     296        bamg_options['field']=options.getfieldvalue('field',np.empty((0,1)))
    291297        bamg_options['gradation']=options.getfieldvalue('gradation',1.5)
    292298        bamg_options['Hessiantype']=options.getfieldvalue('Hessiantype',0)
    293299        bamg_options['hmin']=options.getfieldvalue('hmin',10.**-100)
    294300        bamg_options['hmax']=options.getfieldvalue('hmax',10.**100)
    295         bamg_options['hminVertices']=options.getfieldvalue('hminVertices',numpy.empty((0,1)))
    296         bamg_options['hmaxVertices']=options.getfieldvalue('hmaxVertices',numpy.empty((0,1)))
    297         bamg_options['hVertices']=options.getfieldvalue('hVertices',numpy.empty((0,1)))
     301        bamg_options['hminVertices']=options.getfieldvalue('hminVertices',np.empty((0,1)))
     302        bamg_options['hmaxVertices']=options.getfieldvalue('hmaxVertices',np.empty((0,1)))
     303        bamg_options['hVertices']=options.getfieldvalue('hVertices',np.empty((0,1)))
    298304        bamg_options['KeepVertices']=options.getfieldvalue('KeepVertices',1)
    299305        bamg_options['MaxCornerAngle']=options.getfieldvalue('MaxCornerAngle',10.)
    300306        bamg_options['maxnbv']=options.getfieldvalue('maxnbv',10**6)
    301307        bamg_options['maxsubdiv']=options.getfieldvalue('maxsubdiv',10.)
    302         bamg_options['metric']=options.getfieldvalue('metric',numpy.empty((0,1)))
     308        bamg_options['metric']=options.getfieldvalue('metric',np.empty((0,1)))
    303309        bamg_options['Metrictype']=options.getfieldvalue('Metrictype',0)
    304310        bamg_options['nbjacobi']=options.getfieldvalue('nbjacobi',1)
     
    328334
    329335        #Fill in rest of fields:
    330         md.mesh.numberofelements=numpy.size(md.mesh.elements,axis=0)
    331         md.mesh.numberofvertices=numpy.size(md.mesh.x)
    332         md.mesh.numberofedges=numpy.size(md.mesh.edges,axis=0)
    333         md.mesh.vertexonboundary=numpy.zeros(md.mesh.numberofvertices,bool)
     336        md.mesh.numberofelements=np.size(md.mesh.elements,axis=0)
     337        md.mesh.numberofvertices=np.size(md.mesh.x)
     338        md.mesh.numberofedges=np.size(md.mesh.edges,axis=0)
     339        md.mesh.vertexonboundary=np.zeros(md.mesh.numberofvertices,bool)
    334340        md.mesh.vertexonboundary[md.mesh.segments[:,0:2]-1]=True
    335341        md.mesh.elementconnectivity=md.private.bamg['mesh'].ElementConnectivity
    336         md.mesh.elementconnectivity[numpy.nonzero(numpy.isnan(md.mesh.elementconnectivity))]=0
     342        md.mesh.elementconnectivity[np.nonzero(np.isnan(md.mesh.elementconnectivity))]=0
    337343        md.mesh.elementconnectivity=md.mesh.elementconnectivity.astype(int)
    338344
    339345        #Check for orphan
    340         if numpy.any(numpy.logical_not(numpy.in1d(numpy.arange(1,md.mesh.numberofvertices+1),md.mesh.elements.flat))):
     346        if np.any(np.logical_not(np.in1d(np.arange(1,md.mesh.numberofvertices+1),md.mesh.elements.flat))):
    341347                raise RuntimeError("Output mesh has orphans. Decrease MaxCornerAngle to prevent outside points (ex: 0.01)")
    342348
     
    349355        print "Checking Edge crossing..."
    350356        i=0
    351         while (i<numpy.size(geom.Edges,axis=0)):
     357        while (i<np.size(geom.Edges,axis=0)):
    352358
    353359                #edge counter
     
    362368
    363369                j=i    #test edges located AFTER i only
    364                 while (j<numpy.size(geom.Edges,axis=0)):
     370                while (j<np.size(geom.Edges,axis=0)):
    365371
    366372                        #edge counter
     
    379385
    380386                        #Check if the two edges are crossing one another
    381                         if SegIntersect(numpy.array([[x1,y1],[x2,y2]]),numpy.array([[x3,y3],[x4,y4]])):
     387                        if SegIntersect(np.array([[x1,y1],[x2,y2]]),np.array([[x3,y3],[x4,y4]])):
    382388
    383389                                #Get coordinate of intersection point (http://mathworld.wolfram.com/Line-LineIntersection.html)
    384                                 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]])))
    385                                 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]])))
     390                                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]])))
     391                                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]])))
    386392
    387393                                #Add vertex to the list of vertices
    388                                 geom.Vertices=numpy.vstack((geom.Vertices,[x,y,min(color1,color2)]))
    389                                 id=numpy.size(geom.Vertices,axis=0)
     394                                geom.Vertices=np.vstack((geom.Vertices,[x,y,min(color1,color2)]))
     395                                id=np.size(geom.Vertices,axis=0)
    390396
    391397                                #Update edges i and j
     
    393399                                edgej=geom.Edges[j,:].copy()
    394400                                geom.Edges[i,:]    =[edgei(0),id      ,edgei(2)]
    395                                 geom.Edges=numpy.vstack((geom.Edges,[id      ,edgei(1),edgei(2)]))
     401                                geom.Edges=np.vstack((geom.Edges,[id      ,edgei(1),edgei(2)]))
    396402                                geom.Edges[j,:]    =[edgej(0),id      ,edgej(2)]
    397                                 geom.Edges=numpy.vstack((geom.Edges,[id      ,edgej(1),edgej(2)]))
     403                                geom.Edges=np.vstack((geom.Edges,[id      ,edgej(1),edgej(2)]))
    398404
    399405                                #update current edge second tip
     
    405411        i=0
    406412        num=0
    407         while (i<numpy.size(geom.Vertices,axis=0)):
     413        while (i<np.size(geom.Vertices,axis=0)):
    408414
    409415                #vertex counter
     
    423429
    424430                        #update edges
    425                         posedges=numpy.nonzero(geom.Edges==i)
     431                        posedges=np.nonzero(geom.Edges==i)
    426432                        geom.Edges[posedges[0],:]=[]
    427                         posedges=numpy.nonzero(geom.Edges>i)
     433                        posedges=np.nonzero(geom.Edges>i)
    428434                        geom.Edges[posedges]=geom.Edges[posedges]-1
    429435
  • issm/trunk-jpl/src/m/mesh/meshconvert.py

    r17558 r21303  
    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/m/mesh/planet/gmsh/gmshplanet.py

    r21069 r21303  
    11from MatlabFuncs import *
    22from model import *
    3 from numpy import *
     3from np.import *
    44from pairoptions import *
    55from mesh3dsurface import *
  • issm/trunk-jpl/src/m/mesh/rifts/meshprocessoutsiderifts.py

    r17558 r21303  
    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/m/mesh/rifts/meshprocessrifts.py

    r20910 r21303  
    1 import numpy
     1import numpy as np
    22from TriMeshProcessRifts import TriMeshProcessRifts
    33from ContourToMesh import ContourToMesh
     
    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:
     
    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/m/mesh/roundmesh.py

    r19433 r21303  
    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)
    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        x_list=np.ones(pointsonedge)
     26        y_list=np.ones(pointsonedge)
     27        theta=np.linspace(0.,2.*np.pi,num=pointsonedge,endpoint=False)
     28        x_list=roundsigfig(radius*x_list*np.cos(theta),12)
     29        y_list=roundsigfig(radius*y_list*np.sin(theta),12)
    3030        A=OrderedDict()
    3131        A['x']=[x_list]
     
    3939
    4040        #move the closest node to the center
    41         pos=numpy.argmin(md.mesh.x**2+md.mesh.y**2)
     41        pos=np.argmin(md.mesh.x**2+md.mesh.y**2)
    4242        md.mesh.x[pos]=0.
    4343        md.mesh.y[pos]=0.
     
    5050def roundsigfig(x,n):
    5151
    52         digits=numpy.ceil(numpy.log10(numpy.abs(x)))
     52        digits=np.ceil(np.log10(np.abs(x)))
    5353        x=x/10.**digits
    54         x=numpy.round(x,decimals=n)
     54        x=np.round(x,decimals=n)
    5555        x=x*10.**digits
    5656
    57         pos=numpy.nonzero(numpy.isnan(x))
     57        pos=np.nonzero(np.isnan(x))
    5858        x[pos]=0.
    5959
  • issm/trunk-jpl/src/m/mesh/squaremesh.py

    r20910 r21303  
    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.hstack((np.arange(2,ny+1).reshape(-1,),np.arange(1,ny).reshape(-1,),(2*np.arange(1,ny)-1).reshape(-1,)))
    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.hstack((np.arange(ny*(nx-1)+1,nx*ny).reshape(-1,),np.arange(ny*(nx-1)+2,nx*ny+1).reshape(-1,),2*np.arange((ny-1)*(nx-2)+1,(nx-1)*(ny-1)+1).reshape(-1,)))
    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.hstack((np.arange(2*ny,ny*nx+1,ny).reshape(-1,),np.arange(ny,ny*(nx-1)+1,ny).reshape(-1,),np.arange(2*(ny-1),2*(nx-1)*(ny-1)+1,2*(ny-1)).reshape(-1,)))
    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.hstack((np.arange(1,(nx-2)*ny+2,ny).reshape(-1,),np.arange(ny+1,ny*(nx-1)+2,ny).reshape(-1,),np.arange(1,2*(nx-2)*(ny-1)+2,2*(ny-1)).reshape(-1,)))
    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
  • issm/trunk-jpl/src/m/mesh/triangle.py

    r21174 r21303  
    11import os.path
    2 import numpy
     2import numpy as np
    33from mesh2d import mesh2d
    44from TriMesh import TriMesh
     
    5656
    5757        #Fill in rest of fields:
    58         md.mesh.numberofelements = numpy.size(md.mesh.elements,axis=0)
    59         md.mesh.numberofvertices = numpy.size(md.mesh.x)
    60         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)
    6161        md.mesh.vertexonboundary[md.mesh.segments[:,0:2]-1] = True
    6262
  • issm/trunk-jpl/src/m/miscellaneous/MatlabFuncs.py

    r17264 r21303  
    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
  • issm/trunk-jpl/src/m/miscellaneous/PythonFuncs.py

    r14211 r21303  
     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/m/miscellaneous/fielddisplay.py

    r17480 r21303  
    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/m/miscellaneous/isnans.py

    r13011 r21303  
    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/m/parameterization/contourenvelope.py

    r20910 r21303  
    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:
     42        if np.size(md.mesh.vertexconnectivity,axis=0)!=md.mesh.numberofvertices and np.size(md.mesh.vertexconnectivity,axis=0)!=md.mesh.numberofvertices2d:
    4343                md.mesh.vertexconnectivity=NodeConnectivity(md.mesh.elements,md.mesh.numberofvertices)[0]
    44         if numpy.size(md.mesh.elementconnectivity,axis=0)!=md.mesh.numberofelements and numpy.size(md.mesh.elementconnectivity,axis=0)!=md.mesh.numberofelements2d:
     44        if np.size(md.mesh.elementconnectivity,axis=0)!=md.mesh.numberofelements and np.size(md.mesh.elementconnectivity,axis=0)!=md.mesh.numberofelements2d:
    4545                md.mesh.elementconnectivity=ElementConnectivity(md.mesh.elements,md.mesh.vertexconnectivity)[0]
    4646
     
    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 xrange(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/m/parameterization/setflowequation.py

    r19535 r21303  
    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
     
    3331        #process options
    3432        options=pairoptions(*args)
    35 #       options=deleteduplicates(options,1);
     33        #       options=deleteduplicates(options,1);
    3634
    3735        #Find_out what kind of coupling to use
    3836        coupling_method=options.getfieldvalue('coupling','tiling')
    39         if not m.strcmpi(coupling_method,'tiling') and not m.strcmpi(coupling_method,'penalties'):
     37        if not coupling_method in ['tiling','penalties']:
    4038                raise TypeError("coupling type can only be: tiling or penalties")
    4139
     
    4745        FSflag   = FlagElements(md,options.getfieldvalue('FS',''))
    4846        filltype     = options.getfieldvalue('fill','none')
    49 
    5047        #Flag the elements that have not been flagged as filltype
    51         if   m.strcmpi(filltype,'SIA'):
    52                 SIAflag[numpy.nonzero(numpy.logical_not(p.logical_or_n(SSAflag,HOflag)))]=True
    53         elif m.strcmpi(filltype,'SSA'):
    54                 SSAflag[numpy.nonzero(numpy.logical_not(p.logical_or_n(SIAflag,HOflag,FSflag)))]=True
    55         elif m.strcmpi(filltype,'HO'):
    56                 HOflag[numpy.nonzero(numpy.logical_not(p.logical_or_n(SIAflag,SSAflag,FSflag)))]=True
    57 
     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
    5854        #check that each element has at least one flag
    5955        if not any(SIAflag+SSAflag+L1L2flag+HOflag+FSflag):
     
    6359        if any(SIAflag+SSAflag+L1L2flag+HOflag+FSflag>1):
    6460                print "setflowequation warning message: some elements have several types, higher order type is used for them"
    65                 SIAflag[numpy.nonzero(numpy.logical_and(SIAflag,SSAflag))]=False
    66                 SIAflag[numpy.nonzero(numpy.logical_and(SIAflag,HOflag))]=False
    67                 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')
    6873
    6974        #FS can only be used alone for now:
     
    7277
    7378        #Initialize node fields
    74         nodeonSIA=numpy.zeros(md.mesh.numberofvertices,bool)
    75         nodeonSIA[md.mesh.elements[numpy.nonzero(SIAflag),:]-1]=True
    76         nodeonSSA=numpy.zeros(md.mesh.numberofvertices,bool)
    77         nodeonSSA[md.mesh.elements[numpy.nonzero(SSAflag),:]-1]=True
    78         nodeonL1L2=numpy.zeros(md.mesh.numberofvertices,bool)
    79         nodeonL1L2[md.mesh.elements[numpy.nonzero(L1L2flag),:]-1]=True
    80         nodeonHO=numpy.zeros(md.mesh.numberofvertices,bool)
    81         nodeonHO[md.mesh.elements[numpy.nonzero(HOflag),:]-1]=True
    82         nodeonFS=numpy.zeros(md.mesh.numberofvertices,bool)
    83         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)
    8489
    8590        #First modify FSflag to get rid of elements contrained everywhere (spc + border with HO or SSA)
    8691        if any(FSflag):
    87 #               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
    88                 fullspcnodes=numpy.logical_or(numpy.logical_not(numpy.isnan(md.stressbalance.spcvx)).astype(int)+ \
    89                                               numpy.logical_not(numpy.isnan(md.stressbalance.spcvy)).astype(int)+ \
    90                                               numpy.logical_not(numpy.isnan(md.stressbalance.spcvz)).astype(int)==3, \
    91                                               numpy.logical_and(nodeonHO,nodeonFS)).astype(int)    #find all the nodes on the boundary of the domain without icefront
    92 #               fullspcelems=double(sum(fullspcnodes(md.mesh.elements),2)==6);         %find all the nodes on the boundary of the domain without icefront
    93                 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
    94                 FSflag[numpy.nonzero(fullspcelems.reshape(-1))]=False
    95                 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
    9696
    9797        #Then complete with NoneApproximation or the other model used if there is no FS
    9898        if any(FSflag):
    9999                if   any(HOflag):    #fill with HO
    100                         HOflag[numpy.logical_not(FSflag)]=True
    101                         nodeonHO[md.mesh.elements[numpy.nonzero(HOflag),:]-1]=True
     100                        HOflag[~FSflag]=True
     101                        nodeonHO[md.mesh.elements[np.where(HOflag),:]-1]=True
    102102                elif any(SSAflag):    #fill with SSA
    103                         SSAflag[numpy.logical_not(FSflag)]=True
    104                         nodeonSSA[md.mesh.elements[numpy.nonzero(SSAflag),:]-1]=True
     103                        SSAflag[~FSflag]=True
     104                        nodeonSSA[md.mesh.elements[np.where(SSAflag),:]-1]=True
    105105                else:    #fill with none
    106                         noneflag[numpy.nonzero(numpy.logical_not(FSflag))]=True
     106                        noneflag[np.where(~FSflag)]=True
    107107
    108108        #Now take care of the coupling between SSA and HO
    109         md.stressbalance.vertex_pairing=numpy.array([])
    110         nodeonSSAHO=numpy.zeros(md.mesh.numberofvertices,bool)
    111         nodeonHOFS=numpy.zeros(md.mesh.numberofvertices,bool)
    112         nodeonSSAFS=numpy.zeros(md.mesh.numberofvertices,bool)
    113         SSAHOflag=numpy.zeros(md.mesh.numberofelements,bool)
    114         SSAFSflag=numpy.zeros(md.mesh.numberofelements,bool)
    115         HOFSflag=numpy.zeros(md.mesh.numberofelements,bool)
    116         if   m.strcmpi(coupling_method,'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':
    117117                #Create the border nodes between HO and SSA and extrude them
    118118                numnodes2d=md.mesh.numberofvertices2d
    119119                numlayers=md.mesh.numberoflayers
    120                 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
    121121
    122122                #initialize and fill in penalties structure
    123                 if numpy.all(numpy.logical_not(numpy.isnan(bordernodes2d))):
    124                         penalties=numpy.zeros((0,2))
     123                if np.all(np.logical_not(np.isnan(bordernodes2d))):
     124                        penalties=np.zeros((0,2))
    125125                        for     i in xrange(1,numlayers):
    126                                 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))
    127127                        md.stressbalance.vertex_pairing=penalties
    128128
    129         elif m.strcmpi(coupling_method,'tiling'):
    130                 if   any(SSAflag) and any(HOflag):    #coupling SSA HO
     129        elif coupling_method=='tiling':
     130                if any(SSAflag) and any(HOflag):    #coupling SSA HO
    131131                        #Find node at the border
    132                         nodeonSSAHO[numpy.nonzero(numpy.logical_and(nodeonSSA,nodeonHO))]=True
     132                        nodeonSSAHO[np.where(np.logical_and(nodeonSSA,nodeonHO))]=True
    133133                        #SSA elements in contact with this layer become SSAHO elements
    134                         matrixelements=m.ismember(md.mesh.elements-1,numpy.nonzero(nodeonSSAHO)[0])
    135                         commonelements=numpy.sum(matrixelements,axis=1)!=0
    136                         commonelements[numpy.nonzero(HOflag)]=False    #only one layer: the elements previously in SSA
    137                         SSAflag[numpy.nonzero(commonelements)]=False    #these elements are now SSAHOelements
    138                         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
    139139                        nodeonSSA[:]=False
    140                         nodeonSSA[md.mesh.elements[numpy.nonzero(SSAflag),:]-1]=True
     140                        nodeonSSA[md.mesh.elements[np.where(SSAflag),:]-1]=True
    141141
    142142                        #rule out elements that don't touch the 2 boundaries
    143                         pos=numpy.nonzero(SSAHOflag)[0]
    144                         elist=numpy.zeros(numpy.size(pos),dtype=int)
    145                         elist = elist + numpy.sum(nodeonSSA[md.mesh.elements[pos,:]-1],axis=1).astype(bool)
    146                         elist = elist - numpy.sum(nodeonHO[md.mesh.elements[pos,:]-1]  ,axis=1).astype(bool)
    147                         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]
    148148                        SSAflag[pos[pos1]]=True
    149149                        SSAHOflag[pos[pos1]]=False
    150                         pos2=numpy.nonzero(elist==-1)[0]
     150                        pos2=np.where(elist==-1)[0]
    151151                        HOflag[pos[pos2]]=True
    152152                        SSAHOflag[pos[pos2]]=False
     
    154154                        #Recompute nodes associated to these elements
    155155                        nodeonSSA[:]=False
    156                         nodeonSSA[md.mesh.elements[numpy.nonzero(SSAflag),:]-1]=True
     156                        nodeonSSA[md.mesh.elements[np.where(SSAflag),:]-1]=True
    157157                        nodeonHO[:]=False
    158                         nodeonHO[md.mesh.elements[numpy.nonzero(HOflag),:]-1]=True
     158                        nodeonHO[md.mesh.elements[np.where(HOflag),:]-1]=True
    159159                        nodeonSSAHO[:]=False
    160                         nodeonSSAHO[md.mesh.elements[numpy.nonzero(SSAHOflag),:]-1]=True
     160                        nodeonSSAHO[md.mesh.elements[np.where(SSAHOflag),:]-1]=True
    161161
    162162                elif any(HOflag) and any(FSflag):    #coupling HO FS
    163163                        #Find node at the border
    164                         nodeonHOFS[numpy.nonzero(numpy.logical_and(nodeonHO,nodeonFS))]=True
     164                        nodeonHOFS[np.where(np.logical_and(nodeonHO,nodeonFS))]=True
    165165                        #FS elements in contact with this layer become HOFS elements
    166                         matrixelements=m.ismember(md.mesh.elements-1,numpy.nonzero(nodeonHOFS)[0])
    167                         commonelements=numpy.sum(matrixelements,axis=1)!=0
    168                         commonelements[numpy.nonzero(HOflag)]=False    #only one layer: the elements previously in SSA
    169                         FSflag[numpy.nonzero(commonelements)]=False    #these elements are now SSAHOelements
    170                         HOFSflag[numpy.nonzero(commonelements)]=True
    171                         nodeonFS=numpy.zeros(md.mesh.numberofvertices,bool)
    172                         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
    173173
    174174                        #rule out elements that don't touch the 2 boundaries
    175                         pos=numpy.nonzero(HOFSflag)[0]
    176                         elist=numpy.zeros(numpy.size(pos),dtype=int)
    177                         elist = elist + numpy.sum(nodeonFS[md.mesh.elements[pos,:]-1],axis=1).astype(bool)
    178                         elist = elist - numpy.sum(nodeonHO[md.mesh.elements[pos,:]-1],axis=1).astype(bool)
    179                         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]
    180180                        FSflag[pos[pos1]]=True
    181181                        HOFSflag[pos[pos1]]=False
    182                         pos2=numpy.nonzero(elist==-1)[0]
     182                        pos2=np.where(elist==-1)[0]
    183183                        HOflag[pos[pos2]]=True
    184184                        HOFSflag[pos[pos2]]=False
     
    186186                        #Recompute nodes associated to these elements
    187187                        nodeonFS[:]=False
    188                         nodeonFS[md.mesh.elements[numpy.nonzero(FSflag),:]-1]=True
     188                        nodeonFS[md.mesh.elements[np.where(FSflag),:]-1]=True
    189189                        nodeonHO[:]=False
    190                         nodeonHO[md.mesh.elements[numpy.nonzero(HOflag),:]-1]=True
     190                        nodeonHO[md.mesh.elements[np.where(HOflag),:]-1]=True
    191191                        nodeonHOFS[:]=False
    192                         nodeonHOFS[md.mesh.elements[numpy.nonzero(HOFSflag),:]-1]=True
    193 
     192                        nodeonHOFS[md.mesh.elements[np.where(HOFSflag),:]-1]=True
    194193                elif any(FSflag) and any(SSAflag):
    195194                        #Find node at the border
    196                         nodeonSSAFS[numpy.nonzero(numpy.logical_and(nodeonSSA,nodeonFS))]=True
     195                        nodeonSSAFS[np.where(np.logical_and(nodeonSSA,nodeonFS))]=True
    197196                        #FS elements in contact with this layer become SSAFS elements
    198                         matrixelements=m.ismember(md.mesh.elements-1,numpy.nonzero(nodeonSSAFS)[0])
    199                         commonelements=numpy.sum(matrixelements,axis=1)!=0
    200                         commonelements[numpy.nonzero(SSAflag)]=False    #only one layer: the elements previously in SSA
    201                         FSflag[numpy.nonzero(commonelements)]=False    #these elements are now SSASSAelements
    202                         SSAFSflag[numpy.nonzero(commonelements)]=True
    203                         nodeonFS=numpy.zeros(md.mesh.numberofvertices,bool)
    204                         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
    205204
    206205                        #rule out elements that don't touch the 2 boundaries
    207                         pos=numpy.nonzero(SSAFSflag)[0]
    208                         elist=numpy.zeros(numpy.size(pos),dtype=int)
    209                         elist = elist + numpy.sum(nodeonSSA[md.mesh.elements[pos,:]-1],axis=1).astype(bool)
    210                         elist = elist - numpy.sum(nodeonFS[md.mesh.elements[pos,:]-1]  ,axis=1).astype(bool)
    211                         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]
    212211                        SSAflag[pos[pos1]]=True
    213212                        SSAFSflag[pos[pos1]]=False
    214                         pos2=numpy.nonzero(elist==-1)[0]
     213                        pos2=np.where(elist==-1)[0]
    215214                        FSflag[pos[pos2]]=True
    216215                        SSAFSflag[pos[pos2]]=False
     
    218217                        #Recompute nodes associated to these elements
    219218                        nodeonSSA[:]=False
    220                         nodeonSSA[md.mesh.elements[numpy.nonzero(SSAflag),:]-1]=True
     219                        nodeonSSA[md.mesh.elements[np.where(SSAflag),:]-1]=True
    221220                        nodeonFS[:]=False
    222                         nodeonFS[md.mesh.elements[numpy.nonzero(FSflag),:]-1]=True
     221                        nodeonFS[md.mesh.elements[np.where(FSflag),:]-1]=True
    223222                        nodeonSSAFS[:]=False
    224                         nodeonSSAFS[md.mesh.elements[numpy.nonzero(SSAFSflag),:]-1]=True
     223                        nodeonSSAFS[md.mesh.elements[np.where(SSAFSflag),:]-1]=True
    225224
    226225                elif any(FSflag) and any(SIAflag):
     
    228227
    229228        #Create SSAHOApproximation where needed
    230         md.flowequation.element_equation=numpy.zeros(md.mesh.numberofelements,int)
    231         md.flowequation.element_equation[numpy.nonzero(noneflag)]=0
    232         md.flowequation.element_equation[numpy.nonzero(SIAflag)]=1
    233         md.flowequation.element_equation[numpy.nonzero(SSAflag)]=2
    234         md.flowequation.element_equation[numpy.nonzero(L1L2flag)]=3
    235         md.flowequation.element_equation[numpy.nonzero(HOflag)]=4
    236         md.flowequation.element_equation[numpy.nonzero(FSflag)]=5
    237         md.flowequation.element_equation[numpy.nonzero(SSAHOflag)]=6
    238         md.flowequation.element_equation[numpy.nonzero(SSAFSflag)]=7
    239         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
    240239
    241240        #border
     
    245244
    246245        #Create vertices_type
    247         md.flowequation.vertex_equation=numpy.zeros(md.mesh.numberofvertices,int)
    248         pos=numpy.nonzero(nodeonSSA)
     246        md.flowequation.vertex_equation=np.zeros(md.mesh.numberofvertices,int)
     247        pos=np.where(nodeonSSA)
    249248        md.flowequation.vertex_equation[pos]=2
    250         pos=numpy.nonzero(nodeonL1L2)
     249        pos=np.where(nodeonL1L2)
    251250        md.flowequation.vertex_equation[pos]=3
    252         pos=numpy.nonzero(nodeonHO)
     251        pos=np.where(nodeonHO)
    253252        md.flowequation.vertex_equation[pos]=4
    254         pos=numpy.nonzero(nodeonFS)
     253        pos=np.where(nodeonFS)
    255254        md.flowequation.vertex_equation[pos]=5
    256255        #DO SIA LAST! Otherwise spcs might not be set up correctly (SIA should have priority)
    257         pos=numpy.nonzero(nodeonSIA)
     256        pos=np.where(nodeonSIA)
    258257        md.flowequation.vertex_equation[pos]=1
    259258        if any(FSflag):
    260                 pos=numpy.nonzero(numpy.logical_not(nodeonFS))
     259                pos=np.where(np.logical_not(nodeonFS))
    261260                if not (any(HOflag) or any(SSAflag)):
    262261                        md.flowequation.vertex_equation[pos]=0
    263         pos=numpy.nonzero(nodeonSSAHO)
     262        pos=np.where(nodeonSSAHO)
    264263        md.flowequation.vertex_equation[pos]=6
    265         pos=numpy.nonzero(nodeonHOFS)
     264        pos=np.where(nodeonHOFS)
    266265        md.flowequation.vertex_equation[pos]=7
    267         pos=numpy.nonzero(nodeonSSAFS)
     266        pos=np.where(nodeonSSAFS)
    268267        md.flowequation.vertex_equation[pos]=8
    269268
  • issm/trunk-jpl/src/m/parameterization/sethydrostaticmask.py

    r18294 r21303  
    1 import numpy
     1import numpy as np
    22import os
    33from model import model
     
    2020   """
    2121
    22         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:
    2323                raise IOError("hydrostaticmask error message: fields in md.geometry do not have the right size.")
    2424
     
    2727
    2828   #Check consistency of geometry
    29         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.)]):
    3030           print "WARNING: md.geometry.bed and md.geometry.base not equal on grounded ice"
    3131
    32         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.)]):
    3333                print "WARNING: md.geometry.base < md.geometry.bed on floating ice"
    3434
  • issm/trunk-jpl/src/m/parameterization/setmask.py

    r20910 r21303  
    1 import numpy
     1import numpy as np
    22import os
    33from model import model
     
    2323        """
    2424        #some checks on list of arguments
     25        print type(md)
    2526        if not isinstance(md,model):
    2627                raise TypeError("setmask error message")
     
    4445        #arrays come from domain outlines that can intersect one another:
    4546
    46         elementonfloatingice = numpy.logical_and(elementonfloatingice,numpy.logical_not(elementongroundedice))
    47         elementongroundedice = numpy.logical_not(elementonfloatingice)
     47        elementonfloatingice = np.logical_and(elementonfloatingice,np.logical_not(elementongroundedice))
     48        elementongroundedice = np.logical_not(elementonfloatingice)
    4849
    4950        #the order here is important. we choose vertexongroundedice as default on the grounding line.
    50         vertexonfloatingice = numpy.zeros(md.mesh.numberofvertices,'bool')
    51         vertexongroundedice = numpy.zeros(md.mesh.numberofvertices,'bool')
    52         vertexongroundedice[md.mesh.elements[numpy.nonzero(elementongroundedice),:]-1]=True
    53         vertexonfloatingice[numpy.nonzero(numpy.logical_not(vertexongroundedice))]=True
     51        vertexonfloatingice = np.zeros(md.mesh.numberofvertices,'bool')
     52        vertexongroundedice = np.zeros(md.mesh.numberofvertices,'bool')
     53        vertexongroundedice[md.mesh.elements[np.nonzero(elementongroundedice),:]-1]=True
     54        vertexonfloatingice[np.nonzero(np.logical_not(vertexongroundedice))]=True
    5455        #}}}
    5556
    5657        #level sets
    57         md.mask.groundedice_levelset = -1.*numpy.ones(md.mesh.numberofvertices)
    58         md.mask.groundedice_levelset[md.mesh.elements[numpy.nonzero(elementongroundedice),:]-1]=1.
     58        md.mask.groundedice_levelset = -1.*np.ones(md.mesh.numberofvertices)
     59        md.mask.groundedice_levelset[md.mesh.elements[np.nonzero(elementongroundedice),:]-1]=1.
    5960
    6061        if(len(args)):
    61                 md.mask.ice_levelset = 1.*numpy.ones(md.mesh.numberofvertices)
     62                md.mask.ice_levelset = 1.*np.ones(md.mesh.numberofvertices)
    6263                icedomainfile = options.getfieldvalue('icedomain','none')
    6364                if not os.path.exists(icedomainfile):
     
    6566                #use contourtomesh to set ice values inside ice domain
    6667                vertexinsideicedomain,elementinsideicedomain=ContourToMesh(elements,x,y,icedomainfile,'node',1)
    67                 md.mask.ice_levelset[numpy.nonzero(vertexinsideicedomain)[0]] = -1.
     68                md.mask.ice_levelset[np.nonzero(vertexinsideicedomain)[0]] = -1.
    6869        else:
    69                 md.mask.ice_levelset = -1.*numpy.ones(md.mesh.numberofvertices)
     70                md.mask.ice_levelset = -1.*np.ones(md.mesh.numberofvertices)
    7071
    7172        return md
  • issm/trunk-jpl/src/m/plot/applyoptions.py

    r21297 r21303  
    1 import numpy as np
     1import numpy as  np
    22from cmaptools import truncate_colormap
    33from plot_contour import plot_contour
  • issm/trunk-jpl/src/m/plot/checkplotoptions.py

    r21283 r21303  
    1 import numpy as np
     1import numpy as  np
    22
    33def checkplotoptions(md,options):
  • issm/trunk-jpl/src/m/plot/colormaps/cmaptools.py

    r21254 r21303  
    1 import numpy as np
     1import numpy as  np
    22
    33try:
  • issm/trunk-jpl/src/m/plot/export_gl.py

    r19056 r21303  
    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/m/plot/plot_BC.py

    r21283 r21303  
    44        print "could not import pylab, matplotlib has not been installed, no plotting capabilities enabled"
    55
    6 import numpy as np
     6import numpy as  np
    77from processmesh import processmesh
    88from applyoptions import applyoptions
  • issm/trunk-jpl/src/m/plot/plot_icefront.py

    r21283 r21303  
    33except ImportError:
    44        print "could not import pylab, matplotlib has not been installed, no plotting capabilities enabled"
    5 import numpy as np
     5import numpy as  np
    66from processmesh import processmesh
    77from applyoptions import applyoptions
  • issm/trunk-jpl/src/m/plot/plot_overlay.py

    r21289 r21303  
    1 import numpy as np
     1import numpy as  np
    22from processmesh import processmesh
    33from processdata import processdata
  • issm/trunk-jpl/src/m/plot/plot_quiver.py

    r21283 r21303  
    1 import numpy as np
     1import numpy as  np
    22
    33def plot_quiver(x,y,data,options,ax):
  • issm/trunk-jpl/src/m/plot/plot_streamlines.py

    r21254 r21303  
    1 import numpy as np
     1import numpy as  np
    22from processmesh import processmesh
    33from processdata import processdata
  • issm/trunk-jpl/src/m/plot/plot_unit.py

    r21288 r21303  
    55        import matplotlib as mpl
    66        import matplotlib.pyplot as plt
    7         import numpy as np
     7        import numpy as  np
    88except ImportError:
    99        print "could not import pylab, matplotlib has not been installed, no plotting capabilities enabled"
  • issm/trunk-jpl/src/m/plot/plotmodel.py

    r21298 r21303  
    1 import numpy as np
     1import numpy as  np
    22from plotoptions import plotoptions
    33from plotdoc import plotdoc
  • issm/trunk-jpl/src/m/plot/processdata.py

    r21283 r21303  
    1 import numpy as np
     1import numpy as  np
    22
    33def processdata(md,data,options):
  • issm/trunk-jpl/src/m/plot/processmesh.py

    r21254 r21303  
    11from math import isnan
    2 import numpy as np
     2import numpy as  np
    33
    44def processmesh(md,data,options):
  • issm/trunk-jpl/src/m/plot/writejsfield.py

    r19056 r21303  
    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/m/plot/writejsfile.py

    r19056 r21303  
    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/m/solve/WriteData.py

    r21144 r21303  
    1 import numpy
    2 import math
     1import numpy as np
    32import struct
    43import pairoptions
     
    4443        if options.exist('scale'):
    4544                scale = options.getfieldvalue('scale')
    46                 if numpy.size(data) > 1 :
    47                         if numpy.size(data,0)==timeserieslength:
    48                                 data=numpy.array(data)
     45                if np.size(data) > 1 :
     46                        if np.size(data,0)==timeserieslength:
     47                                data=np.array(data)
    4948                                data[0:-1,:] = scale*data[0:-1,:]
    5049                        else:
     
    5251                else:
    5352                        data  = scale*data
    54         if numpy.size(data) > 1 :
    55                 if numpy.size(data,0)==timeserieslength:
     53        if np.size(data) > 1 :
     54                if np.size(data,0)==timeserieslength:
    5655                        yts = options.getfieldvalue('yts')
    5756                        data[-1,:] = yts*data[-1,:]
     
    119118
    120119                if   isinstance(data,bool):
    121                         data=numpy.array([data])
     120                        data=np.array([data])
    122121                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)
     122                        data=np.array(data).reshape(-1,)
     123                if np.ndim(data) == 1:
     124                        if np.size(data):
     125                                data=data.reshape(np.size(data),)
    127126                        else:
    128127                                data=data.reshape(0,0)
     
    131130                s=data.shape
    132131                #if matrix = NaN, then do not write anything
    133                 if s[0]==1 and s[1]==1 and math.isnan(data[0][0]):
     132                if np.ndim(data)==2 and np.product(s)==1 and np.all(np.isnan(data)):
    134133                        s=(0,0)
    135134
    136135                #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
     136                fid.write(struct.pack('i',4+4+8*np.product(s)+4+4))    #2 integers (32 bits) + the double matrix + code + matrix type
    138137
    139138                #write data code and matrix type:
     
    142141
    143142                #now write matrix
    144                 fid.write(struct.pack('i',s[0]))
    145                 fid.write(struct.pack('i',s[1]))
    146                 for i in xrange(s[0]):
    147                         for j in xrange(s[1]):
    148                                 fid.write(struct.pack('d',float(data[i][j])))    #get to the "c" convention, hence the transpose
     143                if np.ndim(data)==1:
     144                        fid.write(struct.pack('i',s[0]))
     145                        fid.write(struct.pack('i',1))
     146                        for i in xrange(s[0]):
     147                                fid.write(struct.pack('d',float(data[i])))    #get to the "c" convention, hence the transpose
     148                else:
     149                        fid.write(struct.pack('i',s[0]))
     150                        fid.write(struct.pack('i',s[1]))
     151                        for i in xrange(s[0]):
     152                                for j in xrange(s[1]):
     153                                        fid.write(struct.pack('d',float(data[i][j])))    #get to the "c" convention, hence the transpose
    149154                # }}}
    150155
     
    152157
    153158                if   isinstance(data,(int,long)):
    154                         data=numpy.array([data])
     159                        data=np.array([data])
    155160                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)
     161                        data=np.array(data).reshape(-1,)
     162                if np.ndim(data) == 1:
     163                        if np.size(data):
     164                                data=data.reshape(np.size(data),)
    160165                        else:
    161166                                data=data.reshape(0,0)
     
    164169                s=data.shape
    165170                #if matrix = NaN, then do not write anything
    166                 if s[0]==1 and s[1]==1 and math.isnan(data[0][0]):
     171                if np.ndim(data)==2 and np.product(s)==1 and np.all(np.isnan(data)):
    167172                        s=(0,0)
    168173
    169174                #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
     175                fid.write(struct.pack('i',4+4+8*np.product(s)+4+4))    #2 integers (32 bits) + the double matrix + code + matrix type
    171176
    172177                #write data code and matrix type:
     
    175180
    176181                #now write matrix
    177                 fid.write(struct.pack('i',s[0]))
    178                 fid.write(struct.pack('i',s[1]))
    179                 for i in xrange(s[0]):
    180                         for j in xrange(s[1]):
    181                                 fid.write(struct.pack('d',float(data[i][j])))    #get to the "c" convention, hence the transpose
     182                if np.ndim(data) == 1:
     183                        fid.write(struct.pack('i',s[0]))
     184                        fid.write(struct.pack('i',1))
     185                        for i in xrange(s[0]):
     186                                fid.write(struct.pack('d',float(data[i])))    #get to the "c" convention, hence the transpose
     187                else:
     188                        fid.write(struct.pack('i',s[0]))
     189                        fid.write(struct.pack('i',s[1]))
     190                        for i in xrange(s[0]):
     191                                for j in xrange(s[1]):
     192                                        fid.write(struct.pack('d',float(data[i][j])))    #get to the "c" convention, hence the transpose
    182193                # }}}
    183194
     
    185196
    186197                if   isinstance(data,(bool,int,long,float)):
    187                         data=numpy.array([data])
     198                        data=np.array([data])
    188199                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)
     200                        data=np.array(data).reshape(-1,)
     201                if np.ndim(data) == 1:
     202                        if np.size(data):
     203                                data=data.reshape(np.size(data),)
    193204                        else:
    194205                                data=data.reshape(0,0)
     
    197208                s=data.shape
    198209                #if matrix = NaN, then do not write anything
    199                 if s[0]==1 and s[1]==1 and math.isnan(data[0][0]):
     210                if np.ndim(data)==1 and np.product(s)==1 and np.all(np.isnan(data)):
    200211                        s=(0,0)
    201212
    202213                #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
     214                recordlength=4+4+8*np.product(s)+4+4; #2 integers (32 bits) + the double matrix + code + matrix type
    204215                if recordlength > 2**31 :
    205216                        raise ValueError('field %s cannot be marshalled because it is larger than 4^31 bytes!' % enum)
     
    212223
    213224                #now write matrix
    214                 fid.write(struct.pack('i',s[0]))
    215                 fid.write(struct.pack('i',s[1]))
    216                 for i in xrange(s[0]):
    217                         for j in xrange(s[1]):
    218                                 fid.write(struct.pack('d',float(data[i][j])))    #get to the "c" convention, hence the transpose
     225                if np.ndim(data) == 1:
     226                        fid.write(struct.pack('i',s[0]))
     227                        fid.write(struct.pack('i',1))
     228                        for i in xrange(s[0]):
     229                                fid.write(struct.pack('d',float(data[i])))    #get to the "c" convention, hence the transpose
     230                else:
     231                        fid.write(struct.pack('i',s[0]))
     232                        fid.write(struct.pack('i',s[1]))
     233                        for i in xrange(s[0]):
     234                                for j in xrange(s[1]):
     235                                        fid.write(struct.pack('d',float(data[i][j])))    #get to the "c" convention, hence the transpose
    219236                # }}}
    220237
     
    225242                for matrix in data:
    226243                        if   isinstance(matrix,(bool,int,long,float)):
    227                                 matrix=numpy.array([matrix])
     244                                matrix=np.array([matrix])
    228245                        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)
     246                                matrix=np.array(matrix).reshape(-1,)
     247                        if np.ndim(matrix) == 1:
     248                                if np.size(matrix):
     249                                        matrix=matrix.reshape(np.size(matrix),)
    233250                                else:
    234251                                        matrix=matrix.reshape(0,0)
    235252
    236253                        s=matrix.shape
    237                         recordlength+=4*2+s[0]*s[1]*8    #row and col of matrix + matrix of doubles
     254                        recordlength+=4*2+np.product(s)*8    #row and col of matrix + matrix of doubles
    238255
    239256                #write length of record
     
    249266                for matrix in data:
    250267                        if   isinstance(matrix,(bool,int,long,float)):
    251                                 matrix=numpy.array([matrix])
     268                                matrix=np.array([matrix])
    252269                        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)
     270                                matrix=np.array(matrix).reshape(-1,)
     271                        if np.ndim(matrix) == 1:
     272                                matrix=matrix.reshape(np.size(matrix),)
    256273
    257274                        s=matrix.shape
    258                         fid.write(struct.pack('i',s[0]))
    259                         fid.write(struct.pack('i',s[1]))
    260                         for i in xrange(s[0]):
    261                                 for j in xrange(s[1]):
    262                                         fid.write(struct.pack('d',float(matrix[i][j])))
     275                        if np.ndim(data) == 1:
     276                                fid.write(struct.pack('i',s[0]))
     277                                fid.write(struct.pack('i',1))
     278                                for i in xrange(s[0]):
     279                                        fid.write(struct.pack('d',float(matrix[i])))    #get to the "c" convention, hence the transpose
     280                        else:
     281                                fid.write(struct.pack('i',s[0]))
     282                                fid.write(struct.pack('i',s[1]))
     283                                for i in xrange(s[0]):
     284                                        for j in xrange(s[1]):
     285                                                fid.write(struct.pack('d',float(matrix[i][j])))
    263286                # }}}
    264287
  • issm/trunk-jpl/src/m/solve/parseresultsfromdisk.py

    r21267 r21303  
    11import struct
    2 import numpy
     2import numpy as np
    33from collections import OrderedDict
    44import results as resultsclass
     
    153153                M=struct.unpack('i',fid.read(struct.calcsize('i')))[0]
    154154                if   type==1:
    155                         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)
    156156                elif type==2:
    157157                        field=struct.unpack('%ds' % M,fid.read(M))[0][:-1]
     
    159159                        N=struct.unpack('i',fid.read(struct.calcsize('i')))[0]
    160160#                       field=transpose(fread(fid,[N M],'double'));
    161                         field=numpy.zeros(shape=(M,N),dtype=float)
     161                        field=np.zeros(shape=(M,N),dtype=float)
    162162                        for i in xrange(M):
    163163                                field[i,:]=struct.unpack('%dd' % N,fid.read(N*struct.calcsize('d')))
  • issm/trunk-jpl/src/m/solve/solve.py

    r21097 r21303  
    77from waitonlock import waitonlock
    88from loadresultsfromcluster import loadresultsfromcluster
    9 import MatlabFuncs as m
    109
    1110def solve(md,solutionstring,*args):
     
    7675        md.private.solution=solutionstring
    7776        cluster=md.cluster
    78         if m.strcmpi(options.getfieldvalue('batch','no'),'yes'):
     77        if options.getfieldvalue('batch','no')=='yes':
    7978                batch=1
    8079        else:
     
    8281
    8382        #check model consistency
    84         if m.strcmpi(options.getfieldvalue('checkconsistency','yes'),'yes'):
     83        if options.getfieldvalue('checkconsistency','yes')=='yes':
    8584                print "checking model consistency"
    8685                ismodelselfconsistent(md)
     
    117116
    118117        #Stop here if batch mode
    119         if m.strcmpi(options.getfieldvalue('batch','no'),'yes'):
     118        if options.getfieldvalue('batch','no')=='yes':
    120119                print 'batch mode requested: not launching job interactively'
    121120                print 'launch solution sequence on remote cluster by hand'
Note: See TracChangeset for help on using the changeset viewer.